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