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