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