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