aboutsummaryrefslogtreecommitdiffstats
path: root/epan/dissectors/packet-tcp.c
blob: b7065674edbb1971c75630d4baa2796d0fc4b5b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
/* packet-tcp.c
 * Routines for TCP packet disassembly
 *
 * $Id$
 *
 * Ethereal - Network traffic analyzer
 * By Gerald Combs <gerald@ethereal.com>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>
#include <string.h>
#include <glib.h>
#include <epan/in_cksum.h>

#include <epan/packet.h>
#include <epan/addr_resolv.h>
#include <epan/ipproto.h>
#include "ip_opts.h"
#include "follow.h"
#include <epan/prefs.h>
#include "packet-tcp.h"
#include "packet-ip.h"
#include "packet-frame.h"
#include <epan/conversation.h>
#include <epan/strutil.h>
#include "reassemble.h"
#include <epan/tap.h>

static int tcp_tap = -1;

/* Place TCP summary in proto tree */
static gboolean tcp_summary_in_tree = TRUE;

/*
 * Flag to control whether to check the TCP checksum.
 *
 * In at least some Solaris network traces, there are packets with bad
 * TCP checksums, but the traffic appears to indicate that the packets
 * *were* received; the packets were probably sent by the host on which
 * the capture was being done, on a network interface to which
 * checksumming was offloaded, so that DLPI supplied an un-checksummed
 * packet to the capture program but a checksummed packet got put onto
 * the wire.
 */
static gboolean tcp_check_checksum = TRUE;

extern FILE* data_out_file;

static int proto_tcp = -1;
static int hf_tcp_srcport = -1;
static int hf_tcp_dstport = -1;
static int hf_tcp_port = -1;
static int hf_tcp_seq = -1;
static int hf_tcp_nxtseq = -1;
static int hf_tcp_ack = -1;
static int hf_tcp_hdr_len = -1;
static int hf_tcp_flags = -1;
static int hf_tcp_flags_cwr = -1;
static int hf_tcp_flags_ecn = -1;
static int hf_tcp_flags_urg = -1;
static int hf_tcp_flags_ack = -1;
static int hf_tcp_flags_push = -1;
static int hf_tcp_flags_reset = -1;
static int hf_tcp_flags_syn = -1;
static int hf_tcp_flags_fin = -1;
static int hf_tcp_window_size = -1;
static int hf_tcp_checksum = -1;
static int hf_tcp_checksum_bad = -1;
static int hf_tcp_len = -1;
static int hf_tcp_urgent_pointer = -1;
static int hf_tcp_analysis_flags = -1;
static int hf_tcp_analysis_acks_frame = -1;
static int hf_tcp_analysis_ack_rtt = -1;
static int hf_tcp_analysis_retransmission = -1;
static int hf_tcp_analysis_fast_retransmission = -1;
static int hf_tcp_analysis_out_of_order = -1;
static int hf_tcp_analysis_lost_packet = -1;
static int hf_tcp_analysis_ack_lost_packet = -1;
static int hf_tcp_analysis_window_update = -1;
static int hf_tcp_analysis_window_full = -1;
static int hf_tcp_analysis_keep_alive = -1;
static int hf_tcp_analysis_keep_alive_ack = -1;
static int hf_tcp_analysis_duplicate_ack = -1;
static int hf_tcp_analysis_duplicate_ack_num = -1;
static int hf_tcp_analysis_duplicate_ack_frame = -1;
static int hf_tcp_analysis_zero_window = -1;
static int hf_tcp_analysis_zero_window_probe = -1;
static int hf_tcp_analysis_zero_window_violation = -1;
static int hf_tcp_continuation_to = -1;
static int hf_tcp_pdu_time = -1;
static int hf_tcp_pdu_last_frame = -1;
static int hf_tcp_reassembled_in = -1;
static int hf_tcp_segments = -1;
static int hf_tcp_segment = -1;
static int hf_tcp_segment_overlap = -1;
static int hf_tcp_segment_overlap_conflict = -1;
static int hf_tcp_segment_multiple_tails = -1;
static int hf_tcp_segment_too_long_fragment = -1;
static int hf_tcp_segment_error = -1;
static int hf_tcp_option_mss = -1;
static int hf_tcp_option_mss_val = -1;
static int hf_tcp_option_wscale = -1;
static int hf_tcp_option_wscale_val = -1;
static int hf_tcp_option_sack_perm = -1;
static int hf_tcp_option_sack = -1;
static int hf_tcp_option_sack_sle = -1;
static int hf_tcp_option_sack_sre = -1;
static int hf_tcp_option_echo = -1;
static int hf_tcp_option_echo_reply = -1;
static int hf_tcp_option_time_stamp = -1;
static int hf_tcp_option_cc = -1;
static int hf_tcp_option_ccnew = -1;
static int hf_tcp_option_ccecho = -1;
static int hf_tcp_option_md5 = -1;

static gint ett_tcp = -1;
static gint ett_tcp_flags = -1;
static gint ett_tcp_options = -1;
static gint ett_tcp_option_sack = -1;
static gint ett_tcp_analysis = -1;
static gint ett_tcp_analysis_faults = -1;
static gint ett_tcp_segments = -1;
static gint ett_tcp_segment  = -1;


/* not all of the hf_fields below make sense for TCP but we have to provide 
   them anyways to comply with the api (which was aimed for ip fragment 
   reassembly) */
static const fragment_items tcp_segment_items = {
	&ett_tcp_segment,
	&ett_tcp_segments,
	&hf_tcp_segments,
	&hf_tcp_segment,
	&hf_tcp_segment_overlap,
	&hf_tcp_segment_overlap_conflict,
	&hf_tcp_segment_multiple_tails,
	&hf_tcp_segment_too_long_fragment,
	&hf_tcp_segment_error,
	&hf_tcp_reassembled_in,
	"Segments"
};

static dissector_table_t subdissector_table;
static heur_dissector_list_t heur_subdissector_list;
static dissector_handle_t data_handle;

/* TCP structs and definitions */

static void
process_tcp_payload(tvbuff_t *tvb, volatile int offset, packet_info *pinfo,
	proto_tree *tree, proto_tree *tcp_tree, int src_port, int dst_port,
	guint32 seq, guint32 nxtseq, gboolean is_tcp_segment);

/* **************************************************************************
 * stuff to analyze TCP sequencenumbers for retransmissions, missing segments,
 * RTT and reltive sequence numbers.
 * **************************************************************************/
static gboolean tcp_analyze_seq = TRUE;
static gboolean tcp_relative_seq = TRUE;

static GMemChunk *tcp_unacked_chunk = NULL;
static int tcp_unacked_count = 500;	/* one for each packet until it is acked*/
struct tcp_unacked {
	struct tcp_unacked *next;
	guint32 frame;
	guint32	seq;
	guint32 nextseq;
	nstime_t ts;

	/* this is to keep track of zero window and zero window probe */
	guint32 window;

	guint32 flags;
};

/* Idea for gt: either x > y, or y is much bigger (assume wrap) */
#define GT_SEQ(x, y) ((gint32)((y) - (x)) < 0)
#define LT_SEQ(x, y) ((gint32)((x) - (y)) < 0)
#define GE_SEQ(x, y) ((gint32)((y) - (x)) <= 0)
#define LE_SEQ(x, y) ((gint32)((x) - (y)) <= 0)
#define EQ_SEQ(x, y) ((x) == (y))

static GMemChunk *tcp_acked_chunk = NULL;
static int tcp_acked_count = 5000;	/* one for almost every other segment in the capture */
#define TCP_A_RETRANSMISSION		0x0001
#define TCP_A_LOST_PACKET		0x0002
#define TCP_A_ACK_LOST_PACKET		0x0004
#define TCP_A_KEEP_ALIVE		0x0008
#define TCP_A_DUPLICATE_ACK		0x0010
#define TCP_A_ZERO_WINDOW		0x0020
#define TCP_A_ZERO_WINDOW_PROBE		0x0040
#define TCP_A_ZERO_WINDOW_VIOLATION	0x0080
#define TCP_A_KEEP_ALIVE_ACK		0x0100
#define TCP_A_OUT_OF_ORDER		0x0200
#define TCP_A_FAST_RETRANSMISSION	0x0400
#define TCP_A_WINDOW_UPDATE		0x0800
#define TCP_A_WINDOW_FULL		0x1000
struct tcp_acked {
	guint32 frame_acked;
	nstime_t ts;
	guint16 flags;
	guint32 dupack_num;	/* dup ack number */
	guint32 dupack_frame;	/* dup ack to frame # */
};
static GHashTable *tcp_analyze_acked_table = NULL;

static GMemChunk *tcp_rel_seq_chunk = NULL;
static int tcp_rel_seq_count = 10000; /* one for each segment in the capture */
struct tcp_rel_seq {
	guint32 seq_base;
	guint32 ack_base;
	gint16  win_scale;
};
static GHashTable *tcp_rel_seq_table = NULL;

static GMemChunk *tcp_analysis_chunk = NULL;
static int tcp_analysis_count = 20;	/* one for each conversation */
struct tcp_analysis {
	/* These two structs are managed based on comparing the source
	 * and destination addresses and, if they're equal, comparing
	 * the source and destination ports.
	 *
	 * If the source is greater than the destination, then stuff
	 * sent from src is in ual1.
	 *
	 * If the source is less than the destination, then stuff
	 * sent from src is in ual2.
	 *
	 * XXX - if the addresses and ports are equal, we don't guarantee
	 * the behavior.
	 */
	struct tcp_unacked *ual1;	/* UnAcked List 1*/
	guint32 base_seq1;
	struct tcp_unacked *ual2;	/* UnAcked List 2*/
	guint32 base_seq2;
	gint16 win_scale1, win_scale2;
	gint32 win1, win2;
	guint32 ack1, ack2;
	guint32 ack1_frame, ack2_frame;
	nstime_t ack1_time, ack2_time;
	guint32 num1_acks, num2_acks;

	/* these two lists are used to track when PDUs may start
	   inside a segment.
	*/
	struct tcp_next_pdu *pdu_seq1;
	struct tcp_next_pdu *pdu_seq2;
};


static GMemChunk *tcp_next_pdu_chunk = NULL;
static int tcp_next_pdu_count = 20;
struct tcp_next_pdu {
	struct tcp_next_pdu *next;
	guint32 seq;
	guint32 nxtpdu;
	guint32 first_frame;
	guint32 last_frame;
        nstime_t last_frame_time;
};
static GHashTable *tcp_pdu_tracking_table = NULL;
static GHashTable *tcp_pdu_skipping_table = NULL;
static GHashTable *tcp_pdu_time_table = NULL;


static struct tcp_analysis *
get_tcp_conversation_data(packet_info *pinfo)
{
	conversation_t *conv=NULL;
	struct tcp_analysis *tcpd=NULL;

	/* Have we seen this conversation before? */
	if( (conv=find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport, 0)) == NULL){
		/* No this is a new conversation. */
		conv=conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
	}

	/* check if we have any data for this conversation */
	tcpd=conversation_get_proto_data(conv, proto_tcp);
	if(!tcpd){
		/* No no such data yet. Allocate and init it */
		tcpd=g_mem_chunk_alloc(tcp_analysis_chunk);
		tcpd->ual1=NULL;
		tcpd->base_seq1=0;
		tcpd->win1=-1;
		tcpd->win_scale1=-1;
		tcpd->ack1=0;
		tcpd->ack1_frame=0;
		tcpd->ack1_time.secs=0;
		tcpd->ack1_time.nsecs=0;
		tcpd->num1_acks=0;
		tcpd->ual2=NULL;
		tcpd->base_seq2=0;
		tcpd->win2=-1;
		tcpd->win_scale2=-1;
		tcpd->ack2=0;
		tcpd->ack2_frame=0;
		tcpd->ack2_time.secs=0;
		tcpd->ack2_time.nsecs=0;
		tcpd->num2_acks=0;

		tcpd->pdu_seq1=NULL;
		tcpd->pdu_seq2=NULL;

		conversation_add_proto_data(conv, proto_tcp, tcpd);
	}

	return tcpd;
}

/* This function is called from the tcp analysis code to provide
   clues on how the seq and ack numbers are changed.
   To prevent the next_pdu lists from growing uncontrollable in size we
   use this function to do the following :
   IF we see an ACK then we assume that the left edge of the window has changed
      at least to this point and assuming it is rare with reordering and
      trailing duplicate/retransmitted segments, we just assume that after
      we have seen the ACK we will not see any more segments prior to the 
      ACK value.
      If we will not see any segments prior to the ACK value then we can just
      delete all next_pdu entries that describe pdu's starting prior to the 
      ACK.
      If this heuristics is prooved to be too simplistic we can just enhance it
      later.
*/   
/* XXX this function should be ehnanced to handle sequence number wrapping */
/* XXX to handle retransmissions and reordered packets maybe we should only
       discard entries that are more than (guesstimate) 50kb older than the
       specified sequence number ?
*/
static void
prune_next_pdu_list(struct tcp_next_pdu **tnp, guint32 seq)
{
	struct tcp_next_pdu *tmptnp;

	if(*tnp == NULL){
		return;
	}

	for(tmptnp=*tnp;tmptnp;tmptnp=tmptnp->next){
		if(tmptnp->nxtpdu<=seq){
			struct tcp_next_pdu *oldtnp;
			oldtnp=tmptnp;

			if(tmptnp==*tnp){
				tmptnp=tmptnp->next;
				*tnp=tmptnp;
				if(!tmptnp){
					return;
				}
				continue;
			} else {
				for(tmptnp=*tnp;tmptnp;tmptnp=tmptnp->next){
					if(tmptnp->next==oldtnp){
						tmptnp->next=oldtnp->next;
						break;
					}
				}
				if(!tmptnp){
					return;
				}
			}
		}
	}
}
		

static void
print_pdu_tracking_data(packet_info *pinfo, tvbuff_t *tvb, proto_tree *tcp_tree, struct tcp_next_pdu *tnp)
{
	proto_item *item;

	if (check_col(pinfo->cinfo, COL_INFO)){
		col_prepend_fstr(pinfo->cinfo, COL_INFO, "[Continuation to #%u] ", tnp->first_frame);
	}
	item=proto_tree_add_uint(tcp_tree, hf_tcp_continuation_to,
		tvb, 0, 0, tnp->first_frame);
	PROTO_ITEM_SET_GENERATED(item);
}

/* if we know that a PDU starts inside this segment, return the adjusted 
   offset to where that PDU starts or just return offset back
   and let TCP try to find out what it can about this segment
*/
static int
scan_for_next_pdu(tvbuff_t *tvb, proto_tree *tcp_tree, packet_info *pinfo, int offset, guint32 seq, guint32 nxtseq)
{
	struct tcp_analysis *tcpd=NULL;
	struct tcp_next_pdu *tnp=NULL;
	int direction;

	if(!pinfo->fd->flags.visited){
		/* find(or create if needed) the conversation for this tcp session */
		tcpd=get_tcp_conversation_data(pinfo);
		/* check direction and get pdu start lists */
		direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
		/* if the addresses are equal, match the ports instead */
		if(direction==0) {
			direction= (pinfo->srcport > pinfo->destport)*2-1;
		}
		if(direction>=0){
			tnp=tcpd->pdu_seq1;
		} else {
			tnp=tcpd->pdu_seq2;
		}

		/* scan and see if we find any pdus starting inside this tvb */
		for(;tnp;tnp=tnp->next){
			/* XXX here we should also try to handle sequence number
			   wrapping
			*/
			/* If this segment is completely within a previous PDU
			 * then we just skip this packet
			 */
			if(seq>tnp->seq && nxtseq<=tnp->nxtpdu){
				tnp->last_frame=pinfo->fd->num;
				tnp->last_frame_time.secs=pinfo->fd->abs_secs;
				tnp->last_frame_time.nsecs=pinfo->fd->abs_usecs*1000;
				g_hash_table_insert(tcp_pdu_skipping_table, 
					GINT_TO_POINTER(pinfo->fd->num), (void *)tnp);
				print_pdu_tracking_data(pinfo, tvb, tcp_tree, tnp);

				return -1;
			}			
			if(seq<tnp->nxtpdu && nxtseq>tnp->nxtpdu){
				g_hash_table_insert(tcp_pdu_tracking_table, 
					GINT_TO_POINTER(pinfo->fd->num), GUINT_TO_POINTER(tnp->nxtpdu));
				offset+=tnp->nxtpdu-seq;
				break;
			}
		}
	} else {
		guint32 pduseq;

		tnp=(struct tcp_next_pdu *)g_hash_table_lookup(tcp_pdu_time_table, GINT_TO_POINTER(pinfo->fd->num));
		if(tnp){
			proto_item *item;
		 	nstime_t ns;

			item=proto_tree_add_uint(tcp_tree, hf_tcp_pdu_last_frame, tvb, 0, 0, tnp->last_frame);
			PROTO_ITEM_SET_GENERATED(item);

			ns.secs =tnp->last_frame_time.secs-pinfo->fd->abs_secs;
			ns.nsecs=tnp->last_frame_time.nsecs-pinfo->fd->abs_usecs*1000;
			if(ns.nsecs<0){
				ns.nsecs+=1000000000;
				ns.secs--;
			}
			item = proto_tree_add_time(tcp_tree, hf_tcp_pdu_time,
					tvb, 0, 0, &ns);
			PROTO_ITEM_SET_GENERATED(item);

		}

		/* check if this is a segment in the middle of a pdu */
		tnp=(struct tcp_next_pdu *)g_hash_table_lookup(tcp_pdu_skipping_table, GINT_TO_POINTER(pinfo->fd->num));
		if(tnp){
			print_pdu_tracking_data(pinfo, tvb, tcp_tree, tnp);
			return -1;
		}

		pduseq=GPOINTER_TO_UINT(g_hash_table_lookup(tcp_pdu_tracking_table, GINT_TO_POINTER(pinfo->fd->num)));
		if(pduseq){
			offset+=pduseq-seq;
		}
	}

	return offset;
}

/* if we saw a PDU that extended beyond the end of the segment,
   use this function to remember where the next pdu starts
*/
static void
pdu_store_sequencenumber_of_next_pdu(packet_info *pinfo, guint32 seq, guint32 nxtpdu)
{
	struct tcp_analysis *tcpd=NULL;
	struct tcp_next_pdu *tnp=NULL;
	int direction;

 	/* find(or create if needed) the conversation for this tcp session */
	tcpd=get_tcp_conversation_data(pinfo);

	tnp=g_mem_chunk_alloc(tcp_next_pdu_chunk);
	tnp->nxtpdu=nxtpdu;
	tnp->seq=seq;
	tnp->first_frame=pinfo->fd->num;
	tnp->last_frame=pinfo->fd->num;
	tnp->last_frame_time.secs=pinfo->fd->abs_secs;
	tnp->last_frame_time.nsecs=pinfo->fd->abs_usecs*1000;

	/* check direction and get pdu start list */
	direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
	/* if the addresses are equal, match the ports instead */
	if(direction==0) {
		direction= (pinfo->srcport > pinfo->destport)*2-1;
	}
	if(direction>=0){
		tnp->next=tcpd->pdu_seq1;
		tcpd->pdu_seq1=tnp;
	} else {
		tnp->next=tcpd->pdu_seq2;
		tcpd->pdu_seq2=tnp;
	}
	/*QQQ 
	  Add check for ACKs and purge list of sequence numbers
	  already acked.
	*/
	g_hash_table_insert(tcp_pdu_time_table, GINT_TO_POINTER(pinfo->fd->num), (void *)tnp);
}

/* This is called for SYN+ACK packets and the purpose is to verify that we
 * have seen window scaling in both directions.
 * If we cant find window scaling being set in both directions
 * that means it was present in the SYN but not in the SYN+ACK
 * (or the SYN was missing) and then we disable the window scaling
 * for this tcp session.
 */
static void verify_tcp_window_scaling(packet_info *pinfo)
{
	struct tcp_analysis *tcpd=NULL;

	/* find(or create if needed) the conversation for this tcp session */
	tcpd=get_tcp_conversation_data(pinfo);

	if( (tcpd->win_scale1==-1) || (tcpd->win_scale2==-1) ){
		tcpd->win_scale1=-1;
		tcpd->win_scale2=-1;
	}
}

/* if we saw a window scaling option, store it for future reference 
*/
static void pdu_store_window_scale_option(packet_info *pinfo, guint8 ws)
{
	struct tcp_analysis *tcpd=NULL;
	int direction;

	/* find(or create if needed) the conversation for this tcp session */
	tcpd=get_tcp_conversation_data(pinfo);

	/* check direction and get pdu start list */
	direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
	/* if the addresses are equal, match the ports instead */
	if(direction==0) {
		direction= (pinfo->srcport > pinfo->destport)*2-1;
	}
	if(direction>=0){
		tcpd->win_scale1=ws;
	} else {
		tcpd->win_scale2=ws;
	}
}

static void
tcp_get_relative_seq_ack(guint32 frame, guint32 *seq, guint32 *ack, guint32 *win)
{
	struct tcp_rel_seq *trs;

	trs=g_hash_table_lookup(tcp_rel_seq_table, GUINT_TO_POINTER(frame));
	if(!trs){
		return;
	}

	(*seq) -= trs->seq_base;
	(*ack) -= trs->ack_base;
	if(trs->win_scale!=-1){
		(*win)<<=trs->win_scale;
	}
}

static struct tcp_acked *
tcp_analyze_get_acked_struct(guint32 frame, gboolean createflag)
{
	struct tcp_acked *ta;

	ta=g_hash_table_lookup(tcp_analyze_acked_table, GUINT_TO_POINTER(frame));
	if((!ta) && createflag){
		ta=g_mem_chunk_alloc(tcp_acked_chunk);
		ta->frame_acked=0;
		ta->ts.secs=0;
		ta->ts.nsecs=0;
		ta->flags=0;
		ta->dupack_num=0;
		ta->dupack_frame=0;
		g_hash_table_insert(tcp_analyze_acked_table, GUINT_TO_POINTER(frame), ta);
	}
	return ta;
}

static void
tcp_analyze_sequence_number(packet_info *pinfo, guint32 seq, guint32 ack, guint32 seglen, guint8 flags, guint32 window)
{
	struct tcp_analysis *tcpd=NULL;
	int direction;
	struct tcp_unacked *ual1=NULL;
	struct tcp_unacked *ual2=NULL;
	struct tcp_unacked *ual=NULL;
	guint32 base_seq;
	guint32 base_ack;
	guint32 ack1, ack2;
	guint32 ack1_frame, ack2_frame;
	nstime_t *ack1_time, *ack2_time;
	guint32 num1_acks, num2_acks;
	gint32 win1,win2;
	gint16  win_scale1,win_scale2;
	struct tcp_next_pdu **tnp=NULL;

	/* find(or create if needed) the conversation for this tcp session */
	tcpd=get_tcp_conversation_data(pinfo);

	/* check direction and get ua lists */
	direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
	/* if the addresses are equal, match the ports instead */
	if(direction==0) {
		direction= (pinfo->srcport > pinfo->destport)*2-1;
	}
	if(direction>=0){
		ual1=tcpd->ual1;
		ual2=tcpd->ual2;
		ack1=tcpd->ack1;
		ack2=tcpd->ack2;
		ack1_frame=tcpd->ack1_frame;
		ack2_frame=tcpd->ack2_frame;
		ack1_time=&tcpd->ack1_time;
		ack2_time=&tcpd->ack2_time;
		num1_acks=tcpd->num1_acks;
		num2_acks=tcpd->num2_acks;
		tnp=&tcpd->pdu_seq2;
		base_seq=(tcp_relative_seq && (ual1==NULL))?seq:tcpd->base_seq1;
		base_ack=(tcp_relative_seq && (ual2==NULL))?ack:tcpd->base_seq2;
		win_scale1=tcpd->win_scale1;
		win1=tcpd->win1;
		win_scale2=tcpd->win_scale2;
		win2=tcpd->win2;
	} else {
		ual1=tcpd->ual2;
		ual2=tcpd->ual1;
		ack1=tcpd->ack2;
		ack2=tcpd->ack1;
		ack1_frame=tcpd->ack2_frame;
		ack2_frame=tcpd->ack1_frame;
		ack1_time=&tcpd->ack2_time;
		ack2_time=&tcpd->ack1_time;
		num1_acks=tcpd->num2_acks;
		num2_acks=tcpd->num1_acks;
		tnp=&tcpd->pdu_seq1;
		base_seq=(tcp_relative_seq && (ual1==NULL))?seq:tcpd->base_seq2;
		base_ack=(tcp_relative_seq && (ual2==NULL))?ack:tcpd->base_seq1;
		win_scale1=tcpd->win_scale2;
		win1=tcpd->win2;
		win_scale2=tcpd->win_scale1;
		win2=tcpd->win1;
	}

	if(!seglen){
		if(!ack2_frame){
			ack2_frame=pinfo->fd->num;
			ack2=ack;
			ack2_time->secs=pinfo->fd->abs_secs;
			ack2_time->nsecs=pinfo->fd->abs_usecs*1000;
			num2_acks=0;
		} else if(GT_SEQ(ack, ack2)){
			ack2_frame=pinfo->fd->num;
			ack2=ack;
			ack2_time->secs=pinfo->fd->abs_secs;
			ack2_time->nsecs=pinfo->fd->abs_usecs*1000;
			num2_acks=0;
		}
	}

#ifdef REMOVED
/* useful debug ouput   
 * it prints the two lists of the sliding window emulation 
 */
{
struct tcp_unacked *u=NULL;
printf("\n");
printf("analyze_sequence_number(frame:%d seq:%d nextseq:%d ack:%d  baseseq:0x%08x baseack:0x%08x)\n",pinfo->fd->num,seq,seq+seglen,ack,base_seq,base_ack);
printf("UAL1:\n");
for(u=ual1;u;u=u->next){
printf("  Frame:%d seq:%d nseq:%d time:%d.%09d ack:%d:%d\n",u->frame,u->seq,u->nextseq,u->ts.secs,u->ts.nsecs,ack1,ack2);
}
printf("UAL2:\n");
for(u=ual2;u;u=u->next){
printf("  Frame:%d seq:%d nseq:%d time:%d.%09d ack:%d:%d\n",u->frame,u->seq,u->nextseq,u->ts.secs,u->ts.nsecs,ack1,ack2);
}
}
#endif

	/* To handle FIN, just add 1 to the length.
	   else the ACK following the FIN-ACK will look like it was
	   outside the window. */
	if( flags&TH_FIN ){
		seglen+=1;
	}

	/* handle the sequence numbers */
	/* if this was a SYN packet, then remove existing list and
	 * put SEQ+1 first the list */
	if(flags&TH_SYN){
		for(ual=ual1;ual1;ual1=ual){
			ual=ual1->next;
			g_mem_chunk_free(tcp_unacked_chunk, ual1);
		}
		ual1=g_mem_chunk_alloc(tcp_unacked_chunk);
		ual1->next=NULL;
		ual1->frame=pinfo->fd->num;
		ack1_frame=0;
		ack2_frame=0;
		ack1=0;
		ack2=0;
		num1_acks=0;
		num2_acks=0;
		ual1->seq=seq;
		ual1->nextseq=seq+1;
		ual1->ts.secs=pinfo->fd->abs_secs;
		ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
		ual1->window=window;
		ual1->flags=0;
		if(tcp_relative_seq){
			base_seq=seq;
			/* if this was an SYN|ACK packet then set base_ack
			 * reflect the start of the sequence, i.e. one less 
			 */
			if(flags&TH_ACK){
				base_ack=ack-1;
			} else {
				base_ack=ack;
			}
		}
		goto seq_finished;
	}

	/* if this is the first segment we see then just add it */
	if( !ual1 ){
		ual1=g_mem_chunk_alloc(tcp_unacked_chunk);
		ual1->next=NULL;
		ual1->frame=pinfo->fd->num;
		ual1->seq=seq;
		ual1->nextseq=seq+seglen;
		ual1->ts.secs=pinfo->fd->abs_secs;
		ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
		ual1->window=window;
		ual1->flags=0;
		if(tcp_relative_seq){
			base_seq=seq;
			base_ack=ack;
		}
		goto seq_finished;
	}

	/* if we get past here we know that ual1 points to a segment */


	/* if seq is beyond ual1->nextseq we have lost a segment */
	if (GT_SEQ(seq, ual1->nextseq)) {
		struct tcp_acked *ta;

		ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
		ta->flags|=TCP_A_LOST_PACKET;

		/* just add the segment to the beginning of the list */
		ual=g_mem_chunk_alloc(tcp_unacked_chunk);
		ual->next=ual1;
		ual->frame=pinfo->fd->num;
		ual->seq=seq;
		ual->nextseq=seq+seglen;
		ual->ts.secs=pinfo->fd->abs_secs;
		ual->ts.nsecs=pinfo->fd->abs_usecs*1000;
		ual->window=window;
		ual->flags=0;
		ual1=ual;
		goto seq_finished;
	}

	/* keep-alives are empty segments with a sequence number -1 of what
	 * we would expect.
         *
	 * Solaris is an exception, Solaris does not really use KeepAlives
	 * according to RFC793, instead they move the left window edge one
	 * byte to the left and makes up a fake byte to fill in this position
	 * of the enlarged window.
	 * This means that Solaris will do "weird" KeepAlives that actually
	 * contains a one-byte segment with "random" junk data which the
	 * Solaris host then will try to transmit, and posisbly retransmit
	 * to the other side. Of course the other side will ignore this junk
	 * byte since it is outside (left of) the window.
	 * This is actually a brilliant trick that gives them, for free, 
	 * semi-reliable KeepAlives.
	 * (since normal retransmission will handle any lost keepalive segments
	 * , brilliant)
	 */
	if( (seglen<=1) && EQ_SEQ(seq, (ual1->nextseq-1)) ){
		if(!(flags&TH_FIN)){ /* FIN segments are not keepalives */
			struct tcp_acked *ta;
	
			ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
			ta->flags|=TCP_A_KEEP_ALIVE;
			ual1->flags|=TCP_A_KEEP_ALIVE;
			goto seq_finished;
		}
	}

	/* if this is an empty segment, just skip it all */
	if( !seglen ){
		goto seq_finished;
	}

	/* check if the sequence number is lower than expected, i.e. either a 
	 * retransmission a fast retransmission or an out of order segment
	 */
	if( LT_SEQ(seq, ual1->nextseq )){
		gboolean outoforder;
		struct tcp_unacked *tu,*ntu;

		/* assume it is a fast retransmission if
		 * 1 we have seen >=3 dupacks in the other direction for this 
		 *   segment (i.e. >=4 acks)
		 * 2 if this segment is the next unacked segment
		 * 3 this segment came within 10ms of the last dupack
		 *   (10ms is arbitrary but should be low enough not to be
		 *   confused with a retransmission timeout 
		 */
		if( (num1_acks>=4) && (seq==ack1) ){
			guint32 t;

			t=(pinfo->fd->abs_secs-ack1_time->secs)*1000000000;
			t=t+(pinfo->fd->abs_usecs*1000)-ack1_time->nsecs;
			if(t<10000000){
				/* has to be a retransmission then */
				struct tcp_acked *ta;

				ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
				ta->flags|=TCP_A_FAST_RETRANSMISSION;
				goto seq_finished;
			}
		}

		/* check it is a suspected out of order segment.
		 * we assume it is an out of order segment if 
		 * 1 it has not been ACKed yet.
		 * 2 we have not seen the segment before
		 * 3 it arrived within (arbitrary value) 4ms of the
		 *      next semgent in the sequence.
		 *   4 there were no dupacks in the opposite direction.
		 */
		outoforder=TRUE;
#ifdef REMOVED
		/* dont do this test.  For full-duplex capture devices that 
		 * capture in both directions using two NICs it is more common
		 * than one would expect for this to happen since they often
		 * lose the time integrity between the two NICs
		 */
		/* 1 has it already been ACKed ? */
		if(LT_SEQ(seq,ack1)){
			outoforder=FALSE;
		}
#endif
		/* 2 have we seen this segment before ? */
		for(tu=ual1;tu;tu=tu->next){
			if((tu->frame)&&(tu->seq==seq)){
				outoforder=FALSE;
			}
		}
		/* 3 was it received within 4ms of the next segment ?*/
		ntu=NULL;
		for(tu=ual1;tu;tu=tu->next){
			if(LT_SEQ(seq,tu->seq)){
				if(tu->frame){
					ntu=tu;
				}
			}
		}
		if(ntu){
			if(pinfo->fd->abs_secs>(guint32)(ntu->ts.secs+2)){
				outoforder=FALSE;
			} else if((pinfo->fd->abs_secs+2)<(guint32)ntu->ts.secs){
				outoforder=FALSE;
			} else {
				guint32 t;

				t=(ntu->ts.secs-pinfo->fd->abs_secs)*1000000000;
				t=t+ntu->ts.nsecs-(pinfo->fd->abs_usecs*1000);
				if(t>4000000){
					outoforder=FALSE;
				}
			}
		}

		
		if(outoforder) {
			struct tcp_acked *ta;

			ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
			ta->flags|=TCP_A_OUT_OF_ORDER;
		} else {
			/* has to be a retransmission then */
			struct tcp_acked *ta;

			ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
			ta->flags|=TCP_A_RETRANSMISSION;

			/* did this segment contain any more data we havent seen yet?
			 * if so we can just increase nextseq
			 */
			if(GT_SEQ((seq+seglen), ual1->nextseq)){
				ual1->nextseq=seq+seglen;
				ual1->frame=pinfo->fd->num;
				ual1->ts.secs=pinfo->fd->abs_secs;
				ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
			}
		}
		goto seq_finished;
	}

	/* just add the segment to the beginning of the list */
	ual=g_mem_chunk_alloc(tcp_unacked_chunk);
	ual->next=ual1;
	ual->frame=pinfo->fd->num;
	ual->seq=seq;
	ual->nextseq=seq+seglen;
	ual->ts.secs=pinfo->fd->abs_secs;
	ual->ts.nsecs=pinfo->fd->abs_usecs*1000;
	ual->window=window;
	ual->flags=0;
	ual1=ual;

seq_finished:



	/* handle the ack numbers */

	/* if we dont have the ack flag its not much we can do */
	if( !(flags&TH_ACK)){
		goto ack_finished;
	}

	/* if we havent seen anything yet in the other direction we dont
	 * know what this one acks */
	if( !ual2 ){
		goto ack_finished;
	}

	/* if we dont have any real segments in the other direction not
	 * acked yet (as we see from the magic frame==0 entry)
	 * then there is no point in continuing
	 */
	if( !ual2->frame ){
		goto ack_finished;
	}

	/* if we get here we know ual2 is valid */

	/* if we are acking beyong what we have seen in the other direction
	 * we must have lost packets. Not much point in keeping the segments
	 * in the other direction either.
	 */
	if( GT_SEQ(ack, ual2->nextseq )){
		struct tcp_acked *ta;

		ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
		ta->flags|=TCP_A_ACK_LOST_PACKET;
		for(ual=ual2;ual2;ual2=ual){
			ual=ual2->next;
			g_mem_chunk_free(tcp_unacked_chunk, ual2);
		}
		prune_next_pdu_list(tnp, ack-base_ack);
		goto ack_finished;
	}


	/* does this ACK ack all semgents we have seen in the other direction?*/
	if( EQ_SEQ(ack, ual2->nextseq )){
		struct tcp_acked *ta;

		ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
		ta->frame_acked=ual2->frame;
		ta->ts.secs=pinfo->fd->abs_secs-ual2->ts.secs;
		ta->ts.nsecs=pinfo->fd->abs_usecs*1000-ual2->ts.nsecs;
		if(ta->ts.nsecs<0){
			ta->ts.nsecs+=1000000000;
			ta->ts.secs--;
		}

		/* its all been ACKed so we dont need to keep them anymore */
		for(ual=ual2;ual2;ual2=ual){
			ual=ual2->next;
			g_mem_chunk_free(tcp_unacked_chunk, ual2);
		}
		prune_next_pdu_list(tnp, ack-base_ack);
		goto ack_finished;
	}

	/* ok it only ACKs part of what we have seen. Find out how much
	 * update and remove the ACKed segments
	 */
	for(ual=ual2;ual->next;ual=ual->next){
		if( GE_SEQ(ack, ual->next->nextseq)){
			break;
		}
	}
	if(ual->next){
		struct tcp_unacked *tmpual=NULL;
		struct tcp_unacked *ackedual=NULL;
		struct tcp_acked *ta;

		/* XXX normal ACK*/
		ackedual=ual->next;

		ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
		ta->frame_acked=ackedual->frame;
		ta->ts.secs=pinfo->fd->abs_secs-ackedual->ts.secs;
		ta->ts.nsecs=pinfo->fd->abs_usecs*1000-ackedual->ts.nsecs;
		if(ta->ts.nsecs<0){
			ta->ts.nsecs+=1000000000;
			ta->ts.secs--;
		}

		/* just delete all ACKed segments */
		tmpual=ual->next;
		ual->next=NULL;
		for(ual=tmpual;ual;ual=tmpual){
			tmpual=ual->next;
			g_mem_chunk_free(tcp_unacked_chunk, ual);
		}
		prune_next_pdu_list(tnp, ack-base_ack);
	}

ack_finished:
	/* we might have deleted the entire ual2 list, if this is an ACK,
	   make sure ual2 at least has a dummy entry for the current ACK */
	if( (!ual2) && (flags&TH_ACK) ){
		ual2=g_mem_chunk_alloc(tcp_unacked_chunk);
		ual2->next=NULL;
		ual2->frame=0;
		ual2->seq=ack;
		ual2->nextseq=ack;
		ual2->ts.secs=0;
		ual2->ts.nsecs=0;
		ual2->window=window;
		ual2->flags=0;
	}

	/* update the ACK counter and check for
	   duplicate ACKs*/
	/* go to the oldest segment in the list of segments 
	   in the other direction */
	/* XXX we should guarantee ual2 to always be non NULL here
	   so we can skip the ual/ual2 tests */
	for(ual=ual2;ual&&ual->next;ual=ual->next)
		;
	if(ual2){
		/* we only consider this being a potential duplicate ack
		   if the segment length is 0 (ack only segment)
		   and if it acks something previous to oldest segment
		   in the other direction */
		if((!seglen)&&LE_SEQ(ack,ual->seq)){
			/* if this is the first ack to keep track of, it is not
			   a duplicate */
			if(num2_acks==0){
				ack2=ack;
				ack2_frame=pinfo->fd->num;
				num2_acks=1;
			/* if this ack is different, store this one 
			   instead and forget the previous one(s) */
			} else if(ack2!=ack){
				ack2=ack;
				ack2_frame=pinfo->fd->num;
				num2_acks=1;
			/* this has to be a duplicate ack */
			} else {
				num2_acks++;
			}	
			
			/* is this an ACK to a KeepAlive? */
			if( (ual->flags&TCP_A_KEEP_ALIVE)
			&& (ack==ual->seq) ){
				struct tcp_acked *ta;
				ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
				ta->flags|=TCP_A_KEEP_ALIVE_ACK;
				ual->flags^=TCP_A_KEEP_ALIVE;
			} else if(num2_acks>1) {
			/* ok we have found a potential duplicate ack */
				struct tcp_acked *ta;
				ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
				/* keepalives are not dupacks and 
				 * netiher are RST/FIN segments
				 */
				if( (!(ta->flags&TCP_A_KEEP_ALIVE))
				  &&(!(flags&(TH_RST|TH_FIN))) ){
					/* well then   
					 * this could then either be a dupack
					 * or maybe just a window update.
					 */
					if(win1==(gint32)window){
						ta->flags|=TCP_A_DUPLICATE_ACK;
						ta->dupack_num=num2_acks-1;
						ta->dupack_frame=ack2_frame;
					} else {
						ta->flags|=TCP_A_WINDOW_UPDATE;
					}
				}
			}
		}		

	}

	/* see if this semgent has filled up the window completely,
	 * i.e. same thing as if the other side would start sending
	 * zero windows back to us.
	 */
	if( !(flags&TH_RST)){ /* RST segments are never WindowFull segments*/
	  if(win_scale2==-1){
	    if( EQ_SEQ( (seq+seglen), (win2+ack1) ) ){
	      struct tcp_acked *ta;
	      ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
	      ta->flags|=TCP_A_WINDOW_FULL;
	    }
	  } else {
	    if( EQ_SEQ( (seq+seglen), ((win2<<win_scale2)+ack1) ) ){
	      struct tcp_acked *ta;
	      ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
	      ta->flags|=TCP_A_WINDOW_FULL;
	    }
	  }
	}

	/* check for zero window probes 
	   a zero window probe is when a TCP tries to write 1 byte segments
	   where the remote side has advertised a window of 0 bytes.
	   We only do this check if we actually have seen anything from the
	   other side of this connection.

	   We also assume ual still points to the last entry in the ual2
	   list from the section above.

	   At the same time, check for violations, i.e. attempts to write >1
	   byte to a zero-window.
	*/
	/* XXX we should not need to do the ual->frame check here?
	   might be a bug somewhere. look for it later .
	*/
	if(ual2&&(ual->frame)){
		if((seglen==1)&&(ual->window==0)){
			struct tcp_acked *ta;
			ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
			ta->flags|=TCP_A_ZERO_WINDOW_PROBE;
		}
		if((seglen>1)&&(ual->window==0)){
			struct tcp_acked *ta;
			ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
			ta->flags|=TCP_A_ZERO_WINDOW_VIOLATION;
		}
	}

	/* check for zero window
	 * dont check for RST/FIN segments since the window field is 
	 * meaningless for those
	 */
	if( (!window)
	  &&(!(flags&(TH_RST|TH_FIN))) ){
		struct tcp_acked *ta;
		ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
		ta->flags|=TCP_A_ZERO_WINDOW;
	}


	/* store the lists back in our struct */
	if(direction>=0){
		/*
		 * XXX - if direction == 0, that'll be true for packets
		 * from both sides of the connection, so this won't
		 * work.
		 *
		 * That'd be a connection from a given port on a machine
		 * to that same port on the same machine; does that ever
		 * happen?
		 */
		tcpd->ual1=ual1;
		tcpd->ual2=ual2;
		tcpd->ack1=ack1;
		tcpd->ack2=ack2;
		tcpd->ack1_frame=ack1_frame;
		tcpd->ack2_frame=ack2_frame;
		tcpd->num1_acks=num1_acks;
		tcpd->num2_acks=num2_acks;
		tcpd->base_seq1=base_seq;
		tcpd->base_seq2=base_ack;
		tcpd->win1=window;
	} else {
		tcpd->ual1=ual2;
		tcpd->ual2=ual1;
		tcpd->ack1=ack2;
		tcpd->ack2=ack1;
		tcpd->ack1_frame=ack2_frame;
		tcpd->ack2_frame=ack1_frame;
		tcpd->num1_acks=num2_acks;
		tcpd->num2_acks=num1_acks;
		tcpd->base_seq2=base_seq;
		tcpd->base_seq1=base_ack;
		tcpd->win2=window;
	}


	if(tcp_relative_seq){
		struct tcp_rel_seq *trs;
		/* remember relative seq/ack number base for this packet */
		trs=g_mem_chunk_alloc(tcp_rel_seq_chunk);
		trs->seq_base=base_seq;
		trs->ack_base=base_ack;
		trs->win_scale=win_scale1;
		g_hash_table_insert(tcp_rel_seq_table, GINT_TO_POINTER(pinfo->fd->num), trs);
	}
}

static void
tcp_print_sequence_number_analysis(packet_info *pinfo, tvbuff_t *tvb, proto_tree *parent_tree)
{
	struct tcp_acked *ta;
	proto_item *item;
	proto_tree *tree;

	ta=tcp_analyze_get_acked_struct(pinfo->fd->num, FALSE);
	if(!ta){
		return;
	}

	item=proto_tree_add_text(parent_tree, tvb, 0, 0, "SEQ/ACK analysis");
    PROTO_ITEM_SET_GENERATED(item);
	tree=proto_item_add_subtree(item, ett_tcp_analysis);

	/* encapsulate all proto_tree_add_xxx in ifs so we only print what
	   data we actually have */
	if(ta->frame_acked){
		item = proto_tree_add_uint(tree, hf_tcp_analysis_acks_frame,
			tvb, 0, 0, ta->frame_acked);
        	PROTO_ITEM_SET_GENERATED(item);

		/* only display RTT if we actually have something we are acking */
		if( ta->ts.secs || ta->ts.nsecs ){
			item = proto_tree_add_time(tree, hf_tcp_analysis_ack_rtt,
			tvb, 0, 0, &ta->ts);
        		PROTO_ITEM_SET_GENERATED(item);
		}
	}

	if(ta->flags){
		proto_item *flags_item=NULL;
		proto_tree *flags_tree=NULL;

		flags_item = proto_tree_add_item(tree, hf_tcp_analysis_flags, tvb, 0, -1, FALSE);
        PROTO_ITEM_SET_GENERATED(flags_item);
		flags_tree=proto_item_add_subtree(flags_item, ett_tcp_analysis);
		if( ta->flags&TCP_A_RETRANSMISSION ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_retransmission, tvb, 0, 0, "This frame is a (suspected) retransmission");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Retransmission] ");
			}
		}
		if( ta->flags&TCP_A_FAST_RETRANSMISSION ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_fast_retransmission, tvb, 0, 0, "This frame is a (suspected) fast retransmission");
			PROTO_ITEM_SET_GENERATED(flags_item);
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_retransmission, tvb, 0, 0, "This frame is a (suspected) retransmission");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Fast Retransmission] ");
			}
		}
		if( ta->flags&TCP_A_OUT_OF_ORDER ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_out_of_order, tvb, 0, 0, "This frame is a (suspected) out-of-order segment");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Out-Of-Order] ");
			}
		}
		if( ta->flags&TCP_A_LOST_PACKET ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_lost_packet, tvb, 0, 0, "A segment before this frame was lost");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Previous segment lost] ");
			}
		}
		if( ta->flags&TCP_A_ACK_LOST_PACKET ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_ack_lost_packet, tvb, 0, 0, "This frame ACKs a segment we have not seen (lost?)");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ACKed lost segment] ");
			}
		}
		if( ta->flags&TCP_A_WINDOW_UPDATE ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_window_update, tvb, 0, 0, "This is a tcp window update");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Window Update] ");
			}
		}
		if( ta->flags&TCP_A_WINDOW_FULL ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_window_full, tvb, 0, 0, "The transmission window is now completely full");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Window Full] ");
			}
		}
		if( ta->flags&TCP_A_KEEP_ALIVE ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_keep_alive, tvb, 0, 0, "This is a TCP keep-alive segment");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Keep-Alive] ");
			}
		}
		if( ta->flags&TCP_A_KEEP_ALIVE_ACK ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_keep_alive_ack, tvb, 0, 0, "This is an ACK to a TCP keep-alive segment");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Keep-Alive ACK] ");
			}
		}
		if( ta->dupack_num){
			if( ta->flags&TCP_A_DUPLICATE_ACK ){
				flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_duplicate_ack, tvb, 0, 0, "This is a TCP duplicate ack");
				PROTO_ITEM_SET_GENERATED(flags_item);
				if(check_col(pinfo->cinfo, COL_INFO)){
					col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Dup ACK %u#%u] ", ta->dupack_frame, ta->dupack_num);
				}
			}
			flags_item=proto_tree_add_uint(tree, hf_tcp_analysis_duplicate_ack_num,
				tvb, 0, 0, ta->dupack_num);
			PROTO_ITEM_SET_GENERATED(flags_item);
			flags_item=proto_tree_add_uint(tree, hf_tcp_analysis_duplicate_ack_frame,
				tvb, 0, 0, ta->dupack_frame);
			PROTO_ITEM_SET_GENERATED(flags_item);
		}
		if( ta->flags&TCP_A_ZERO_WINDOW_PROBE ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window_probe, tvb, 0, 0, "This is a TCP zero-window-probe");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindowProbe] ");
			}
		}
		if( ta->flags&TCP_A_ZERO_WINDOW ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window, tvb, 0, 0, "This is a ZeroWindow segment");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindow] ");
			}
		}
		if( ta->flags&TCP_A_ZERO_WINDOW_VIOLATION ){
			flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window_violation, tvb, 0, 0, "This is a ZeroWindow violation, attempts to write >1 byte of data to a zero-window");
			PROTO_ITEM_SET_GENERATED(flags_item);
			if(check_col(pinfo->cinfo, COL_INFO)){
				col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindowViolation] ");
			}
		}
	}

}


/* Do we still need to do this ...remove_all() even though we dont need
 * to do anything special?  The glib docs are not clear on this and
 * its better safe than sorry
 */
static gboolean
free_all_acked(gpointer key_arg _U_, gpointer value _U_, gpointer user_data _U_)
{
	return TRUE;
}

static guint
tcp_acked_hash(gconstpointer k)
{
	guint32 frame = GPOINTER_TO_UINT(k);

	return frame;
}
static gint
tcp_acked_equal(gconstpointer k1, gconstpointer k2)
{
	guint32 frame1 = GPOINTER_TO_UINT(k1);
	guint32 frame2 = GPOINTER_TO_UINT(k2);

	return frame1==frame2;
}

static void
tcp_analyze_seq_init(void)
{
	/* first destroy the tables */
	if( tcp_analyze_acked_table ){
		g_hash_table_foreach_remove(tcp_analyze_acked_table,
			free_all_acked, NULL);
		g_hash_table_destroy(tcp_analyze_acked_table);
		tcp_analyze_acked_table = NULL;
	}
	if( tcp_rel_seq_table ){
		g_hash_table_foreach_remove(tcp_rel_seq_table,
			free_all_acked, NULL);
		g_hash_table_destroy(tcp_rel_seq_table);
		tcp_rel_seq_table = NULL;
	}
	if( tcp_pdu_tracking_table ){
		g_hash_table_foreach_remove(tcp_pdu_tracking_table,
			free_all_acked, NULL);
		g_hash_table_destroy(tcp_pdu_tracking_table);
		tcp_pdu_tracking_table = NULL;
	}
	if( tcp_pdu_time_table ){
		g_hash_table_foreach_remove(tcp_pdu_time_table,
			free_all_acked, NULL);
		g_hash_table_destroy(tcp_pdu_time_table);
		tcp_pdu_time_table = NULL;
	}
	if( tcp_pdu_skipping_table ){
		g_hash_table_foreach_remove(tcp_pdu_skipping_table,
			free_all_acked, NULL);
		g_hash_table_destroy(tcp_pdu_skipping_table);
		tcp_pdu_skipping_table = NULL;
	}

	/*
	 * Now destroy the chunk from which the conversation table
	 * structures were allocated.
	 */
	if (tcp_next_pdu_chunk) {
		g_mem_chunk_destroy(tcp_next_pdu_chunk);
		tcp_next_pdu_chunk = NULL;
	}
	if (tcp_analysis_chunk) {
		g_mem_chunk_destroy(tcp_analysis_chunk);
		tcp_analysis_chunk = NULL;
	}
	if (tcp_unacked_chunk) {
		g_mem_chunk_destroy(tcp_unacked_chunk);
		tcp_unacked_chunk = NULL;
	}
	if (tcp_acked_chunk) {
		g_mem_chunk_destroy(tcp_acked_chunk);
		tcp_acked_chunk = NULL;
	}
	if (tcp_rel_seq_chunk) {
		g_mem_chunk_destroy(tcp_rel_seq_chunk);
		tcp_rel_seq_chunk = NULL;
	}

	if(tcp_analyze_seq){
		tcp_analyze_acked_table = g_hash_table_new(tcp_acked_hash,
			tcp_acked_equal);
		tcp_rel_seq_table = g_hash_table_new(tcp_acked_hash,
			tcp_acked_equal);
		tcp_pdu_time_table = g_hash_table_new(tcp_acked_hash,
			tcp_acked_equal);
		tcp_pdu_tracking_table = g_hash_table_new(tcp_acked_hash,
			tcp_acked_equal);
		tcp_pdu_skipping_table = g_hash_table_new(tcp_acked_hash,
			tcp_acked_equal);
		tcp_next_pdu_chunk = g_mem_chunk_new("tcp_next_pdu_chunk",
			sizeof(struct tcp_next_pdu),
			tcp_next_pdu_count * sizeof(struct tcp_next_pdu),
			G_ALLOC_ONLY);
		tcp_analysis_chunk = g_mem_chunk_new("tcp_analysis_chunk",
			sizeof(struct tcp_analysis),
			tcp_analysis_count * sizeof(struct tcp_analysis),
			G_ALLOC_ONLY);
		tcp_unacked_chunk = g_mem_chunk_new("tcp_unacked_chunk",
			sizeof(struct tcp_unacked),
			tcp_unacked_count * sizeof(struct tcp_unacked),
			G_ALLOC_ONLY);
		tcp_acked_chunk = g_mem_chunk_new("tcp_acked_chunk",
			sizeof(struct tcp_acked),
			tcp_acked_count * sizeof(struct tcp_acked),
			G_ALLOC_ONLY);
		if(tcp_relative_seq){
			tcp_rel_seq_chunk = g_mem_chunk_new("tcp_rel_seq_chunk",
				sizeof(struct tcp_rel_seq),
				tcp_rel_seq_count * sizeof(struct tcp_rel_seq),
				G_ALLOC_ONLY);
		}
	}

}

/* **************************************************************************
 * End of tcp sequence number analysis
 * **************************************************************************/




/* Minimum TCP header length. */
#define	TCPH_MIN_LEN	20

/*
 *	TCP option
 */

#define TCPOPT_NOP		1	/* Padding */
#define TCPOPT_EOL		0	/* End of options */
#define TCPOPT_MSS		2	/* Segment size negotiating */
#define TCPOPT_WINDOW		3	/* Window scaling */
#define TCPOPT_SACK_PERM        4       /* SACK Permitted */
#define TCPOPT_SACK             5       /* SACK Block */
#define TCPOPT_ECHO             6
#define TCPOPT_ECHOREPLY        7
#define TCPOPT_TIMESTAMP	8	/* Better RTT estimations/PAWS */
#define TCPOPT_CC               11
#define TCPOPT_CCNEW            12
#define TCPOPT_CCECHO           13
#define TCPOPT_MD5              19      /* RFC2385 */

/*
 *     TCP option lengths
 */

#define TCPOLEN_MSS            4
#define TCPOLEN_WINDOW         3
#define TCPOLEN_SACK_PERM      2
#define TCPOLEN_SACK_MIN       2
#define TCPOLEN_ECHO           6
#define TCPOLEN_ECHOREPLY      6
#define TCPOLEN_TIMESTAMP      10
#define TCPOLEN_CC             6
#define TCPOLEN_CCNEW          6
#define TCPOLEN_CCECHO         6
#define TCPOLEN_MD5            18



/* Desegmentation of TCP streams */
/* table to hold defragmented TCP streams */
static GHashTable *tcp_fragment_table = NULL;
static void
tcp_fragment_init(void)
{
	fragment_table_init(&tcp_fragment_table);
}

/* functions to trace tcp segments */
/* Enable desegmenting of TCP streams */
static gboolean tcp_desegment = FALSE;

static GHashTable *tcp_segment_table = NULL;
static GMemChunk *tcp_segment_key_chunk = NULL;
static int tcp_segment_init_count = 200;
static GMemChunk *tcp_segment_address_chunk = NULL;
static int tcp_segment_address_init_count = 500;

typedef struct _tcp_segment_key {
	/* for own bookkeeping inside packet-tcp.c */
	address *src;
	address *dst;
	guint32 seq;
	/* xxx */
	guint16 sport;
	guint16 dport;
	guint32 start_seq;
	guint32 tot_len;
	guint32 first_frame;
} tcp_segment_key;

static gboolean
free_all_segments(gpointer key_arg, gpointer value _U_, gpointer user_data _U_)
{
	tcp_segment_key *key = key_arg;

	if((key->src)&&(key->src->data)){
		g_free((gpointer)key->src->data);
		key->src->data=NULL;
	}

	if((key->dst)&&(key->dst->data)){
		g_free((gpointer)key->dst->data);
		key->dst->data=NULL;
	}

	return TRUE;
}

static guint
tcp_segment_hash(gconstpointer k)
{
	const tcp_segment_key *key = (const tcp_segment_key *)k;

	return key->seq+key->sport;
}

static gint
tcp_segment_equal(gconstpointer k1, gconstpointer k2)
{
	const tcp_segment_key *key1 = (const tcp_segment_key *)k1;
	const tcp_segment_key *key2 = (const tcp_segment_key *)k2;

	return ( ( (key1->seq==key2->seq)
		 &&(ADDRESSES_EQUAL(key1->src, key2->src))
		 &&(ADDRESSES_EQUAL(key1->dst, key2->dst))
		 &&(key1->sport==key2->sport)
		 &&(key1->dport==key2->dport)
		 ) ? TRUE:FALSE);
}

static void
tcp_desegment_init(void)
{
	/*
	 * Free this before freeing any memory chunks; those
	 * chunks contain data we'll look at in "free_all_segments()".
	 */
	if(tcp_segment_table){
		g_hash_table_foreach_remove(tcp_segment_table,
			free_all_segments, NULL);
		g_hash_table_destroy(tcp_segment_table);
		tcp_segment_table = NULL;
	}

	if(tcp_segment_key_chunk){
		g_mem_chunk_destroy(tcp_segment_key_chunk);
		tcp_segment_key_chunk = NULL;
	}
	if(tcp_segment_address_chunk){
		g_mem_chunk_destroy(tcp_segment_address_chunk);
		tcp_segment_address_chunk = NULL;
	}

	/* dont allocate any hash table or memory chunks unless the user
	   really uses this option
	*/
	if(!tcp_desegment){
		return;
	}

	tcp_segment_table = g_hash_table_new(tcp_segment_hash,
		tcp_segment_equal);

	tcp_segment_key_chunk = g_mem_chunk_new("tcp_segment_key_chunk",
		sizeof(tcp_segment_key),
		tcp_segment_init_count*sizeof(tcp_segment_key),
		G_ALLOC_ONLY);

	tcp_segment_address_chunk = g_mem_chunk_new("tcp_segment_address_chunk",
		sizeof(address),
		tcp_segment_address_init_count*sizeof(address),
		G_ALLOC_ONLY);
}

static void
desegment_tcp(tvbuff_t *tvb, packet_info *pinfo, int offset,
		guint32 seq, guint32 nxtseq,
		guint32 sport, guint32 dport,
		proto_tree *tree, proto_tree *tcp_tree)
{
	struct tcpinfo *tcpinfo = pinfo->private_data;
	fragment_data *ipfd_head=NULL;
	tcp_segment_key old_tsk, *tsk;
	gboolean must_desegment = FALSE;
	gboolean called_dissector = FALSE;
	int deseg_offset;
	guint32 deseg_seq;
	gint nbytes;
    proto_item *item;

	/*
	 * Initialize these to assume no desegmentation.
	 * If that's not the case, these will be set appropriately
	 * by the subdissector.
	 */
	pinfo->desegment_offset = 0;
	pinfo->desegment_len = 0;

	/*
	 * Initialize this to assume that this segment will just be
	 * added to the middle of a desegmented chunk of data, so
	 * that we should show it all as data.
	 * If that's not the case, it will be set appropriately.
	 */
	deseg_offset = offset;

	/* First we must check if this TCP segment should be desegmented.
	   This is only to check if we should desegment this packet,
	   so we dont spend time doing COPY_ADDRESS/g_free.
	   We just "borrow" some address structures from pinfo instead. Cheaper.
	*/
	old_tsk.src = &pinfo->src;
	old_tsk.dst = &pinfo->dst;
	old_tsk.sport = sport;
	old_tsk.dport = dport;
	old_tsk.seq = seq;
	tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);

	if(tsk){
		/* OK, this segment was found, which means it continues
		   a higher-level PDU. This means we must desegment it.
		   Add it to the defragmentation lists.
		*/
		ipfd_head = fragment_add(tvb, offset, pinfo, tsk->first_frame,
			tcp_fragment_table,
			seq - tsk->start_seq,
			nxtseq - seq,
			(LT_SEQ (nxtseq,tsk->start_seq + tsk->tot_len)) );

		if(!ipfd_head){
			/* fragment_add() returned NULL, This means that
			   desegmentation is not completed yet.
			   (its like defragmentation but we know we will
			    always add the segments in order).
			   XXX - no, we don't; there is no guarantee that
			   TCP segments are in order on the wire.

			   we must add next segment to our table so we will
			   find it later.
			*/
			tcp_segment_key *new_tsk;

			new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
			memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
			new_tsk->seq=nxtseq;
			g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
		}
	} else {
		/* This segment was not found in our table, so it doesn't
		   contain a continuation of a higher-level PDU.
		   Call the normal subdissector.
		*/
		process_tcp_payload(tvb, offset, pinfo, tree, tcp_tree,
				sport, dport, 0, 0, FALSE);
		called_dissector = TRUE;

		/* Did the subdissector ask us to desegment some more data
		   before it could handle the packet?
		   If so we have to create some structures in our table but
		   this is something we only do the first time we see this
		   packet.
		*/
		if(pinfo->desegment_len) {
			if (!pinfo->fd->flags.visited)
				must_desegment = TRUE;

			/*
			 * Set "deseg_offset" to the offset in "tvb"
			 * of the first byte of data that the
			 * subdissector didn't process.
			 */
			deseg_offset = offset + pinfo->desegment_offset;
		}

		/* Either no desegmentation is necessary, or this is
		   segment contains the beginning but not the end of
		   a higher-level PDU and thus isn't completely
		   desegmented.
		*/
		ipfd_head = NULL;
	}

	/* is it completely desegmented? */
	if(ipfd_head){
		fragment_data *ipfd;

		/*
		 * Yes, we think it is.
		 * We only call subdissector for the last segment.
		 * Note that the last segment may include more than what
		 * we needed.
		 */
		if(GE_SEQ(nxtseq, tsk->start_seq + tsk->tot_len)){
			/*
			 * OK, this is the last segment.
			 * Let's call the subdissector with the desegmented
			 * data.
			 */
			tvbuff_t *next_tvb;
			int old_len;

			/* create a new TVB structure for desegmented data */
			next_tvb = tvb_new_real_data(ipfd_head->data,
					ipfd_head->datalen, ipfd_head->datalen);

			/* add this tvb as a child to the original one */
			tvb_set_child_real_data_tvbuff(tvb, next_tvb);

			/* add desegmented data to the data source list */
			add_new_data_source(pinfo, next_tvb, "Reassembled TCP");

			/*
			 * Supply the sequence number of the first of the
			 * reassembled bytes.
			 */
			tcpinfo->seq = tsk->start_seq;

			/* indicate that this is reassembled data */
			tcpinfo->is_reassembled = TRUE;

			/* call subdissector */
			process_tcp_payload(next_tvb, 0, pinfo, tree,
			    tcp_tree, sport, dport, 0, 0, FALSE);
			called_dissector = TRUE;

			/*
			 * OK, did the subdissector think it was completely
			 * desegmented, or does it think we need even more
			 * data?
			 */
			old_len=(int)(tvb_reported_length(next_tvb)-tvb_reported_length_remaining(tvb, offset));
			if(pinfo->desegment_len &&
			    pinfo->desegment_offset<=old_len){
				tcp_segment_key *new_tsk;

				/*
				 * "desegment_len" isn't 0, so it needs more
				 * data for something - and "desegment_offset"
				 * is before "old_len", so it needs more data
				 * to dissect the stuff we thought was
				 * completely desegmented (as opposed to the
				 * stuff at the beginning being completely
				 * desegmented, but the stuff at the end
				 * being a new higher-level PDU that also
				 * needs desegmentation).
				 */
				fragment_set_partial_reassembly(pinfo,tsk->first_frame,tcp_fragment_table);
				tsk->tot_len = tvb_reported_length(next_tvb) + pinfo->desegment_len;

				/*
				 * Update tsk structure.
				 * Can ask ->next->next because at least there's a hdr and one
				 * entry in fragment_add()
				 */
				for(ipfd=ipfd_head->next; ipfd->next; ipfd=ipfd->next){
					old_tsk.seq = tsk->start_seq + ipfd->offset;
					new_tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
					new_tsk->tot_len = tsk->tot_len;
				}

				/* this is the next segment in the sequence we want */
				new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
				memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
				new_tsk->seq = nxtseq;
				g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
			} else {
				/*
				 * Show the stuff in this TCP segment as
				 * just raw TCP segment data.
				 */
				nbytes =
				    tvb_reported_length_remaining(tvb, offset);
				proto_tree_add_text(tcp_tree, tvb, offset, -1,
				    "TCP segment data (%u byte%s)", nbytes,
				    plurality(nbytes, "", "s"));

				/*
				 * The subdissector thought it was completely
				 * desegmented (although the stuff at the
				 * end may, in turn, require desegmentation),
				 * so we show a tree with all segments.
				 */
				show_fragment_tree(ipfd_head, &tcp_segment_items,
					tcp_tree, pinfo, next_tvb);

				/* Did the subdissector ask us to desegment
				   some more data?  This means that the data
				   at the beginning of this segment completed
				   a higher-level PDU, but the data at the
				   end of this segment started a higher-level
				   PDU but didn't complete it.

				   If so, we have to create some structures
				   in our table, but this is something we
				   only do the first time we see this packet.
				*/
				if(pinfo->desegment_len) {
					if (!pinfo->fd->flags.visited)
						must_desegment = TRUE;

					/* The stuff we couldn't dissect
					   must have come from this segment,
					   so it's all in "tvb".

				 	   "pinfo->desegment_offset" is
				 	   relative to the beginning of
				 	   "next_tvb"; we want an offset
				 	   relative to the beginning of "tvb".

				 	   First, compute the offset relative
				 	   to the *end* of "next_tvb" - i.e.,
				 	   the number of bytes before the end
				 	   of "next_tvb" at which the
				 	   subdissector stopped.  That's the
				 	   length of "next_tvb" minus the
				 	   offset, relative to the beginning
				 	   of "next_tvb, at which the
				 	   subdissector stopped.
				 	*/
					deseg_offset =
					    ipfd_head->datalen - pinfo->desegment_offset;

					/* "tvb" and "next_tvb" end at the
					   same byte of data, so the offset
					   relative to the end of "next_tvb"
					   of the byte at which we stopped
					   is also the offset relative to
					   the end of "tvb" of the byte at
					   which we stopped.

					   Convert that back into an offset
					   relative to the beginninng of
					   "tvb", by taking the length of
					   "tvb" and subtracting the offset
					   relative to the end.
					*/
					deseg_offset=tvb_reported_length(tvb) - deseg_offset;
				}
			}
		}
	}

	if (must_desegment) {
	    tcp_segment_key *tsk, *new_tsk;

	    /*
	     * The sequence number at which the stuff to be desegmented
	     * starts is the sequence number of the byte at an offset
	     * of "deseg_offset" into "tvb".
	     *
	     * The sequence number of the byte at an offset of "offset"
	     * is "seq", i.e. the starting sequence number of this
	     * segment, so the sequence number of the byte at
	     * "deseg_offset" is "seq + (deseg_offset - offset)".
	     */
	    deseg_seq = seq + (deseg_offset - offset);

	    /*
	     * XXX - how do we detect out-of-order transmissions?
	     * We can't just check for "nxtseq" being greater than
	     * "tsk->start_seq"; for now, we check for the difference
	     * being less than a megabyte, but this is a really
	     * gross hack - we really need to handle out-of-order
	     * transmissions correctly.
	     */
	    if ((nxtseq - deseg_seq) <= 1024*1024) {
		/* OK, subdissector wants us to desegment
		   some data before it can process it. Add
		   what remains of this packet and set
		   up next packet/sequence number as well.

		   We must remember this segment
		*/
		tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
		tsk->src = g_mem_chunk_alloc(tcp_segment_address_chunk);
		COPY_ADDRESS(tsk->src, &pinfo->src);
		tsk->dst = g_mem_chunk_alloc(tcp_segment_address_chunk);
		COPY_ADDRESS(tsk->dst, &pinfo->dst);
		tsk->seq = deseg_seq;
		tsk->start_seq = tsk->seq;
		tsk->tot_len = nxtseq - tsk->start_seq + pinfo->desegment_len;
		tsk->first_frame = pinfo->fd->num;
		tsk->sport=sport;
		tsk->dport=dport;
		g_hash_table_insert(tcp_segment_table, tsk, tsk);

		/* Add portion of segment unprocessed by the subdissector
		   to defragmentation lists */
		fragment_add(tvb, deseg_offset, pinfo, tsk->first_frame,
		    tcp_fragment_table,
		    tsk->seq - tsk->start_seq,
		    nxtseq - tsk->start_seq,
		    LT_SEQ (nxtseq, tsk->start_seq + tsk->tot_len));

		/* this is the next segment in the sequence we want */
		new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
		memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
		new_tsk->seq = nxtseq;
		g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
	    }
	}

	if (!called_dissector || pinfo->desegment_len != 0) {
		if (ipfd_head != NULL && ipfd_head->reassembled_in != 0) {
			/*
			 * We know what frame this PDU is reassembled in;
			 * let the user know.
			 */
			item=proto_tree_add_uint(tcp_tree, hf_tcp_reassembled_in,
			    tvb, 0, 0, ipfd_head->reassembled_in);
            PROTO_ITEM_SET_GENERATED(item);
		}

		/*
		 * Either we didn't call the subdissector at all (i.e.,
		 * this is a segment that contains the middle of a
		 * higher-level PDU, but contains neither the beginning
		 * nor the end), or the subdissector couldn't dissect it
		 * all, as some data was missing (i.e., it set
		 * "pinfo->desegment_len" to the amount of additional
		 * data it needs).
		 */
		if (pinfo->desegment_offset == 0) {
			/*
			 * It couldn't, in fact, dissect any of it (the
			 * first byte it couldn't dissect is at an offset
			 * of "pinfo->desegment_offset" from the beginning
			 * of the payload, and that's 0).
			 * Just mark this as TCP.
			 */
			if (check_col(pinfo->cinfo, COL_PROTOCOL)){
				col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
			}
			if (check_col(pinfo->cinfo, COL_INFO)){
				col_set_str(pinfo->cinfo, COL_INFO, "[TCP segment of a reassembled PDU]");
			}
		}

		/*
		 * Show what's left in the packet as just raw TCP segment
		 * data.
		 * XXX - remember what protocol the last subdissector
		 * was, and report it as a continuation of that, instead?
		 */
		nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
		proto_tree_add_text(tcp_tree, tvb, deseg_offset, -1,
		    "TCP segment data (%u byte%s)", nbytes,
		    plurality(nbytes, "", "s"));
	}
	pinfo->can_desegment=0;
	pinfo->desegment_offset = 0;
	pinfo->desegment_len = 0;
}

/*
 * Loop for dissecting PDUs within a TCP stream; assumes that a PDU
 * consists of a fixed-length chunk of data that contains enough information
 * to determine the length of the PDU, followed by rest of the PDU.
 *
 * The first three arguments are the arguments passed to the dissector
 * that calls this routine.
 *
 * "proto_desegment" is the dissector's flag controlling whether it should
 * desegment PDUs that cross TCP segment boundaries.
 *
 * "fixed_len" is the length of the fixed-length part of the PDU.
 *
 * "get_pdu_len()" is a routine called to get the length of the PDU from
 * the fixed-length part of the PDU; it's passed "tvb" and "offset".
 *
 * "dissect_pdu()" is the routine to dissect a PDU.
 */
void
tcp_dissect_pdus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
		 gboolean proto_desegment, guint fixed_len,
		 guint (*get_pdu_len)(tvbuff_t *, int),
		 void (*dissect_pdu)(tvbuff_t *, packet_info *, proto_tree *))
{
  volatile int offset = 0;
  int offset_before;
  guint length_remaining;
  guint plen;
  guint length;
  tvbuff_t *next_tvb;

  while (tvb_reported_length_remaining(tvb, offset) != 0) {
    /*
     * We use "tvb_ensure_length_remaining()" to make sure there actually
     * *is* data remaining.  The protocol we're handling could conceivably
     * consists of a sequence of fixed-length PDUs, and therefore the
     * "get_pdu_len" routine might not actually fetch anything from
     * the tvbuff, and thus might not cause an exception to be thrown if
     * we've run past the end of the tvbuff.
     *
     * This means we're guaranteed that "length_remaining" is positive.
     */
    length_remaining = tvb_ensure_length_remaining(tvb, offset);

    /*
     * Can we do reassembly?
     */
    if (proto_desegment && pinfo->can_desegment) {
      /*
       * Yes - is the fixed-length part of the PDU split across segment
       * boundaries?
       */
      if (length_remaining < fixed_len) {
	/*
	 * Yes.  Tell the TCP dissector where the data for this message
	 * starts in the data it handed us, and how many more bytes we
	 * need, and return.
	 */
	pinfo->desegment_offset = offset;
	pinfo->desegment_len = fixed_len - length_remaining;
	return;
      }
    }

    /*
     * Get the length of the PDU.
     */
    plen = (*get_pdu_len)(tvb, offset);
    if (plen < fixed_len) {
      /*
       * The PDU length from the fixed-length portion probably didn't
       * include the fixed-length portion's length, and was probably so
       * large that the total length overflowed.
       *
       * Report this as an error.
       */
      show_reported_bounds_error(tvb, pinfo, tree);
      return;
    }

    /* give a hint to TCP where the next PDU starts
     * so that it can attempt to find it in case it starts
     * somewhere in the middle of a segment.
     */
    if(!pinfo->fd->flags.visited && tcp_analyze_seq){
       guint remaining_bytes;
       remaining_bytes=tvb_reported_length_remaining(tvb, offset);
       if(plen>remaining_bytes){
          pinfo->want_pdu_tracking=2;
          pinfo->bytes_until_next_pdu=plen-remaining_bytes;
       }
    }

    /*
     * Can we do reassembly?
     */
    if (proto_desegment && pinfo->can_desegment) {
      /*
       * Yes - is the PDU split across segment boundaries?
       */
      if (length_remaining < plen) {
	/*
	 * Yes.  Tell the TCP dissector where the data for this message
	 * starts in the data it handed us, and how many more bytes we
	 * need, and return.
	 */
	pinfo->desegment_offset = offset;
	pinfo->desegment_len = plen - length_remaining;
	return;
      }
    }

    /*
     * Construct a tvbuff containing the amount of the payload we have
     * available.  Make its reported length the amount of data in the PDU.
     *
     * XXX - if reassembly isn't enabled. the subdissector will throw a
     * BoundsError exception, rather than a ReportedBoundsError exception.
     * We really want a tvbuff where the length is "length", the reported
     * length is "plen", and the "if the snapshot length were infinite"
     * length is the minimum of the reported length of the tvbuff handed
     * to us and "plen", with a new type of exception thrown if the offset
     * is within the reported length but beyond that third length, with
     * that exception getting the "Unreassembled Packet" error.
     */
    length = length_remaining;
    if (length > plen)
	length = plen;
    next_tvb = tvb_new_subset(tvb, offset, length, plen);

    /*
     * Dissect the PDU.
     *
     * Catch the ReportedBoundsError exception; if this particular message
     * happens to get a ReportedBoundsError exception, that doesn't mean
     * that we should stop dissecting PDUs within this frame or chunk of
     * reassembled data.
     *
     * If it gets a BoundsError, we can stop, as there's nothing more to
     * see, so we just re-throw it.
     */
    TRY {
      (*dissect_pdu)(next_tvb, pinfo, tree);
    }
    CATCH(BoundsError) {
      RETHROW;
    }
    CATCH(ReportedBoundsError) {
      show_reported_bounds_error(tvb, pinfo, tree);
    }
    ENDTRY;

    /*
     * Step to the next PDU.
     * Make sure we don't overflow.
     */
    offset_before = offset;
    offset += plen;
    if (offset <= offset_before)
      break;
  }
}

static void
tcp_info_append_uint(packet_info *pinfo, const char *abbrev, guint32 val)
{
  if (check_col(pinfo->cinfo, COL_INFO))
    col_append_fstr(pinfo->cinfo, COL_INFO, " %s=%u", abbrev, val);
}

static void
dissect_tcpopt_maxseg(const ip_tcp_opt *optp, tvbuff_t *tvb,
    int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
{
  guint16 mss;

  mss = tvb_get_ntohs(tvb, offset + 2);
  proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_mss, tvb, offset,
				optlen, TRUE);
  proto_tree_add_uint_format(opt_tree, hf_tcp_option_mss_val, tvb, offset,
			     optlen, mss, "%s: %u bytes", optp->name, mss);
  tcp_info_append_uint(pinfo, "MSS", mss);
}

static void
dissect_tcpopt_wscale(const ip_tcp_opt *optp, tvbuff_t *tvb,
    int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
{
  guint8 ws;

  ws = tvb_get_guint8(tvb, offset + 2);
  proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_wscale, tvb, 
				offset, optlen, TRUE);
  proto_tree_add_uint_format(opt_tree, hf_tcp_option_wscale_val, tvb,
			     offset, optlen, ws, "%s: %u (multiply by %u)", 
			     optp->name, ws, 1 << ws);
  tcp_info_append_uint(pinfo, "WS", ws);
  if(!pinfo->fd->flags.visited && tcp_analyze_seq && tcp_relative_seq){
    pdu_store_window_scale_option(pinfo, ws);
  }
}

static void
dissect_tcpopt_sack(const ip_tcp_opt *optp, tvbuff_t *tvb,
    int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
{
  proto_tree *field_tree = NULL;
  proto_item *tf=NULL;
  guint32 leftedge, rightedge;
  struct tcp_analysis *tcpd=NULL;
  int direction;
  guint32 base_ack=0;

  if(tcp_relative_seq){
    /* find(or create if needed) the conversation for this tcp session */
    tcpd=get_tcp_conversation_data(pinfo);

    /* check direction and get ua lists */
    direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
    /* if the addresses are equal, match the ports instead */
    if(direction==0) {
      direction= (pinfo->srcport > pinfo->destport)*2-1;
    }
    if(direction>=0){
      base_ack=tcpd->base_seq2;
    } else {
      base_ack=tcpd->base_seq1;
    }
  }

  tf = proto_tree_add_text(opt_tree, tvb, offset,      optlen, "%s:", optp->name);
  offset += 2;	/* skip past type and length */
  optlen -= 2;	/* subtract size of type and length */
  while (optlen > 0) {
    if (field_tree == NULL) {
      /* Haven't yet made a subtree out of this option.  Do so. */
      field_tree = proto_item_add_subtree(tf, *optp->subtree_index);
      proto_tree_add_boolean_hidden(field_tree, hf_tcp_option_sack, tvb, 
				    offset, optlen, TRUE);
    }
    if (optlen < 4) {
      proto_tree_add_text(field_tree, tvb, offset,      optlen,
        "(suboption would go past end of option)");
      break;
    }
    leftedge = tvb_get_ntohl(tvb, offset)-base_ack;
    proto_tree_add_uint_format(field_tree, hf_tcp_option_sack_sle, tvb, 
			       offset, 4, leftedge, 
			       "left edge = %u%s", leftedge,
			       tcp_relative_seq ? " (relative)" : "");

    optlen -= 4;
    if (optlen < 4) {
      proto_tree_add_text(field_tree, tvb, offset,      optlen,
        "(suboption would go past end of option)");
      break;
    }
    /* XXX - check whether it goes past end of packet */
    rightedge = tvb_get_ntohl(tvb, offset + 4)-base_ack;
    optlen -= 4;
    proto_tree_add_uint_format(field_tree, hf_tcp_option_sack_sre, tvb, 
			       offset+4, 4, rightedge, 
			       "right edge = %u%s", rightedge,
			       tcp_relative_seq ? " (relative)" : "");
    tcp_info_append_uint(pinfo, "SLE", leftedge);
    tcp_info_append_uint(pinfo, "SRE", rightedge);
    proto_item_append_text(field_tree, " %u-%u", leftedge, rightedge);
    offset += 8;
  }
}

static void
dissect_tcpopt_echo(const ip_tcp_opt *optp, tvbuff_t *tvb,
    int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
{
  guint32 echo;

  echo = tvb_get_ntohl(tvb, offset + 2);
  proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_echo, tvb, offset,
				optlen, TRUE);
  proto_tree_add_text(opt_tree, tvb, offset,      optlen,
			"%s: %u", optp->name, echo);
  tcp_info_append_uint(pinfo, "ECHO", echo);
}

static void
dissect_tcpopt_timestamp(const ip_tcp_opt *optp, tvbuff_t *tvb,
    int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
{
  guint32 tsv, tser;

  tsv = tvb_get_ntohl(tvb, offset + 2);
  tser = tvb_get_ntohl(tvb, offset + 6);
  proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_time_stamp, tvb, 
				offset, optlen, TRUE);
  proto_tree_add_text(opt_tree, tvb, offset,      optlen,
    "%s: tsval %u, tsecr %u", optp->name, tsv, tser);
  tcp_info_append_uint(pinfo, "TSV", tsv);
  tcp_info_append_uint(pinfo, "TSER", tser);
}

static void
dissect_tcpopt_cc(const ip_tcp_opt *optp, tvbuff_t *tvb,
    int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
{
  guint32 cc;

  cc = tvb_get_ntohl(tvb, offset + 2);
  proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_cc, tvb, offset,
				optlen, TRUE);
  proto_tree_add_text(opt_tree, tvb, offset,      optlen,
			"%s: %u", optp->name, cc);
  tcp_info_append_uint(pinfo, "CC", cc);
}

static const ip_tcp_opt tcpopts[] = {
  {
    TCPOPT_EOL,
    "EOL",
    NULL,
    NO_LENGTH,
    0,
    NULL,
  },
  {
    TCPOPT_NOP,
    "NOP",
    NULL,
    NO_LENGTH,
    0,
    NULL,
  },
  {
    TCPOPT_MSS,
    "Maximum segment size",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_MSS,
    dissect_tcpopt_maxseg
  },
  {
    TCPOPT_WINDOW,
    "Window scale",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_WINDOW,
    dissect_tcpopt_wscale
  },
  {
    TCPOPT_SACK_PERM,
    "SACK permitted",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_SACK_PERM,
    NULL,
  },
  {
    TCPOPT_SACK,
    "SACK",
    &ett_tcp_option_sack,
    VARIABLE_LENGTH,
    TCPOLEN_SACK_MIN,
    dissect_tcpopt_sack
  },
  {
    TCPOPT_ECHO,
    "Echo",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_ECHO,
    dissect_tcpopt_echo
  },
  {
    TCPOPT_ECHOREPLY,
    "Echo reply",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_ECHOREPLY,
    dissect_tcpopt_echo
  },
  {
    TCPOPT_TIMESTAMP,
    "Time stamp",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_TIMESTAMP,
    dissect_tcpopt_timestamp
  },
  {
    TCPOPT_CC,
    "CC",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_CC,
    dissect_tcpopt_cc
  },
  {
    TCPOPT_CCNEW,
    "CC.NEW",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_CCNEW,
    dissect_tcpopt_cc
  },
  {
    TCPOPT_CCECHO,
    "CC.ECHO",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_CCECHO,
    dissect_tcpopt_cc
  },
  {
    TCPOPT_MD5,
    "TCP MD5 signature",
    NULL,
    FIXED_LENGTH,
    TCPOLEN_MD5,
    NULL
  }
};

#define N_TCP_OPTS	(sizeof tcpopts / sizeof tcpopts[0])

/* Determine if there is a sub-dissector and call it; return TRUE
   if there was a sub-dissector, FALSE otherwise.

   This has been separated into a stand alone routine to other protocol
   dissectors can call to it, e.g., SOCKS. */

static gboolean try_heuristic_first = FALSE;

gboolean
decode_tcp_ports(tvbuff_t *tvb, int offset, packet_info *pinfo,
	proto_tree *tree, int src_port, int dst_port)
{
  tvbuff_t *next_tvb;
  int low_port, high_port;

  next_tvb = tvb_new_subset(tvb, offset, -1, -1);

/* determine if this packet is part of a conversation and call dissector */
/* for the conversation if available */

  if (try_conversation_dissector(&pinfo->src, &pinfo->dst, PT_TCP,
		src_port, dst_port, next_tvb, pinfo, tree)){
    pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
    return TRUE;
  }

  if (try_heuristic_first) {
    /* do lookup with the heuristic subdissector table */
    if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree)){
       pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
       return TRUE;
    }
  }

  /* Do lookups with the subdissector table.
     We try the port number with the lower value first, followed by the
     port number with the higher value.  This means that, for packets
     where a dissector is registered for *both* port numbers:

	1) we pick the same dissector for traffic going in both directions;

	2) we prefer the port number that's more likely to be the right
	   one (as that prefers well-known ports to reserved ports);

     although there is, of course, no guarantee that any such strategy
     will always pick the right port number.

     XXX - we ignore port numbers of 0, as some dissectors use a port
     number of 0 to disable the port. */
  if (src_port > dst_port) {
    low_port = dst_port;
    high_port = src_port;
  } else {
    low_port = src_port;
    high_port = dst_port;
  }
  if (low_port != 0 &&
      dissector_try_port(subdissector_table, low_port, next_tvb, pinfo, tree)){
    pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
    return TRUE;
  }
  if (high_port != 0 &&
      dissector_try_port(subdissector_table, high_port, next_tvb, pinfo, tree)){
    pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
    return TRUE;
  }

  if (!try_heuristic_first) {
    /* do lookup with the heuristic subdissector table */
    if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree)){
       pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
       return TRUE;
    }
  }

  /* Oh, well, we don't know this; dissect it as data. */
  call_dissector(data_handle,next_tvb, pinfo, tree);

  pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
  return FALSE;
}

static void
process_tcp_payload(tvbuff_t *tvb, volatile int offset, packet_info *pinfo,
	proto_tree *tree, proto_tree *tcp_tree, int src_port, int dst_port,
	guint32 seq, guint32 nxtseq, gboolean is_tcp_segment)
{
	pinfo->want_pdu_tracking=0;

	TRY {
		if(is_tcp_segment){
			/*qqq   see if it is an unaligned PDU */
			if(tcp_analyze_seq && (!tcp_desegment)){
				if(seq || nxtseq){
					offset=scan_for_next_pdu(tvb, tcp_tree, pinfo, offset,
						seq, nxtseq);
				}
			}
		}
		/* if offset is -1 this means that this segment is known
		 * to be fully inside a previously detected pdu
		 * so we dont even need to try to dissect it either.
		 */
		if( (offset!=-1) &&
		    decode_tcp_ports(tvb, offset, pinfo, tree, src_port,
		        dst_port) ){
			/*
			 * We succeeded in handing off to a subdissector.
			 *
			 * Is this a TCP segment or a reassembled chunk of
			 * TCP payload?
			 */
			if(is_tcp_segment){
				/* if !visited, check want_pdu_tracking and
				   store it in table */
				if((!pinfo->fd->flags.visited) &&
				    tcp_analyze_seq && pinfo->want_pdu_tracking){
					if(seq || nxtseq){
						pdu_store_sequencenumber_of_next_pdu(
						    pinfo,
                	                            seq,
						    nxtseq+pinfo->bytes_until_next_pdu);
					}
				}
			}
		}
	}
	CATCH_ALL {
		/* We got an exception. At this point the dissection is
		 * completely aborted and execution will be transfered back
		 * to (probably) the frame dissector.
		 * Here we have to place whatever we want the dissector
		 * to do before aborting the tcp dissection.
		 */
		/*
		 * Is this a TCP segment or a reassembled chunk of TCP
		 * payload?
		 */
		if(is_tcp_segment){
			/*
			 * It's from a TCP segment.
			 *
			 * Handle TCP seq# analysis, print any extra SEQ/ACK
			 * data for this segment.
			 */
			if(tcp_analyze_seq){
				tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree);
			}
			/*
			 * if !visited, check want_pdu_tracking and store it
			 * in table 
			 */
			if((!pinfo->fd->flags.visited) && tcp_analyze_seq && pinfo->want_pdu_tracking){
				if(seq || nxtseq){
					pdu_store_sequencenumber_of_next_pdu(pinfo,
        	                            seq,
					    nxtseq+pinfo->bytes_until_next_pdu);
				}
			}
		}
		RETHROW;
	}
	ENDTRY;
}

void
dissect_tcp_payload(tvbuff_t *tvb, packet_info *pinfo, int offset, guint32 seq,
		    guint32 nxtseq, guint32 sport, guint32 dport,
		    proto_tree *tree, proto_tree *tcp_tree)
{
  gboolean save_fragmented;

  /* Can we desegment this segment? */
  if (pinfo->can_desegment) {
    /* Yes. */
    desegment_tcp(tvb, pinfo, offset, seq, nxtseq, sport, dport, tree,
        tcp_tree);
  } else {
    /* No - just call the subdissector.
       Mark this as fragmented, so if somebody throws an exception,
       we don't report it as a malformed frame. */
    save_fragmented = pinfo->fragmented;
    pinfo->fragmented = TRUE;
    process_tcp_payload(tvb, offset, pinfo, tree, tcp_tree, sport, dport,
        seq, nxtseq, TRUE);
    pinfo->fragmented = save_fragmented;
  }
}

static void
dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
  guint8  th_off_x2; /* combines th_off and th_x2 */
  guint16 th_sum;
  guint16 th_urp;
  proto_tree *tcp_tree = NULL, *field_tree = NULL;
  proto_item *ti = NULL, *tf;
  int        offset = 0;
  gchar      flags[64] = "<None>";
  gchar     *fstr[] = {"FIN", "SYN", "RST", "PSH", "ACK", "URG", "ECN", "CWR" };
  gint       fpos = 0, i;
  guint      bpos;
  guint      optlen;
  guint32    nxtseq = 0;
  guint      reported_len;
  vec_t      cksum_vec[4];
  guint32    phdr[2];
  guint16    computed_cksum;
  guint16    real_window;
  guint      length_remaining;
  gboolean   desegment_ok;
  struct tcpinfo tcpinfo;
  static struct tcpheader tcphstruct[4], *tcph;
  static int tcph_count=0;

  tcph_count++;
  if(tcph_count>=4){
     tcph_count=0;
  }
  tcph=&tcphstruct[tcph_count];
  SET_ADDRESS(&tcph->ip_src, pinfo->src.type, pinfo->src.len, pinfo->src.data);
  SET_ADDRESS(&tcph->ip_dst, pinfo->dst.type, pinfo->dst.len, pinfo->dst.data);

  if (check_col(pinfo->cinfo, COL_PROTOCOL))
    col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");

  /* Clear out the Info column. */
  if (check_col(pinfo->cinfo, COL_INFO))
    col_clear(pinfo->cinfo, COL_INFO);

  tcph->th_sport = tvb_get_ntohs(tvb, offset);
  tcph->th_dport = tvb_get_ntohs(tvb, offset + 2);
  if (check_col(pinfo->cinfo, COL_INFO)) {
    col_append_fstr(pinfo->cinfo, COL_INFO, "%s > %s",
      get_tcp_port(tcph->th_sport), get_tcp_port(tcph->th_dport));
  }
  if (tree) {
    if (tcp_summary_in_tree) {
	    ti = proto_tree_add_protocol_format(tree, proto_tcp, tvb, 0, -1,
		"Transmission Control Protocol, Src Port: %s (%u), Dst Port: %s (%u)",
		get_tcp_port(tcph->th_sport), tcph->th_sport,
		get_tcp_port(tcph->th_dport), tcph->th_dport);
    }
    else {
	    ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, FALSE);
    }
    tcp_tree = proto_item_add_subtree(ti, ett_tcp);
    proto_tree_add_uint_format(tcp_tree, hf_tcp_srcport, tvb, offset, 2, tcph->th_sport,
	"Source port: %s (%u)", get_tcp_port(tcph->th_sport), tcph->th_sport);
    proto_tree_add_uint_format(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, tcph->th_dport,
	"Destination port: %s (%u)", get_tcp_port(tcph->th_dport), tcph->th_dport);
    proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset, 2, tcph->th_sport);
    proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, tcph->th_dport);
  }

  /* Set the source and destination port numbers as soon as we get them,
     so that they're available to the "Follow TCP Stream" code even if
     we throw an exception dissecting the rest of the TCP header. */
  pinfo->ptype = PT_TCP;
  pinfo->srcport = tcph->th_sport;
  pinfo->destport = tcph->th_dport;

  tcph->th_seq = tvb_get_ntohl(tvb, offset + 4);
  tcph->th_ack = tvb_get_ntohl(tvb, offset + 8);
  th_off_x2 = tvb_get_guint8(tvb, offset + 12);
  tcph->th_flags = tvb_get_guint8(tvb, offset + 13);
  tcph->th_win = tvb_get_ntohs(tvb, offset + 14);
  real_window = tcph->th_win;
  tcph->th_hlen = hi_nibble(th_off_x2) * 4;  /* TCP header length, in bytes */

  /*
   * If we've been handed an IP fragment, we don't know how big the TCP
   * segment is, so don't do anything that requires that we know that.
   *
   * The same applies if we're part of an error packet.  (XXX - if the
   * ICMP and ICMPv6 dissectors could set a "this is how big the IP
   * header says it is" length in the tvbuff, we could use that; such
   * a length might also be useful for handling packets where the IP
   * length is bigger than the actual data available in the frame; the
   * dissectors should trust that length, and then throw a
   * ReportedBoundsError exception when they go past the end of the frame.)
   *
   * We also can't determine the segment length if the reported length
   * of the TCP packet is less than the TCP header length.
   */
  reported_len = tvb_reported_length(tvb);

  if (!pinfo->fragmented && !pinfo->in_error_pkt) {
    if (reported_len < tcph->th_hlen) {
      proto_tree_add_text(tcp_tree, tvb, offset, 0,
        "Short segment. Segment/fragment does not contain a full TCP header"
        " (might be NMAP or someone else deliberately sending unusual packets)");
      tcph->th_have_seglen = FALSE;
    } else {
      /* Compute the length of data in this segment. */
      tcph->th_seglen = reported_len - tcph->th_hlen;
      tcph->th_have_seglen = TRUE;

      if (tree) { /* Add the seglen as an invisible field */

        proto_tree_add_uint_hidden(ti, hf_tcp_len, tvb, offset, 4, tcph->th_seglen);

      }

      /* handle TCP seq# analysis parse all new segments we see */
      if(tcp_analyze_seq){
          if(!(pinfo->fd->flags.visited)){
              tcp_analyze_sequence_number(pinfo, tcph->th_seq, tcph->th_ack, tcph->th_seglen, tcph->th_flags, tcph->th_win);
          }
          if(tcp_relative_seq){
              tcp_get_relative_seq_ack(pinfo->fd->num, &(tcph->th_seq), &(tcph->th_ack), &(tcph->th_win));
          }
      }

      /* Compute the sequence number of next octet after this segment. */
      nxtseq = tcph->th_seq + tcph->th_seglen;
    }
  } else
    tcph->th_have_seglen = FALSE;

  if (check_col(pinfo->cinfo, COL_INFO) || tree) {
    for (i = 0; i < 8; i++) {
      bpos = 1 << i;
      if (tcph->th_flags & bpos) {
        if (fpos) {
          strcpy(&flags[fpos], ", ");
          fpos += 2;
        }
        strcpy(&flags[fpos], fstr[i]);
        fpos += 3;
      }
    }
    flags[fpos] = '\0';
  }

  if (check_col(pinfo->cinfo, COL_INFO)) {
    col_append_fstr(pinfo->cinfo, COL_INFO, " [%s] Seq=%u Ack=%u Win=%u",
      flags, tcph->th_seq, tcph->th_ack, tcph->th_win);
  }

  if (tree) {
    if (tcp_summary_in_tree) {
      proto_item_append_text(ti, ", Seq: %u", tcph->th_seq);
    }
    if(tcp_relative_seq){
      proto_tree_add_uint_format(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq, "Sequence number: %u    (relative sequence number)", tcph->th_seq);
    } else {
      proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq);
    }
  }

  if (tcph->th_hlen < TCPH_MIN_LEN) {
    /* Give up at this point; we put the source and destination port in
       the tree, before fetching the header length, so that they'll
       show up if this is in the failing packet in an ICMP error packet,
       but it's now time to give up if the header length is bogus. */
    if (check_col(pinfo->cinfo, COL_INFO))
      col_append_fstr(pinfo->cinfo, COL_INFO, ", bogus TCP header length (%u, must be at least %u)",
        tcph->th_hlen, TCPH_MIN_LEN);
    if (tree) {
      proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, tcph->th_hlen,
       "Header length: %u bytes (bogus, must be at least %u)", tcph->th_hlen,
       TCPH_MIN_LEN);
    }
    return;
  }

  if (tree) {
    if (tcp_summary_in_tree) {
      proto_item_append_text(ti, ", Ack: %u", tcph->th_ack);
      if (tcph->th_have_seglen)
        proto_item_append_text(ti, ", Len: %u", tcph->th_seglen);
    }
    proto_item_set_len(ti, tcph->th_hlen);
    if (tcph->th_have_seglen) {
      if (nxtseq != tcph->th_seq) {
        if(tcp_relative_seq){
          tf=proto_tree_add_uint_format(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq, "Next sequence number: %u    (relative sequence number)", nxtseq);
        } else {
          tf=proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);
        }
        PROTO_ITEM_SET_GENERATED(tf);
      }
    }
    if (tcph->th_flags & TH_ACK) {
      if(tcp_relative_seq){
        proto_tree_add_uint_format(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack, "Acknowledgement number: %u    (relative ack number)", tcph->th_ack);
      } else {
        proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack);
      }
    }
    proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, tcph->th_hlen,
	"Header length: %u bytes", tcph->th_hlen);
    tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 13, 1,
	tcph->th_flags, "Flags: 0x%04x (%s)", tcph->th_flags, flags);
    field_tree = proto_item_add_subtree(tf, ett_tcp_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, tcph->th_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, tcph->th_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, tcph->th_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, tcph->th_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, tcph->th_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, tcph->th_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, tcph->th_flags);
    proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, tcph->th_flags);
    if(tcp_relative_seq && (tcph->th_win!=real_window)){
      proto_tree_add_uint_format(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win, "Window size: %u (scaled)", tcph->th_win);
    } else {
      proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win);
    }
  }

  /* Supply the sequence number of the first byte and of the first byte
     after the segment. */
  tcpinfo.seq = tcph->th_seq;
  tcpinfo.nxtseq = nxtseq;

  /* Assume we'll pass un-reassembled data to subdissectors. */
  tcpinfo.is_reassembled = FALSE;

  pinfo->private_data = &tcpinfo;

  /*
   * Assume, initially, that we can't desegment.
   */
  pinfo->can_desegment = 0;
  th_sum = tvb_get_ntohs(tvb, offset + 16);
  if (!pinfo->fragmented && tvb_bytes_exist(tvb, 0, reported_len)) {
    /* The packet isn't part of an un-reassembled fragmented datagram
       and isn't truncated.  This means we have all the data, and thus
       can checksum it and, unless it's being returned in an error
       packet, are willing to allow subdissectors to request reassembly
       on it. */

    if (tcp_check_checksum) {
      /* We haven't turned checksum checking off; checksum it. */

      /* Set up the fields of the pseudo-header. */
      cksum_vec[0].ptr = pinfo->src.data;
      cksum_vec[0].len = pinfo->src.len;
      cksum_vec[1].ptr = pinfo->dst.data;
      cksum_vec[1].len = pinfo->dst.len;
      cksum_vec[2].ptr = (const guint8 *)&phdr;
      switch (pinfo->src.type) {

      case AT_IPv4:
        phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);
        cksum_vec[2].len = 4;
        break;

      case AT_IPv6:
        phdr[0] = g_htonl(reported_len);
        phdr[1] = g_htonl(IP_PROTO_TCP);
        cksum_vec[2].len = 8;
        break;

      default:
        /* TCP runs only atop IPv4 and IPv6.... */
        g_assert_not_reached();
        break;
      }
      cksum_vec[3].ptr = tvb_get_ptr(tvb, offset, reported_len);
      cksum_vec[3].len = reported_len;
      computed_cksum = in_cksum(&cksum_vec[0], 4);
      if (computed_cksum == 0) {
        proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
          offset + 16, 2, th_sum, "Checksum: 0x%04x (correct)", th_sum);

        /* Checksum is valid, so we're willing to desegment it. */
        desegment_ok = TRUE;
      } else {
        proto_tree_add_boolean_hidden(tcp_tree, hf_tcp_checksum_bad, tvb,
	   offset + 16, 2, TRUE);
        proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
           offset + 16, 2, th_sum,
	   "Checksum: 0x%04x (incorrect, should be 0x%04x)", th_sum,
	   in_cksum_shouldbe(th_sum, computed_cksum));

        if (check_col(pinfo->cinfo, COL_INFO))
          col_append_fstr(pinfo->cinfo, COL_INFO, " [CHECKSUM INCORRECT]");

        /* Checksum is invalid, so we're not willing to desegment it. */
        desegment_ok = FALSE;
        pinfo->noreassembly_reason = " (incorrect TCP checksum)";
      }
    } else {
      proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
         offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);

      /* We didn't check the checksum, and don't care if it's valid,
         so we're willing to desegment it. */
      desegment_ok = TRUE;
    }
  } else {
    /* We don't have all the packet data, so we can't checksum it... */
    proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
       offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);

    /* ...and aren't willing to desegment it. */
    desegment_ok = FALSE;
  }

  if (desegment_ok) {
    /* We're willing to desegment this.  Is desegmentation enabled? */
    if (tcp_desegment) {
      /* Yes - is this segment being returned in an error packet? */
      if (!pinfo->in_error_pkt) {
	/* No - indicate that we will desegment.
	   We do NOT want to desegment segments returned in error
	   packets, as they're not part of a TCP connection. */
	pinfo->can_desegment = 2;
      }
    }
  }

  if (tcph->th_flags & TH_URG) {
    th_urp = tvb_get_ntohs(tvb, offset + 18);
    /* Export the urgent pointer, for the benefit of protocols such as
       rlogin. */
    tcpinfo.urgent = TRUE;
    tcpinfo.urgent_pointer = th_urp;
    if (check_col(pinfo->cinfo, COL_INFO))
      col_append_fstr(pinfo->cinfo, COL_INFO, " Urg=%u", th_urp);
    if (tcp_tree != NULL)
      proto_tree_add_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, th_urp);
  } else
    tcpinfo.urgent = FALSE;

  if (tcph->th_have_seglen) {
    if (check_col(pinfo->cinfo, COL_INFO))
      col_append_fstr(pinfo->cinfo, COL_INFO, " Len=%u", tcph->th_seglen);
  }

  /* Decode TCP options, if any. */
  if (tcph->th_hlen > TCPH_MIN_LEN) {
    /* There's more than just the fixed-length header.  Decode the
       options. */
    optlen = tcph->th_hlen - TCPH_MIN_LEN; /* length of options, in bytes */
    if (tcp_tree != NULL) {
      tf = proto_tree_add_text(tcp_tree, tvb, offset +  20, optlen,
        "Options: (%u bytes)", optlen);
      field_tree = proto_item_add_subtree(tf, ett_tcp_options);
    } else
      field_tree = NULL;
    dissect_ip_tcp_options(tvb, offset + 20, optlen,
      tcpopts, N_TCP_OPTS, TCPOPT_EOL, pinfo, field_tree);
  }

  /* If there was window scaling in the SYN packet byt none in the SYN+ACK
   * then we should just forget about the windowscaling completely.
   */
  if(!pinfo->fd->flags.visited){
    if(tcp_analyze_seq && tcp_relative_seq){
      if((tcph->th_flags & (TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) {
        verify_tcp_window_scaling(pinfo);
      }
    }
  }

  /* Skip over header + options */
  offset += tcph->th_hlen;

  /* Check the packet length to see if there's more data
     (it could be an ACK-only packet) */
  length_remaining = tvb_length_remaining(tvb, offset);

  if (tcph->th_have_seglen) {
    if( data_out_file ) {
      reassemble_tcp( tcph->th_seq,		/* sequence number */
          tcph->th_seglen,			/* data length */
          tvb_get_ptr(tvb, offset, length_remaining),	/* data */
          length_remaining,		/* captured data length */
          ( tcph->th_flags & TH_SYN ),		/* is syn set? */
          &pinfo->net_src,
          &pinfo->net_dst,
          pinfo->srcport,
          pinfo->destport);
    }
  }

  /*
   * XXX - what, if any, of this should we do if this is included in an
   * error packet?  It might be nice to see the details of the packet
   * that caused the ICMP error, but it might not be nice to have the
   * dissector update state based on it.
   * Also, we probably don't want to run TCP taps on those packets.
   */
  if (length_remaining != 0) {
    if (tcph->th_flags & TH_RST) {
      /*
       * RFC1122 says:
       *
       *	4.2.2.12  RST Segment: RFC-793 Section 3.4
       *
       *	  A TCP SHOULD allow a received RST segment to include data.
       *
       *	  DISCUSSION
       * 	       It has been suggested that a RST segment could contain
       * 	       ASCII text that encoded and explained the cause of the
       *	       RST.  No standard has yet been established for such
       *	       data.
       *
       * so for segments with RST we just display the data as text.
       */
      proto_tree_add_text(tcp_tree, tvb, offset, length_remaining,
			    "Reset cause: %s",
			    tvb_format_text(tvb, offset, length_remaining));
    } else {
      dissect_tcp_payload(tvb, pinfo, offset, tcph->th_seq, nxtseq,
          tcph->th_sport, tcph->th_dport, tree, tcp_tree);
    }
  }

  /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/
  if(tcp_analyze_seq){
      tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree);
  }
  tap_queue_packet(tcp_tap, pinfo, tcph);
}

void
proto_register_tcp(void)
{
	static hf_register_info hf[] = {

		{ &hf_tcp_srcport,
		{ "Source Port",		"tcp.srcport", FT_UINT16, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_dstport,
		{ "Destination Port",		"tcp.dstport", FT_UINT16, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_port,
		{ "Source or Destination Port",	"tcp.port", FT_UINT16, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_seq,
		{ "Sequence number",		"tcp.seq", FT_UINT32, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_nxtseq,
		{ "Next sequence number",	"tcp.nxtseq", FT_UINT32, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_ack,
		{ "Acknowledgement number",	"tcp.ack", FT_UINT32, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_hdr_len,
		{ "Header Length",		"tcp.hdr_len", FT_UINT8, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_flags,
		{ "Flags",			"tcp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_flags_cwr,
		{ "Congestion Window Reduced (CWR)",			"tcp.flags.cwr", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_CWR,
			"", HFILL }},

		{ &hf_tcp_flags_ecn,
		{ "ECN-Echo",			"tcp.flags.ecn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ECN,
			"", HFILL }},

		{ &hf_tcp_flags_urg,
		{ "Urgent",			"tcp.flags.urg", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_URG,
			"", HFILL }},

		{ &hf_tcp_flags_ack,
		{ "Acknowledgment",		"tcp.flags.ack", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ACK,
			"", HFILL }},

		{ &hf_tcp_flags_push,
		{ "Push",			"tcp.flags.push", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_PUSH,
			"", HFILL }},

		{ &hf_tcp_flags_reset,
		{ "Reset",			"tcp.flags.reset", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_RST,
			"", HFILL }},

		{ &hf_tcp_flags_syn,
		{ "Syn",			"tcp.flags.syn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_SYN,
			"", HFILL }},

		{ &hf_tcp_flags_fin,
		{ "Fin",			"tcp.flags.fin", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_FIN,
			"", HFILL }},

		/* 32 bits so we can present some values adjusted to window scaling */
		{ &hf_tcp_window_size,
		{ "Window size",		"tcp.window_size", FT_UINT32, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_checksum,
		{ "Checksum",			"tcp.checksum", FT_UINT16, BASE_HEX, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_checksum_bad,
		{ "Bad Checksum",		"tcp.checksum_bad", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_analysis_flags,
		{ "TCP Analysis Flags",		"tcp.analysis.flags", FT_NONE, BASE_NONE, NULL, 0x0,
			"This frame has some of the TCP analysis flags set", HFILL }},

		{ &hf_tcp_analysis_retransmission,
		{ "Retransmission",		"tcp.analysis.retransmission", FT_NONE, BASE_NONE, NULL, 0x0,
			"This frame is a suspected TCP retransmission", HFILL }},

		{ &hf_tcp_analysis_fast_retransmission,
		{ "Fast Retransmission",		"tcp.analysis.fast_retransmission", FT_NONE, BASE_NONE, NULL, 0x0,
			"This frame is a suspected TCP fast retransmission", HFILL }},

		{ &hf_tcp_analysis_out_of_order,
		{ "Out Of Order",		"tcp.analysis.out_of_order", FT_NONE, BASE_NONE, NULL, 0x0,
			"This frame is a suspected Out-Of-Order segment", HFILL }},

		{ &hf_tcp_analysis_lost_packet,
		{ "Previous Segment Lost",		"tcp.analysis.lost_segment", FT_NONE, BASE_NONE, NULL, 0x0,
			"A segment before this one was lost from the capture", HFILL }},

		{ &hf_tcp_analysis_ack_lost_packet,
		{ "ACKed Lost Packet",		"tcp.analysis.ack_lost_segment", FT_NONE, BASE_NONE, NULL, 0x0,
			"This frame ACKs a lost segment", HFILL }},

		{ &hf_tcp_analysis_window_update,
		{ "Window update",		"tcp.analysis.window_update", FT_NONE, BASE_NONE, NULL, 0x0,
			"This frame is a tcp window update", HFILL }},

		{ &hf_tcp_analysis_window_full,
		{ "Window full",		"tcp.analysis.window_full", FT_NONE, BASE_NONE, NULL, 0x0,
			"The this segment has caused the allowed window to become 100% full", HFILL }},

		{ &hf_tcp_analysis_keep_alive,
		{ "Keep Alive",		"tcp.analysis.keep_alive", FT_NONE, BASE_NONE, NULL, 0x0,
			"This is a keep-alive segment", HFILL }},

		{ &hf_tcp_analysis_keep_alive_ack,
		{ "Keep Alive ACK",		"tcp.analysis.keep_alive_ack", FT_NONE, BASE_NONE, NULL, 0x0,
			"This is an ACK to a keep-alive segment", HFILL }},

		{ &hf_tcp_analysis_duplicate_ack,
		{ "Duplicate ACK",		"tcp.analysis.duplicate_ack", FT_NONE, BASE_NONE, NULL, 0x0,
			"This is a duplicate ACK", HFILL }},

		{ &hf_tcp_analysis_duplicate_ack_num,
		{ "Duplicate ACK #",		"tcp.analysis.duplicate_ack_num", FT_UINT32, BASE_DEC, NULL, 0x0,
			"This is duplicate ACK number #", HFILL }},

		{ &hf_tcp_analysis_duplicate_ack_frame,
		{ "Duplicate to the ACK in frame",		"tcp.analysis.duplicate_ack_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
			"This is a duplicate to the ACK in frame #", HFILL }},

		{ &hf_tcp_continuation_to,
		{ "This is a continuation to the PDU in frame",		"tcp.continuation_to", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
			"This is a continuation to the PDU in frame #", HFILL }},

		{ &hf_tcp_analysis_zero_window_violation,
		{ "Zero Window Violation",		"tcp.analysis.zero_window_violation", FT_NONE, BASE_NONE, NULL, 0x0,
			"This is a zero-window violation, an attempt to write >1 byte to a zero-window", HFILL }},

		{ &hf_tcp_analysis_zero_window_probe,
		{ "Zero Window Probe",		"tcp.analysis.zero_window_probe", FT_NONE, BASE_NONE, NULL, 0x0,
			"This is a zero-window-probe", HFILL }},

		{ &hf_tcp_analysis_zero_window,
		{ "Zero Window",		"tcp.analysis.zero_window", FT_NONE, BASE_NONE, NULL, 0x0,
			"This is a zero-window", HFILL }},

		{ &hf_tcp_len,
		  { "TCP Segment Len",            "tcp.len", FT_UINT32, BASE_DEC, NULL, 0x0,
		    "", HFILL}},

		{ &hf_tcp_analysis_acks_frame,
		  { "This is an ACK to the segment in frame",            "tcp.analysis.acks_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
		    "Which previous segment is this an ACK for", HFILL}},

		{ &hf_tcp_analysis_ack_rtt,
		  { "The RTT to ACK the segment was",            "tcp.analysis.ack_rtt", FT_RELATIVE_TIME, BASE_NONE, NULL, 0x0,
		    "How long time it took to ACK the segment (RTT)", HFILL}},

		{ &hf_tcp_urgent_pointer,
		{ "Urgent pointer",		"tcp.urgent_pointer", FT_UINT16, BASE_DEC, NULL, 0x0,
			"", HFILL }},

		{ &hf_tcp_segment_overlap,
		{ "Segment overlap",	"tcp.segment.overlap", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
			"Segment overlaps with other segments", HFILL }},

		{ &hf_tcp_segment_overlap_conflict,
		{ "Conflicting data in segment overlap",	"tcp.segment.overlap.conflict", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
			"Overlapping segments contained conflicting data", HFILL }},

		{ &hf_tcp_segment_multiple_tails,
		{ "Multiple tail segments found",	"tcp.segment.multipletails", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
			"Several tails were found when reassembling the pdu", HFILL }},

		{ &hf_tcp_segment_too_long_fragment,
		{ "Segment too long",	"tcp.segment.toolongfragment", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
			"Segment contained data past end of the pdu", HFILL }},

		{ &hf_tcp_segment_error,
		{ "Reassembling error", "tcp.segment.error", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
			"Reassembling error due to illegal segments", HFILL }},

		{ &hf_tcp_segment,
		{ "TCP Segment", "tcp.segment", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
			"TCP Segment", HFILL }},

		{ &hf_tcp_segments,
		{ "TCP Segments", "tcp.segments", FT_NONE, BASE_NONE, NULL, 0x0,
			"TCP Segments", HFILL }},

		{ &hf_tcp_reassembled_in,
		{ "Reassembled PDU in frame", "tcp.reassembled_in", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
			"The PDU that doesn't end in this segment is reassembled in this frame", HFILL }},

		{ &hf_tcp_option_mss,
		  { "TCP MSS Option", "tcp.options.mss", FT_BOOLEAN, 
		    BASE_NONE, NULL, 0x0, "TCP MSS Option", HFILL }},

		{ &hf_tcp_option_mss_val,
		  { "TCP MSS Option Value", "tcp.options.mss_val", FT_UINT16,
		    BASE_DEC, NULL, 0x0, "TCP MSS Option Value", HFILL}},

		{ &hf_tcp_option_wscale,
		  { "TCP Window Scale Option", "tcp.options.wscale", 
		    FT_BOOLEAN, 
		    BASE_NONE, NULL, 0x0, "TCP Window Option", HFILL}},

		{ &hf_tcp_option_wscale_val,
		  { "TCP Windows Scale Option Value", "tcp.options.wscale_val",
		    FT_UINT8, BASE_DEC, NULL, 0x0, "TCP Window Scale Value",
		    HFILL}},

		{ &hf_tcp_option_sack_perm, 
		  { "TCP Sack Perm Option", "tcp.options.sack_perm", 
		    FT_BOOLEAN,
		    BASE_NONE, NULL, 0x0, "TCP Sack Perm Option", HFILL}},

		{ &hf_tcp_option_sack,
		  { "TCP Sack Option", "tcp.options.sack", FT_BOOLEAN, 
		    BASE_NONE, NULL, 0x0, "TCP Sack Option", HFILL}},

		{ &hf_tcp_option_sack_sle,
		  {"TCP Sack Left Edge", "tcp.options.sack_le", FT_UINT32,
		   BASE_DEC, NULL, 0x0, "TCP Sack Left Edge", HFILL}},

		{ &hf_tcp_option_sack_sre,
		  {"TCP Sack Right Edge", "tcp.options.sack_re", FT_UINT32,
		   BASE_DEC, NULL, 0x0, "TCP Sack Right Edge", HFILL}},

		{ &hf_tcp_option_echo,
		  { "TCP Echo Option", "tcp.options.echo", FT_BOOLEAN, 
		    BASE_NONE, NULL, 0x0, "TCP Sack Echo", HFILL}},

		{ &hf_tcp_option_echo_reply,
		  { "TCP Echo Reply Option", "tcp.options.echo_reply", 
		    FT_BOOLEAN,
		    BASE_NONE, NULL, 0x0, "TCP Echo Reply Option", HFILL}},

		{ &hf_tcp_option_time_stamp,
		  { "TCP Time Stamp Option", "tcp.options.time_stamp", 
		    FT_BOOLEAN,
		    BASE_NONE, NULL, 0x0, "TCP Time Stamp Option", HFILL}},

		{ &hf_tcp_option_cc,
		  { "TCP CC Option", "tcp.options.cc", FT_BOOLEAN, BASE_NONE,
		    NULL, 0x0, "TCP CC Option", HFILL}},

		{ &hf_tcp_option_ccnew,
		  { "TCP CC New Option", "tcp.options.ccnew", FT_BOOLEAN, 
		    BASE_NONE, NULL, 0x0, "TCP CC New Option", HFILL}},

		{ &hf_tcp_option_ccecho,
		  { "TCP CC Echo Option", "tcp.options.ccecho", FT_BOOLEAN,
		    BASE_NONE, NULL, 0x0, "TCP CC Echo Option", HFILL}},

		{ &hf_tcp_option_md5,
		  { "TCP MD5 Option", "tcp.options.md5", FT_BOOLEAN, BASE_NONE,
		    NULL, 0x0, "TCP MD5 Option", HFILL}},

		{ &hf_tcp_pdu_time,
		  { "Time until the last segment of this PDU", "tcp.pdu.time", FT_RELATIVE_TIME, BASE_NONE, NULL, 0x0,
		    "How long time has passed until the last frame of this PDU", HFILL}},
		{ &hf_tcp_pdu_last_frame,
		  { "Last frame of this PDU", "tcp.pdu.last_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
			"This is the last frame of the PDU starting in this segment", HFILL }},

	};
	static gint *ett[] = {
		&ett_tcp,
		&ett_tcp_flags,
		&ett_tcp_options,
		&ett_tcp_option_sack,
		&ett_tcp_analysis_faults,
		&ett_tcp_analysis,
		&ett_tcp_segments,
		&ett_tcp_segment
	};
	module_t *tcp_module;

	proto_tcp = proto_register_protocol("Transmission Control Protocol",
	    "TCP", "tcp");
	proto_register_field_array(proto_tcp, hf, array_length(hf));
	proto_register_subtree_array(ett, array_length(ett));

	/* subdissector code */
	subdissector_table = register_dissector_table("tcp.port",
	    "TCP port", FT_UINT16, BASE_DEC);
	register_heur_dissector_list("tcp", &heur_subdissector_list);

	/* Register configuration preferences */
	tcp_module = prefs_register_protocol(proto_tcp, NULL);
	prefs_register_bool_preference(tcp_module, "summary_in_tree",
	    "Show TCP summary in protocol tree",
	    "Whether the TCP summary line should be shown in the protocol tree",
	    &tcp_summary_in_tree);
	prefs_register_bool_preference(tcp_module, "check_checksum",
	    "Check the validity of the TCP checksum when possible",
	    "Whether to check the validity of the TCP checksum",
	    &tcp_check_checksum);
	prefs_register_bool_preference(tcp_module, "desegment_tcp_streams",
	    "Allow subdissector to reassemble TCP streams",
	    "Whether subdissector can request TCP streams to be reassembled",
	    &tcp_desegment);
	prefs_register_bool_preference(tcp_module, "analyze_sequence_numbers",
	    "Analyze TCP sequence numbers",
	    "Make the TCP dissector analyze TCP sequence numbers to find and flag segment retransmissions, missing segments and RTT",
	    &tcp_analyze_seq);
	prefs_register_bool_preference(tcp_module, "relative_sequence_numbers",
	    "Relative sequence numbers and window scaling",
	    "Make the TCP dissector use relative sequence numbers instead of absolute ones. "
	    "To use this option you must also enable \"Analyze TCP sequence numbers\". "
	    "This option will also try to track and adjust the window field according to any TCP window scaling options seen.",
	    &tcp_relative_seq);
	prefs_register_bool_preference(tcp_module, "try_heuristic_first",
	    "Try heuristic sub-dissectors first",
	    "Try to decode a packet using an heuristic sub-dissector before using a sub-dissector registered to a specific port",
	    &try_heuristic_first);

	register_init_routine(tcp_analyze_seq_init);
	register_init_routine(tcp_desegment_init);
	register_init_routine(tcp_fragment_init);
}

void
proto_reg_handoff_tcp(void)
{
	dissector_handle_t tcp_handle;

	tcp_handle = create_dissector_handle(dissect_tcp, proto_tcp);
	dissector_add("ip.proto", IP_PROTO_TCP, tcp_handle);
	data_handle = find_dissector("data");
	tcp_tap = register_tap("tcp");
}