da7717cf0ef49280d7794d7eb2fb33c19bdaa24a
[obnox/wireshark/wip.git] / packet-tcp.c
1 /* packet-tcp.c
2  * Routines for TCP packet disassembly
3  *
4  * $Id: packet-tcp.c,v 1.211 2003/10/28 08:50:39 sahlberg Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <glib.h>
32 #include "in_cksum.h"
33
34 #include <epan/packet.h>
35 #include <epan/resolv.h>
36 #include "ipproto.h"
37 #include "ip_opts.h"
38 #include "follow.h"
39 #include "prefs.h"
40 #include "packet-tcp.h"
41 #include "packet-ip.h"
42 #include "packet-frame.h"
43 #include <epan/conversation.h>
44 #include <epan/strutil.h>
45 #include "reassemble.h"
46 #include "tap.h"
47
48 static int tcp_tap = -1;
49
50 /* Place TCP summary in proto tree */
51 static gboolean tcp_summary_in_tree = TRUE;
52
53 /*
54  * Flag to control whether to check the TCP checksum.
55  *
56  * In at least some Solaris network traces, there are packets with bad
57  * TCP checksums, but the traffic appears to indicate that the packets
58  * *were* received; the packets were probably sent by the host on which
59  * the capture was being done, on a network interface to which
60  * checksumming was offloaded, so that DLPI supplied an un-checksummed
61  * packet to the capture program but a checksummed packet got put onto
62  * the wire.
63  */
64 static gboolean tcp_check_checksum = TRUE;
65
66 extern FILE* data_out_file;
67
68 static int proto_tcp = -1;
69 static int hf_tcp_srcport = -1;
70 static int hf_tcp_dstport = -1;
71 static int hf_tcp_port = -1;
72 static int hf_tcp_seq = -1;
73 static int hf_tcp_nxtseq = -1;
74 static int hf_tcp_ack = -1;
75 static int hf_tcp_hdr_len = -1;
76 static int hf_tcp_flags = -1;
77 static int hf_tcp_flags_cwr = -1;
78 static int hf_tcp_flags_ecn = -1;
79 static int hf_tcp_flags_urg = -1;
80 static int hf_tcp_flags_ack = -1;
81 static int hf_tcp_flags_push = -1;
82 static int hf_tcp_flags_reset = -1;
83 static int hf_tcp_flags_syn = -1;
84 static int hf_tcp_flags_fin = -1;
85 static int hf_tcp_window_size = -1;
86 static int hf_tcp_checksum = -1;
87 static int hf_tcp_checksum_bad = -1;
88 static int hf_tcp_len = -1;
89 static int hf_tcp_urgent_pointer = -1;
90 static int hf_tcp_analysis_flags = -1;
91 static int hf_tcp_analysis_acks_frame = -1;
92 static int hf_tcp_analysis_ack_rtt = -1;
93 static int hf_tcp_analysis_retransmission = -1;
94 static int hf_tcp_analysis_fast_retransmission = -1;
95 static int hf_tcp_analysis_out_of_order = -1;
96 static int hf_tcp_analysis_lost_packet = -1;
97 static int hf_tcp_analysis_ack_lost_packet = -1;
98 static int hf_tcp_analysis_keep_alive = -1;
99 static int hf_tcp_analysis_keep_alive_ack = -1;
100 static int hf_tcp_analysis_duplicate_ack = -1;
101 static int hf_tcp_analysis_duplicate_ack_num = -1;
102 static int hf_tcp_analysis_duplicate_ack_frame = -1;
103 static int hf_tcp_analysis_zero_window = -1;
104 static int hf_tcp_analysis_zero_window_probe = -1;
105 static int hf_tcp_analysis_zero_window_violation = -1;
106 static int hf_tcp_reassembled_in = -1;
107 static int hf_tcp_segments = -1;
108 static int hf_tcp_segment = -1;
109 static int hf_tcp_segment_overlap = -1;
110 static int hf_tcp_segment_overlap_conflict = -1;
111 static int hf_tcp_segment_multiple_tails = -1;
112 static int hf_tcp_segment_too_long_fragment = -1;
113 static int hf_tcp_segment_error = -1;
114 static int hf_tcp_option_mss = -1;
115 static int hf_tcp_option_mss_val = -1;
116 static int hf_tcp_option_wscale = -1;
117 static int hf_tcp_option_wscale_val = -1;
118 static int hf_tcp_option_sack_perm = -1;
119 static int hf_tcp_option_sack = -1;
120 static int hf_tcp_option_sack_sle = -1;
121 static int hf_tcp_option_sack_sre = -1;
122 static int hf_tcp_option_echo = -1;
123 static int hf_tcp_option_echo_reply = -1;
124 static int hf_tcp_option_time_stamp = -1;
125 static int hf_tcp_option_cc = -1;
126 static int hf_tcp_option_ccnew = -1;
127 static int hf_tcp_option_ccecho = -1;
128 static int hf_tcp_option_md5 = -1;
129
130 static gint ett_tcp = -1;
131 static gint ett_tcp_flags = -1;
132 static gint ett_tcp_options = -1;
133 static gint ett_tcp_option_sack = -1;
134 static gint ett_tcp_analysis = -1;
135 static gint ett_tcp_analysis_faults = -1;
136 static gint ett_tcp_segments = -1;
137 static gint ett_tcp_segment  = -1;
138
139
140 /* not all of the hf_fields below make sense for TCP but we have to provide 
141    them anyways to comply with the api (which was aimed for ip fragment 
142    reassembly) */
143 static const fragment_items tcp_segment_items = {
144         &ett_tcp_segment,
145         &ett_tcp_segments,
146         &hf_tcp_segments,
147         &hf_tcp_segment,
148         &hf_tcp_segment_overlap,
149         &hf_tcp_segment_overlap_conflict,
150         &hf_tcp_segment_multiple_tails,
151         &hf_tcp_segment_too_long_fragment,
152         &hf_tcp_segment_error,
153         &hf_tcp_reassembled_in,
154         "Segments"
155 };
156
157 static dissector_table_t subdissector_table;
158 static heur_dissector_list_t heur_subdissector_list;
159 static dissector_handle_t data_handle;
160
161 /* TCP structs and definitions */
162
163
164 /* **************************************************************************
165  * stuff to analyze TCP sequencenumbers for retransmissions, missing segments,
166  * RTT and reltive sequence numbers.
167  * **************************************************************************/
168 static gboolean tcp_analyze_seq = FALSE;
169 static gboolean tcp_relative_seq = FALSE;
170
171 static GMemChunk *tcp_unacked_chunk = NULL;
172 static int tcp_unacked_count = 500;     /* one for each packet until it is acked*/
173 struct tcp_unacked {
174         struct tcp_unacked *next;
175         guint32 frame;
176         guint32 seq;
177         guint32 nextseq;
178         nstime_t ts;
179
180         /* this is to keep track of zero window and zero window probe */
181         guint32 window;
182
183         guint32 flags;
184 };
185
186 /* Idea for gt: either x > y, or y is much bigger (assume wrap) */
187 #define GT_SEQ(x, y) ((gint32)((y) - (x)) < 0)
188 #define LT_SEQ(x, y) ((gint32)((x) - (y)) < 0)
189 #define GE_SEQ(x, y) ((gint32)((y) - (x)) <= 0)
190 #define LE_SEQ(x, y) ((gint32)((x) - (y)) <= 0)
191 #define EQ_SEQ(x, y) ((x) == (y))
192
193 static GMemChunk *tcp_acked_chunk = NULL;
194 static int tcp_acked_count = 5000;      /* one for almost every other segment in the capture */
195 #define TCP_A_RETRANSMISSION            0x0001
196 #define TCP_A_LOST_PACKET               0x0002
197 #define TCP_A_ACK_LOST_PACKET           0x0004
198 #define TCP_A_KEEP_ALIVE                0x0008
199 #define TCP_A_DUPLICATE_ACK             0x0010
200 #define TCP_A_ZERO_WINDOW               0x0020
201 #define TCP_A_ZERO_WINDOW_PROBE         0x0040
202 #define TCP_A_ZERO_WINDOW_VIOLATION     0x0080
203 #define TCP_A_KEEP_ALIVE_ACK            0x0100
204 #define TCP_A_OUT_OF_ORDER              0x0200
205 #define TCP_A_FAST_RETRANSMISSION       0x0400
206 struct tcp_acked {
207         guint32 frame_acked;
208         nstime_t ts;
209         guint16 flags;
210         guint32 dupack_num;     /* dup ack number */
211         guint32 dupack_frame;   /* dup ack to frame # */
212 };
213 static GHashTable *tcp_analyze_acked_table = NULL;
214
215 static GMemChunk *tcp_rel_seq_chunk = NULL;
216 static int tcp_rel_seq_count = 10000; /* one for each segment in the capture */
217 struct tcp_rel_seq {
218         guint32 seq_base;
219         guint32 ack_base;
220         gint16  win_scale;
221 };
222 static GHashTable *tcp_rel_seq_table = NULL;
223
224 static GMemChunk *tcp_analysis_chunk = NULL;
225 static int tcp_analysis_count = 20;     /* one for each conversation */
226 struct tcp_analysis {
227         /* These two structs are managed based on comparing the source
228          * and destination addresses and, if they're equal, comparing
229          * the source and destination ports.
230          *
231          * If the source is greater than the destination, then stuff
232          * sent from src is in ual1.
233          *
234          * If the source is less than the destination, then stuff
235          * sent from src is in ual2.
236          *
237          * XXX - if the addresses and ports are equal, we don't guarantee
238          * the behavior.
239          */
240         struct tcp_unacked *ual1;       /* UnAcked List 1*/
241         guint32 base_seq1;
242         struct tcp_unacked *ual2;       /* UnAcked List 2*/
243         guint32 base_seq2;
244         gint16 win_scale1;
245         gint16 win_scale2;
246         guint32 ack1, ack2;
247         guint32 ack1_frame, ack2_frame;
248         nstime_t ack1_time, ack2_time;
249         guint32 num1_acks, num2_acks;
250
251         /* these two lists are used to track when PDUs may start
252            inside a segment.
253         */
254         struct tcp_next_pdu *pdu_seq1;
255         struct tcp_next_pdu *pdu_seq2;
256 };
257
258
259 static GMemChunk *tcp_next_pdu_chunk = NULL;
260 static int tcp_next_pdu_count = 20;
261 struct tcp_next_pdu {
262         struct tcp_next_pdu *next;
263         guint32 seq;
264 };
265 static GHashTable *tcp_pdu_tracking_table = NULL;
266
267
268 static struct tcp_analysis *
269 get_tcp_conversation_data(packet_info *pinfo)
270 {
271         conversation_t *conv=NULL;
272         struct tcp_analysis *tcpd=NULL;
273
274         /* Have we seen this conversation before? */
275         if( (conv=find_conversation(&pinfo->src, &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport, 0)) == NULL){
276                 /* No this is a new conversation. */
277                 conv=conversation_new(&pinfo->src, &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
278         }
279
280         /* check if we have any data for this conversation */
281         tcpd=conversation_get_proto_data(conv, proto_tcp);
282         if(!tcpd){
283                 /* No no such data yet. Allocate and init it */
284                 tcpd=g_mem_chunk_alloc(tcp_analysis_chunk);
285                 tcpd->ual1=NULL;
286                 tcpd->base_seq1=0;
287                 tcpd->win_scale1=-1;
288                 tcpd->ack1=0;
289                 tcpd->ack1_frame=0;
290                 tcpd->ack1_time.secs=0;
291                 tcpd->ack1_time.nsecs=0;
292                 tcpd->num1_acks=0;
293                 tcpd->ual2=NULL;
294                 tcpd->base_seq2=0;
295                 tcpd->win_scale2=-1;
296                 tcpd->ack2=0;
297                 tcpd->ack2_frame=0;
298                 tcpd->ack2_time.secs=0;
299                 tcpd->ack2_time.nsecs=0;
300                 tcpd->num2_acks=0;
301
302                 tcpd->pdu_seq1=NULL;
303                 tcpd->pdu_seq2=NULL;
304
305                 conversation_add_proto_data(conv, proto_tcp, tcpd);
306         }
307
308         return tcpd;
309 }
310
311 /* This function is called from the tcp analysis code to provide
312    clues on how the seq and ack numbers are changed.
313    To prevent the next_pdu lists from growing uncontrollable in size we
314    use this function to do the following :
315    IF we see an ACK then we assume that the left edge of the window has changed
316       at least to this point and assuming it is rare with reordering and
317       trailing duplicate/retransmitted segments, we just assume that after
318       we have seen the ACK we will not see any more segments prior to the 
319       ACK value.
320       If we will not see any segments prior to the ACK value then we can just
321       delete all next_pdu entries that describe pdu's starting prior to the 
322       ACK.
323       If this heuristics is prooved to be too simplistic we can just enhance it
324       later.
325 */   
326 /* XXX this function should be ehnanced to handle sequence number wrapping */
327 /* XXX to handle retransmissions and reordered packets maybe we should only
328        discard entries that are more than (guesstimate) 50kb older than the
329        specified sequence number ?
330 */
331 static void
332 prune_next_pdu_list(struct tcp_next_pdu **tnp, guint32 seq)
333 {
334         struct tcp_next_pdu *tmptnp;
335
336         if(*tnp == NULL){
337                 return;
338         }
339
340         for(tmptnp=*tnp;tmptnp;tmptnp=tmptnp->next){
341                 if(tmptnp->seq<=seq){
342                         struct tcp_next_pdu *oldtnp;
343                         oldtnp=tmptnp;
344
345                         if(tmptnp==*tnp){
346                                 tmptnp=tmptnp->next;
347                                 *tnp=tmptnp;
348                                 g_mem_chunk_free(tcp_next_pdu_chunk, oldtnp);
349                                 if(!tmptnp){
350                                         return;
351                                 }
352                                 continue;
353                         } else {
354                                 for(tmptnp=*tnp;tmptnp;tmptnp=tmptnp->next){
355                                         if(tmptnp->next==oldtnp){
356                                                 tmptnp->next=oldtnp->next;
357                                                 g_mem_chunk_free(tcp_next_pdu_chunk, oldtnp);
358                                                 break;
359                                         }
360                                 }
361                                 if(!tmptnp){
362                                         return;
363                                 }
364                         }
365                 }
366         }
367 }
368                 
369
370 /* if we know that a PDU starts inside this segment, return the adjusted 
371    offset to where that PDU starts or just return offset back
372    and let TCP try to find out what it can about this segment
373 */
374 static int
375 scan_for_next_pdu(packet_info *pinfo, int offset, guint32 seq, guint32 nxtseq)
376 {
377         struct tcp_analysis *tcpd=NULL;
378         struct tcp_next_pdu *tnp=NULL;
379         int direction;
380
381         if(!pinfo->fd->flags.visited){
382                 /* find(or create if needed) the conversation for this tcp session */
383                 tcpd=get_tcp_conversation_data(pinfo);
384                 /* check direction and get pdu start lists */
385                 direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
386                 /* if the addresses are equal, match the ports instead */
387                 if(direction==0) {
388                         direction= (pinfo->srcport > pinfo->destport)*2-1;
389                 }
390                 if(direction>=0){
391                         tnp=tcpd->pdu_seq1;
392                 } else {
393                         tnp=tcpd->pdu_seq2;
394                 }
395
396                 /* scan and see if we find any pdus starting inside this tvb */
397                 for(;tnp;tnp=tnp->next){
398                         /* XXX here we should also try to handle sequence number
399                            wrapping
400                         */
401                         if(seq<tnp->seq && nxtseq>tnp->seq){
402                                 g_hash_table_insert(tcp_pdu_tracking_table, 
403                                         (void *)pinfo->fd->num, (void *)tnp->seq);
404                                 offset+=tnp->seq-seq;
405                                 break;
406                         }
407                 }
408         } else {
409                 guint32 pduseq;
410
411                 pduseq=(guint32)g_hash_table_lookup(tcp_pdu_tracking_table, (void *)pinfo->fd->num);
412                 if(pduseq){
413                         offset+=pduseq-seq;
414                 }
415         }
416
417         return offset;
418 }
419
420 /* if we saw a PDU that extended beyond the end of the segment,
421    use this function to remember where the next pdu starts
422 */
423 static void
424 pdu_store_sequencenumber_of_next_pdu(packet_info *pinfo, guint32 nxtpdu)
425 {
426         struct tcp_analysis *tcpd=NULL;
427         struct tcp_next_pdu *tnp=NULL;
428         int direction;
429
430         /* find(or create if needed) the conversation for this tcp session */
431         tcpd=get_tcp_conversation_data(pinfo);
432
433         tnp=g_mem_chunk_alloc(tcp_next_pdu_chunk);
434         tnp->seq=nxtpdu;
435
436         /* check direction and get pdu start list */
437         direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
438         /* if the addresses are equal, match the ports instead */
439         if(direction==0) {
440                 direction= (pinfo->srcport > pinfo->destport)*2-1;
441         }
442         if(direction>=0){
443                 tnp->next=tcpd->pdu_seq1;
444                 tcpd->pdu_seq1=tnp;
445         } else {
446                 tnp->next=tcpd->pdu_seq2;
447                 tcpd->pdu_seq2=tnp;
448         }
449         /*QQQ 
450           Add check for ACKs and purge list of sequence numbers
451           already acked.
452         */
453 }
454
455 /* if we saw a window scaling option, store it for future reference 
456 */
457 static void
458 pdu_store_window_scale_option(packet_info *pinfo, guint8 ws)
459 {
460         struct tcp_analysis *tcpd=NULL;
461         int direction;
462
463         /* find(or create if needed) the conversation for this tcp session */
464         tcpd=get_tcp_conversation_data(pinfo);
465
466         /* check direction and get pdu start list */
467         direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
468         /* if the addresses are equal, match the ports instead */
469         if(direction==0) {
470                 direction= (pinfo->srcport > pinfo->destport)*2-1;
471         }
472         if(direction>=0){
473                 tcpd->win_scale1=ws;
474         } else {
475                 tcpd->win_scale2=ws;
476         }
477 }
478
479 static void
480 tcp_get_relative_seq_ack(guint32 frame, guint32 *seq, guint32 *ack, guint32 *win)
481 {
482         struct tcp_rel_seq *trs;
483
484         trs=g_hash_table_lookup(tcp_rel_seq_table, (void *)frame);
485         if(!trs){
486                 return;
487         }
488
489         (*seq) -= trs->seq_base;
490         (*ack) -= trs->ack_base;
491         if(trs->win_scale!=-1){
492                 (*win)<<=trs->win_scale;
493         }
494 }
495
496 static struct tcp_acked *
497 tcp_analyze_get_acked_struct(guint32 frame, gboolean createflag)
498 {
499         struct tcp_acked *ta;
500
501         ta=g_hash_table_lookup(tcp_analyze_acked_table, (void *)frame);
502         if((!ta) && createflag){
503                 ta=g_mem_chunk_alloc(tcp_acked_chunk);
504                 ta->frame_acked=0;
505                 ta->ts.secs=0;
506                 ta->ts.nsecs=0;
507                 ta->flags=0;
508                 ta->dupack_num=0;
509                 ta->dupack_frame=0;
510                 g_hash_table_insert(tcp_analyze_acked_table, (void *)frame, ta);
511         }
512         return ta;
513 }
514
515 static void
516 tcp_analyze_sequence_number(packet_info *pinfo, guint32 seq, guint32 ack, guint32 seglen, guint8 flags, guint16 window)
517 {
518         struct tcp_analysis *tcpd=NULL;
519         int direction;
520         struct tcp_unacked *ual1=NULL;
521         struct tcp_unacked *ual2=NULL;
522         struct tcp_unacked *ual=NULL;
523         guint32 base_seq;
524         guint32 base_ack;
525         guint32 ack1, ack2;
526         guint32 ack1_frame, ack2_frame;
527         nstime_t *ack1_time, *ack2_time;
528         guint32 num1_acks, num2_acks;
529         gint16  win_scale;
530         struct tcp_next_pdu **tnp=NULL;
531
532         /* find(or create if needed) the conversation for this tcp session */
533         tcpd=get_tcp_conversation_data(pinfo);
534
535         /* check direction and get ua lists */
536         direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
537         /* if the addresses are equal, match the ports instead */
538         if(direction==0) {
539                 direction= (pinfo->srcport > pinfo->destport)*2-1;
540         }
541         if(direction>=0){
542                 ual1=tcpd->ual1;
543                 ual2=tcpd->ual2;
544                 ack1=tcpd->ack1;
545                 ack2=tcpd->ack2;
546                 ack1_frame=tcpd->ack1_frame;
547                 ack2_frame=tcpd->ack2_frame;
548                 ack1_time=&tcpd->ack1_time;
549                 ack2_time=&tcpd->ack2_time;
550                 num1_acks=tcpd->num1_acks;
551                 num2_acks=tcpd->num2_acks;
552                 tnp=&tcpd->pdu_seq2;
553                 base_seq=(tcp_relative_seq && (ual1==NULL))?seq:tcpd->base_seq1;
554                 base_ack=(tcp_relative_seq && (ual2==NULL))?ack:tcpd->base_seq2;
555                 win_scale=tcpd->win_scale1;
556         } else {
557                 ual1=tcpd->ual2;
558                 ual2=tcpd->ual1;
559                 ack1=tcpd->ack2;
560                 ack2=tcpd->ack1;
561                 ack1_frame=tcpd->ack2_frame;
562                 ack2_frame=tcpd->ack1_frame;
563                 ack1_time=&tcpd->ack2_time;
564                 ack2_time=&tcpd->ack1_time;
565                 num1_acks=tcpd->num2_acks;
566                 num2_acks=tcpd->num1_acks;
567                 tnp=&tcpd->pdu_seq1;
568                 base_seq=(tcp_relative_seq && (ual1==NULL))?seq:tcpd->base_seq2;
569                 base_ack=(tcp_relative_seq && (ual2==NULL))?ack:tcpd->base_seq1;
570                 win_scale=tcpd->win_scale2;
571         }
572
573         if(!seglen){
574                 if(!ack2_frame){
575                         ack2_frame=pinfo->fd->num;
576                         ack2=ack;
577                         ack2_time->secs=pinfo->fd->abs_secs;
578                         ack2_time->nsecs=pinfo->fd->abs_usecs*1000;
579                         num2_acks=0;
580                 } else if(GT_SEQ(ack, ack2)){
581                         ack2_frame=pinfo->fd->num;
582                         ack2=ack;
583                         ack2_time->secs=pinfo->fd->abs_secs;
584                         ack2_time->nsecs=pinfo->fd->abs_usecs*1000;
585                         num2_acks=0;
586                 }
587         }
588
589 #ifdef REMOVED
590 /* useful debug ouput   
591  * it prints the two lists of the sliding window emulation 
592  */
593 {
594 struct tcp_unacked *u=NULL;
595 printf("\n");
596 printf("analyze_sequence_number(frame:%d seq:%d nextseq:%d ack:%d)\n",pinfo->fd->num,seq,seq+seglen,ack);
597 printf("UAL1:\n");
598 for(u=ual1;u;u=u->next){
599 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);
600 }
601 printf("UAL2:\n");
602 for(u=ual2;u;u=u->next){
603 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);
604 }
605 }
606 #endif
607
608         /* To handle FIN, just add 1 to the length.
609            else the ACK following the FIN-ACK will look like it was
610            outside the window. */
611         if( flags&TH_FIN ){
612                 seglen+=1;
613         }
614
615         /* handle the sequence numbers */
616         /* if this was a SYN packet, then remove existing list and
617          * put SEQ+1 first the list */
618         if(flags&TH_SYN){
619                 for(ual=ual1;ual1;ual1=ual){
620                         ual=ual1->next;
621                         g_mem_chunk_free(tcp_unacked_chunk, ual1);
622                 }
623                 ual1=g_mem_chunk_alloc(tcp_unacked_chunk);
624                 ual1->next=NULL;
625                 ual1->frame=pinfo->fd->num;
626                 ack1_frame=0;
627                 ack2_frame=0;
628                 ack1=0;
629                 ack2=0;
630                 num1_acks=0;
631                 num2_acks=0;
632                 ual1->seq=seq+1;
633                 ual1->nextseq=seq+1;
634                 ual1->ts.secs=pinfo->fd->abs_secs;
635                 ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
636                 ual1->window=window;
637                 ual1->flags=0;
638                 if(tcp_relative_seq){
639                         base_seq=seq;
640                         base_ack=ack;
641                 }
642                 goto seq_finished;
643         }
644
645         /* if this is the first segment we see then just add it */
646         if( !ual1 ){
647                 ual1=g_mem_chunk_alloc(tcp_unacked_chunk);
648                 ual1->next=NULL;
649                 ual1->frame=pinfo->fd->num;
650                 ual1->seq=seq;
651                 ual1->nextseq=seq+seglen;
652                 ual1->ts.secs=pinfo->fd->abs_secs;
653                 ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
654                 ual1->window=window;
655                 ual1->flags=0;
656                 if(tcp_relative_seq){
657                         base_seq=seq;
658                         base_ack=ack;
659                 }
660                 goto seq_finished;
661         }
662
663         /* if we get past here we know that ual1 points to a segment */
664
665
666         /* if seq is beyond ual1->nextseq we have lost a segment */
667         if (GT_SEQ(seq, ual1->nextseq)) {
668                 struct tcp_acked *ta;
669
670                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
671                 ta->flags|=TCP_A_LOST_PACKET;
672
673                 /* just add the segment to the beginning of the list */
674                 ual=g_mem_chunk_alloc(tcp_unacked_chunk);
675                 ual->next=ual1;
676                 ual->frame=pinfo->fd->num;
677                 ual->seq=seq;
678                 ual->nextseq=seq+seglen;
679                 ual->ts.secs=pinfo->fd->abs_secs;
680                 ual->ts.nsecs=pinfo->fd->abs_usecs*1000;
681                 ual->window=window;
682                 ual->flags=0;
683                 ual1=ual;
684                 goto seq_finished;
685         }
686
687         /* keep-alives are empty segments with a sequence number -1 of what
688          * we would expect.
689          *
690          * Solaris is an exception, Solaris does not really use KeepAlives
691          * according to RFC793, instead they move the left window edge one
692          * byte to the left and makes up a fake byte to fill in this position
693          * of the enlarged window.
694          * This means that Solaris will do "weird" KeepAlives that actually
695          * contains a one-byte segment with "random" junk data which the
696          * Solaris host then will try to transmit, and posisbly retransmit
697          * to the other side. Of course the other side will ignore this junk
698          * byte since it is outside (left of) the window.
699          * This is actually a brilliant trick that gives them, for free, 
700          * semi-reliable KeepAlives.
701          * (since normal retransmission will handle any lost keepalive segments
702          * , brilliant)
703          */
704         if( (seglen<=1) && EQ_SEQ(seq, (ual1->nextseq-1)) ){
705                 if(!(flags&TH_FIN)){ /* FIN segments are not keepalives */
706                         struct tcp_acked *ta;
707         
708                         ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
709                         ta->flags|=TCP_A_KEEP_ALIVE;
710                         ual1->flags|=TCP_A_KEEP_ALIVE;
711                         goto seq_finished;
712                 }
713         }
714
715
716         /* if this is an empty segment, just skip it all */
717         if( !seglen ){
718                 goto seq_finished;
719         }
720
721         /* check if the sequence number is lower than expected, i.e. either a 
722          * retransmission a fast retransmission or an out of order segment
723          */
724         if( LT_SEQ(seq, ual1->nextseq )){
725                 gboolean outoforder;
726                 struct tcp_unacked *tu,*ntu;
727
728                 /* assume it is a fast retransmission if
729                  * 1 we have seen >=3 dupacks in the other direction for this 
730                  *   segment (i.e. >=4 acks)
731                  * 2 if this segment is the next unacked segment
732                  * 3 this segment came within 10ms of the last dupack
733                  *   (10ms is arbitrary but should be low enough not to be
734                  *   confused with a retransmission timeout 
735                  */
736                 if( (num1_acks>=4) && (seq==ack1) ){
737                         guint32 t;
738
739                         t=(pinfo->fd->abs_secs-ack1_time->secs)*1000000000;
740                         t=t+(pinfo->fd->abs_usecs*1000)-ack1_time->nsecs;
741                         if(t<10000000){
742                                 /* has to be a retransmission then */
743                                 struct tcp_acked *ta;
744
745                                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
746                                 ta->flags|=TCP_A_FAST_RETRANSMISSION;
747                                 goto seq_finished;
748                         }
749                 }
750
751                 /* check it is a suspected out of order segment.
752                  * we assume it is an out of order segment if 
753                  * 1 it has not been ACKed yet.
754                  * 2 we have not seen the segment before
755                  * 3 it arrived within (arbitrary value) 4ms of the
756                  *      next semgent in the sequence.
757                  *   4 there were no dupacks in the opposite direction.
758                  */
759                 outoforder=TRUE;
760 #ifdef REMOVED
761                 /* dont do this test.  For full-duplex capture devices that 
762                  * capture in both directions using two NICs it is more common
763                  * than one would expect for this to happen since they often
764                  * lose the time integrity between the two NICs
765                  */
766                 /* 1 has it already been ACKed ? */
767                 if(LT_SEQ(seq,ack1)){
768                         outoforder=FALSE;
769                 }
770 #endif
771                 /* 2 have we seen this segment before ? */
772                 for(tu=ual1;tu;tu=tu->next){
773                         if((tu->frame)&&(tu->seq==seq)){
774                                 outoforder=FALSE;
775                         }
776                 }
777                 /* 3 was it received within 4ms of the next segment ?*/
778                 ntu=NULL;
779                 for(tu=ual1;tu;tu=tu->next){
780                         if(LT_SEQ(seq,tu->seq)){
781                                 if(tu->frame){
782                                         ntu=tu;
783                                 }
784                         }
785                 }
786                 if(ntu){
787                         if(pinfo->fd->abs_secs>(guint32)(ntu->ts.secs+2)){
788                                 outoforder=FALSE;
789                         } else if((pinfo->fd->abs_secs+2)<(guint32)ntu->ts.secs){
790                                 outoforder=FALSE;
791                         } else {
792                                 guint32 t;
793
794                                 t=(ntu->ts.secs-pinfo->fd->abs_secs)*1000000000;
795                                 t=t+ntu->ts.nsecs-(pinfo->fd->abs_usecs*1000);
796                                 if(t>4000000){
797                                         outoforder=FALSE;
798                                 }
799                         }
800                 }
801
802                 
803                 if(outoforder) {
804                         struct tcp_acked *ta;
805
806                         ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
807                         ta->flags|=TCP_A_OUT_OF_ORDER;
808                 } else {
809                         /* has to be a retransmission then */
810                         struct tcp_acked *ta;
811
812                         ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
813                         ta->flags|=TCP_A_RETRANSMISSION;
814
815                         /* did this segment contain any more data we havent seen yet?
816                          * if so we can just increase nextseq
817                          */
818                         if(GT_SEQ((seq+seglen), ual1->nextseq)){
819                                 ual1->nextseq=seq+seglen;
820                                 ual1->frame=pinfo->fd->num;
821                                 ual1->ts.secs=pinfo->fd->abs_secs;
822                                 ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
823                         }
824                 }
825                 goto seq_finished;
826         }
827
828         /* just add the segment to the beginning of the list */
829         ual=g_mem_chunk_alloc(tcp_unacked_chunk);
830         ual->next=ual1;
831         ual->frame=pinfo->fd->num;
832         ual->seq=seq;
833         ual->nextseq=seq+seglen;
834         ual->ts.secs=pinfo->fd->abs_secs;
835         ual->ts.nsecs=pinfo->fd->abs_usecs*1000;
836         ual->window=window;
837         ual->flags=0;
838         ual1=ual;
839
840 seq_finished:
841
842
843         /* handle the ack numbers */
844
845         /* if we dont have the ack flag its not much we can do */
846         if( !(flags&TH_ACK)){
847                 goto ack_finished;
848         }
849
850         /* if we havent seen anything yet in the other direction we dont
851          * know what this one acks */
852         if( !ual2 ){
853                 goto ack_finished;
854         }
855
856         /* if we dont have any real segments in the other direction not
857          * acked yet (as we see from the magic frame==0 entry)
858          * then there is no point in continuing
859          */
860         if( !ual2->frame ){
861                 goto ack_finished;
862         }
863
864         /* if we get here we know ual2 is valid */
865
866         /* if we are acking beyong what we have seen in the other direction
867          * we must have lost packets. Not much point in keeping the segments
868          * in the other direction either.
869          */
870         if( GT_SEQ(ack, ual2->nextseq )){
871                 struct tcp_acked *ta;
872
873                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
874                 ta->flags|=TCP_A_ACK_LOST_PACKET;
875                 for(ual=ual2;ual2;ual2=ual){
876                         ual=ual2->next;
877                         g_mem_chunk_free(tcp_unacked_chunk, ual2);
878                 }
879                 prune_next_pdu_list(tnp, ack-base_ack);
880                 goto ack_finished;
881         }
882
883
884         /* does this ACK ack all semgents we have seen in the other direction?*/
885         if( EQ_SEQ(ack, ual2->nextseq )){
886                 struct tcp_acked *ta;
887
888                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
889                 ta->frame_acked=ual2->frame;
890                 ta->ts.secs=pinfo->fd->abs_secs-ual2->ts.secs;
891                 ta->ts.nsecs=pinfo->fd->abs_usecs*1000-ual2->ts.nsecs;
892                 if(ta->ts.nsecs<0){
893                         ta->ts.nsecs+=1000000000;
894                         ta->ts.secs--;
895                 }
896
897                 /* its all been ACKed so we dont need to keep them anymore */
898                 for(ual=ual2;ual2;ual2=ual){
899                         ual=ual2->next;
900                         g_mem_chunk_free(tcp_unacked_chunk, ual2);
901                 }
902                 prune_next_pdu_list(tnp, ack-base_ack);
903                 goto ack_finished;
904         }
905
906         /* ok it only ACKs part of what we have seen. Find out how much
907          * update and remove the ACKed segments
908          */
909         for(ual=ual2;ual->next;ual=ual->next){
910                 if( GE_SEQ(ack, ual->next->nextseq)){
911                         break;
912                 }
913         }
914         if(ual->next){
915                 struct tcp_unacked *tmpual=NULL;
916                 struct tcp_unacked *ackedual=NULL;
917                 struct tcp_acked *ta;
918
919                 /* XXX normal ACK*/
920                 ackedual=ual->next;
921
922                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
923                 ta->frame_acked=ackedual->frame;
924                 ta->ts.secs=pinfo->fd->abs_secs-ackedual->ts.secs;
925                 ta->ts.nsecs=pinfo->fd->abs_usecs*1000-ackedual->ts.nsecs;
926                 if(ta->ts.nsecs<0){
927                         ta->ts.nsecs+=1000000000;
928                         ta->ts.secs--;
929                 }
930
931                 /* just delete all ACKed segments */
932                 tmpual=ual->next;
933                 ual->next=NULL;
934                 for(ual=tmpual;ual;ual=tmpual){
935                         tmpual=ual->next;
936                         g_mem_chunk_free(tcp_unacked_chunk, ual);
937                 }
938                 prune_next_pdu_list(tnp, ack-base_ack);
939         }
940
941 ack_finished:
942         /* we might have deleted the entire ual2 list, if this is an ACK,
943            make sure ual2 at least has a dummy entry for the current ACK */
944         if( (!ual2) && (flags&TH_ACK) ){
945                 ual2=g_mem_chunk_alloc(tcp_unacked_chunk);
946                 ual2->next=NULL;
947                 ual2->frame=0;
948                 ual2->seq=ack;
949                 ual2->nextseq=ack;
950                 ual2->ts.secs=0;
951                 ual2->ts.nsecs=0;
952                 ual2->window=window;
953                 ual2->flags=0;
954         }
955
956         /* update the ACK counter and check for
957            duplicate ACKs*/
958         /* go to the oldest segment in the list of segments 
959            in the other direction */
960         /* XXX we should guarantee ual2 to always be non NULL here
961            so we can skip the ual/ual2 tests */
962         for(ual=ual2;ual&&ual->next;ual=ual->next)
963                 ;
964         if(ual2){
965                 /* we only consider this being a potential duplicate ack
966                    if the segment length is 0 (ack only segment)
967                    and if it acks something previous to oldest segment
968                    in the other direction */
969                 if((!seglen)&&LE_SEQ(ack,ual->seq)){
970                         /* if this is the first ack to keep track of, it is not
971                            a duplicate */
972                         if(num2_acks==0){
973                                 ack2=ack;
974                                 ack2_frame=pinfo->fd->num;
975                                 num2_acks=1;
976                         /* if this ack is different, store this one 
977                            instead and forget the previous one(s) */
978                         } else if(ack2!=ack){
979                                 ack2=ack;
980                                 ack2_frame=pinfo->fd->num;
981                                 num2_acks=1;
982                         /* this has to be a duplicate ack */
983                         } else {
984                                 num2_acks++;
985                         }       
986                         
987                         /* is this an ACK to a KeepAlive? */
988                         if( (ual->flags&TCP_A_KEEP_ALIVE)
989                         && (ack==ual->seq) ){
990                                 struct tcp_acked *ta;
991                                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
992                                 ta->flags|=TCP_A_KEEP_ALIVE_ACK;
993                                 ual->flags^=TCP_A_KEEP_ALIVE;
994                         } else if(num2_acks>1) {
995                         /* ok we have found a potential duplicate ack */
996                                 struct tcp_acked *ta;
997                                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
998                                 /* keepalives are not dupacks */
999                                 if( (!(ta->flags&TCP_A_KEEP_ALIVE)) ){
1000                                         ta->flags|=TCP_A_DUPLICATE_ACK;
1001                                         ta->dupack_num=num2_acks-1;
1002                                         ta->dupack_frame=ack2_frame;
1003                                 }
1004                         }
1005                 }               
1006
1007         }
1008
1009
1010         /* check for zero window probes 
1011            a zero window probe is when a TCP tries to write 1 byte segments
1012            where the remote side has advertised a window of 0 bytes.
1013            We only do this check if we actually have seen anything from the
1014            other side of this connection.
1015
1016            We also assume ual still points to the last entry in the ual2
1017            list from the section above.
1018
1019            At the same time, check for violations, i.e. attempts to write >1
1020            byte to a zero-window.
1021         */
1022         /* XXX we should not need to do the ual->frame check here?
1023            might be a bug somewhere. look for it later .
1024         */
1025         if(ual2&&(ual->frame)){
1026                 if((seglen==1)&&(ual->window==0)){
1027                         struct tcp_acked *ta;
1028                         ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
1029                         ta->flags|=TCP_A_ZERO_WINDOW_PROBE;
1030                 }
1031                 if((seglen>1)&&(ual->window==0)){
1032                         struct tcp_acked *ta;
1033                         ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
1034                         ta->flags|=TCP_A_ZERO_WINDOW_VIOLATION;
1035                 }
1036         }
1037
1038         /* check for zero window */
1039         if(!window){
1040                 struct tcp_acked *ta;
1041                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
1042                 ta->flags|=TCP_A_ZERO_WINDOW;
1043         }
1044
1045
1046         /* store the lists back in our struct */
1047         if(direction>=0){
1048                 /*
1049                  * XXX - if direction == 0, that'll be true for packets
1050                  * from both sides of the connection, so this won't
1051                  * work.
1052                  *
1053                  * That'd be a connection from a given port on a machine
1054                  * to that same port on the same machine; does that ever
1055                  * happen?
1056                  */
1057                 tcpd->ual1=ual1;
1058                 tcpd->ual2=ual2;
1059                 tcpd->ack1=ack1;
1060                 tcpd->ack2=ack2;
1061                 tcpd->ack1_frame=ack1_frame;
1062                 tcpd->ack2_frame=ack2_frame;
1063                 tcpd->num1_acks=num1_acks;
1064                 tcpd->num2_acks=num2_acks;
1065                 tcpd->base_seq1=base_seq;
1066                 tcpd->base_seq2=base_ack;
1067         } else {
1068                 tcpd->ual1=ual2;
1069                 tcpd->ual2=ual1;
1070                 tcpd->ack1=ack2;
1071                 tcpd->ack2=ack1;
1072                 tcpd->ack1_frame=ack2_frame;
1073                 tcpd->ack2_frame=ack1_frame;
1074                 tcpd->num1_acks=num2_acks;
1075                 tcpd->num2_acks=num1_acks;
1076                 tcpd->base_seq2=base_seq;
1077                 tcpd->base_seq1=base_ack;
1078         }
1079
1080
1081         if(tcp_relative_seq){
1082                 struct tcp_rel_seq *trs;
1083                 /* remember relative seq/ack number base for this packet */
1084                 trs=g_mem_chunk_alloc(tcp_rel_seq_chunk);
1085                 trs->seq_base=base_seq;
1086                 trs->ack_base=base_ack;
1087                 trs->win_scale=win_scale;
1088                 g_hash_table_insert(tcp_rel_seq_table, (void *)pinfo->fd->num, trs);
1089         }
1090 }
1091
1092 static void
1093 tcp_print_sequence_number_analysis(packet_info *pinfo, tvbuff_t *tvb, proto_tree *parent_tree)
1094 {
1095         struct tcp_acked *ta;
1096         proto_item *item;
1097         proto_tree *tree;
1098
1099         ta=tcp_analyze_get_acked_struct(pinfo->fd->num, FALSE);
1100         if(!ta){
1101                 return;
1102         }
1103
1104         item=proto_tree_add_text(parent_tree, tvb, 0, 0, "SEQ/ACK analysis");
1105         tree=proto_item_add_subtree(item, ett_tcp_analysis);
1106
1107         /* encapsulate all proto_tree_add_xxx in ifs so we only print what
1108            data we actually have */
1109         if(ta->frame_acked){
1110                 proto_tree_add_uint(tree, hf_tcp_analysis_acks_frame,
1111                         tvb, 0, 0, ta->frame_acked);
1112         }
1113         if( ta->ts.secs || ta->ts.nsecs ){
1114                 proto_tree_add_time(tree, hf_tcp_analysis_ack_rtt,
1115                 tvb, 0, 0, &ta->ts);
1116         }
1117
1118         if(ta->flags){
1119                 proto_item *flags_item=NULL;
1120                 proto_tree *flags_tree=NULL;
1121
1122                 flags_item = proto_tree_add_item(tree, hf_tcp_analysis_flags, tvb, 0, -1, FALSE);
1123                 flags_tree=proto_item_add_subtree(flags_item, ett_tcp_analysis);
1124                 if( ta->flags&TCP_A_RETRANSMISSION ){
1125                         proto_tree_add_none_format(flags_tree, hf_tcp_analysis_retransmission, tvb, 0, 0, "This frame is a (suspected) retransmission");
1126                         if(check_col(pinfo->cinfo, COL_INFO)){
1127                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Retransmission] ");
1128                         }
1129                 }
1130                 if( ta->flags&TCP_A_FAST_RETRANSMISSION ){
1131                         proto_tree_add_none_format(flags_tree, hf_tcp_analysis_fast_retransmission, tvb, 0, 0, "This frame is a (suspected) fast retransmission");
1132                         proto_tree_add_none_format(flags_tree, hf_tcp_analysis_retransmission, tvb, 0, 0, "This frame is a (suspected) retransmission");
1133                         if(check_col(pinfo->cinfo, COL_INFO)){
1134                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Fast Retransmission] ");
1135                         }
1136                 }
1137                 if( ta->flags&TCP_A_OUT_OF_ORDER ){
1138                         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");
1139                         if(check_col(pinfo->cinfo, COL_INFO)){
1140                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Out-Of-Order] ");
1141                         }
1142                 }
1143                 if( ta->flags&TCP_A_LOST_PACKET ){
1144                         proto_tree_add_none_format(flags_tree, hf_tcp_analysis_lost_packet, tvb, 0, 0, "A segment before this frame was lost");
1145                         if(check_col(pinfo->cinfo, COL_INFO)){
1146                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Previous segment lost] ");
1147                         }
1148                 }
1149                 if( ta->flags&TCP_A_ACK_LOST_PACKET ){
1150                         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?)");
1151                         if(check_col(pinfo->cinfo, COL_INFO)){
1152                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ACKed lost segment] ");
1153                         }
1154                 }
1155                 if( ta->flags&TCP_A_KEEP_ALIVE ){
1156                         proto_tree_add_none_format(flags_tree, hf_tcp_analysis_keep_alive, tvb, 0, 0, "This is a TCP keep-alive segment");
1157                         if(check_col(pinfo->cinfo, COL_INFO)){
1158                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Keep-Alive] ");
1159                         }
1160                 }
1161                 if( ta->flags&TCP_A_KEEP_ALIVE_ACK ){
1162                         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");
1163                         if(check_col(pinfo->cinfo, COL_INFO)){
1164                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Keep-Alive ACK] ");
1165                         }
1166                 }
1167                 if( ta->dupack_num){
1168                         if( ta->flags&TCP_A_DUPLICATE_ACK ){
1169                                 proto_tree_add_none_format(flags_tree, hf_tcp_analysis_duplicate_ack, tvb, 0, 0, "This is a TCP duplicate ack");
1170                                 if(check_col(pinfo->cinfo, COL_INFO)){
1171                                         col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Dup ACK %d#%d] ", ta->dupack_frame, ta->dupack_num);
1172                                 }
1173                         }
1174                         proto_tree_add_uint(tree, hf_tcp_analysis_duplicate_ack_num,
1175                                 tvb, 0, 0, ta->dupack_num);
1176                         proto_tree_add_uint(tree, hf_tcp_analysis_duplicate_ack_frame,
1177                                 tvb, 0, 0, ta->dupack_frame);
1178                 }
1179                 if( ta->flags&TCP_A_ZERO_WINDOW_PROBE ){
1180                         proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window_probe, tvb, 0, 0, "This is a TCP zero-window-probe");
1181                         if(check_col(pinfo->cinfo, COL_INFO)){
1182                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindowProbe] ");
1183                         }
1184                 }
1185                 if( ta->flags&TCP_A_ZERO_WINDOW ){
1186                         proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window, tvb, 0, 0, "This is a ZeroWindow segment");
1187                         if(check_col(pinfo->cinfo, COL_INFO)){
1188                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindow] ");
1189                         }
1190                 }
1191                 if( ta->flags&TCP_A_ZERO_WINDOW_VIOLATION ){
1192                         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");
1193                         if(check_col(pinfo->cinfo, COL_INFO)){
1194                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindowViolation] ");
1195                         }
1196                 }
1197         }
1198
1199 }
1200
1201
1202 /* Do we still need to do this ...remove_all() even though we dont need
1203  * to do anything special?  The glib docs are not clear on this and
1204  * its better safe than sorry
1205  */
1206 static gboolean
1207 free_all_acked(gpointer key_arg _U_, gpointer value _U_, gpointer user_data _U_)
1208 {
1209         return TRUE;
1210 }
1211
1212 static guint
1213 tcp_acked_hash(gconstpointer k)
1214 {
1215         guint32 frame = (guint32)k;
1216
1217         return frame;
1218 }
1219 static gint
1220 tcp_acked_equal(gconstpointer k1, gconstpointer k2)
1221 {
1222         guint32 frame1 = (guint32)k1;
1223         guint32 frame2 = (guint32)k2;
1224
1225         return frame1==frame2;
1226 }
1227
1228 static void
1229 tcp_analyze_seq_init(void)
1230 {
1231         /* first destroy the tables */
1232         if( tcp_analyze_acked_table ){
1233                 g_hash_table_foreach_remove(tcp_analyze_acked_table,
1234                         free_all_acked, NULL);
1235                 g_hash_table_destroy(tcp_analyze_acked_table);
1236                 tcp_analyze_acked_table = NULL;
1237         }
1238         if( tcp_rel_seq_table ){
1239                 g_hash_table_foreach_remove(tcp_rel_seq_table,
1240                         free_all_acked, NULL);
1241                 g_hash_table_destroy(tcp_rel_seq_table);
1242                 tcp_rel_seq_table = NULL;
1243         }
1244         if( tcp_pdu_tracking_table ){
1245                 g_hash_table_foreach_remove(tcp_pdu_tracking_table,
1246                         free_all_acked, NULL);
1247                 g_hash_table_destroy(tcp_pdu_tracking_table);
1248                 tcp_pdu_tracking_table = NULL;
1249         }
1250
1251         /*
1252          * Now destroy the chunk from which the conversation table
1253          * structures were allocated.
1254          */
1255         if (tcp_next_pdu_chunk) {
1256                 g_mem_chunk_destroy(tcp_next_pdu_chunk);
1257                 tcp_next_pdu_chunk = NULL;
1258         }
1259         if (tcp_analysis_chunk) {
1260                 g_mem_chunk_destroy(tcp_analysis_chunk);
1261                 tcp_analysis_chunk = NULL;
1262         }
1263         if (tcp_unacked_chunk) {
1264                 g_mem_chunk_destroy(tcp_unacked_chunk);
1265                 tcp_unacked_chunk = NULL;
1266         }
1267         if (tcp_acked_chunk) {
1268                 g_mem_chunk_destroy(tcp_acked_chunk);
1269                 tcp_acked_chunk = NULL;
1270         }
1271         if (tcp_rel_seq_chunk) {
1272                 g_mem_chunk_destroy(tcp_rel_seq_chunk);
1273                 tcp_rel_seq_chunk = NULL;
1274         }
1275
1276         if(tcp_analyze_seq){
1277                 tcp_analyze_acked_table = g_hash_table_new(tcp_acked_hash,
1278                         tcp_acked_equal);
1279                 tcp_rel_seq_table = g_hash_table_new(tcp_acked_hash,
1280                         tcp_acked_equal);
1281                 tcp_pdu_tracking_table = g_hash_table_new(tcp_acked_hash,
1282                         tcp_acked_equal);
1283                 tcp_next_pdu_chunk = g_mem_chunk_new("tcp_next_pdu_chunk",
1284                         sizeof(struct tcp_next_pdu),
1285                         tcp_next_pdu_count * sizeof(struct tcp_next_pdu),
1286                         G_ALLOC_ONLY);
1287                 tcp_analysis_chunk = g_mem_chunk_new("tcp_analysis_chunk",
1288                         sizeof(struct tcp_analysis),
1289                         tcp_analysis_count * sizeof(struct tcp_analysis),
1290                         G_ALLOC_ONLY);
1291                 tcp_unacked_chunk = g_mem_chunk_new("tcp_unacked_chunk",
1292                         sizeof(struct tcp_unacked),
1293                         tcp_unacked_count * sizeof(struct tcp_unacked),
1294                         G_ALLOC_ONLY);
1295                 tcp_acked_chunk = g_mem_chunk_new("tcp_acked_chunk",
1296                         sizeof(struct tcp_acked),
1297                         tcp_acked_count * sizeof(struct tcp_acked),
1298                         G_ALLOC_ONLY);
1299                 if(tcp_relative_seq){
1300                         tcp_rel_seq_chunk = g_mem_chunk_new("tcp_rel_seq_chunk",
1301                                 sizeof(struct tcp_rel_seq),
1302                                 tcp_rel_seq_count * sizeof(struct tcp_rel_seq),
1303                                 G_ALLOC_ONLY);
1304                 }
1305         }
1306
1307 }
1308
1309 /* **************************************************************************
1310  * End of tcp sequence number analysis
1311  * **************************************************************************/
1312
1313
1314
1315
1316 /* Minimum TCP header length. */
1317 #define TCPH_MIN_LEN    20
1318
1319 /*
1320  *      TCP option
1321  */
1322
1323 #define TCPOPT_NOP              1       /* Padding */
1324 #define TCPOPT_EOL              0       /* End of options */
1325 #define TCPOPT_MSS              2       /* Segment size negotiating */
1326 #define TCPOPT_WINDOW           3       /* Window scaling */
1327 #define TCPOPT_SACK_PERM        4       /* SACK Permitted */
1328 #define TCPOPT_SACK             5       /* SACK Block */
1329 #define TCPOPT_ECHO             6
1330 #define TCPOPT_ECHOREPLY        7
1331 #define TCPOPT_TIMESTAMP        8       /* Better RTT estimations/PAWS */
1332 #define TCPOPT_CC               11
1333 #define TCPOPT_CCNEW            12
1334 #define TCPOPT_CCECHO           13
1335 #define TCPOPT_MD5              19      /* RFC2385 */
1336
1337 /*
1338  *     TCP option lengths
1339  */
1340
1341 #define TCPOLEN_MSS            4
1342 #define TCPOLEN_WINDOW         3
1343 #define TCPOLEN_SACK_PERM      2
1344 #define TCPOLEN_SACK_MIN       2
1345 #define TCPOLEN_ECHO           6
1346 #define TCPOLEN_ECHOREPLY      6
1347 #define TCPOLEN_TIMESTAMP      10
1348 #define TCPOLEN_CC             6
1349 #define TCPOLEN_CCNEW          6
1350 #define TCPOLEN_CCECHO         6
1351 #define TCPOLEN_MD5            18
1352
1353
1354
1355 /* Desegmentation of TCP streams */
1356 /* table to hold defragmented TCP streams */
1357 static GHashTable *tcp_fragment_table = NULL;
1358 static void
1359 tcp_fragment_init(void)
1360 {
1361         fragment_table_init(&tcp_fragment_table);
1362 }
1363
1364 /* functions to trace tcp segments */
1365 /* Enable desegmenting of TCP streams */
1366 static gboolean tcp_desegment = FALSE;
1367
1368 static GHashTable *tcp_segment_table = NULL;
1369 static GMemChunk *tcp_segment_key_chunk = NULL;
1370 static int tcp_segment_init_count = 200;
1371 static GMemChunk *tcp_segment_address_chunk = NULL;
1372 static int tcp_segment_address_init_count = 500;
1373
1374 typedef struct _tcp_segment_key {
1375         /* for own bookkeeping inside packet-tcp.c */
1376         address *src;
1377         address *dst;
1378         guint32 seq;
1379         /* xxx */
1380         guint16 sport;
1381         guint16 dport;
1382         guint32 start_seq;
1383         guint32 tot_len;
1384         guint32 first_frame;
1385 } tcp_segment_key;
1386
1387 static gboolean
1388 free_all_segments(gpointer key_arg, gpointer value _U_, gpointer user_data _U_)
1389 {
1390         tcp_segment_key *key = key_arg;
1391
1392         if((key->src)&&(key->src->data)){
1393                 g_free((gpointer)key->src->data);
1394                 key->src->data=NULL;
1395         }
1396
1397         if((key->dst)&&(key->dst->data)){
1398                 g_free((gpointer)key->dst->data);
1399                 key->dst->data=NULL;
1400         }
1401
1402         return TRUE;
1403 }
1404
1405 static guint
1406 tcp_segment_hash(gconstpointer k)
1407 {
1408         const tcp_segment_key *key = (const tcp_segment_key *)k;
1409
1410         return key->seq+key->sport;
1411 }
1412
1413 static gint
1414 tcp_segment_equal(gconstpointer k1, gconstpointer k2)
1415 {
1416         const tcp_segment_key *key1 = (const tcp_segment_key *)k1;
1417         const tcp_segment_key *key2 = (const tcp_segment_key *)k2;
1418
1419         return ( ( (key1->seq==key2->seq)
1420                  &&(ADDRESSES_EQUAL(key1->src, key2->src))
1421                  &&(ADDRESSES_EQUAL(key1->dst, key2->dst))
1422                  &&(key1->sport==key2->sport)
1423                  &&(key1->dport==key2->dport)
1424                  ) ? TRUE:FALSE);
1425 }
1426
1427 static void
1428 tcp_desegment_init(void)
1429 {
1430         /*
1431          * Free this before freeing any memory chunks; those
1432          * chunks contain data we'll look at in "free_all_segments()".
1433          */
1434         if(tcp_segment_table){
1435                 g_hash_table_foreach_remove(tcp_segment_table,
1436                         free_all_segments, NULL);
1437                 g_hash_table_destroy(tcp_segment_table);
1438                 tcp_segment_table = NULL;
1439         }
1440
1441         if(tcp_segment_key_chunk){
1442                 g_mem_chunk_destroy(tcp_segment_key_chunk);
1443                 tcp_segment_key_chunk = NULL;
1444         }
1445         if(tcp_segment_address_chunk){
1446                 g_mem_chunk_destroy(tcp_segment_address_chunk);
1447                 tcp_segment_address_chunk = NULL;
1448         }
1449
1450         /* dont allocate any hash table or memory chunks unless the user
1451            really uses this option
1452         */
1453         if(!tcp_desegment){
1454                 return;
1455         }
1456
1457         tcp_segment_table = g_hash_table_new(tcp_segment_hash,
1458                 tcp_segment_equal);
1459
1460         tcp_segment_key_chunk = g_mem_chunk_new("tcp_segment_key_chunk",
1461                 sizeof(tcp_segment_key),
1462                 tcp_segment_init_count*sizeof(tcp_segment_key),
1463                 G_ALLOC_ONLY);
1464
1465         tcp_segment_address_chunk = g_mem_chunk_new("tcp_segment_address_chunk",
1466                 sizeof(address),
1467                 tcp_segment_address_init_count*sizeof(address),
1468                 G_ALLOC_ONLY);
1469 }
1470
1471 static void
1472 desegment_tcp(tvbuff_t *tvb, packet_info *pinfo, int offset,
1473                 guint32 seq, guint32 nxtseq,
1474                 guint32 sport, guint32 dport,
1475                 proto_tree *tree, proto_tree *tcp_tree)
1476 {
1477         struct tcpinfo *tcpinfo = pinfo->private_data;
1478         fragment_data *ipfd_head=NULL;
1479         tcp_segment_key old_tsk, *tsk;
1480         gboolean must_desegment = FALSE;
1481         gboolean called_dissector = FALSE;
1482         int deseg_offset;
1483         guint32 deseg_seq;
1484         gint nbytes;
1485
1486         /*
1487          * Initialize these to assume no desegmentation.
1488          * If that's not the case, these will be set appropriately
1489          * by the subdissector.
1490          */
1491         pinfo->desegment_offset = 0;
1492         pinfo->desegment_len = 0;
1493
1494         /*
1495          * Initialize this to assume that this segment will just be
1496          * added to the middle of a desegmented chunk of data, so
1497          * that we should show it all as data.
1498          * If that's not the case, it will be set appropriately.
1499          */
1500         deseg_offset = offset;
1501
1502         /* First we must check if this TCP segment should be desegmented.
1503            This is only to check if we should desegment this packet,
1504            so we dont spend time doing COPY_ADDRESS/g_free.
1505            We just "borrow" some address structures from pinfo instead. Cheaper.
1506         */
1507         old_tsk.src = &pinfo->src;
1508         old_tsk.dst = &pinfo->dst;
1509         old_tsk.sport = sport;
1510         old_tsk.dport = dport;
1511         old_tsk.seq = seq;
1512         tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
1513
1514         if(tsk){
1515                 /* OK, this segment was found, which means it continues
1516                    a higher-level PDU. This means we must desegment it.
1517                    Add it to the defragmentation lists.
1518                 */
1519                 ipfd_head = fragment_add(tvb, offset, pinfo, tsk->first_frame,
1520                         tcp_fragment_table,
1521                         seq - tsk->start_seq,
1522                         nxtseq - seq,
1523                         (LT_SEQ (nxtseq,tsk->start_seq + tsk->tot_len)) );
1524
1525                 if(!ipfd_head){
1526                         /* fragment_add() returned NULL, This means that
1527                            desegmentation is not completed yet.
1528                            (its like defragmentation but we know we will
1529                             always add the segments in order).
1530                            XXX - no, we don't; there is no guarantee that
1531                            TCP segments are in order on the wire.
1532
1533                            we must add next segment to our table so we will
1534                            find it later.
1535                         */
1536                         tcp_segment_key *new_tsk;
1537
1538                         new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1539                         memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1540                         new_tsk->seq=nxtseq;
1541                         g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1542                 }
1543         } else {
1544                 /* This segment was not found in our table, so it doesn't
1545                    contain a continuation of a higher-level PDU.
1546                    Call the normal subdissector.
1547                 */
1548                 decode_tcp_ports(tvb, offset, pinfo, tree,
1549                                 sport, dport, 0);
1550                 called_dissector = TRUE;
1551
1552                 /* Did the subdissector ask us to desegment some more data
1553                    before it could handle the packet?
1554                    If so we have to create some structures in our table but
1555                    this is something we only do the first time we see this
1556                    packet.
1557                 */
1558                 if(pinfo->desegment_len) {
1559                         if (!pinfo->fd->flags.visited)
1560                                 must_desegment = TRUE;
1561
1562                         /*
1563                          * Set "deseg_offset" to the offset in "tvb"
1564                          * of the first byte of data that the
1565                          * subdissector didn't process.
1566                          */
1567                         deseg_offset = offset + pinfo->desegment_offset;
1568                 }
1569
1570                 /* Either no desegmentation is necessary, or this is
1571                    segment contains the beginning but not the end of
1572                    a higher-level PDU and thus isn't completely
1573                    desegmented.
1574                 */
1575                 ipfd_head = NULL;
1576         }
1577
1578         /* is it completely desegmented? */
1579         if(ipfd_head){
1580                 fragment_data *ipfd;
1581
1582                 /*
1583                  * Yes, we think it is.
1584                  * We only call subdissector for the last segment.
1585                  * Note that the last segment may include more than what
1586                  * we needed.
1587                  */
1588                 if(GE_SEQ(nxtseq, tsk->start_seq + tsk->tot_len)){
1589                         /*
1590                          * OK, this is the last segment.
1591                          * Let's call the subdissector with the desegmented
1592                          * data.
1593                          */
1594                         tvbuff_t *next_tvb;
1595                         int old_len;
1596
1597                         /* create a new TVB structure for desegmented data */
1598                         next_tvb = tvb_new_real_data(ipfd_head->data,
1599                                         ipfd_head->datalen, ipfd_head->datalen);
1600
1601                         /* add this tvb as a child to the original one */
1602                         tvb_set_child_real_data_tvbuff(tvb, next_tvb);
1603
1604                         /* add desegmented data to the data source list */
1605                         add_new_data_source(pinfo, next_tvb, "Desegmented");
1606
1607                         /*
1608                          * Supply the sequence number of the first of the
1609                          * reassembled bytes.
1610                          */
1611                         tcpinfo->seq = tsk->start_seq;
1612
1613                         /* indicate that this is reassembled data */
1614                         tcpinfo->is_reassembled = TRUE;
1615
1616                         /* call subdissector */
1617                         decode_tcp_ports(next_tvb, 0, pinfo, tree,
1618                                 sport, dport, 0);
1619                         called_dissector = TRUE;
1620
1621                         /*
1622                          * OK, did the subdissector think it was completely
1623                          * desegmented, or does it think we need even more
1624                          * data?
1625                          */
1626                         old_len=(int)(tvb_reported_length(next_tvb)-tvb_reported_length_remaining(tvb, offset));
1627                         if(pinfo->desegment_len &&
1628                             pinfo->desegment_offset<=old_len){
1629                                 tcp_segment_key *new_tsk;
1630
1631                                 /*
1632                                  * "desegment_len" isn't 0, so it needs more
1633                                  * data for something - and "desegment_offset"
1634                                  * is before "old_len", so it needs more data
1635                                  * to dissect the stuff we thought was
1636                                  * completely desegmented (as opposed to the
1637                                  * stuff at the beginning being completely
1638                                  * desegmented, but the stuff at the end
1639                                  * being a new higher-level PDU that also
1640                                  * needs desegmentation).
1641                                  */
1642                                 fragment_set_partial_reassembly(pinfo,tsk->first_frame,tcp_fragment_table);
1643                                 tsk->tot_len = tvb_reported_length(next_tvb) + pinfo->desegment_len;
1644
1645                                 /*
1646                                  * Update tsk structure.
1647                                  * Can ask ->next->next because at least there's a hdr and one
1648                                  * entry in fragment_add()
1649                                  */
1650                                 for(ipfd=ipfd_head->next; ipfd->next; ipfd=ipfd->next){
1651                                         old_tsk.seq = tsk->start_seq + ipfd->offset;
1652                                         new_tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
1653                                         new_tsk->tot_len = tsk->tot_len;
1654                                 }
1655
1656                                 /* this is the next segment in the sequence we want */
1657                                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1658                                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1659                                 new_tsk->seq = nxtseq;
1660                                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1661                         } else {
1662                                 /*
1663                                  * Show the stuff in this TCP segment as
1664                                  * just raw TCP segment data.
1665                                  */
1666                                 nbytes =
1667                                     tvb_reported_length_remaining(tvb, offset);
1668                                 proto_tree_add_text(tcp_tree, tvb, offset, -1,
1669                                     "TCP segment data (%u byte%s)", nbytes,
1670                                     plurality(nbytes, "", "s"));
1671
1672                                 /*
1673                                  * The subdissector thought it was completely
1674                                  * desegmented (although the stuff at the
1675                                  * end may, in turn, require desegmentation),
1676                                  * so we show a tree with all segments.
1677                                  */
1678                                 show_fragment_tree(ipfd_head, &tcp_segment_items,
1679                                         tcp_tree, pinfo, next_tvb);
1680
1681                                 /* Did the subdissector ask us to desegment
1682                                    some more data?  This means that the data
1683                                    at the beginning of this segment completed
1684                                    a higher-level PDU, but the data at the
1685                                    end of this segment started a higher-level
1686                                    PDU but didn't complete it.
1687
1688                                    If so, we have to create some structures
1689                                    in our table, but this is something we
1690                                    only do the first time we see this packet.
1691                                 */
1692                                 if(pinfo->desegment_len) {
1693                                         if (!pinfo->fd->flags.visited)
1694                                                 must_desegment = TRUE;
1695
1696                                         /* The stuff we couldn't dissect
1697                                            must have come from this segment,
1698                                            so it's all in "tvb".
1699
1700                                            "pinfo->desegment_offset" is
1701                                            relative to the beginning of
1702                                            "next_tvb"; we want an offset
1703                                            relative to the beginning of "tvb".
1704
1705                                            First, compute the offset relative
1706                                            to the *end* of "next_tvb" - i.e.,
1707                                            the number of bytes before the end
1708                                            of "next_tvb" at which the
1709                                            subdissector stopped.  That's the
1710                                            length of "next_tvb" minus the
1711                                            offset, relative to the beginning
1712                                            of "next_tvb, at which the
1713                                            subdissector stopped.
1714                                         */
1715                                         deseg_offset =
1716                                             ipfd_head->datalen - pinfo->desegment_offset;
1717
1718                                         /* "tvb" and "next_tvb" end at the
1719                                            same byte of data, so the offset
1720                                            relative to the end of "next_tvb"
1721                                            of the byte at which we stopped
1722                                            is also the offset relative to
1723                                            the end of "tvb" of the byte at
1724                                            which we stopped.
1725
1726                                            Convert that back into an offset
1727                                            relative to the beginninng of
1728                                            "tvb", by taking the length of
1729                                            "tvb" and subtracting the offset
1730                                            relative to the end.
1731                                         */
1732                                         deseg_offset=tvb_reported_length(tvb) - deseg_offset;
1733                                 }
1734                         }
1735                 }
1736         }
1737
1738         if (must_desegment) {
1739             tcp_segment_key *tsk, *new_tsk;
1740
1741             /*
1742              * The sequence number at which the stuff to be desegmented
1743              * starts is the sequence number of the byte at an offset
1744              * of "deseg_offset" into "tvb".
1745              *
1746              * The sequence number of the byte at an offset of "offset"
1747              * is "seq", i.e. the starting sequence number of this
1748              * segment, so the sequence number of the byte at
1749              * "deseg_offset" is "seq + (deseg_offset - offset)".
1750              */
1751             deseg_seq = seq + (deseg_offset - offset);
1752
1753             /*
1754              * XXX - how do we detect out-of-order transmissions?
1755              * We can't just check for "nxtseq" being greater than
1756              * "tsk->start_seq"; for now, we check for the difference
1757              * being less than a megabyte, but this is a really
1758              * gross hack - we really need to handle out-of-order
1759              * transmissions correctly.
1760              */
1761             if ((nxtseq - deseg_seq) <= 1024*1024) {
1762                 /* OK, subdissector wants us to desegment
1763                    some data before it can process it. Add
1764                    what remains of this packet and set
1765                    up next packet/sequence number as well.
1766
1767                    We must remember this segment
1768                 */
1769                 tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1770                 tsk->src = g_mem_chunk_alloc(tcp_segment_address_chunk);
1771                 COPY_ADDRESS(tsk->src, &pinfo->src);
1772                 tsk->dst = g_mem_chunk_alloc(tcp_segment_address_chunk);
1773                 COPY_ADDRESS(tsk->dst, &pinfo->dst);
1774                 tsk->seq = deseg_seq;
1775                 tsk->start_seq = tsk->seq;
1776                 tsk->tot_len = nxtseq - tsk->start_seq + pinfo->desegment_len;
1777                 tsk->first_frame = pinfo->fd->num;
1778                 tsk->sport=sport;
1779                 tsk->dport=dport;
1780                 g_hash_table_insert(tcp_segment_table, tsk, tsk);
1781
1782                 /* Add portion of segment unprocessed by the subdissector
1783                    to defragmentation lists */
1784                 fragment_add(tvb, deseg_offset, pinfo, tsk->first_frame,
1785                     tcp_fragment_table,
1786                     tsk->seq - tsk->start_seq,
1787                     nxtseq - tsk->start_seq,
1788                     LT_SEQ (nxtseq, tsk->start_seq + tsk->tot_len));
1789
1790                 /* this is the next segment in the sequence we want */
1791                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1792                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1793                 new_tsk->seq = nxtseq;
1794                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1795             }
1796         }
1797
1798         if (!called_dissector || pinfo->desegment_len != 0) {
1799                 if (ipfd_head != NULL && ipfd_head->reassembled_in != 0) {
1800                         /*
1801                          * We know what frame this PDU is reassembled in;
1802                          * let the user know.
1803                          */
1804                         proto_tree_add_uint(tcp_tree, hf_tcp_reassembled_in,
1805                             tvb, 0, 0, ipfd_head->reassembled_in);
1806                 }
1807
1808                 /*
1809                  * Either we didn't call the subdissector at all (i.e.,
1810                  * this is a segment that contains the middle of a
1811                  * higher-level PDU, but contains neither the beginning
1812                  * nor the end), or the subdissector couldn't dissect it
1813                  * all, as some data was missing (i.e., it set
1814                  * "pinfo->desegment_len" to the amount of additional
1815                  * data it needs).
1816                  */
1817                 if (pinfo->desegment_offset == 0) {
1818                         /*
1819                          * It couldn't, in fact, dissect any of it (the
1820                          * first byte it couldn't dissect is at an offset
1821                          * of "pinfo->desegment_offset" from the beginning
1822                          * of the payload, and that's 0).
1823                          * Just mark this as TCP.
1824                          */
1825                         if (check_col(pinfo->cinfo, COL_PROTOCOL)){
1826                                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
1827                         }
1828                         if (check_col(pinfo->cinfo, COL_INFO)){
1829                                 col_set_str(pinfo->cinfo, COL_INFO, "[Desegmented TCP]");
1830                         }
1831                 }
1832
1833                 /*
1834                  * Show what's left in the packet as just raw TCP segment
1835                  * data.
1836                  * XXX - remember what protocol the last subdissector
1837                  * was, and report it as a continuation of that, instead?
1838                  */
1839                 nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
1840                 proto_tree_add_text(tcp_tree, tvb, deseg_offset, -1,
1841                     "TCP segment data (%u byte%s)", nbytes,
1842                     plurality(nbytes, "", "s"));
1843         }
1844         pinfo->can_desegment=0;
1845         pinfo->desegment_offset = 0;
1846         pinfo->desegment_len = 0;
1847 }
1848
1849 /*
1850  * Loop for dissecting PDUs within a TCP stream; assumes that a PDU
1851  * consists of a fixed-length chunk of data that contains enough information
1852  * to determine the length of the PDU, followed by rest of the PDU.
1853  *
1854  * The first three arguments are the arguments passed to the dissector
1855  * that calls this routine.
1856  *
1857  * "proto_desegment" is the dissector's flag controlling whether it should
1858  * desegment PDUs that cross TCP segment boundaries.
1859  *
1860  * "fixed_len" is the length of the fixed-length part of the PDU.
1861  *
1862  * "get_pdu_len()" is a routine called to get the length of the PDU from
1863  * the fixed-length part of the PDU; it's passed "tvb" and "offset".
1864  *
1865  * "dissect_pdu()" is the routine to dissect a PDU.
1866  */
1867 void
1868 tcp_dissect_pdus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
1869                  gboolean proto_desegment, guint fixed_len,
1870                  guint (*get_pdu_len)(tvbuff_t *, int),
1871                  void (*dissect_pdu)(tvbuff_t *, packet_info *, proto_tree *))
1872 {
1873   volatile int offset = 0;
1874   int offset_before;
1875   guint length_remaining;
1876   guint plen;
1877   guint length;
1878   tvbuff_t *next_tvb;
1879
1880   while (tvb_reported_length_remaining(tvb, offset) != 0) {
1881     /*
1882      * We use "tvb_ensure_length_remaining()" to make sure there actually
1883      * *is* data remaining.  The protocol we're handling could conceivably
1884      * consists of a sequence of fixed-length PDUs, and therefore the
1885      * "get_pdu_len" routine might not actually fetch anything from
1886      * the tvbuff, and thus might not cause an exception to be thrown if
1887      * we've run past the end of the tvbuff.
1888      *
1889      * This means we're guaranteed that "length_remaining" is positive.
1890      */
1891     length_remaining = tvb_ensure_length_remaining(tvb, offset);
1892
1893     /*
1894      * Can we do reassembly?
1895      */
1896     if (proto_desegment && pinfo->can_desegment) {
1897       /*
1898        * Yes - is the fixed-length part of the PDU split across segment
1899        * boundaries?
1900        */
1901       if (length_remaining < fixed_len) {
1902         /*
1903          * Yes.  Tell the TCP dissector where the data for this message
1904          * starts in the data it handed us, and how many more bytes we
1905          * need, and return.
1906          */
1907         pinfo->desegment_offset = offset;
1908         pinfo->desegment_len = fixed_len - length_remaining;
1909         return;
1910       }
1911     }
1912
1913     /*
1914      * Get the length of the PDU.
1915      */
1916     plen = (*get_pdu_len)(tvb, offset);
1917     if (plen < fixed_len) {
1918       /*
1919        * The PDU length from the fixed-length portion probably didn't
1920        * include the fixed-length portion's length, and was probably so
1921        * large that the total length overflowed.
1922        *
1923        * Report this as an error.
1924        */
1925       show_reported_bounds_error(tvb, pinfo, tree);
1926       return;
1927     }
1928
1929     /*
1930      * Can we do reassembly?
1931      */
1932     if (proto_desegment && pinfo->can_desegment) {
1933       /*
1934        * Yes - is the PDU split across segment boundaries?
1935        */
1936       if (length_remaining < plen) {
1937         /*
1938          * Yes.  Tell the TCP dissector where the data for this message
1939          * starts in the data it handed us, and how many more bytes we
1940          * need, and return.
1941          */
1942         pinfo->desegment_offset = offset;
1943         pinfo->desegment_len = plen - length_remaining;
1944         return;
1945       }
1946     }
1947
1948     /*
1949      * Construct a tvbuff containing the amount of the payload we have
1950      * available.  Make its reported length the amount of data in the PDU.
1951      *
1952      * XXX - if reassembly isn't enabled. the subdissector will throw a
1953      * BoundsError exception, rather than a ReportedBoundsError exception.
1954      * We really want a tvbuff where the length is "length", the reported
1955      * length is "plen", and the "if the snapshot length were infinite"
1956      * length is the minimum of the reported length of the tvbuff handed
1957      * to us and "plen", with a new type of exception thrown if the offset
1958      * is within the reported length but beyond that third length, with
1959      * that exception getting the "Unreassembled Packet" error.
1960      */
1961     length = length_remaining;
1962     if (length > plen)
1963         length = plen;
1964     next_tvb = tvb_new_subset(tvb, offset, length, plen);
1965
1966     /*
1967      * Dissect the PDU.
1968      *
1969      * Catch the ReportedBoundsError exception; if this particular message
1970      * happens to get a ReportedBoundsError exception, that doesn't mean
1971      * that we should stop dissecting PDUs within this frame or chunk of
1972      * reassembled data.
1973      *
1974      * If it gets a BoundsError, we can stop, as there's nothing more to
1975      * see, so we just re-throw it.
1976      */
1977     TRY {
1978       (*dissect_pdu)(next_tvb, pinfo, tree);
1979     }
1980     CATCH(BoundsError) {
1981       RETHROW;
1982     }
1983     CATCH(ReportedBoundsError) {
1984       show_reported_bounds_error(tvb, pinfo, tree);
1985     }
1986     ENDTRY;
1987
1988     /*
1989      * Step to the next PDU.
1990      * Make sure we don't overflow.
1991      */
1992     offset_before = offset;
1993     offset += plen;
1994     if (offset <= offset_before)
1995       break;
1996   }
1997 }
1998
1999 static void
2000 tcp_info_append_uint(packet_info *pinfo, const char *abbrev, guint32 val)
2001 {
2002   if (check_col(pinfo->cinfo, COL_INFO))
2003     col_append_fstr(pinfo->cinfo, COL_INFO, " %s=%u", abbrev, val);
2004 }
2005
2006 static void
2007 dissect_tcpopt_maxseg(const ip_tcp_opt *optp, tvbuff_t *tvb,
2008     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2009 {
2010   guint16 mss;
2011
2012   mss = tvb_get_ntohs(tvb, offset + 2);
2013   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_mss, tvb, offset,
2014                                 optlen, TRUE);
2015   proto_tree_add_uint_format(opt_tree, hf_tcp_option_mss_val, tvb, offset,
2016                              optlen, mss, "%s: %u bytes", optp->name, mss);
2017   tcp_info_append_uint(pinfo, "MSS", mss);
2018 }
2019
2020 static void
2021 dissect_tcpopt_wscale(const ip_tcp_opt *optp, tvbuff_t *tvb,
2022     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2023 {
2024   guint8 ws;
2025
2026   ws = tvb_get_guint8(tvb, offset + 2);
2027   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_wscale, tvb, 
2028                                 offset, optlen, TRUE);
2029   proto_tree_add_uint_format(opt_tree, hf_tcp_option_wscale_val, tvb,
2030                              offset, optlen, ws, "%s: %u (multiply by %u)", 
2031                              optp->name, ws, 1 << ws);
2032   tcp_info_append_uint(pinfo, "WS", ws);
2033   if(!pinfo->fd->flags.visited && tcp_analyze_seq && tcp_relative_seq){
2034     pdu_store_window_scale_option(pinfo, ws);
2035   }
2036 }
2037
2038 static void
2039 dissect_tcpopt_sack(const ip_tcp_opt *optp, tvbuff_t *tvb,
2040     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2041 {
2042   proto_tree *field_tree = NULL;
2043   proto_item *tf;
2044   guint leftedge, rightedge;
2045
2046   tf = proto_tree_add_text(opt_tree, tvb, offset,      optlen, "%s:", optp->name);
2047   offset += 2;  /* skip past type and length */
2048   optlen -= 2;  /* subtract size of type and length */
2049   while (optlen > 0) {
2050     if (field_tree == NULL) {
2051       /* Haven't yet made a subtree out of this option.  Do so. */
2052       field_tree = proto_item_add_subtree(tf, *optp->subtree_index);
2053       proto_tree_add_boolean_hidden(field_tree, hf_tcp_option_sack, tvb, 
2054                                     offset, optlen, TRUE);
2055     }
2056     if (optlen < 4) {
2057       proto_tree_add_text(field_tree, tvb, offset,      optlen,
2058         "(suboption would go past end of option)");
2059       break;
2060     }
2061     leftedge = tvb_get_ntohl(tvb, offset);
2062     proto_tree_add_uint_format(field_tree, hf_tcp_option_sack_sle, tvb, 
2063                                offset, 4, leftedge, 
2064                                "left edge = %u", leftedge);
2065     optlen -= 4;
2066     if (optlen < 4) {
2067       proto_tree_add_text(field_tree, tvb, offset,      optlen,
2068         "(suboption would go past end of option)");
2069       break;
2070     }
2071     /* XXX - check whether it goes past end of packet */
2072     rightedge = tvb_get_ntohl(tvb, offset + 4);
2073     optlen -= 4;
2074     proto_tree_add_uint_format(field_tree, hf_tcp_option_sack_sre, tvb, 
2075                                offset+4, 4, rightedge, 
2076                                "right edge = %u", rightedge);
2077     tcp_info_append_uint(pinfo, "SLE", leftedge);
2078     tcp_info_append_uint(pinfo, "SRE", rightedge);
2079     offset += 8;
2080   }
2081 }
2082
2083 static void
2084 dissect_tcpopt_echo(const ip_tcp_opt *optp, tvbuff_t *tvb,
2085     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2086 {
2087   guint32 echo;
2088
2089   echo = tvb_get_ntohl(tvb, offset + 2);
2090   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_echo, tvb, offset,
2091                                 optlen, TRUE);
2092   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
2093                         "%s: %u", optp->name, echo);
2094   tcp_info_append_uint(pinfo, "ECHO", echo);
2095 }
2096
2097 static void
2098 dissect_tcpopt_timestamp(const ip_tcp_opt *optp, tvbuff_t *tvb,
2099     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2100 {
2101   guint32 tsv, tser;
2102
2103   tsv = tvb_get_ntohl(tvb, offset + 2);
2104   tser = tvb_get_ntohl(tvb, offset + 6);
2105   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_time_stamp, tvb, 
2106                                 offset, optlen, TRUE);
2107   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
2108     "%s: tsval %u, tsecr %u", optp->name, tsv, tser);
2109   tcp_info_append_uint(pinfo, "TSV", tsv);
2110   tcp_info_append_uint(pinfo, "TSER", tser);
2111 }
2112
2113 static void
2114 dissect_tcpopt_cc(const ip_tcp_opt *optp, tvbuff_t *tvb,
2115     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2116 {
2117   guint32 cc;
2118
2119   cc = tvb_get_ntohl(tvb, offset + 2);
2120   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_cc, tvb, offset,
2121                                 optlen, TRUE);
2122   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
2123                         "%s: %u", optp->name, cc);
2124   tcp_info_append_uint(pinfo, "CC", cc);
2125 }
2126
2127 static const ip_tcp_opt tcpopts[] = {
2128   {
2129     TCPOPT_EOL,
2130     "EOL",
2131     NULL,
2132     NO_LENGTH,
2133     0,
2134     NULL,
2135   },
2136   {
2137     TCPOPT_NOP,
2138     "NOP",
2139     NULL,
2140     NO_LENGTH,
2141     0,
2142     NULL,
2143   },
2144   {
2145     TCPOPT_MSS,
2146     "Maximum segment size",
2147     NULL,
2148     FIXED_LENGTH,
2149     TCPOLEN_MSS,
2150     dissect_tcpopt_maxseg
2151   },
2152   {
2153     TCPOPT_WINDOW,
2154     "Window scale",
2155     NULL,
2156     FIXED_LENGTH,
2157     TCPOLEN_WINDOW,
2158     dissect_tcpopt_wscale
2159   },
2160   {
2161     TCPOPT_SACK_PERM,
2162     "SACK permitted",
2163     NULL,
2164     FIXED_LENGTH,
2165     TCPOLEN_SACK_PERM,
2166     NULL,
2167   },
2168   {
2169     TCPOPT_SACK,
2170     "SACK",
2171     &ett_tcp_option_sack,
2172     VARIABLE_LENGTH,
2173     TCPOLEN_SACK_MIN,
2174     dissect_tcpopt_sack
2175   },
2176   {
2177     TCPOPT_ECHO,
2178     "Echo",
2179     NULL,
2180     FIXED_LENGTH,
2181     TCPOLEN_ECHO,
2182     dissect_tcpopt_echo
2183   },
2184   {
2185     TCPOPT_ECHOREPLY,
2186     "Echo reply",
2187     NULL,
2188     FIXED_LENGTH,
2189     TCPOLEN_ECHOREPLY,
2190     dissect_tcpopt_echo
2191   },
2192   {
2193     TCPOPT_TIMESTAMP,
2194     "Time stamp",
2195     NULL,
2196     FIXED_LENGTH,
2197     TCPOLEN_TIMESTAMP,
2198     dissect_tcpopt_timestamp
2199   },
2200   {
2201     TCPOPT_CC,
2202     "CC",
2203     NULL,
2204     FIXED_LENGTH,
2205     TCPOLEN_CC,
2206     dissect_tcpopt_cc
2207   },
2208   {
2209     TCPOPT_CCNEW,
2210     "CC.NEW",
2211     NULL,
2212     FIXED_LENGTH,
2213     TCPOLEN_CCNEW,
2214     dissect_tcpopt_cc
2215   },
2216   {
2217     TCPOPT_CCECHO,
2218     "CC.ECHO",
2219     NULL,
2220     FIXED_LENGTH,
2221     TCPOLEN_CCECHO,
2222     dissect_tcpopt_cc
2223   },
2224   {
2225     TCPOPT_MD5,
2226     "TCP MD5 signature",
2227     NULL,
2228     FIXED_LENGTH,
2229     TCPOLEN_MD5,
2230     NULL
2231   }
2232 };
2233
2234 #define N_TCP_OPTS      (sizeof tcpopts / sizeof tcpopts[0])
2235
2236 /* Determine if there is a sub-dissector and call it.  This has been */
2237 /* separated into a stand alone routine to other protocol dissectors */
2238 /* can call to it, ie. socks    */
2239
2240 static gboolean try_heuristic_first = FALSE;
2241
2242 void
2243 decode_tcp_ports(tvbuff_t *tvb, int offset, packet_info *pinfo,
2244         proto_tree *tree, int src_port, int dst_port, guint32 nxtseq)
2245 {
2246   tvbuff_t *next_tvb;
2247   int low_port, high_port;
2248
2249 /*qqq   see if it is an unaligned PDU */
2250   if(nxtseq && tcp_analyze_seq && (!tcp_desegment)){
2251     guint32 seq;
2252     seq=nxtseq-tvb_reported_length_remaining(tvb, offset);
2253     offset=scan_for_next_pdu(pinfo, offset, seq, nxtseq);
2254   }
2255
2256   next_tvb = tvb_new_subset(tvb, offset, -1, -1);
2257
2258 /* determine if this packet is part of a conversation and call dissector */
2259 /* for the conversation if available */
2260
2261   if (try_conversation_dissector(&pinfo->src, &pinfo->dst, PT_TCP,
2262                 src_port, dst_port, next_tvb, pinfo, tree))
2263     goto end_decode_tcp_ports;
2264
2265   if (try_heuristic_first) {
2266     /* do lookup with the heuristic subdissector table */
2267     if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree))
2268        goto end_decode_tcp_ports;
2269   }
2270
2271   /* Do lookups with the subdissector table.
2272      We try the port number with the lower value first, followed by the
2273      port number with the higher value.  This means that, for packets
2274      where a dissector is registered for *both* port numbers:
2275
2276         1) we pick the same dissector for traffic going in both directions;
2277
2278         2) we prefer the port number that's more likely to be the right
2279            one (as that prefers well-known ports to reserved ports);
2280
2281      although there is, of course, no guarantee that any such strategy
2282      will always pick the right port number.
2283
2284      XXX - we ignore port numbers of 0, as some dissectors use a port
2285      number of 0 to disable the port. */
2286   if (src_port > dst_port) {
2287     low_port = dst_port;
2288     high_port = src_port;
2289   } else {
2290     low_port = src_port;
2291     high_port = dst_port;
2292   }
2293   if (low_port != 0 &&
2294       dissector_try_port(subdissector_table, low_port, next_tvb, pinfo, tree))
2295     goto end_decode_tcp_ports;
2296   if (high_port != 0 &&
2297       dissector_try_port(subdissector_table, high_port, next_tvb, pinfo, tree))
2298     goto end_decode_tcp_ports;
2299
2300   if (!try_heuristic_first) {
2301     /* do lookup with the heuristic subdissector table */
2302     if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree))
2303        goto end_decode_tcp_ports;
2304   }
2305
2306   /* Oh, well, we don't know this; dissect it as data. */
2307   call_dissector(data_handle,next_tvb, pinfo, tree);
2308   return;
2309
2310 end_decode_tcp_ports:
2311   /* if !visited, check want_pdu_tracking and store it in table */
2312   /* XXX fix nxtseq so that it always has valid content and skip the ==0 check */
2313   if((!pinfo->fd->flags.visited) && nxtseq && tcp_analyze_seq && pinfo->want_pdu_tracking){
2314     pdu_store_sequencenumber_of_next_pdu(pinfo, nxtseq+pinfo->bytes_until_next_pdu);
2315   }
2316
2317 }
2318
2319
2320 static void
2321 dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2322 {
2323   guint8  th_off_x2; /* combines th_off and th_x2 */
2324   guint16 th_sum;
2325   guint16 th_urp;
2326   proto_tree *tcp_tree = NULL, *field_tree = NULL;
2327   proto_item *ti = NULL, *tf;
2328   int        offset = 0;
2329   gchar      flags[64] = "<None>";
2330   gchar     *fstr[] = {"FIN", "SYN", "RST", "PSH", "ACK", "URG", "ECN", "CWR" };
2331   gint       fpos = 0, i;
2332   guint      bpos;
2333   guint      optlen;
2334   guint32    nxtseq = 0;
2335   guint      reported_len;
2336   vec_t      cksum_vec[4];
2337   guint32    phdr[2];
2338   guint16    computed_cksum;
2339   guint      length_remaining;
2340   gboolean   desegment_ok;
2341   struct tcpinfo tcpinfo;
2342   gboolean   save_fragmented;
2343   static struct tcpheader tcphstruct[4], *tcph;
2344   static int tcph_count=0;
2345
2346   tcph_count++;
2347   if(tcph_count>=4){
2348      tcph_count=0;
2349   }
2350   tcph=&tcphstruct[tcph_count];
2351   SET_ADDRESS(&tcph->ip_src, pinfo->src.type, pinfo->src.len, pinfo->src.data);
2352   SET_ADDRESS(&tcph->ip_dst, pinfo->dst.type, pinfo->dst.len, pinfo->dst.data);
2353
2354   if (check_col(pinfo->cinfo, COL_PROTOCOL))
2355     col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
2356
2357   /* Clear out the Info column. */
2358   if (check_col(pinfo->cinfo, COL_INFO))
2359     col_clear(pinfo->cinfo, COL_INFO);
2360
2361   tcph->th_sport = tvb_get_ntohs(tvb, offset);
2362   tcph->th_dport = tvb_get_ntohs(tvb, offset + 2);
2363   if (check_col(pinfo->cinfo, COL_INFO)) {
2364     col_append_fstr(pinfo->cinfo, COL_INFO, "%s > %s",
2365       get_tcp_port(tcph->th_sport), get_tcp_port(tcph->th_dport));
2366   }
2367   if (tree) {
2368     if (tcp_summary_in_tree) {
2369             ti = proto_tree_add_protocol_format(tree, proto_tcp, tvb, 0, -1,
2370                 "Transmission Control Protocol, Src Port: %s (%u), Dst Port: %s (%u)",
2371                 get_tcp_port(tcph->th_sport), tcph->th_sport,
2372                 get_tcp_port(tcph->th_dport), tcph->th_dport);
2373     }
2374     else {
2375             ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, FALSE);
2376     }
2377     tcp_tree = proto_item_add_subtree(ti, ett_tcp);
2378     proto_tree_add_uint_format(tcp_tree, hf_tcp_srcport, tvb, offset, 2, tcph->th_sport,
2379         "Source port: %s (%u)", get_tcp_port(tcph->th_sport), tcph->th_sport);
2380     proto_tree_add_uint_format(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, tcph->th_dport,
2381         "Destination port: %s (%u)", get_tcp_port(tcph->th_dport), tcph->th_dport);
2382     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset, 2, tcph->th_sport);
2383     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, tcph->th_dport);
2384   }
2385
2386   /* Set the source and destination port numbers as soon as we get them,
2387      so that they're available to the "Follow TCP Stream" code even if
2388      we throw an exception dissecting the rest of the TCP header. */
2389   pinfo->ptype = PT_TCP;
2390   pinfo->srcport = tcph->th_sport;
2391   pinfo->destport = tcph->th_dport;
2392
2393   tcph->th_seq = tvb_get_ntohl(tvb, offset + 4);
2394   tcph->th_ack = tvb_get_ntohl(tvb, offset + 8);
2395   th_off_x2 = tvb_get_guint8(tvb, offset + 12);
2396   tcph->th_flags = tvb_get_guint8(tvb, offset + 13);
2397   tcph->th_win = tvb_get_ntohs(tvb, offset + 14);
2398   tcph->th_hlen = hi_nibble(th_off_x2) * 4;  /* TCP header length, in bytes */
2399
2400   /*
2401    * If we've been handed an IP fragment, we don't know how big the TCP
2402    * segment is, so don't do anything that requires that we know that.
2403    *
2404    * The same applies if we're part of an error packet.  (XXX - if the
2405    * ICMP and ICMPv6 dissectors could set a "this is how big the IP
2406    * header says it is" length in the tvbuff, we could use that; such
2407    * a length might also be useful for handling packets where the IP
2408    * length is bigger than the actual data available in the frame; the
2409    * dissectors should trust that length, and then throw a
2410    * ReportedBoundsError exception when they go past the end of the frame.)
2411    *
2412    * We also can't determine the segment length if the reported length
2413    * of the TCP packet is less than the TCP header length.
2414    */
2415   reported_len = tvb_reported_length(tvb);
2416
2417   if (!pinfo->fragmented && !pinfo->in_error_pkt) {
2418     if (reported_len < tcph->th_hlen) {
2419       proto_tree_add_text(tcp_tree, tvb, offset, 0,
2420         "Short segment. Segment/fragment does not contain a full TCP header"
2421         " (might be NMAP or someone else deliberately sending unusual packets)");
2422       tcph->th_have_seglen = FALSE;
2423     } else {
2424       /* Compute the length of data in this segment. */
2425       tcph->th_seglen = reported_len - tcph->th_hlen;
2426       tcph->th_have_seglen = TRUE;
2427
2428       if (tree) { /* Add the seglen as an invisible field */
2429
2430         proto_tree_add_uint_hidden(ti, hf_tcp_len, tvb, offset, 4, tcph->th_seglen);
2431
2432       }
2433
2434       /* handle TCP seq# analysis parse all new segments we see */
2435       if(tcp_analyze_seq){
2436           if(!(pinfo->fd->flags.visited)){
2437               tcp_analyze_sequence_number(pinfo, tcph->th_seq, tcph->th_ack, tcph->th_seglen, tcph->th_flags, tcph->th_win);
2438           }
2439           if(tcp_relative_seq){
2440               tcp_get_relative_seq_ack(pinfo->fd->num, &(tcph->th_seq), &(tcph->th_ack), &(tcph->th_win));
2441           }
2442       }
2443
2444       /* Compute the sequence number of next octet after this segment. */
2445       nxtseq = tcph->th_seq + tcph->th_seglen;
2446     }
2447   } else
2448     tcph->th_have_seglen = FALSE;
2449
2450   if (check_col(pinfo->cinfo, COL_INFO) || tree) {
2451     for (i = 0; i < 8; i++) {
2452       bpos = 1 << i;
2453       if (tcph->th_flags & bpos) {
2454         if (fpos) {
2455           strcpy(&flags[fpos], ", ");
2456           fpos += 2;
2457         }
2458         strcpy(&flags[fpos], fstr[i]);
2459         fpos += 3;
2460       }
2461     }
2462     flags[fpos] = '\0';
2463   }
2464
2465   if (check_col(pinfo->cinfo, COL_INFO)) {
2466     col_append_fstr(pinfo->cinfo, COL_INFO, " [%s] Seq=%u Ack=%u Win=%u",
2467       flags, tcph->th_seq, tcph->th_ack, tcph->th_win);
2468   }
2469
2470   if (tree) {
2471     if (tcp_summary_in_tree) {
2472       proto_item_append_text(ti, ", Seq: %u", tcph->th_seq);
2473     }
2474     proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq);
2475   }
2476
2477   if (tcph->th_hlen < TCPH_MIN_LEN) {
2478     /* Give up at this point; we put the source and destination port in
2479        the tree, before fetching the header length, so that they'll
2480        show up if this is in the failing packet in an ICMP error packet,
2481        but it's now time to give up if the header length is bogus. */
2482     if (check_col(pinfo->cinfo, COL_INFO))
2483       col_append_fstr(pinfo->cinfo, COL_INFO, ", bogus TCP header length (%u, must be at least %u)",
2484         tcph->th_hlen, TCPH_MIN_LEN);
2485     if (tree) {
2486       proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, tcph->th_hlen,
2487        "Header length: %u bytes (bogus, must be at least %u)", tcph->th_hlen,
2488        TCPH_MIN_LEN);
2489     }
2490     return;
2491   }
2492
2493   if (tree) {
2494     if (tcp_summary_in_tree) {
2495       proto_item_append_text(ti, ", Ack: %u", tcph->th_ack);
2496       if (tcph->th_have_seglen)
2497         proto_item_append_text(ti, ", Len: %u", tcph->th_seglen);
2498     }
2499     proto_item_set_len(ti, tcph->th_hlen);
2500     if (tcph->th_have_seglen) {
2501       if (nxtseq != tcph->th_seq) {
2502         proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);
2503       }
2504     }
2505     if (tcph->th_flags & TH_ACK)
2506       proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack);
2507     proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, tcph->th_hlen,
2508         "Header length: %u bytes", tcph->th_hlen);
2509     tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 13, 1,
2510         tcph->th_flags, "Flags: 0x%04x (%s)", tcph->th_flags, flags);
2511     field_tree = proto_item_add_subtree(tf, ett_tcp_flags);
2512     proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, tcph->th_flags);
2513     proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, tcph->th_flags);
2514     proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, tcph->th_flags);
2515     proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, tcph->th_flags);
2516     proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, tcph->th_flags);
2517     proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, tcph->th_flags);
2518     proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, tcph->th_flags);
2519     proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, tcph->th_flags);
2520     proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win);
2521   }
2522
2523   /* Supply the sequence number of the first byte. */
2524   tcpinfo.seq = tcph->th_seq;
2525
2526   /* Assume we'll pass un-reassembled data to subdissectors. */
2527   tcpinfo.is_reassembled = FALSE;
2528
2529   pinfo->private_data = &tcpinfo;
2530
2531   /*
2532    * Assume, initially, that we can't desegment.
2533    */
2534   pinfo->can_desegment = 0;
2535   th_sum = tvb_get_ntohs(tvb, offset + 16);
2536   if (!pinfo->fragmented && tvb_bytes_exist(tvb, 0, reported_len)) {
2537     /* The packet isn't part of an un-reassembled fragmented datagram
2538        and isn't truncated.  This means we have all the data, and thus
2539        can checksum it and, unless it's being returned in an error
2540        packet, are willing to allow subdissectors to request reassembly
2541        on it. */
2542
2543     if (tcp_check_checksum) {
2544       /* We haven't turned checksum checking off; checksum it. */
2545
2546       /* Set up the fields of the pseudo-header. */
2547       cksum_vec[0].ptr = pinfo->src.data;
2548       cksum_vec[0].len = pinfo->src.len;
2549       cksum_vec[1].ptr = pinfo->dst.data;
2550       cksum_vec[1].len = pinfo->dst.len;
2551       cksum_vec[2].ptr = (const guint8 *)&phdr;
2552       switch (pinfo->src.type) {
2553
2554       case AT_IPv4:
2555         phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);
2556         cksum_vec[2].len = 4;
2557         break;
2558
2559       case AT_IPv6:
2560         phdr[0] = g_htonl(reported_len);
2561         phdr[1] = g_htonl(IP_PROTO_TCP);
2562         cksum_vec[2].len = 8;
2563         break;
2564
2565       default:
2566         /* TCP runs only atop IPv4 and IPv6.... */
2567         g_assert_not_reached();
2568         break;
2569       }
2570       cksum_vec[3].ptr = tvb_get_ptr(tvb, offset, reported_len);
2571       cksum_vec[3].len = reported_len;
2572       computed_cksum = in_cksum(&cksum_vec[0], 4);
2573       if (computed_cksum == 0) {
2574         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2575           offset + 16, 2, th_sum, "Checksum: 0x%04x (correct)", th_sum);
2576
2577         /* Checksum is valid, so we're willing to desegment it. */
2578         desegment_ok = TRUE;
2579       } else {
2580         proto_tree_add_boolean_hidden(tcp_tree, hf_tcp_checksum_bad, tvb,
2581            offset + 16, 2, TRUE);
2582         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2583            offset + 16, 2, th_sum,
2584            "Checksum: 0x%04x (incorrect, should be 0x%04x)", th_sum,
2585            in_cksum_shouldbe(th_sum, computed_cksum));
2586
2587         /* Checksum is invalid, so we're not willing to desegment it. */
2588         desegment_ok = FALSE;
2589         pinfo->noreassembly_reason = " (incorrect TCP checksum)";
2590       }
2591     } else {
2592       proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2593          offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
2594
2595       /* We didn't check the checksum, and don't care if it's valid,
2596          so we're willing to desegment it. */
2597       desegment_ok = TRUE;
2598     }
2599   } else {
2600     /* We don't have all the packet data, so we can't checksum it... */
2601     proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2602        offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
2603
2604     /* ...and aren't willing to desegment it. */
2605     desegment_ok = FALSE;
2606   }
2607
2608   if (desegment_ok) {
2609     /* We're willing to desegment this.  Is desegmentation enabled? */
2610     if (tcp_desegment) {
2611       /* Yes - is this segment being returned in an error packet? */
2612       if (!pinfo->in_error_pkt) {
2613         /* No - indicate that we will desegment.
2614            We do NOT want to desegment segments returned in error
2615            packets, as they're not part of a TCP connection. */
2616         pinfo->can_desegment = 2;
2617       }
2618     }
2619   }
2620
2621   if (tcph->th_flags & TH_URG) {
2622     th_urp = tvb_get_ntohs(tvb, offset + 18);
2623     /* Export the urgent pointer, for the benefit of protocols such as
2624        rlogin. */
2625     tcpinfo.urgent = TRUE;
2626     tcpinfo.urgent_pointer = th_urp;
2627     if (check_col(pinfo->cinfo, COL_INFO))
2628       col_append_fstr(pinfo->cinfo, COL_INFO, " Urg=%u", th_urp);
2629     if (tcp_tree != NULL)
2630       proto_tree_add_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, th_urp);
2631   } else
2632     tcpinfo.urgent = FALSE;
2633
2634   if (tcph->th_have_seglen) {
2635     if (check_col(pinfo->cinfo, COL_INFO))
2636       col_append_fstr(pinfo->cinfo, COL_INFO, " Len=%u", tcph->th_seglen);
2637   }
2638
2639   /* Decode TCP options, if any. */
2640   if (tree && tcph->th_hlen > TCPH_MIN_LEN) {
2641     /* There's more than just the fixed-length header.  Decode the
2642        options. */
2643     optlen = tcph->th_hlen - TCPH_MIN_LEN; /* length of options, in bytes */
2644     tf = proto_tree_add_text(tcp_tree, tvb, offset +  20, optlen,
2645       "Options: (%u bytes)", optlen);
2646     field_tree = proto_item_add_subtree(tf, ett_tcp_options);
2647     dissect_ip_tcp_options(tvb, offset + 20, optlen,
2648       tcpopts, N_TCP_OPTS, TCPOPT_EOL, pinfo, field_tree);
2649   }
2650
2651   /* Skip over header + options */
2652   offset += tcph->th_hlen;
2653
2654   /* Check the packet length to see if there's more data
2655      (it could be an ACK-only packet) */
2656   length_remaining = tvb_length_remaining(tvb, offset);
2657
2658   if (tcph->th_have_seglen) {
2659     if( data_out_file ) {
2660       reassemble_tcp( tcph->th_seq,             /* sequence number */
2661           tcph->th_seglen,                      /* data length */
2662           tvb_get_ptr(tvb, offset, length_remaining),   /* data */
2663           length_remaining,             /* captured data length */
2664           ( tcph->th_flags & TH_SYN ),          /* is syn set? */
2665           &pinfo->net_src,
2666           &pinfo->net_dst,
2667           pinfo->srcport,
2668           pinfo->destport);
2669     }
2670   }
2671
2672   /*
2673    * XXX - what, if any, of this should we do if this is included in an
2674    * error packet?  It might be nice to see the details of the packet
2675    * that caused the ICMP error, but it might not be nice to have the
2676    * dissector update state based on it.
2677    * Also, we probably don't want to run TCP taps on those packets.
2678    */
2679   if (length_remaining != 0) {
2680     if (tcph->th_flags & TH_RST) {
2681       /*
2682        * RFC1122 says:
2683        *
2684        *        4.2.2.12  RST Segment: RFC-793 Section 3.4
2685        *
2686        *          A TCP SHOULD allow a received RST segment to include data.
2687        *
2688        *          DISCUSSION
2689        *               It has been suggested that a RST segment could contain
2690        *               ASCII text that encoded and explained the cause of the
2691        *               RST.  No standard has yet been established for such
2692        *               data.
2693        *
2694        * so for segments with RST we just display the data as text.
2695        */
2696       proto_tree_add_text(tcp_tree, tvb, offset, length_remaining,
2697                             "Reset cause: %s",
2698                             tvb_format_text(tvb, offset, length_remaining));
2699     } else {
2700       /* Can we desegment this segment? */
2701       if (pinfo->can_desegment) {
2702         /* Yes. */
2703         desegment_tcp(tvb, pinfo, offset, tcph->th_seq, nxtseq, tcph->th_sport, tcph->th_dport, tree, tcp_tree);
2704       } else {
2705         /* No - just call the subdissector.
2706            Mark this as fragmented, so if somebody throws an exception,
2707            we don't report it as a malformed frame. */
2708         save_fragmented = pinfo->fragmented;
2709         pinfo->fragmented = TRUE;
2710         decode_tcp_ports(tvb, offset, pinfo, tree, tcph->th_sport, tcph->th_dport, nxtseq);
2711         pinfo->fragmented = save_fragmented;
2712       }
2713     }
2714   }
2715
2716   /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/
2717   if(tcp_analyze_seq){
2718       tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree);
2719   }
2720   tap_queue_packet(tcp_tap, pinfo, tcph);
2721 }
2722
2723 void
2724 proto_register_tcp(void)
2725 {
2726         static hf_register_info hf[] = {
2727
2728                 { &hf_tcp_srcport,
2729                 { "Source Port",                "tcp.srcport", FT_UINT16, BASE_DEC, NULL, 0x0,
2730                         "", HFILL }},
2731
2732                 { &hf_tcp_dstport,
2733                 { "Destination Port",           "tcp.dstport", FT_UINT16, BASE_DEC, NULL, 0x0,
2734                         "", HFILL }},
2735
2736                 { &hf_tcp_port,
2737                 { "Source or Destination Port", "tcp.port", FT_UINT16, BASE_DEC, NULL, 0x0,
2738                         "", HFILL }},
2739
2740                 { &hf_tcp_seq,
2741                 { "Sequence number",            "tcp.seq", FT_UINT32, BASE_DEC, NULL, 0x0,
2742                         "", HFILL }},
2743
2744                 { &hf_tcp_nxtseq,
2745                 { "Next sequence number",       "tcp.nxtseq", FT_UINT32, BASE_DEC, NULL, 0x0,
2746                         "", HFILL }},
2747
2748                 { &hf_tcp_ack,
2749                 { "Acknowledgement number",     "tcp.ack", FT_UINT32, BASE_DEC, NULL, 0x0,
2750                         "", HFILL }},
2751
2752                 { &hf_tcp_hdr_len,
2753                 { "Header Length",              "tcp.hdr_len", FT_UINT8, BASE_DEC, NULL, 0x0,
2754                         "", HFILL }},
2755
2756                 { &hf_tcp_flags,
2757                 { "Flags",                      "tcp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
2758                         "", HFILL }},
2759
2760                 { &hf_tcp_flags_cwr,
2761                 { "Congestion Window Reduced (CWR)",                    "tcp.flags.cwr", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_CWR,
2762                         "", HFILL }},
2763
2764                 { &hf_tcp_flags_ecn,
2765                 { "ECN-Echo",                   "tcp.flags.ecn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ECN,
2766                         "", HFILL }},
2767
2768                 { &hf_tcp_flags_urg,
2769                 { "Urgent",                     "tcp.flags.urg", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_URG,
2770                         "", HFILL }},
2771
2772                 { &hf_tcp_flags_ack,
2773                 { "Acknowledgment",             "tcp.flags.ack", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ACK,
2774                         "", HFILL }},
2775
2776                 { &hf_tcp_flags_push,
2777                 { "Push",                       "tcp.flags.push", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_PUSH,
2778                         "", HFILL }},
2779
2780                 { &hf_tcp_flags_reset,
2781                 { "Reset",                      "tcp.flags.reset", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_RST,
2782                         "", HFILL }},
2783
2784                 { &hf_tcp_flags_syn,
2785                 { "Syn",                        "tcp.flags.syn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_SYN,
2786                         "", HFILL }},
2787
2788                 { &hf_tcp_flags_fin,
2789                 { "Fin",                        "tcp.flags.fin", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_FIN,
2790                         "", HFILL }},
2791
2792                 /* 32 bits so we can present some values adjusted to window scaling */
2793                 { &hf_tcp_window_size,
2794                 { "Window size",                "tcp.window_size", FT_UINT32, BASE_DEC, NULL, 0x0,
2795                         "", HFILL }},
2796
2797                 { &hf_tcp_checksum,
2798                 { "Checksum",                   "tcp.checksum", FT_UINT16, BASE_HEX, NULL, 0x0,
2799                         "", HFILL }},
2800
2801                 { &hf_tcp_checksum_bad,
2802                 { "Bad Checksum",               "tcp.checksum_bad", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2803                         "", HFILL }},
2804
2805                 { &hf_tcp_analysis_flags,
2806                 { "TCP Analysis Flags",         "tcp.analysis.flags", FT_NONE, BASE_NONE, NULL, 0x0,
2807                         "This frame has some of the TCP analysis flags set", HFILL }},
2808
2809                 { &hf_tcp_analysis_retransmission,
2810                 { "Retransmission",             "tcp.analysis.retransmission", FT_NONE, BASE_NONE, NULL, 0x0,
2811                         "This frame is a suspected TCP retransmission", HFILL }},
2812
2813                 { &hf_tcp_analysis_fast_retransmission,
2814                 { "Fast Retransmission",                "tcp.analysis.fast_retransmission", FT_NONE, BASE_NONE, NULL, 0x0,
2815                         "This frame is a suspected TCP fast retransmission", HFILL }},
2816
2817                 { &hf_tcp_analysis_out_of_order,
2818                 { "Out Of Order",               "tcp.analysis.out_of_order", FT_NONE, BASE_NONE, NULL, 0x0,
2819                         "This frame is a suspected Out-Of-Order segment", HFILL }},
2820
2821                 { &hf_tcp_analysis_lost_packet,
2822                 { "Previous Segment Lost",              "tcp.analysis.lost_segment", FT_NONE, BASE_NONE, NULL, 0x0,
2823                         "A segment before this one was lost from the capture", HFILL }},
2824
2825                 { &hf_tcp_analysis_ack_lost_packet,
2826                 { "ACKed Lost Packet",          "tcp.analysis.ack_lost_segment", FT_NONE, BASE_NONE, NULL, 0x0,
2827                         "This frame ACKs a lost segment", HFILL }},
2828
2829                 { &hf_tcp_analysis_keep_alive,
2830                 { "Keep Alive",         "tcp.analysis.keep_alive", FT_NONE, BASE_NONE, NULL, 0x0,
2831                         "This is a keep-alive segment", HFILL }},
2832
2833                 { &hf_tcp_analysis_keep_alive_ack,
2834                 { "Keep Alive ACK",             "tcp.analysis.keep_alive_ack", FT_NONE, BASE_NONE, NULL, 0x0,
2835                         "This is an ACK to a keep-alive segment", HFILL }},
2836
2837                 { &hf_tcp_analysis_duplicate_ack,
2838                 { "Duplicate ACK",              "tcp.analysis.duplicate_ack", FT_NONE, BASE_NONE, NULL, 0x0,
2839                         "This is a duplicate ACK", HFILL }},
2840
2841                 { &hf_tcp_analysis_duplicate_ack_num,
2842                 { "Duplicate ACK #",            "tcp.analysis.duplicate_ack_num", FT_UINT32, BASE_DEC, NULL, 0x0,
2843                         "This is duplicate ACK number #", HFILL }},
2844
2845                 { &hf_tcp_analysis_duplicate_ack_frame,
2846                 { "Duplicate to the ACK in frame",              "tcp.analysis.duplicate_ack_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
2847                         "This is a duplicate to the ACK in frame #", HFILL }},
2848
2849                 { &hf_tcp_analysis_zero_window_violation,
2850                 { "Zero Window Violation",              "tcp.analysis.zero_window_violation", FT_NONE, BASE_NONE, NULL, 0x0,
2851                         "This is a zero-window violation, an attempt to write >1 byte to a zero-window", HFILL }},
2852
2853                 { &hf_tcp_analysis_zero_window_probe,
2854                 { "Zero Window Probe",          "tcp.analysis.zero_window_probe", FT_NONE, BASE_NONE, NULL, 0x0,
2855                         "This is a zero-window-probe", HFILL }},
2856
2857                 { &hf_tcp_analysis_zero_window,
2858                 { "Zero Window",                "tcp.analysis.zero_window", FT_NONE, BASE_NONE, NULL, 0x0,
2859                         "This is a Zero-Window", HFILL }},
2860
2861                 { &hf_tcp_len,
2862                   { "TCP Segment Len",            "tcp.len", FT_UINT32, BASE_DEC, NULL, 0x0,
2863                     "", HFILL}},
2864
2865                 { &hf_tcp_analysis_acks_frame,
2866                   { "This is an ACK to the segment in frame",            "tcp.analysis.acks_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
2867                     "Which previous segment is this an ACK for", HFILL}},
2868
2869                 { &hf_tcp_analysis_ack_rtt,
2870                   { "The RTT to ACK the segment was",            "tcp.analysis.ack_rtt", FT_RELATIVE_TIME, BASE_NONE, NULL, 0x0,
2871                     "How long time it took to ACK the segment (RTT)", HFILL}},
2872
2873                 { &hf_tcp_urgent_pointer,
2874                 { "Urgent pointer",             "tcp.urgent_pointer", FT_UINT16, BASE_DEC, NULL, 0x0,
2875                         "", HFILL }},
2876
2877                 { &hf_tcp_segment_overlap,
2878                 { "Segment overlap",    "tcp.segment.overlap", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2879                         "Segment overlaps with other segments", HFILL }},
2880
2881                 { &hf_tcp_segment_overlap_conflict,
2882                 { "Conflicting data in segment overlap",        "tcp.segment.overlap.conflict", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2883                         "Overlapping segments contained conflicting data", HFILL }},
2884
2885                 { &hf_tcp_segment_multiple_tails,
2886                 { "Multiple tail segments found",       "tcp.segment.multipletails", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2887                         "Several tails were found when desegmenting the pdu", HFILL }},
2888
2889                 { &hf_tcp_segment_too_long_fragment,
2890                 { "Segment too long",   "tcp.segment.toolongfragment", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2891                         "Segment contained data past end of the pdu", HFILL }},
2892
2893                 { &hf_tcp_segment_error,
2894                 { "Desegmentation error", "tcp.segment.error", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
2895                         "Desegmentation error due to illegal segments", HFILL }},
2896
2897                 { &hf_tcp_segment,
2898                 { "TCP Segment", "tcp.segment", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
2899                         "TCP Segment", HFILL }},
2900
2901                 { &hf_tcp_segments,
2902                 { "TCP Segments", "tcp.segments", FT_NONE, BASE_NONE, NULL, 0x0,
2903                         "TCP Segments", HFILL }},
2904
2905                 { &hf_tcp_reassembled_in,
2906                 { "Reassembled PDU in frame", "tcp.reassembled_in", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
2907                         "The PDU that starts but doesn't end in this segment is reassembled in this frame", HFILL }},
2908
2909                 { &hf_tcp_option_mss,
2910                   { "TCP MSS Option", "tcp.options.mss", FT_BOOLEAN, 
2911                     BASE_NONE, NULL, 0x0, "TCP MSS Option", HFILL }},
2912
2913                 { &hf_tcp_option_mss_val,
2914                   { "TCP MSS Option Value", "tcp.options.mss_val", FT_UINT16,
2915                     BASE_DEC, NULL, 0x0, "TCP MSS Option Value", HFILL}},
2916
2917                 { &hf_tcp_option_wscale,
2918                   { "TCP Window Scale Option", "tcp.options.wscale", 
2919                     FT_BOOLEAN, 
2920                     BASE_NONE, NULL, 0x0, "TCP Window Option", HFILL}},
2921
2922                 { &hf_tcp_option_wscale_val,
2923                   { "TCP Windows Scale Option Value", "tcp.options.wscale_val",
2924                     FT_UINT8, BASE_DEC, NULL, 0x0, "TCP Window Scale Value",
2925                     HFILL}},
2926
2927                 { &hf_tcp_option_sack_perm, 
2928                   { "TCP Sack Perm Option", "tcp.options.sack_perm", 
2929                     FT_BOOLEAN,
2930                     BASE_NONE, NULL, 0x0, "TCP Sack Perm Option", HFILL}},
2931
2932                 { &hf_tcp_option_sack,
2933                   { "TCP Sack Option", "tcp.options.sack", FT_BOOLEAN, 
2934                     BASE_NONE, NULL, 0x0, "TCP Sack Option", HFILL}},
2935
2936                 { &hf_tcp_option_sack_sle,
2937                   {"TCP Sack Left Edge", "tcp.options.sack_le", FT_UINT32,
2938                    BASE_DEC, NULL, 0x0, "TCP Sack Left Edge", HFILL}},
2939
2940                 { &hf_tcp_option_sack_sre,
2941                   {"TCP Sack Right Edge", "tcp.options.sack_re", FT_UINT32,
2942                    BASE_DEC, NULL, 0x0, "TCP Sack Right Edge", HFILL}},
2943
2944                 { &hf_tcp_option_echo,
2945                   { "TCP Echo Option", "tcp.options.echo", FT_BOOLEAN, 
2946                     BASE_NONE, NULL, 0x0, "TCP Sack Echo", HFILL}},
2947
2948                 { &hf_tcp_option_echo_reply,
2949                   { "TCP Echo Reply Option", "tcp.options.echo_reply", 
2950                     FT_BOOLEAN,
2951                     BASE_NONE, NULL, 0x0, "TCP Echo Reply Option", HFILL}},
2952
2953                 { &hf_tcp_option_time_stamp,
2954                   { "TCP Time Stamp Option", "tcp.options.time_stamp", 
2955                     FT_BOOLEAN,
2956                     BASE_NONE, NULL, 0x0, "TCP Time Stamp Option", HFILL}},
2957
2958                 { &hf_tcp_option_cc,
2959                   { "TCP CC Option", "tcp.options.cc", FT_BOOLEAN, BASE_NONE,
2960                     NULL, 0x0, "TCP CC Option", HFILL}},
2961
2962                 { &hf_tcp_option_ccnew,
2963                   { "TCP CC New Option", "tcp.options.ccnew", FT_BOOLEAN, 
2964                     BASE_NONE, NULL, 0x0, "TCP CC New Option", HFILL}},
2965
2966                 { &hf_tcp_option_ccecho,
2967                   { "TCP CC Echo Option", "tcp.options.ccecho", FT_BOOLEAN,
2968                     BASE_NONE, NULL, 0x0, "TCP CC Echo Option", HFILL}},
2969
2970                 { &hf_tcp_option_md5,
2971                   { "TCP MD5 Option", "tcp.options.md5", FT_BOOLEAN, BASE_NONE,
2972                     NULL, 0x0, "TCP MD5 Option", HFILL}},
2973         };
2974         static gint *ett[] = {
2975                 &ett_tcp,
2976                 &ett_tcp_flags,
2977                 &ett_tcp_options,
2978                 &ett_tcp_option_sack,
2979                 &ett_tcp_analysis_faults,
2980                 &ett_tcp_analysis,
2981                 &ett_tcp_segments,
2982                 &ett_tcp_segment
2983         };
2984         module_t *tcp_module;
2985
2986         proto_tcp = proto_register_protocol("Transmission Control Protocol",
2987             "TCP", "tcp");
2988         proto_register_field_array(proto_tcp, hf, array_length(hf));
2989         proto_register_subtree_array(ett, array_length(ett));
2990
2991         /* subdissector code */
2992         subdissector_table = register_dissector_table("tcp.port",
2993             "TCP port", FT_UINT16, BASE_DEC);
2994         register_heur_dissector_list("tcp", &heur_subdissector_list);
2995
2996         /* Register configuration preferences */
2997         tcp_module = prefs_register_protocol(proto_tcp, NULL);
2998         prefs_register_bool_preference(tcp_module, "summary_in_tree",
2999             "Show TCP summary in protocol tree",
3000             "Whether the TCP summary line should be shown in the protocol tree",
3001             &tcp_summary_in_tree);
3002         prefs_register_bool_preference(tcp_module, "check_checksum",
3003             "Check the validity of the TCP checksum when possible",
3004             "Whether to check the validity of the TCP checksum",
3005             &tcp_check_checksum);
3006         prefs_register_bool_preference(tcp_module, "desegment_tcp_streams",
3007             "Allow subdissector to desegment TCP streams",
3008             "Whether subdissector can request TCP streams to be desegmented",
3009             &tcp_desegment);
3010         prefs_register_bool_preference(tcp_module, "analyze_sequence_numbers",
3011             "Analyze TCP sequence numbers",
3012             "Make the TCP dissector analyze TCP sequence numbers to find and flag segment retransmissions, missing segments and RTT",
3013             &tcp_analyze_seq);
3014         prefs_register_bool_preference(tcp_module, "relative_sequence_numbers",
3015             "Relative sequence numbers and window scaling",
3016             "Make the TCP dissector use relative sequence numbers instead of absolute ones. "
3017             "To use this option you must also enable \"Analyze TCP sequence numbers\". "
3018             "This option will also try to track and adjust the window field according to any TCP window scaling options seen.",
3019             &tcp_relative_seq);
3020         prefs_register_bool_preference(tcp_module, "try_heuristic_first",
3021             "Try heuristic sub-dissectors first",
3022             "Try to decode a packet using an heuristic sub-dissector before using a sub-dissector registered to a specific port",
3023             &try_heuristic_first);
3024
3025         register_init_routine(tcp_analyze_seq_init);
3026         register_init_routine(tcp_desegment_init);
3027         register_init_routine(tcp_fragment_init);
3028 }
3029
3030 void
3031 proto_reg_handoff_tcp(void)
3032 {
3033         dissector_handle_t tcp_handle;
3034
3035         tcp_handle = create_dissector_handle(dissect_tcp, proto_tcp);
3036         dissector_add("ip.proto", IP_PROTO_TCP, tcp_handle);
3037         data_handle = find_dissector("data");
3038         tcp_tap = register_tap("tcp");
3039 }