Replaced the column string [Reassembled TCP] by [TCP segment of a reassembled PDU...
[obnox/wireshark/wip.git] / epan / dissectors / packet-tcp.c
1 /* packet-tcp.c
2  * Routines for TCP packet disassembly
3  *
4  * $Id$
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <glib.h>
32 #include "in_cksum.h"
33
34 #include <epan/packet.h>
35 #include <epan/addr_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 *tcp_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(tcp_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(tcp_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     PROTO_ITEM_SET_GENERATED(item);
1154         tree=proto_item_add_subtree(item, ett_tcp_analysis);
1155
1156         /* encapsulate all proto_tree_add_xxx in ifs so we only print what
1157            data we actually have */
1158         if(ta->frame_acked){
1159                 item = proto_tree_add_uint(tree, hf_tcp_analysis_acks_frame,
1160                         tvb, 0, 0, ta->frame_acked);
1161         PROTO_ITEM_SET_GENERATED(item);
1162         }
1163         if( ta->ts.secs || ta->ts.nsecs ){
1164                 item = proto_tree_add_time(tree, hf_tcp_analysis_ack_rtt,
1165                 tvb, 0, 0, &ta->ts);
1166         PROTO_ITEM_SET_GENERATED(item);
1167         }
1168
1169         if(ta->flags){
1170                 proto_item *flags_item=NULL;
1171                 proto_tree *flags_tree=NULL;
1172
1173                 flags_item = proto_tree_add_item(tree, hf_tcp_analysis_flags, tvb, 0, -1, FALSE);
1174         PROTO_ITEM_SET_GENERATED(flags_item);
1175                 flags_tree=proto_item_add_subtree(flags_item, ett_tcp_analysis);
1176                 if( ta->flags&TCP_A_RETRANSMISSION ){
1177                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_retransmission, tvb, 0, 0, "This frame is a (suspected) retransmission");
1178                         PROTO_ITEM_SET_GENERATED(flags_item);
1179                         if(check_col(pinfo->cinfo, COL_INFO)){
1180                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Retransmission] ");
1181                         }
1182                 }
1183                 if( ta->flags&TCP_A_FAST_RETRANSMISSION ){
1184                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_fast_retransmission, tvb, 0, 0, "This frame is a (suspected) fast retransmission");
1185                         PROTO_ITEM_SET_GENERATED(flags_item);
1186                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_retransmission, tvb, 0, 0, "This frame is a (suspected) retransmission");
1187                         PROTO_ITEM_SET_GENERATED(flags_item);
1188                         if(check_col(pinfo->cinfo, COL_INFO)){
1189                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Fast Retransmission] ");
1190                         }
1191                 }
1192                 if( ta->flags&TCP_A_OUT_OF_ORDER ){
1193                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_out_of_order, tvb, 0, 0, "This frame is a (suspected) out-of-order segment");
1194                         PROTO_ITEM_SET_GENERATED(flags_item);
1195                         if(check_col(pinfo->cinfo, COL_INFO)){
1196                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Out-Of-Order] ");
1197                         }
1198                 }
1199                 if( ta->flags&TCP_A_LOST_PACKET ){
1200                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_lost_packet, tvb, 0, 0, "A segment before this frame was lost");
1201                         PROTO_ITEM_SET_GENERATED(flags_item);
1202                         if(check_col(pinfo->cinfo, COL_INFO)){
1203                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Previous segment lost] ");
1204                         }
1205                 }
1206                 if( ta->flags&TCP_A_ACK_LOST_PACKET ){
1207                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_ack_lost_packet, tvb, 0, 0, "This frame ACKs a segment we have not seen (lost?)");
1208                         PROTO_ITEM_SET_GENERATED(flags_item);
1209                         if(check_col(pinfo->cinfo, COL_INFO)){
1210                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ACKed lost segment] ");
1211                         }
1212                 }
1213                 if( ta->flags&TCP_A_KEEP_ALIVE ){
1214                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_keep_alive, tvb, 0, 0, "This is a TCP keep-alive segment");
1215                         PROTO_ITEM_SET_GENERATED(flags_item);
1216                         if(check_col(pinfo->cinfo, COL_INFO)){
1217                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Keep-Alive] ");
1218                         }
1219                 }
1220                 if( ta->flags&TCP_A_KEEP_ALIVE_ACK ){
1221                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_keep_alive_ack, tvb, 0, 0, "This is an ACK to a TCP keep-alive segment");
1222                         PROTO_ITEM_SET_GENERATED(flags_item);
1223                         if(check_col(pinfo->cinfo, COL_INFO)){
1224                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Keep-Alive ACK] ");
1225                         }
1226                 }
1227                 if( ta->dupack_num){
1228                         if( ta->flags&TCP_A_DUPLICATE_ACK ){
1229                                 flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_duplicate_ack, tvb, 0, 0, "This is a TCP duplicate ack");
1230                                 PROTO_ITEM_SET_GENERATED(flags_item);
1231                                 if(check_col(pinfo->cinfo, COL_INFO)){
1232                                         col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Dup ACK %d#%d] ", ta->dupack_frame, ta->dupack_num);
1233                                 }
1234                         }
1235                         flags_item=proto_tree_add_uint(tree, hf_tcp_analysis_duplicate_ack_num,
1236                                 tvb, 0, 0, ta->dupack_num);
1237                         PROTO_ITEM_SET_GENERATED(flags_item);
1238                         flags_item=proto_tree_add_uint(tree, hf_tcp_analysis_duplicate_ack_frame,
1239                                 tvb, 0, 0, ta->dupack_frame);
1240                         PROTO_ITEM_SET_GENERATED(flags_item);
1241                 }
1242                 if( ta->flags&TCP_A_ZERO_WINDOW_PROBE ){
1243                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window_probe, tvb, 0, 0, "This is a TCP zero-window-probe");
1244                         PROTO_ITEM_SET_GENERATED(flags_item);
1245                         if(check_col(pinfo->cinfo, COL_INFO)){
1246                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindowProbe] ");
1247                         }
1248                 }
1249                 if( ta->flags&TCP_A_ZERO_WINDOW ){
1250                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window, tvb, 0, 0, "This is a ZeroWindow segment");
1251                         PROTO_ITEM_SET_GENERATED(flags_item);
1252                         if(check_col(pinfo->cinfo, COL_INFO)){
1253                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindow] ");
1254                         }
1255                 }
1256                 if( ta->flags&TCP_A_ZERO_WINDOW_VIOLATION ){
1257                         flags_item=proto_tree_add_none_format(flags_tree, hf_tcp_analysis_zero_window_violation, tvb, 0, 0, "This is a ZeroWindow violation, attempts to write >1 byte of data to a zero-window");
1258                         PROTO_ITEM_SET_GENERATED(flags_item);
1259                         if(check_col(pinfo->cinfo, COL_INFO)){
1260                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ZeroWindowViolation] ");
1261                         }
1262                 }
1263         }
1264
1265 }
1266
1267
1268 /* Do we still need to do this ...remove_all() even though we dont need
1269  * to do anything special?  The glib docs are not clear on this and
1270  * its better safe than sorry
1271  */
1272 static gboolean
1273 free_all_acked(gpointer key_arg _U_, gpointer value _U_, gpointer user_data _U_)
1274 {
1275         return TRUE;
1276 }
1277
1278 static guint
1279 tcp_acked_hash(gconstpointer k)
1280 {
1281         guint32 frame = (guint32)k;
1282
1283         return frame;
1284 }
1285 static gint
1286 tcp_acked_equal(gconstpointer k1, gconstpointer k2)
1287 {
1288         guint32 frame1 = (guint32)k1;
1289         guint32 frame2 = (guint32)k2;
1290
1291         return frame1==frame2;
1292 }
1293
1294 static void
1295 tcp_analyze_seq_init(void)
1296 {
1297         /* first destroy the tables */
1298         if( tcp_analyze_acked_table ){
1299                 g_hash_table_foreach_remove(tcp_analyze_acked_table,
1300                         free_all_acked, NULL);
1301                 g_hash_table_destroy(tcp_analyze_acked_table);
1302                 tcp_analyze_acked_table = NULL;
1303         }
1304         if( tcp_rel_seq_table ){
1305                 g_hash_table_foreach_remove(tcp_rel_seq_table,
1306                         free_all_acked, NULL);
1307                 g_hash_table_destroy(tcp_rel_seq_table);
1308                 tcp_rel_seq_table = NULL;
1309         }
1310         if( tcp_pdu_tracking_table ){
1311                 g_hash_table_foreach_remove(tcp_pdu_tracking_table,
1312                         free_all_acked, NULL);
1313                 g_hash_table_destroy(tcp_pdu_tracking_table);
1314                 tcp_pdu_tracking_table = NULL;
1315         }
1316         if( tcp_pdu_skipping_table ){
1317                 g_hash_table_foreach_remove(tcp_pdu_skipping_table,
1318                         free_all_acked, NULL);
1319                 g_hash_table_destroy(tcp_pdu_skipping_table);
1320                 tcp_pdu_skipping_table = NULL;
1321         }
1322
1323         /*
1324          * Now destroy the chunk from which the conversation table
1325          * structures were allocated.
1326          */
1327         if (tcp_next_pdu_chunk) {
1328                 g_mem_chunk_destroy(tcp_next_pdu_chunk);
1329                 tcp_next_pdu_chunk = NULL;
1330         }
1331         if (tcp_analysis_chunk) {
1332                 g_mem_chunk_destroy(tcp_analysis_chunk);
1333                 tcp_analysis_chunk = NULL;
1334         }
1335         if (tcp_unacked_chunk) {
1336                 g_mem_chunk_destroy(tcp_unacked_chunk);
1337                 tcp_unacked_chunk = NULL;
1338         }
1339         if (tcp_acked_chunk) {
1340                 g_mem_chunk_destroy(tcp_acked_chunk);
1341                 tcp_acked_chunk = NULL;
1342         }
1343         if (tcp_rel_seq_chunk) {
1344                 g_mem_chunk_destroy(tcp_rel_seq_chunk);
1345                 tcp_rel_seq_chunk = NULL;
1346         }
1347
1348         if(tcp_analyze_seq){
1349                 tcp_analyze_acked_table = g_hash_table_new(tcp_acked_hash,
1350                         tcp_acked_equal);
1351                 tcp_rel_seq_table = g_hash_table_new(tcp_acked_hash,
1352                         tcp_acked_equal);
1353                 tcp_pdu_tracking_table = g_hash_table_new(tcp_acked_hash,
1354                         tcp_acked_equal);
1355                 tcp_pdu_skipping_table = g_hash_table_new(tcp_acked_hash,
1356                         tcp_acked_equal);
1357                 tcp_next_pdu_chunk = g_mem_chunk_new("tcp_next_pdu_chunk",
1358                         sizeof(struct tcp_next_pdu),
1359                         tcp_next_pdu_count * sizeof(struct tcp_next_pdu),
1360                         G_ALLOC_ONLY);
1361                 tcp_analysis_chunk = g_mem_chunk_new("tcp_analysis_chunk",
1362                         sizeof(struct tcp_analysis),
1363                         tcp_analysis_count * sizeof(struct tcp_analysis),
1364                         G_ALLOC_ONLY);
1365                 tcp_unacked_chunk = g_mem_chunk_new("tcp_unacked_chunk",
1366                         sizeof(struct tcp_unacked),
1367                         tcp_unacked_count * sizeof(struct tcp_unacked),
1368                         G_ALLOC_ONLY);
1369                 tcp_acked_chunk = g_mem_chunk_new("tcp_acked_chunk",
1370                         sizeof(struct tcp_acked),
1371                         tcp_acked_count * sizeof(struct tcp_acked),
1372                         G_ALLOC_ONLY);
1373                 if(tcp_relative_seq){
1374                         tcp_rel_seq_chunk = g_mem_chunk_new("tcp_rel_seq_chunk",
1375                                 sizeof(struct tcp_rel_seq),
1376                                 tcp_rel_seq_count * sizeof(struct tcp_rel_seq),
1377                                 G_ALLOC_ONLY);
1378                 }
1379         }
1380
1381 }
1382
1383 /* **************************************************************************
1384  * End of tcp sequence number analysis
1385  * **************************************************************************/
1386
1387
1388
1389
1390 /* Minimum TCP header length. */
1391 #define TCPH_MIN_LEN    20
1392
1393 /*
1394  *      TCP option
1395  */
1396
1397 #define TCPOPT_NOP              1       /* Padding */
1398 #define TCPOPT_EOL              0       /* End of options */
1399 #define TCPOPT_MSS              2       /* Segment size negotiating */
1400 #define TCPOPT_WINDOW           3       /* Window scaling */
1401 #define TCPOPT_SACK_PERM        4       /* SACK Permitted */
1402 #define TCPOPT_SACK             5       /* SACK Block */
1403 #define TCPOPT_ECHO             6
1404 #define TCPOPT_ECHOREPLY        7
1405 #define TCPOPT_TIMESTAMP        8       /* Better RTT estimations/PAWS */
1406 #define TCPOPT_CC               11
1407 #define TCPOPT_CCNEW            12
1408 #define TCPOPT_CCECHO           13
1409 #define TCPOPT_MD5              19      /* RFC2385 */
1410
1411 /*
1412  *     TCP option lengths
1413  */
1414
1415 #define TCPOLEN_MSS            4
1416 #define TCPOLEN_WINDOW         3
1417 #define TCPOLEN_SACK_PERM      2
1418 #define TCPOLEN_SACK_MIN       2
1419 #define TCPOLEN_ECHO           6
1420 #define TCPOLEN_ECHOREPLY      6
1421 #define TCPOLEN_TIMESTAMP      10
1422 #define TCPOLEN_CC             6
1423 #define TCPOLEN_CCNEW          6
1424 #define TCPOLEN_CCECHO         6
1425 #define TCPOLEN_MD5            18
1426
1427
1428
1429 /* Desegmentation of TCP streams */
1430 /* table to hold defragmented TCP streams */
1431 static GHashTable *tcp_fragment_table = NULL;
1432 static void
1433 tcp_fragment_init(void)
1434 {
1435         fragment_table_init(&tcp_fragment_table);
1436 }
1437
1438 /* functions to trace tcp segments */
1439 /* Enable desegmenting of TCP streams */
1440 static gboolean tcp_desegment = FALSE;
1441
1442 static GHashTable *tcp_segment_table = NULL;
1443 static GMemChunk *tcp_segment_key_chunk = NULL;
1444 static int tcp_segment_init_count = 200;
1445 static GMemChunk *tcp_segment_address_chunk = NULL;
1446 static int tcp_segment_address_init_count = 500;
1447
1448 typedef struct _tcp_segment_key {
1449         /* for own bookkeeping inside packet-tcp.c */
1450         address *src;
1451         address *dst;
1452         guint32 seq;
1453         /* xxx */
1454         guint16 sport;
1455         guint16 dport;
1456         guint32 start_seq;
1457         guint32 tot_len;
1458         guint32 first_frame;
1459 } tcp_segment_key;
1460
1461 static gboolean
1462 free_all_segments(gpointer key_arg, gpointer value _U_, gpointer user_data _U_)
1463 {
1464         tcp_segment_key *key = key_arg;
1465
1466         if((key->src)&&(key->src->data)){
1467                 g_free((gpointer)key->src->data);
1468                 key->src->data=NULL;
1469         }
1470
1471         if((key->dst)&&(key->dst->data)){
1472                 g_free((gpointer)key->dst->data);
1473                 key->dst->data=NULL;
1474         }
1475
1476         return TRUE;
1477 }
1478
1479 static guint
1480 tcp_segment_hash(gconstpointer k)
1481 {
1482         const tcp_segment_key *key = (const tcp_segment_key *)k;
1483
1484         return key->seq+key->sport;
1485 }
1486
1487 static gint
1488 tcp_segment_equal(gconstpointer k1, gconstpointer k2)
1489 {
1490         const tcp_segment_key *key1 = (const tcp_segment_key *)k1;
1491         const tcp_segment_key *key2 = (const tcp_segment_key *)k2;
1492
1493         return ( ( (key1->seq==key2->seq)
1494                  &&(ADDRESSES_EQUAL(key1->src, key2->src))
1495                  &&(ADDRESSES_EQUAL(key1->dst, key2->dst))
1496                  &&(key1->sport==key2->sport)
1497                  &&(key1->dport==key2->dport)
1498                  ) ? TRUE:FALSE);
1499 }
1500
1501 static void
1502 tcp_desegment_init(void)
1503 {
1504         /*
1505          * Free this before freeing any memory chunks; those
1506          * chunks contain data we'll look at in "free_all_segments()".
1507          */
1508         if(tcp_segment_table){
1509                 g_hash_table_foreach_remove(tcp_segment_table,
1510                         free_all_segments, NULL);
1511                 g_hash_table_destroy(tcp_segment_table);
1512                 tcp_segment_table = NULL;
1513         }
1514
1515         if(tcp_segment_key_chunk){
1516                 g_mem_chunk_destroy(tcp_segment_key_chunk);
1517                 tcp_segment_key_chunk = NULL;
1518         }
1519         if(tcp_segment_address_chunk){
1520                 g_mem_chunk_destroy(tcp_segment_address_chunk);
1521                 tcp_segment_address_chunk = NULL;
1522         }
1523
1524         /* dont allocate any hash table or memory chunks unless the user
1525            really uses this option
1526         */
1527         if(!tcp_desegment){
1528                 return;
1529         }
1530
1531         tcp_segment_table = g_hash_table_new(tcp_segment_hash,
1532                 tcp_segment_equal);
1533
1534         tcp_segment_key_chunk = g_mem_chunk_new("tcp_segment_key_chunk",
1535                 sizeof(tcp_segment_key),
1536                 tcp_segment_init_count*sizeof(tcp_segment_key),
1537                 G_ALLOC_ONLY);
1538
1539         tcp_segment_address_chunk = g_mem_chunk_new("tcp_segment_address_chunk",
1540                 sizeof(address),
1541                 tcp_segment_address_init_count*sizeof(address),
1542                 G_ALLOC_ONLY);
1543 }
1544
1545 static void
1546 desegment_tcp(tvbuff_t *tvb, packet_info *pinfo, int offset,
1547                 guint32 seq, guint32 nxtseq,
1548                 guint32 sport, guint32 dport,
1549                 proto_tree *tree, proto_tree *tcp_tree)
1550 {
1551         struct tcpinfo *tcpinfo = pinfo->private_data;
1552         fragment_data *ipfd_head=NULL;
1553         tcp_segment_key old_tsk, *tsk;
1554         gboolean must_desegment = FALSE;
1555         gboolean called_dissector = FALSE;
1556         int deseg_offset;
1557         guint32 deseg_seq;
1558         gint nbytes;
1559     proto_item *item;
1560
1561         /*
1562          * Initialize these to assume no desegmentation.
1563          * If that's not the case, these will be set appropriately
1564          * by the subdissector.
1565          */
1566         pinfo->desegment_offset = 0;
1567         pinfo->desegment_len = 0;
1568
1569         /*
1570          * Initialize this to assume that this segment will just be
1571          * added to the middle of a desegmented chunk of data, so
1572          * that we should show it all as data.
1573          * If that's not the case, it will be set appropriately.
1574          */
1575         deseg_offset = offset;
1576
1577         /* First we must check if this TCP segment should be desegmented.
1578            This is only to check if we should desegment this packet,
1579            so we dont spend time doing COPY_ADDRESS/g_free.
1580            We just "borrow" some address structures from pinfo instead. Cheaper.
1581         */
1582         old_tsk.src = &pinfo->src;
1583         old_tsk.dst = &pinfo->dst;
1584         old_tsk.sport = sport;
1585         old_tsk.dport = dport;
1586         old_tsk.seq = seq;
1587         tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
1588
1589         if(tsk){
1590                 /* OK, this segment was found, which means it continues
1591                    a higher-level PDU. This means we must desegment it.
1592                    Add it to the defragmentation lists.
1593                 */
1594                 ipfd_head = fragment_add(tvb, offset, pinfo, tsk->first_frame,
1595                         tcp_fragment_table,
1596                         seq - tsk->start_seq,
1597                         nxtseq - seq,
1598                         (LT_SEQ (nxtseq,tsk->start_seq + tsk->tot_len)) );
1599
1600                 if(!ipfd_head){
1601                         /* fragment_add() returned NULL, This means that
1602                            desegmentation is not completed yet.
1603                            (its like defragmentation but we know we will
1604                             always add the segments in order).
1605                            XXX - no, we don't; there is no guarantee that
1606                            TCP segments are in order on the wire.
1607
1608                            we must add next segment to our table so we will
1609                            find it later.
1610                         */
1611                         tcp_segment_key *new_tsk;
1612
1613                         new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1614                         memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1615                         new_tsk->seq=nxtseq;
1616                         g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1617                 }
1618         } else {
1619                 /* This segment was not found in our table, so it doesn't
1620                    contain a continuation of a higher-level PDU.
1621                    Call the normal subdissector.
1622                 */
1623                 process_tcp_payload(tvb, offset, pinfo, tree, tcp_tree,
1624                                 sport, dport, 0, 0, FALSE);
1625                 called_dissector = TRUE;
1626
1627                 /* Did the subdissector ask us to desegment some more data
1628                    before it could handle the packet?
1629                    If so we have to create some structures in our table but
1630                    this is something we only do the first time we see this
1631                    packet.
1632                 */
1633                 if(pinfo->desegment_len) {
1634                         if (!pinfo->fd->flags.visited)
1635                                 must_desegment = TRUE;
1636
1637                         /*
1638                          * Set "deseg_offset" to the offset in "tvb"
1639                          * of the first byte of data that the
1640                          * subdissector didn't process.
1641                          */
1642                         deseg_offset = offset + pinfo->desegment_offset;
1643                 }
1644
1645                 /* Either no desegmentation is necessary, or this is
1646                    segment contains the beginning but not the end of
1647                    a higher-level PDU and thus isn't completely
1648                    desegmented.
1649                 */
1650                 ipfd_head = NULL;
1651         }
1652
1653         /* is it completely desegmented? */
1654         if(ipfd_head){
1655                 fragment_data *ipfd;
1656
1657                 /*
1658                  * Yes, we think it is.
1659                  * We only call subdissector for the last segment.
1660                  * Note that the last segment may include more than what
1661                  * we needed.
1662                  */
1663                 if(GE_SEQ(nxtseq, tsk->start_seq + tsk->tot_len)){
1664                         /*
1665                          * OK, this is the last segment.
1666                          * Let's call the subdissector with the desegmented
1667                          * data.
1668                          */
1669                         tvbuff_t *next_tvb;
1670                         int old_len;
1671
1672                         /* create a new TVB structure for desegmented data */
1673                         next_tvb = tvb_new_real_data(ipfd_head->data,
1674                                         ipfd_head->datalen, ipfd_head->datalen);
1675
1676                         /* add this tvb as a child to the original one */
1677                         tvb_set_child_real_data_tvbuff(tvb, next_tvb);
1678
1679                         /* add desegmented data to the data source list */
1680                         add_new_data_source(pinfo, next_tvb, "Reassembled TCP");
1681
1682                         /*
1683                          * Supply the sequence number of the first of the
1684                          * reassembled bytes.
1685                          */
1686                         tcpinfo->seq = tsk->start_seq;
1687
1688                         /* indicate that this is reassembled data */
1689                         tcpinfo->is_reassembled = TRUE;
1690
1691                         /* call subdissector */
1692                         process_tcp_payload(next_tvb, 0, pinfo, tree,
1693                             tcp_tree, sport, dport, 0, 0, FALSE);
1694                         called_dissector = TRUE;
1695
1696                         /*
1697                          * OK, did the subdissector think it was completely
1698                          * desegmented, or does it think we need even more
1699                          * data?
1700                          */
1701                         old_len=(int)(tvb_reported_length(next_tvb)-tvb_reported_length_remaining(tvb, offset));
1702                         if(pinfo->desegment_len &&
1703                             pinfo->desegment_offset<=old_len){
1704                                 tcp_segment_key *new_tsk;
1705
1706                                 /*
1707                                  * "desegment_len" isn't 0, so it needs more
1708                                  * data for something - and "desegment_offset"
1709                                  * is before "old_len", so it needs more data
1710                                  * to dissect the stuff we thought was
1711                                  * completely desegmented (as opposed to the
1712                                  * stuff at the beginning being completely
1713                                  * desegmented, but the stuff at the end
1714                                  * being a new higher-level PDU that also
1715                                  * needs desegmentation).
1716                                  */
1717                                 fragment_set_partial_reassembly(pinfo,tsk->first_frame,tcp_fragment_table);
1718                                 tsk->tot_len = tvb_reported_length(next_tvb) + pinfo->desegment_len;
1719
1720                                 /*
1721                                  * Update tsk structure.
1722                                  * Can ask ->next->next because at least there's a hdr and one
1723                                  * entry in fragment_add()
1724                                  */
1725                                 for(ipfd=ipfd_head->next; ipfd->next; ipfd=ipfd->next){
1726                                         old_tsk.seq = tsk->start_seq + ipfd->offset;
1727                                         new_tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
1728                                         new_tsk->tot_len = tsk->tot_len;
1729                                 }
1730
1731                                 /* this is the next segment in the sequence we want */
1732                                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1733                                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1734                                 new_tsk->seq = nxtseq;
1735                                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1736                         } else {
1737                                 /*
1738                                  * Show the stuff in this TCP segment as
1739                                  * just raw TCP segment data.
1740                                  */
1741                                 nbytes =
1742                                     tvb_reported_length_remaining(tvb, offset);
1743                                 proto_tree_add_text(tcp_tree, tvb, offset, -1,
1744                                     "TCP segment data (%u byte%s)", nbytes,
1745                                     plurality(nbytes, "", "s"));
1746
1747                                 /*
1748                                  * The subdissector thought it was completely
1749                                  * desegmented (although the stuff at the
1750                                  * end may, in turn, require desegmentation),
1751                                  * so we show a tree with all segments.
1752                                  */
1753                                 show_fragment_tree(ipfd_head, &tcp_segment_items,
1754                                         tcp_tree, pinfo, next_tvb);
1755
1756                                 /* Did the subdissector ask us to desegment
1757                                    some more data?  This means that the data
1758                                    at the beginning of this segment completed
1759                                    a higher-level PDU, but the data at the
1760                                    end of this segment started a higher-level
1761                                    PDU but didn't complete it.
1762
1763                                    If so, we have to create some structures
1764                                    in our table, but this is something we
1765                                    only do the first time we see this packet.
1766                                 */
1767                                 if(pinfo->desegment_len) {
1768                                         if (!pinfo->fd->flags.visited)
1769                                                 must_desegment = TRUE;
1770
1771                                         /* The stuff we couldn't dissect
1772                                            must have come from this segment,
1773                                            so it's all in "tvb".
1774
1775                                            "pinfo->desegment_offset" is
1776                                            relative to the beginning of
1777                                            "next_tvb"; we want an offset
1778                                            relative to the beginning of "tvb".
1779
1780                                            First, compute the offset relative
1781                                            to the *end* of "next_tvb" - i.e.,
1782                                            the number of bytes before the end
1783                                            of "next_tvb" at which the
1784                                            subdissector stopped.  That's the
1785                                            length of "next_tvb" minus the
1786                                            offset, relative to the beginning
1787                                            of "next_tvb, at which the
1788                                            subdissector stopped.
1789                                         */
1790                                         deseg_offset =
1791                                             ipfd_head->datalen - pinfo->desegment_offset;
1792
1793                                         /* "tvb" and "next_tvb" end at the
1794                                            same byte of data, so the offset
1795                                            relative to the end of "next_tvb"
1796                                            of the byte at which we stopped
1797                                            is also the offset relative to
1798                                            the end of "tvb" of the byte at
1799                                            which we stopped.
1800
1801                                            Convert that back into an offset
1802                                            relative to the beginninng of
1803                                            "tvb", by taking the length of
1804                                            "tvb" and subtracting the offset
1805                                            relative to the end.
1806                                         */
1807                                         deseg_offset=tvb_reported_length(tvb) - deseg_offset;
1808                                 }
1809                         }
1810                 }
1811         }
1812
1813         if (must_desegment) {
1814             tcp_segment_key *tsk, *new_tsk;
1815
1816             /*
1817              * The sequence number at which the stuff to be desegmented
1818              * starts is the sequence number of the byte at an offset
1819              * of "deseg_offset" into "tvb".
1820              *
1821              * The sequence number of the byte at an offset of "offset"
1822              * is "seq", i.e. the starting sequence number of this
1823              * segment, so the sequence number of the byte at
1824              * "deseg_offset" is "seq + (deseg_offset - offset)".
1825              */
1826             deseg_seq = seq + (deseg_offset - offset);
1827
1828             /*
1829              * XXX - how do we detect out-of-order transmissions?
1830              * We can't just check for "nxtseq" being greater than
1831              * "tsk->start_seq"; for now, we check for the difference
1832              * being less than a megabyte, but this is a really
1833              * gross hack - we really need to handle out-of-order
1834              * transmissions correctly.
1835              */
1836             if ((nxtseq - deseg_seq) <= 1024*1024) {
1837                 /* OK, subdissector wants us to desegment
1838                    some data before it can process it. Add
1839                    what remains of this packet and set
1840                    up next packet/sequence number as well.
1841
1842                    We must remember this segment
1843                 */
1844                 tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1845                 tsk->src = g_mem_chunk_alloc(tcp_segment_address_chunk);
1846                 COPY_ADDRESS(tsk->src, &pinfo->src);
1847                 tsk->dst = g_mem_chunk_alloc(tcp_segment_address_chunk);
1848                 COPY_ADDRESS(tsk->dst, &pinfo->dst);
1849                 tsk->seq = deseg_seq;
1850                 tsk->start_seq = tsk->seq;
1851                 tsk->tot_len = nxtseq - tsk->start_seq + pinfo->desegment_len;
1852                 tsk->first_frame = pinfo->fd->num;
1853                 tsk->sport=sport;
1854                 tsk->dport=dport;
1855                 g_hash_table_insert(tcp_segment_table, tsk, tsk);
1856
1857                 /* Add portion of segment unprocessed by the subdissector
1858                    to defragmentation lists */
1859                 fragment_add(tvb, deseg_offset, pinfo, tsk->first_frame,
1860                     tcp_fragment_table,
1861                     tsk->seq - tsk->start_seq,
1862                     nxtseq - tsk->start_seq,
1863                     LT_SEQ (nxtseq, tsk->start_seq + tsk->tot_len));
1864
1865                 /* this is the next segment in the sequence we want */
1866                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1867                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1868                 new_tsk->seq = nxtseq;
1869                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1870             }
1871         }
1872
1873         if (!called_dissector || pinfo->desegment_len != 0) {
1874                 if (ipfd_head != NULL && ipfd_head->reassembled_in != 0) {
1875                         /*
1876                          * We know what frame this PDU is reassembled in;
1877                          * let the user know.
1878                          */
1879                         item=proto_tree_add_uint(tcp_tree, hf_tcp_reassembled_in,
1880                             tvb, 0, 0, ipfd_head->reassembled_in);
1881             PROTO_ITEM_SET_GENERATED(item);
1882                 }
1883
1884                 /*
1885                  * Either we didn't call the subdissector at all (i.e.,
1886                  * this is a segment that contains the middle of a
1887                  * higher-level PDU, but contains neither the beginning
1888                  * nor the end), or the subdissector couldn't dissect it
1889                  * all, as some data was missing (i.e., it set
1890                  * "pinfo->desegment_len" to the amount of additional
1891                  * data it needs).
1892                  */
1893                 if (pinfo->desegment_offset == 0) {
1894                         /*
1895                          * It couldn't, in fact, dissect any of it (the
1896                          * first byte it couldn't dissect is at an offset
1897                          * of "pinfo->desegment_offset" from the beginning
1898                          * of the payload, and that's 0).
1899                          * Just mark this as TCP.
1900                          */
1901                         if (check_col(pinfo->cinfo, COL_PROTOCOL)){
1902                                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
1903                         }
1904                         if (check_col(pinfo->cinfo, COL_INFO)){
1905                                 col_set_str(pinfo->cinfo, COL_INFO, "[TCP segment of a reassembled PDU]");
1906                         }
1907                 }
1908
1909                 /*
1910                  * Show what's left in the packet as just raw TCP segment
1911                  * data.
1912                  * XXX - remember what protocol the last subdissector
1913                  * was, and report it as a continuation of that, instead?
1914                  */
1915                 nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
1916                 proto_tree_add_text(tcp_tree, tvb, deseg_offset, -1,
1917                     "TCP segment data (%u byte%s)", nbytes,
1918                     plurality(nbytes, "", "s"));
1919         }
1920         pinfo->can_desegment=0;
1921         pinfo->desegment_offset = 0;
1922         pinfo->desegment_len = 0;
1923 }
1924
1925 /*
1926  * Loop for dissecting PDUs within a TCP stream; assumes that a PDU
1927  * consists of a fixed-length chunk of data that contains enough information
1928  * to determine the length of the PDU, followed by rest of the PDU.
1929  *
1930  * The first three arguments are the arguments passed to the dissector
1931  * that calls this routine.
1932  *
1933  * "proto_desegment" is the dissector's flag controlling whether it should
1934  * desegment PDUs that cross TCP segment boundaries.
1935  *
1936  * "fixed_len" is the length of the fixed-length part of the PDU.
1937  *
1938  * "get_pdu_len()" is a routine called to get the length of the PDU from
1939  * the fixed-length part of the PDU; it's passed "tvb" and "offset".
1940  *
1941  * "dissect_pdu()" is the routine to dissect a PDU.
1942  */
1943 void
1944 tcp_dissect_pdus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
1945                  gboolean proto_desegment, guint fixed_len,
1946                  guint (*get_pdu_len)(tvbuff_t *, int),
1947                  void (*dissect_pdu)(tvbuff_t *, packet_info *, proto_tree *))
1948 {
1949   volatile int offset = 0;
1950   int offset_before;
1951   guint length_remaining;
1952   guint plen;
1953   guint length;
1954   tvbuff_t *next_tvb;
1955
1956   while (tvb_reported_length_remaining(tvb, offset) != 0) {
1957     /*
1958      * We use "tvb_ensure_length_remaining()" to make sure there actually
1959      * *is* data remaining.  The protocol we're handling could conceivably
1960      * consists of a sequence of fixed-length PDUs, and therefore the
1961      * "get_pdu_len" routine might not actually fetch anything from
1962      * the tvbuff, and thus might not cause an exception to be thrown if
1963      * we've run past the end of the tvbuff.
1964      *
1965      * This means we're guaranteed that "length_remaining" is positive.
1966      */
1967     length_remaining = tvb_ensure_length_remaining(tvb, offset);
1968
1969     /*
1970      * Can we do reassembly?
1971      */
1972     if (proto_desegment && pinfo->can_desegment) {
1973       /*
1974        * Yes - is the fixed-length part of the PDU split across segment
1975        * boundaries?
1976        */
1977       if (length_remaining < fixed_len) {
1978         /*
1979          * Yes.  Tell the TCP dissector where the data for this message
1980          * starts in the data it handed us, and how many more bytes we
1981          * need, and return.
1982          */
1983         pinfo->desegment_offset = offset;
1984         pinfo->desegment_len = fixed_len - length_remaining;
1985         return;
1986       }
1987     }
1988
1989     /*
1990      * Get the length of the PDU.
1991      */
1992     plen = (*get_pdu_len)(tvb, offset);
1993     if (plen < fixed_len) {
1994       /*
1995        * The PDU length from the fixed-length portion probably didn't
1996        * include the fixed-length portion's length, and was probably so
1997        * large that the total length overflowed.
1998        *
1999        * Report this as an error.
2000        */
2001       show_reported_bounds_error(tvb, pinfo, tree);
2002       return;
2003     }
2004
2005     /* give a hint to TCP where the next PDU starts
2006      * so that it can attempt to find it in case it starts
2007      * somewhere in the middle of a segment.
2008      */
2009     if(!pinfo->fd->flags.visited && tcp_analyze_seq){
2010        guint remaining_bytes;
2011        remaining_bytes=tvb_reported_length_remaining(tvb, offset);
2012        if(plen>remaining_bytes){
2013           pinfo->want_pdu_tracking=2;
2014           pinfo->bytes_until_next_pdu=plen-remaining_bytes;
2015        }
2016     }
2017
2018     /*
2019      * Can we do reassembly?
2020      */
2021     if (proto_desegment && pinfo->can_desegment) {
2022       /*
2023        * Yes - is the PDU split across segment boundaries?
2024        */
2025       if (length_remaining < plen) {
2026         /*
2027          * Yes.  Tell the TCP dissector where the data for this message
2028          * starts in the data it handed us, and how many more bytes we
2029          * need, and return.
2030          */
2031         pinfo->desegment_offset = offset;
2032         pinfo->desegment_len = plen - length_remaining;
2033         return;
2034       }
2035     }
2036
2037     /*
2038      * Construct a tvbuff containing the amount of the payload we have
2039      * available.  Make its reported length the amount of data in the PDU.
2040      *
2041      * XXX - if reassembly isn't enabled. the subdissector will throw a
2042      * BoundsError exception, rather than a ReportedBoundsError exception.
2043      * We really want a tvbuff where the length is "length", the reported
2044      * length is "plen", and the "if the snapshot length were infinite"
2045      * length is the minimum of the reported length of the tvbuff handed
2046      * to us and "plen", with a new type of exception thrown if the offset
2047      * is within the reported length but beyond that third length, with
2048      * that exception getting the "Unreassembled Packet" error.
2049      */
2050     length = length_remaining;
2051     if (length > plen)
2052         length = plen;
2053     next_tvb = tvb_new_subset(tvb, offset, length, plen);
2054
2055     /*
2056      * Dissect the PDU.
2057      *
2058      * Catch the ReportedBoundsError exception; if this particular message
2059      * happens to get a ReportedBoundsError exception, that doesn't mean
2060      * that we should stop dissecting PDUs within this frame or chunk of
2061      * reassembled data.
2062      *
2063      * If it gets a BoundsError, we can stop, as there's nothing more to
2064      * see, so we just re-throw it.
2065      */
2066     TRY {
2067       (*dissect_pdu)(next_tvb, pinfo, tree);
2068     }
2069     CATCH(BoundsError) {
2070       RETHROW;
2071     }
2072     CATCH(ReportedBoundsError) {
2073       show_reported_bounds_error(tvb, pinfo, tree);
2074     }
2075     ENDTRY;
2076
2077     /*
2078      * Step to the next PDU.
2079      * Make sure we don't overflow.
2080      */
2081     offset_before = offset;
2082     offset += plen;
2083     if (offset <= offset_before)
2084       break;
2085   }
2086 }
2087
2088 static void
2089 tcp_info_append_uint(packet_info *pinfo, const char *abbrev, guint32 val)
2090 {
2091   if (check_col(pinfo->cinfo, COL_INFO))
2092     col_append_fstr(pinfo->cinfo, COL_INFO, " %s=%u", abbrev, val);
2093 }
2094
2095 static void
2096 dissect_tcpopt_maxseg(const ip_tcp_opt *optp, tvbuff_t *tvb,
2097     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2098 {
2099   guint16 mss;
2100
2101   mss = tvb_get_ntohs(tvb, offset + 2);
2102   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_mss, tvb, offset,
2103                                 optlen, TRUE);
2104   proto_tree_add_uint_format(opt_tree, hf_tcp_option_mss_val, tvb, offset,
2105                              optlen, mss, "%s: %u bytes", optp->name, mss);
2106   tcp_info_append_uint(pinfo, "MSS", mss);
2107 }
2108
2109 static void
2110 dissect_tcpopt_wscale(const ip_tcp_opt *optp, tvbuff_t *tvb,
2111     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2112 {
2113   guint8 ws;
2114
2115   ws = tvb_get_guint8(tvb, offset + 2);
2116   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_wscale, tvb, 
2117                                 offset, optlen, TRUE);
2118   proto_tree_add_uint_format(opt_tree, hf_tcp_option_wscale_val, tvb,
2119                              offset, optlen, ws, "%s: %u (multiply by %u)", 
2120                              optp->name, ws, 1 << ws);
2121   tcp_info_append_uint(pinfo, "WS", ws);
2122   if(!pinfo->fd->flags.visited && tcp_analyze_seq && tcp_relative_seq){
2123     pdu_store_window_scale_option(pinfo, ws);
2124   }
2125 }
2126
2127 static void
2128 dissect_tcpopt_sack(const ip_tcp_opt *optp, tvbuff_t *tvb,
2129     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2130 {
2131   proto_tree *field_tree = NULL;
2132   proto_item *tf;
2133   guint leftedge, rightedge;
2134
2135   tf = proto_tree_add_text(opt_tree, tvb, offset,      optlen, "%s:", optp->name);
2136   offset += 2;  /* skip past type and length */
2137   optlen -= 2;  /* subtract size of type and length */
2138   while (optlen > 0) {
2139     if (field_tree == NULL) {
2140       /* Haven't yet made a subtree out of this option.  Do so. */
2141       field_tree = proto_item_add_subtree(tf, *optp->subtree_index);
2142       proto_tree_add_boolean_hidden(field_tree, hf_tcp_option_sack, tvb, 
2143                                     offset, optlen, TRUE);
2144     }
2145     if (optlen < 4) {
2146       proto_tree_add_text(field_tree, tvb, offset,      optlen,
2147         "(suboption would go past end of option)");
2148       break;
2149     }
2150     leftedge = tvb_get_ntohl(tvb, offset);
2151     proto_tree_add_uint_format(field_tree, hf_tcp_option_sack_sle, tvb, 
2152                                offset, 4, leftedge, 
2153                                "left edge = %u", leftedge);
2154     optlen -= 4;
2155     if (optlen < 4) {
2156       proto_tree_add_text(field_tree, tvb, offset,      optlen,
2157         "(suboption would go past end of option)");
2158       break;
2159     }
2160     /* XXX - check whether it goes past end of packet */
2161     rightedge = tvb_get_ntohl(tvb, offset + 4);
2162     optlen -= 4;
2163     proto_tree_add_uint_format(field_tree, hf_tcp_option_sack_sre, tvb, 
2164                                offset+4, 4, rightedge, 
2165                                "right edge = %u", rightedge);
2166     tcp_info_append_uint(pinfo, "SLE", leftedge);
2167     tcp_info_append_uint(pinfo, "SRE", rightedge);
2168     offset += 8;
2169   }
2170 }
2171
2172 static void
2173 dissect_tcpopt_echo(const ip_tcp_opt *optp, tvbuff_t *tvb,
2174     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2175 {
2176   guint32 echo;
2177
2178   echo = tvb_get_ntohl(tvb, offset + 2);
2179   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_echo, tvb, offset,
2180                                 optlen, TRUE);
2181   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
2182                         "%s: %u", optp->name, echo);
2183   tcp_info_append_uint(pinfo, "ECHO", echo);
2184 }
2185
2186 static void
2187 dissect_tcpopt_timestamp(const ip_tcp_opt *optp, tvbuff_t *tvb,
2188     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2189 {
2190   guint32 tsv, tser;
2191
2192   tsv = tvb_get_ntohl(tvb, offset + 2);
2193   tser = tvb_get_ntohl(tvb, offset + 6);
2194   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_time_stamp, tvb, 
2195                                 offset, optlen, TRUE);
2196   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
2197     "%s: tsval %u, tsecr %u", optp->name, tsv, tser);
2198   tcp_info_append_uint(pinfo, "TSV", tsv);
2199   tcp_info_append_uint(pinfo, "TSER", tser);
2200 }
2201
2202 static void
2203 dissect_tcpopt_cc(const ip_tcp_opt *optp, tvbuff_t *tvb,
2204     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
2205 {
2206   guint32 cc;
2207
2208   cc = tvb_get_ntohl(tvb, offset + 2);
2209   proto_tree_add_boolean_hidden(opt_tree, hf_tcp_option_cc, tvb, offset,
2210                                 optlen, TRUE);
2211   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
2212                         "%s: %u", optp->name, cc);
2213   tcp_info_append_uint(pinfo, "CC", cc);
2214 }
2215
2216 static const ip_tcp_opt tcpopts[] = {
2217   {
2218     TCPOPT_EOL,
2219     "EOL",
2220     NULL,
2221     NO_LENGTH,
2222     0,
2223     NULL,
2224   },
2225   {
2226     TCPOPT_NOP,
2227     "NOP",
2228     NULL,
2229     NO_LENGTH,
2230     0,
2231     NULL,
2232   },
2233   {
2234     TCPOPT_MSS,
2235     "Maximum segment size",
2236     NULL,
2237     FIXED_LENGTH,
2238     TCPOLEN_MSS,
2239     dissect_tcpopt_maxseg
2240   },
2241   {
2242     TCPOPT_WINDOW,
2243     "Window scale",
2244     NULL,
2245     FIXED_LENGTH,
2246     TCPOLEN_WINDOW,
2247     dissect_tcpopt_wscale
2248   },
2249   {
2250     TCPOPT_SACK_PERM,
2251     "SACK permitted",
2252     NULL,
2253     FIXED_LENGTH,
2254     TCPOLEN_SACK_PERM,
2255     NULL,
2256   },
2257   {
2258     TCPOPT_SACK,
2259     "SACK",
2260     &ett_tcp_option_sack,
2261     VARIABLE_LENGTH,
2262     TCPOLEN_SACK_MIN,
2263     dissect_tcpopt_sack
2264   },
2265   {
2266     TCPOPT_ECHO,
2267     "Echo",
2268     NULL,
2269     FIXED_LENGTH,
2270     TCPOLEN_ECHO,
2271     dissect_tcpopt_echo
2272   },
2273   {
2274     TCPOPT_ECHOREPLY,
2275     "Echo reply",
2276     NULL,
2277     FIXED_LENGTH,
2278     TCPOLEN_ECHOREPLY,
2279     dissect_tcpopt_echo
2280   },
2281   {
2282     TCPOPT_TIMESTAMP,
2283     "Time stamp",
2284     NULL,
2285     FIXED_LENGTH,
2286     TCPOLEN_TIMESTAMP,
2287     dissect_tcpopt_timestamp
2288   },
2289   {
2290     TCPOPT_CC,
2291     "CC",
2292     NULL,
2293     FIXED_LENGTH,
2294     TCPOLEN_CC,
2295     dissect_tcpopt_cc
2296   },
2297   {
2298     TCPOPT_CCNEW,
2299     "CC.NEW",
2300     NULL,
2301     FIXED_LENGTH,
2302     TCPOLEN_CCNEW,
2303     dissect_tcpopt_cc
2304   },
2305   {
2306     TCPOPT_CCECHO,
2307     "CC.ECHO",
2308     NULL,
2309     FIXED_LENGTH,
2310     TCPOLEN_CCECHO,
2311     dissect_tcpopt_cc
2312   },
2313   {
2314     TCPOPT_MD5,
2315     "TCP MD5 signature",
2316     NULL,
2317     FIXED_LENGTH,
2318     TCPOLEN_MD5,
2319     NULL
2320   }
2321 };
2322
2323 #define N_TCP_OPTS      (sizeof tcpopts / sizeof tcpopts[0])
2324
2325 /* Determine if there is a sub-dissector and call it; return TRUE
2326    if there was a sub-dissector, FALSE otherwise.
2327
2328    This has been separated into a stand alone routine to other protocol
2329    dissectors can call to it, e.g., SOCKS. */
2330
2331 static gboolean try_heuristic_first = FALSE;
2332
2333 gboolean
2334 decode_tcp_ports(tvbuff_t *tvb, int offset, packet_info *pinfo,
2335         proto_tree *tree, int src_port, int dst_port)
2336 {
2337   tvbuff_t *next_tvb;
2338   int low_port, high_port;
2339
2340   next_tvb = tvb_new_subset(tvb, offset, -1, -1);
2341
2342 /* determine if this packet is part of a conversation and call dissector */
2343 /* for the conversation if available */
2344
2345   if (try_conversation_dissector(&pinfo->src, &pinfo->dst, PT_TCP,
2346                 src_port, dst_port, next_tvb, pinfo, tree)){
2347     pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
2348     return TRUE;
2349   }
2350
2351   if (try_heuristic_first) {
2352     /* do lookup with the heuristic subdissector table */
2353     if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree)){
2354        pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
2355        return TRUE;
2356     }
2357   }
2358
2359   /* Do lookups with the subdissector table.
2360      We try the port number with the lower value first, followed by the
2361      port number with the higher value.  This means that, for packets
2362      where a dissector is registered for *both* port numbers:
2363
2364         1) we pick the same dissector for traffic going in both directions;
2365
2366         2) we prefer the port number that's more likely to be the right
2367            one (as that prefers well-known ports to reserved ports);
2368
2369      although there is, of course, no guarantee that any such strategy
2370      will always pick the right port number.
2371
2372      XXX - we ignore port numbers of 0, as some dissectors use a port
2373      number of 0 to disable the port. */
2374   if (src_port > dst_port) {
2375     low_port = dst_port;
2376     high_port = src_port;
2377   } else {
2378     low_port = src_port;
2379     high_port = dst_port;
2380   }
2381   if (low_port != 0 &&
2382       dissector_try_port(subdissector_table, low_port, next_tvb, pinfo, tree)){
2383     pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
2384     return TRUE;
2385   }
2386   if (high_port != 0 &&
2387       dissector_try_port(subdissector_table, high_port, next_tvb, pinfo, tree)){
2388     pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
2389     return TRUE;
2390   }
2391
2392   if (!try_heuristic_first) {
2393     /* do lookup with the heuristic subdissector table */
2394     if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree)){
2395        pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
2396        return TRUE;
2397     }
2398   }
2399
2400   /* Oh, well, we don't know this; dissect it as data. */
2401   call_dissector(data_handle,next_tvb, pinfo, tree);
2402
2403   pinfo->want_pdu_tracking -= !!(pinfo->want_pdu_tracking);
2404   return FALSE;
2405 }
2406
2407 static void
2408 process_tcp_payload(tvbuff_t *tvb, volatile int offset, packet_info *pinfo,
2409         proto_tree *tree, proto_tree *tcp_tree, int src_port, int dst_port,
2410         guint32 seq, guint32 nxtseq, gboolean is_tcp_segment)
2411 {
2412         pinfo->want_pdu_tracking=0;
2413
2414         TRY {
2415                 if(is_tcp_segment){
2416                         /*qqq   see if it is an unaligned PDU */
2417                         if(tcp_analyze_seq && (!tcp_desegment)){
2418                                 if(seq || nxtseq){
2419                                         offset=scan_for_next_pdu(tvb, tcp_tree, pinfo, offset,
2420                                                 seq, nxtseq);
2421                                 }
2422                         }
2423                 }
2424                 /* if offset is -1 this means that this segment is known
2425                  * to be fully inside a previously detected pdu
2426                  * so we dont even need to try to dissect it either.
2427                  */
2428                 if( (offset!=-1) &&
2429                     decode_tcp_ports(tvb, offset, pinfo, tree, src_port,
2430                         dst_port) ){
2431                         /*
2432                          * We succeeded in handing off to a subdissector.
2433                          *
2434                          * Is this a TCP segment or a reassembled chunk of
2435                          * TCP payload?
2436                          */
2437                         if(is_tcp_segment){
2438                                 /* if !visited, check want_pdu_tracking and
2439                                    store it in table */
2440                                 if((!pinfo->fd->flags.visited) &&
2441                                     tcp_analyze_seq && pinfo->want_pdu_tracking){
2442                                         if(seq || nxtseq){
2443                                                 pdu_store_sequencenumber_of_next_pdu(
2444                                                     pinfo,
2445                                                     seq,
2446                                                     nxtseq+pinfo->bytes_until_next_pdu);
2447                                         }
2448                                 }
2449                         }
2450                 }
2451         }
2452         CATCH_ALL {
2453                 /* We got an exception. At this point the dissection is
2454                  * completely aborted and execution will be transfered back
2455                  * to (probably) the frame dissector.
2456                  * Here we have to place whatever we want the dissector
2457                  * to do before aborting the tcp dissection.
2458                  */
2459                 /*
2460                  * Is this a TCP segment or a reassembled chunk of TCP
2461                  * payload?
2462                  */
2463                 if(is_tcp_segment){
2464                         /*
2465                          * It's from a TCP segment.
2466                          *
2467                          * Handle TCP seq# analysis, print any extra SEQ/ACK
2468                          * data for this segment.
2469                          */
2470                         if(tcp_analyze_seq){
2471                                 tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree);
2472                         }
2473                         /*
2474                          * if !visited, check want_pdu_tracking and store it
2475                          * in table 
2476                          */
2477                         if((!pinfo->fd->flags.visited) && tcp_analyze_seq && pinfo->want_pdu_tracking){
2478                                 if(seq || nxtseq){
2479                                         pdu_store_sequencenumber_of_next_pdu(pinfo,
2480                                             seq,
2481                                             nxtseq+pinfo->bytes_until_next_pdu);
2482                                 }
2483                         }
2484                 }
2485                 RETHROW;
2486         }
2487         ENDTRY;
2488 }
2489
2490 void
2491 dissect_tcp_payload(tvbuff_t *tvb, packet_info *pinfo, int offset, guint32 seq,
2492                     guint32 nxtseq, guint32 sport, guint32 dport,
2493                     proto_tree *tree, proto_tree *tcp_tree)
2494 {
2495   gboolean save_fragmented;
2496
2497   /* Can we desegment this segment? */
2498   if (pinfo->can_desegment) {
2499     /* Yes. */
2500     desegment_tcp(tvb, pinfo, offset, seq, nxtseq, sport, dport, tree,
2501         tcp_tree);
2502   } else {
2503     /* No - just call the subdissector.
2504        Mark this as fragmented, so if somebody throws an exception,
2505        we don't report it as a malformed frame. */
2506     save_fragmented = pinfo->fragmented;
2507     pinfo->fragmented = TRUE;
2508     process_tcp_payload(tvb, offset, pinfo, tree, tcp_tree, sport, dport,
2509         seq, nxtseq, TRUE);
2510     pinfo->fragmented = save_fragmented;
2511   }
2512 }
2513
2514 static void
2515 dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2516 {
2517   guint8  th_off_x2; /* combines th_off and th_x2 */
2518   guint16 th_sum;
2519   guint16 th_urp;
2520   proto_tree *tcp_tree = NULL, *field_tree = NULL;
2521   proto_item *ti = NULL, *tf;
2522   int        offset = 0;
2523   gchar      flags[64] = "<None>";
2524   gchar     *fstr[] = {"FIN", "SYN", "RST", "PSH", "ACK", "URG", "ECN", "CWR" };
2525   gint       fpos = 0, i;
2526   guint      bpos;
2527   guint      optlen;
2528   guint32    nxtseq = 0;
2529   guint      reported_len;
2530   vec_t      cksum_vec[4];
2531   guint32    phdr[2];
2532   guint16    computed_cksum;
2533   guint      length_remaining;
2534   gboolean   desegment_ok;
2535   struct tcpinfo tcpinfo;
2536   static struct tcpheader tcphstruct[4], *tcph;
2537   static int tcph_count=0;
2538
2539   tcph_count++;
2540   if(tcph_count>=4){
2541      tcph_count=0;
2542   }
2543   tcph=&tcphstruct[tcph_count];
2544   SET_ADDRESS(&tcph->ip_src, pinfo->src.type, pinfo->src.len, pinfo->src.data);
2545   SET_ADDRESS(&tcph->ip_dst, pinfo->dst.type, pinfo->dst.len, pinfo->dst.data);
2546
2547   if (check_col(pinfo->cinfo, COL_PROTOCOL))
2548     col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
2549
2550   /* Clear out the Info column. */
2551   if (check_col(pinfo->cinfo, COL_INFO))
2552     col_clear(pinfo->cinfo, COL_INFO);
2553
2554   tcph->th_sport = tvb_get_ntohs(tvb, offset);
2555   tcph->th_dport = tvb_get_ntohs(tvb, offset + 2);
2556   if (check_col(pinfo->cinfo, COL_INFO)) {
2557     col_append_fstr(pinfo->cinfo, COL_INFO, "%s > %s",
2558       get_tcp_port(tcph->th_sport), get_tcp_port(tcph->th_dport));
2559   }
2560   if (tree) {
2561     if (tcp_summary_in_tree) {
2562             ti = proto_tree_add_protocol_format(tree, proto_tcp, tvb, 0, -1,
2563                 "Transmission Control Protocol, Src Port: %s (%u), Dst Port: %s (%u)",
2564                 get_tcp_port(tcph->th_sport), tcph->th_sport,
2565                 get_tcp_port(tcph->th_dport), tcph->th_dport);
2566     }
2567     else {
2568             ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, FALSE);
2569     }
2570     tcp_tree = proto_item_add_subtree(ti, ett_tcp);
2571     proto_tree_add_uint_format(tcp_tree, hf_tcp_srcport, tvb, offset, 2, tcph->th_sport,
2572         "Source port: %s (%u)", get_tcp_port(tcph->th_sport), tcph->th_sport);
2573     proto_tree_add_uint_format(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, tcph->th_dport,
2574         "Destination port: %s (%u)", get_tcp_port(tcph->th_dport), tcph->th_dport);
2575     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset, 2, tcph->th_sport);
2576     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, tcph->th_dport);
2577   }
2578
2579   /* Set the source and destination port numbers as soon as we get them,
2580      so that they're available to the "Follow TCP Stream" code even if
2581      we throw an exception dissecting the rest of the TCP header. */
2582   pinfo->ptype = PT_TCP;
2583   pinfo->srcport = tcph->th_sport;
2584   pinfo->destport = tcph->th_dport;
2585
2586   tcph->th_seq = tvb_get_ntohl(tvb, offset + 4);
2587   tcph->th_ack = tvb_get_ntohl(tvb, offset + 8);
2588   th_off_x2 = tvb_get_guint8(tvb, offset + 12);
2589   tcph->th_flags = tvb_get_guint8(tvb, offset + 13);
2590   tcph->th_win = tvb_get_ntohs(tvb, offset + 14);
2591   tcph->th_hlen = hi_nibble(th_off_x2) * 4;  /* TCP header length, in bytes */
2592
2593   /*
2594    * If we've been handed an IP fragment, we don't know how big the TCP
2595    * segment is, so don't do anything that requires that we know that.
2596    *
2597    * The same applies if we're part of an error packet.  (XXX - if the
2598    * ICMP and ICMPv6 dissectors could set a "this is how big the IP
2599    * header says it is" length in the tvbuff, we could use that; such
2600    * a length might also be useful for handling packets where the IP
2601    * length is bigger than the actual data available in the frame; the
2602    * dissectors should trust that length, and then throw a
2603    * ReportedBoundsError exception when they go past the end of the frame.)
2604    *
2605    * We also can't determine the segment length if the reported length
2606    * of the TCP packet is less than the TCP header length.
2607    */
2608   reported_len = tvb_reported_length(tvb);
2609
2610   if (!pinfo->fragmented && !pinfo->in_error_pkt) {
2611     if (reported_len < tcph->th_hlen) {
2612       proto_tree_add_text(tcp_tree, tvb, offset, 0,
2613         "Short segment. Segment/fragment does not contain a full TCP header"
2614         " (might be NMAP or someone else deliberately sending unusual packets)");
2615       tcph->th_have_seglen = FALSE;
2616     } else {
2617       /* Compute the length of data in this segment. */
2618       tcph->th_seglen = reported_len - tcph->th_hlen;
2619       tcph->th_have_seglen = TRUE;
2620
2621       if (tree) { /* Add the seglen as an invisible field */
2622
2623         proto_tree_add_uint_hidden(ti, hf_tcp_len, tvb, offset, 4, tcph->th_seglen);
2624
2625       }
2626
2627       /* handle TCP seq# analysis parse all new segments we see */
2628       if(tcp_analyze_seq){
2629           if(!(pinfo->fd->flags.visited)){
2630               tcp_analyze_sequence_number(pinfo, tcph->th_seq, tcph->th_ack, tcph->th_seglen, tcph->th_flags, tcph->th_win);
2631           }
2632           if(tcp_relative_seq){
2633               tcp_get_relative_seq_ack(pinfo->fd->num, &(tcph->th_seq), &(tcph->th_ack), &(tcph->th_win));
2634           }
2635       }
2636
2637       /* Compute the sequence number of next octet after this segment. */
2638       nxtseq = tcph->th_seq + tcph->th_seglen;
2639     }
2640   } else
2641     tcph->th_have_seglen = FALSE;
2642
2643   if (check_col(pinfo->cinfo, COL_INFO) || tree) {
2644     for (i = 0; i < 8; i++) {
2645       bpos = 1 << i;
2646       if (tcph->th_flags & bpos) {
2647         if (fpos) {
2648           strcpy(&flags[fpos], ", ");
2649           fpos += 2;
2650         }
2651         strcpy(&flags[fpos], fstr[i]);
2652         fpos += 3;
2653       }
2654     }
2655     flags[fpos] = '\0';
2656   }
2657
2658   if (check_col(pinfo->cinfo, COL_INFO)) {
2659     col_append_fstr(pinfo->cinfo, COL_INFO, " [%s] Seq=%u Ack=%u Win=%u",
2660       flags, tcph->th_seq, tcph->th_ack, tcph->th_win);
2661   }
2662
2663   if (tree) {
2664     if (tcp_summary_in_tree) {
2665       proto_item_append_text(ti, ", Seq: %u", tcph->th_seq);
2666     }
2667     if(tcp_relative_seq){
2668       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);
2669     } else {
2670       proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq);
2671     }
2672   }
2673
2674   if (tcph->th_hlen < TCPH_MIN_LEN) {
2675     /* Give up at this point; we put the source and destination port in
2676        the tree, before fetching the header length, so that they'll
2677        show up if this is in the failing packet in an ICMP error packet,
2678        but it's now time to give up if the header length is bogus. */
2679     if (check_col(pinfo->cinfo, COL_INFO))
2680       col_append_fstr(pinfo->cinfo, COL_INFO, ", bogus TCP header length (%u, must be at least %u)",
2681         tcph->th_hlen, TCPH_MIN_LEN);
2682     if (tree) {
2683       proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, tcph->th_hlen,
2684        "Header length: %u bytes (bogus, must be at least %u)", tcph->th_hlen,
2685        TCPH_MIN_LEN);
2686     }
2687     return;
2688   }
2689
2690   if (tree) {
2691     if (tcp_summary_in_tree) {
2692       proto_item_append_text(ti, ", Ack: %u", tcph->th_ack);
2693       if (tcph->th_have_seglen)
2694         proto_item_append_text(ti, ", Len: %u", tcph->th_seglen);
2695     }
2696     proto_item_set_len(ti, tcph->th_hlen);
2697     if (tcph->th_have_seglen) {
2698       if (nxtseq != tcph->th_seq) {
2699         if(tcp_relative_seq){
2700           tf=proto_tree_add_uint_format(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq, "Next sequence number: %u    (relative sequence number)", nxtseq);
2701         } else {
2702           tf=proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);
2703         }
2704         PROTO_ITEM_SET_GENERATED(tf);
2705       }
2706     }
2707     if (tcph->th_flags & TH_ACK) {
2708       if(tcp_relative_seq){
2709         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);
2710       } else {
2711         proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack);
2712       }
2713     }
2714     proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, tcph->th_hlen,
2715         "Header length: %u bytes", tcph->th_hlen);
2716     tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 13, 1,
2717         tcph->th_flags, "Flags: 0x%04x (%s)", tcph->th_flags, flags);
2718     field_tree = proto_item_add_subtree(tf, ett_tcp_flags);
2719     proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, tcph->th_flags);
2720     proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, tcph->th_flags);
2721     proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, tcph->th_flags);
2722     proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, tcph->th_flags);
2723     proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, tcph->th_flags);
2724     proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, tcph->th_flags);
2725     proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, tcph->th_flags);
2726     proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, tcph->th_flags);
2727     proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win);
2728   }
2729
2730   /* Supply the sequence number of the first byte and of the first byte
2731      after the segment. */
2732   tcpinfo.seq = tcph->th_seq;
2733   tcpinfo.nxtseq = nxtseq;
2734
2735   /* Assume we'll pass un-reassembled data to subdissectors. */
2736   tcpinfo.is_reassembled = FALSE;
2737
2738   pinfo->private_data = &tcpinfo;
2739
2740   /*
2741    * Assume, initially, that we can't desegment.
2742    */
2743   pinfo->can_desegment = 0;
2744   th_sum = tvb_get_ntohs(tvb, offset + 16);
2745   if (!pinfo->fragmented && tvb_bytes_exist(tvb, 0, reported_len)) {
2746     /* The packet isn't part of an un-reassembled fragmented datagram
2747        and isn't truncated.  This means we have all the data, and thus
2748        can checksum it and, unless it's being returned in an error
2749        packet, are willing to allow subdissectors to request reassembly
2750        on it. */
2751
2752     if (tcp_check_checksum) {
2753       /* We haven't turned checksum checking off; checksum it. */
2754
2755       /* Set up the fields of the pseudo-header. */
2756       cksum_vec[0].ptr = pinfo->src.data;
2757       cksum_vec[0].len = pinfo->src.len;
2758       cksum_vec[1].ptr = pinfo->dst.data;
2759       cksum_vec[1].len = pinfo->dst.len;
2760       cksum_vec[2].ptr = (const guint8 *)&phdr;
2761       switch (pinfo->src.type) {
2762
2763       case AT_IPv4:
2764         phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);
2765         cksum_vec[2].len = 4;
2766         break;
2767
2768       case AT_IPv6:
2769         phdr[0] = g_htonl(reported_len);
2770         phdr[1] = g_htonl(IP_PROTO_TCP);
2771         cksum_vec[2].len = 8;
2772         break;
2773
2774       default:
2775         /* TCP runs only atop IPv4 and IPv6.... */
2776         g_assert_not_reached();
2777         break;
2778       }
2779       cksum_vec[3].ptr = tvb_get_ptr(tvb, offset, reported_len);
2780       cksum_vec[3].len = reported_len;
2781       computed_cksum = in_cksum(&cksum_vec[0], 4);
2782       if (computed_cksum == 0) {
2783         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2784           offset + 16, 2, th_sum, "Checksum: 0x%04x (correct)", th_sum);
2785
2786         /* Checksum is valid, so we're willing to desegment it. */
2787         desegment_ok = TRUE;
2788       } else {
2789         proto_tree_add_boolean_hidden(tcp_tree, hf_tcp_checksum_bad, tvb,
2790            offset + 16, 2, TRUE);
2791         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2792            offset + 16, 2, th_sum,
2793            "Checksum: 0x%04x (incorrect, should be 0x%04x)", th_sum,
2794            in_cksum_shouldbe(th_sum, computed_cksum));
2795
2796         if (check_col(pinfo->cinfo, COL_INFO))
2797           col_append_fstr(pinfo->cinfo, COL_INFO, " [CHECKSUM INCORRECT]");
2798
2799         /* Checksum is invalid, so we're not willing to desegment it. */
2800         desegment_ok = FALSE;
2801         pinfo->noreassembly_reason = " (incorrect TCP checksum)";
2802       }
2803     } else {
2804       proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2805          offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
2806
2807       /* We didn't check the checksum, and don't care if it's valid,
2808          so we're willing to desegment it. */
2809       desegment_ok = TRUE;
2810     }
2811   } else {
2812     /* We don't have all the packet data, so we can't checksum it... */
2813     proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
2814        offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
2815
2816     /* ...and aren't willing to desegment it. */
2817     desegment_ok = FALSE;
2818   }
2819
2820   if (desegment_ok) {
2821     /* We're willing to desegment this.  Is desegmentation enabled? */
2822     if (tcp_desegment) {
2823       /* Yes - is this segment being returned in an error packet? */
2824       if (!pinfo->in_error_pkt) {
2825         /* No - indicate that we will desegment.
2826            We do NOT want to desegment segments returned in error
2827            packets, as they're not part of a TCP connection. */
2828         pinfo->can_desegment = 2;
2829       }
2830     }
2831   }
2832
2833   if (tcph->th_flags & TH_URG) {
2834     th_urp = tvb_get_ntohs(tvb, offset + 18);
2835     /* Export the urgent pointer, for the benefit of protocols such as
2836        rlogin. */
2837     tcpinfo.urgent = TRUE;
2838     tcpinfo.urgent_pointer = th_urp;
2839     if (check_col(pinfo->cinfo, COL_INFO))
2840       col_append_fstr(pinfo->cinfo, COL_INFO, " Urg=%u", th_urp);
2841     if (tcp_tree != NULL)
2842       proto_tree_add_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, th_urp);
2843   } else
2844     tcpinfo.urgent = FALSE;
2845
2846   if (tcph->th_have_seglen) {
2847     if (check_col(pinfo->cinfo, COL_INFO))
2848       col_append_fstr(pinfo->cinfo, COL_INFO, " Len=%u", tcph->th_seglen);
2849   }
2850
2851   /* Decode TCP options, if any. */
2852   if (tcph->th_hlen > TCPH_MIN_LEN) {
2853     /* There's more than just the fixed-length header.  Decode the
2854        options. */
2855     optlen = tcph->th_hlen - TCPH_MIN_LEN; /* length of options, in bytes */
2856     if (tcp_tree != NULL) {
2857       tf = proto_tree_add_text(tcp_tree, tvb, offset +  20, optlen,
2858         "Options: (%u bytes)", optlen);
2859       field_tree = proto_item_add_subtree(tf, ett_tcp_options);
2860     } else
2861       field_tree = NULL;
2862     dissect_ip_tcp_options(tvb, offset + 20, optlen,
2863       tcpopts, N_TCP_OPTS, TCPOPT_EOL, pinfo, field_tree);
2864   }
2865
2866   /* Skip over header + options */
2867   offset += tcph->th_hlen;
2868
2869   /* Check the packet length to see if there's more data
2870      (it could be an ACK-only packet) */
2871   length_remaining = tvb_length_remaining(tvb, offset);
2872
2873   if (tcph->th_have_seglen) {
2874     if( data_out_file ) {
2875       reassemble_tcp( tcph->th_seq,             /* sequence number */
2876           tcph->th_seglen,                      /* data length */
2877           tvb_get_ptr(tvb, offset, length_remaining),   /* data */
2878           length_remaining,             /* captured data length */
2879           ( tcph->th_flags & TH_SYN ),          /* is syn set? */
2880           &pinfo->net_src,
2881           &pinfo->net_dst,
2882           pinfo->srcport,
2883           pinfo->destport);
2884     }
2885   }
2886
2887   /*
2888    * XXX - what, if any, of this should we do if this is included in an
2889    * error packet?  It might be nice to see the details of the packet
2890    * that caused the ICMP error, but it might not be nice to have the
2891    * dissector update state based on it.
2892    * Also, we probably don't want to run TCP taps on those packets.
2893    */
2894   if (length_remaining != 0) {
2895     if (tcph->th_flags & TH_RST) {
2896       /*
2897        * RFC1122 says:
2898        *
2899        *        4.2.2.12  RST Segment: RFC-793 Section 3.4
2900        *
2901        *          A TCP SHOULD allow a received RST segment to include data.
2902        *
2903        *          DISCUSSION
2904        *               It has been suggested that a RST segment could contain
2905        *               ASCII text that encoded and explained the cause of the
2906        *               RST.  No standard has yet been established for such
2907        *               data.
2908        *
2909        * so for segments with RST we just display the data as text.
2910        */
2911       proto_tree_add_text(tcp_tree, tvb, offset, length_remaining,
2912                             "Reset cause: %s",
2913                             tvb_format_text(tvb, offset, length_remaining));
2914     } else {
2915       dissect_tcp_payload(tvb, pinfo, offset, tcph->th_seq, nxtseq,
2916           tcph->th_sport, tcph->th_dport, tree, tcp_tree);
2917     }
2918   }
2919
2920   /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/
2921   if(tcp_analyze_seq){
2922       tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree);
2923   }
2924   tap_queue_packet(tcp_tap, pinfo, tcph);
2925 }
2926
2927 void
2928 proto_register_tcp(void)
2929 {
2930         static hf_register_info hf[] = {
2931
2932                 { &hf_tcp_srcport,
2933                 { "Source Port",                "tcp.srcport", FT_UINT16, BASE_DEC, NULL, 0x0,
2934                         "", HFILL }},
2935
2936                 { &hf_tcp_dstport,
2937                 { "Destination Port",           "tcp.dstport", FT_UINT16, BASE_DEC, NULL, 0x0,
2938                         "", HFILL }},
2939
2940                 { &hf_tcp_port,
2941                 { "Source or Destination Port", "tcp.port", FT_UINT16, BASE_DEC, NULL, 0x0,
2942                         "", HFILL }},
2943
2944                 { &hf_tcp_seq,
2945                 { "Sequence number",            "tcp.seq", FT_UINT32, BASE_DEC, NULL, 0x0,
2946                         "", HFILL }},
2947
2948                 { &hf_tcp_nxtseq,
2949                 { "Next sequence number",       "tcp.nxtseq", FT_UINT32, BASE_DEC, NULL, 0x0,
2950                         "", HFILL }},
2951
2952                 { &hf_tcp_ack,
2953                 { "Acknowledgement number",     "tcp.ack", FT_UINT32, BASE_DEC, NULL, 0x0,
2954                         "", HFILL }},
2955
2956                 { &hf_tcp_hdr_len,
2957                 { "Header Length",              "tcp.hdr_len", FT_UINT8, BASE_DEC, NULL, 0x0,
2958                         "", HFILL }},
2959
2960                 { &hf_tcp_flags,
2961                 { "Flags",                      "tcp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
2962                         "", HFILL }},
2963
2964                 { &hf_tcp_flags_cwr,
2965                 { "Congestion Window Reduced (CWR)",                    "tcp.flags.cwr", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_CWR,
2966                         "", HFILL }},
2967
2968                 { &hf_tcp_flags_ecn,
2969                 { "ECN-Echo",                   "tcp.flags.ecn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ECN,
2970                         "", HFILL }},
2971
2972                 { &hf_tcp_flags_urg,
2973                 { "Urgent",                     "tcp.flags.urg", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_URG,
2974                         "", HFILL }},
2975
2976                 { &hf_tcp_flags_ack,
2977                 { "Acknowledgment",             "tcp.flags.ack", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ACK,
2978                         "", HFILL }},
2979
2980                 { &hf_tcp_flags_push,
2981                 { "Push",                       "tcp.flags.push", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_PUSH,
2982                         "", HFILL }},
2983
2984                 { &hf_tcp_flags_reset,
2985                 { "Reset",                      "tcp.flags.reset", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_RST,
2986                         "", HFILL }},
2987
2988                 { &hf_tcp_flags_syn,
2989                 { "Syn",                        "tcp.flags.syn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_SYN,
2990                         "", HFILL }},
2991
2992                 { &hf_tcp_flags_fin,
2993                 { "Fin",                        "tcp.flags.fin", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_FIN,
2994                         "", HFILL }},
2995
2996                 /* 32 bits so we can present some values adjusted to window scaling */
2997                 { &hf_tcp_window_size,
2998                 { "Window size",                "tcp.window_size", FT_UINT32, BASE_DEC, NULL, 0x0,
2999                         "", HFILL }},
3000
3001                 { &hf_tcp_checksum,
3002                 { "Checksum",                   "tcp.checksum", FT_UINT16, BASE_HEX, NULL, 0x0,
3003                         "", HFILL }},
3004
3005                 { &hf_tcp_checksum_bad,
3006                 { "Bad Checksum",               "tcp.checksum_bad", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3007                         "", HFILL }},
3008
3009                 { &hf_tcp_analysis_flags,
3010                 { "TCP Analysis Flags",         "tcp.analysis.flags", FT_NONE, BASE_NONE, NULL, 0x0,
3011                         "This frame has some of the TCP analysis flags set", HFILL }},
3012
3013                 { &hf_tcp_analysis_retransmission,
3014                 { "Retransmission",             "tcp.analysis.retransmission", FT_NONE, BASE_NONE, NULL, 0x0,
3015                         "This frame is a suspected TCP retransmission", HFILL }},
3016
3017                 { &hf_tcp_analysis_fast_retransmission,
3018                 { "Fast Retransmission",                "tcp.analysis.fast_retransmission", FT_NONE, BASE_NONE, NULL, 0x0,
3019                         "This frame is a suspected TCP fast retransmission", HFILL }},
3020
3021                 { &hf_tcp_analysis_out_of_order,
3022                 { "Out Of Order",               "tcp.analysis.out_of_order", FT_NONE, BASE_NONE, NULL, 0x0,
3023                         "This frame is a suspected Out-Of-Order segment", HFILL }},
3024
3025                 { &hf_tcp_analysis_lost_packet,
3026                 { "Previous Segment Lost",              "tcp.analysis.lost_segment", FT_NONE, BASE_NONE, NULL, 0x0,
3027                         "A segment before this one was lost from the capture", HFILL }},
3028
3029                 { &hf_tcp_analysis_ack_lost_packet,
3030                 { "ACKed Lost Packet",          "tcp.analysis.ack_lost_segment", FT_NONE, BASE_NONE, NULL, 0x0,
3031                         "This frame ACKs a lost segment", HFILL }},
3032
3033                 { &hf_tcp_analysis_keep_alive,
3034                 { "Keep Alive",         "tcp.analysis.keep_alive", FT_NONE, BASE_NONE, NULL, 0x0,
3035                         "This is a keep-alive segment", HFILL }},
3036
3037                 { &hf_tcp_analysis_keep_alive_ack,
3038                 { "Keep Alive ACK",             "tcp.analysis.keep_alive_ack", FT_NONE, BASE_NONE, NULL, 0x0,
3039                         "This is an ACK to a keep-alive segment", HFILL }},
3040
3041                 { &hf_tcp_analysis_duplicate_ack,
3042                 { "Duplicate ACK",              "tcp.analysis.duplicate_ack", FT_NONE, BASE_NONE, NULL, 0x0,
3043                         "This is a duplicate ACK", HFILL }},
3044
3045                 { &hf_tcp_analysis_duplicate_ack_num,
3046                 { "Duplicate ACK #",            "tcp.analysis.duplicate_ack_num", FT_UINT32, BASE_DEC, NULL, 0x0,
3047                         "This is duplicate ACK number #", HFILL }},
3048
3049                 { &hf_tcp_analysis_duplicate_ack_frame,
3050                 { "Duplicate to the ACK in frame",              "tcp.analysis.duplicate_ack_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
3051                         "This is a duplicate to the ACK in frame #", HFILL }},
3052
3053                 { &hf_tcp_continuation_to,
3054                 { "This is a continuation to the PDU in frame",         "tcp.continuation_to", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
3055                         "This is a continuation to the PDU in frame #", HFILL }},
3056
3057                 { &hf_tcp_analysis_zero_window_violation,
3058                 { "Zero Window Violation",              "tcp.analysis.zero_window_violation", FT_NONE, BASE_NONE, NULL, 0x0,
3059                         "This is a zero-window violation, an attempt to write >1 byte to a zero-window", HFILL }},
3060
3061                 { &hf_tcp_analysis_zero_window_probe,
3062                 { "Zero Window Probe",          "tcp.analysis.zero_window_probe", FT_NONE, BASE_NONE, NULL, 0x0,
3063                         "This is a zero-window-probe", HFILL }},
3064
3065                 { &hf_tcp_analysis_zero_window,
3066                 { "Zero Window",                "tcp.analysis.zero_window", FT_NONE, BASE_NONE, NULL, 0x0,
3067                         "This is a zero-window", HFILL }},
3068
3069                 { &hf_tcp_len,
3070                   { "TCP Segment Len",            "tcp.len", FT_UINT32, BASE_DEC, NULL, 0x0,
3071                     "", HFILL}},
3072
3073                 { &hf_tcp_analysis_acks_frame,
3074                   { "This is an ACK to the segment in frame",            "tcp.analysis.acks_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
3075                     "Which previous segment is this an ACK for", HFILL}},
3076
3077                 { &hf_tcp_analysis_ack_rtt,
3078                   { "The RTT to ACK the segment was",            "tcp.analysis.ack_rtt", FT_RELATIVE_TIME, BASE_NONE, NULL, 0x0,
3079                     "How long time it took to ACK the segment (RTT)", HFILL}},
3080
3081                 { &hf_tcp_urgent_pointer,
3082                 { "Urgent pointer",             "tcp.urgent_pointer", FT_UINT16, BASE_DEC, NULL, 0x0,
3083                         "", HFILL }},
3084
3085                 { &hf_tcp_segment_overlap,
3086                 { "Segment overlap",    "tcp.segment.overlap", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3087                         "Segment overlaps with other segments", HFILL }},
3088
3089                 { &hf_tcp_segment_overlap_conflict,
3090                 { "Conflicting data in segment overlap",        "tcp.segment.overlap.conflict", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3091                         "Overlapping segments contained conflicting data", HFILL }},
3092
3093                 { &hf_tcp_segment_multiple_tails,
3094                 { "Multiple tail segments found",       "tcp.segment.multipletails", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3095                         "Several tails were found when reassembling the pdu", HFILL }},
3096
3097                 { &hf_tcp_segment_too_long_fragment,
3098                 { "Segment too long",   "tcp.segment.toolongfragment", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3099                         "Segment contained data past end of the pdu", HFILL }},
3100
3101                 { &hf_tcp_segment_error,
3102                 { "Reassembling error", "tcp.segment.error", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
3103                         "Reassembling error due to illegal segments", HFILL }},
3104
3105                 { &hf_tcp_segment,
3106                 { "TCP Segment", "tcp.segment", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
3107                         "TCP Segment", HFILL }},
3108
3109                 { &hf_tcp_segments,
3110                 { "TCP Segments", "tcp.segments", FT_NONE, BASE_NONE, NULL, 0x0,
3111                         "TCP Segments", HFILL }},
3112
3113                 { &hf_tcp_reassembled_in,
3114                 { "Reassembled PDU in frame", "tcp.reassembled_in", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
3115                         "The PDU that doesn't end in this segment is reassembled in this frame", HFILL }},
3116
3117                 { &hf_tcp_option_mss,
3118                   { "TCP MSS Option", "tcp.options.mss", FT_BOOLEAN, 
3119                     BASE_NONE, NULL, 0x0, "TCP MSS Option", HFILL }},
3120
3121                 { &hf_tcp_option_mss_val,
3122                   { "TCP MSS Option Value", "tcp.options.mss_val", FT_UINT16,
3123                     BASE_DEC, NULL, 0x0, "TCP MSS Option Value", HFILL}},
3124
3125                 { &hf_tcp_option_wscale,
3126                   { "TCP Window Scale Option", "tcp.options.wscale", 
3127                     FT_BOOLEAN, 
3128                     BASE_NONE, NULL, 0x0, "TCP Window Option", HFILL}},
3129
3130                 { &hf_tcp_option_wscale_val,
3131                   { "TCP Windows Scale Option Value", "tcp.options.wscale_val",
3132                     FT_UINT8, BASE_DEC, NULL, 0x0, "TCP Window Scale Value",
3133                     HFILL}},
3134
3135                 { &hf_tcp_option_sack_perm, 
3136                   { "TCP Sack Perm Option", "tcp.options.sack_perm", 
3137                     FT_BOOLEAN,
3138                     BASE_NONE, NULL, 0x0, "TCP Sack Perm Option", HFILL}},
3139
3140                 { &hf_tcp_option_sack,
3141                   { "TCP Sack Option", "tcp.options.sack", FT_BOOLEAN, 
3142                     BASE_NONE, NULL, 0x0, "TCP Sack Option", HFILL}},
3143
3144                 { &hf_tcp_option_sack_sle,
3145                   {"TCP Sack Left Edge", "tcp.options.sack_le", FT_UINT32,
3146                    BASE_DEC, NULL, 0x0, "TCP Sack Left Edge", HFILL}},
3147
3148                 { &hf_tcp_option_sack_sre,
3149                   {"TCP Sack Right Edge", "tcp.options.sack_re", FT_UINT32,
3150                    BASE_DEC, NULL, 0x0, "TCP Sack Right Edge", HFILL}},
3151
3152                 { &hf_tcp_option_echo,
3153                   { "TCP Echo Option", "tcp.options.echo", FT_BOOLEAN, 
3154                     BASE_NONE, NULL, 0x0, "TCP Sack Echo", HFILL}},
3155
3156                 { &hf_tcp_option_echo_reply,
3157                   { "TCP Echo Reply Option", "tcp.options.echo_reply", 
3158                     FT_BOOLEAN,
3159                     BASE_NONE, NULL, 0x0, "TCP Echo Reply Option", HFILL}},
3160
3161                 { &hf_tcp_option_time_stamp,
3162                   { "TCP Time Stamp Option", "tcp.options.time_stamp", 
3163                     FT_BOOLEAN,
3164                     BASE_NONE, NULL, 0x0, "TCP Time Stamp Option", HFILL}},
3165
3166                 { &hf_tcp_option_cc,
3167                   { "TCP CC Option", "tcp.options.cc", FT_BOOLEAN, BASE_NONE,
3168                     NULL, 0x0, "TCP CC Option", HFILL}},
3169
3170                 { &hf_tcp_option_ccnew,
3171                   { "TCP CC New Option", "tcp.options.ccnew", FT_BOOLEAN, 
3172                     BASE_NONE, NULL, 0x0, "TCP CC New Option", HFILL}},
3173
3174                 { &hf_tcp_option_ccecho,
3175                   { "TCP CC Echo Option", "tcp.options.ccecho", FT_BOOLEAN,
3176                     BASE_NONE, NULL, 0x0, "TCP CC Echo Option", HFILL}},
3177
3178                 { &hf_tcp_option_md5,
3179                   { "TCP MD5 Option", "tcp.options.md5", FT_BOOLEAN, BASE_NONE,
3180                     NULL, 0x0, "TCP MD5 Option", HFILL}},
3181         };
3182         static gint *ett[] = {
3183                 &ett_tcp,
3184                 &ett_tcp_flags,
3185                 &ett_tcp_options,
3186                 &ett_tcp_option_sack,
3187                 &ett_tcp_analysis_faults,
3188                 &ett_tcp_analysis,
3189                 &ett_tcp_segments,
3190                 &ett_tcp_segment
3191         };
3192         module_t *tcp_module;
3193
3194         proto_tcp = proto_register_protocol("Transmission Control Protocol",
3195             "TCP", "tcp");
3196         proto_register_field_array(proto_tcp, hf, array_length(hf));
3197         proto_register_subtree_array(ett, array_length(ett));
3198
3199         /* subdissector code */
3200         subdissector_table = register_dissector_table("tcp.port",
3201             "TCP port", FT_UINT16, BASE_DEC);
3202         register_heur_dissector_list("tcp", &heur_subdissector_list);
3203
3204         /* Register configuration preferences */
3205         tcp_module = prefs_register_protocol(proto_tcp, NULL);
3206         prefs_register_bool_preference(tcp_module, "summary_in_tree",
3207             "Show TCP summary in protocol tree",
3208             "Whether the TCP summary line should be shown in the protocol tree",
3209             &tcp_summary_in_tree);
3210         prefs_register_bool_preference(tcp_module, "check_checksum",
3211             "Check the validity of the TCP checksum when possible",
3212             "Whether to check the validity of the TCP checksum",
3213             &tcp_check_checksum);
3214         prefs_register_bool_preference(tcp_module, "desegment_tcp_streams",
3215             "Allow subdissector to reassemble TCP streams",
3216             "Whether subdissector can request TCP streams to be reassembled",
3217             &tcp_desegment);
3218         prefs_register_bool_preference(tcp_module, "analyze_sequence_numbers",
3219             "Analyze TCP sequence numbers",
3220             "Make the TCP dissector analyze TCP sequence numbers to find and flag segment retransmissions, missing segments and RTT",
3221             &tcp_analyze_seq);
3222         prefs_register_bool_preference(tcp_module, "relative_sequence_numbers",
3223             "Relative sequence numbers and window scaling",
3224             "Make the TCP dissector use relative sequence numbers instead of absolute ones. "
3225             "To use this option you must also enable \"Analyze TCP sequence numbers\". "
3226             "This option will also try to track and adjust the window field according to any TCP window scaling options seen.",
3227             &tcp_relative_seq);
3228         prefs_register_bool_preference(tcp_module, "try_heuristic_first",
3229             "Try heuristic sub-dissectors first",
3230             "Try to decode a packet using an heuristic sub-dissector before using a sub-dissector registered to a specific port",
3231             &try_heuristic_first);
3232
3233         register_init_routine(tcp_analyze_seq_init);
3234         register_init_routine(tcp_desegment_init);
3235         register_init_routine(tcp_fragment_init);
3236 }
3237
3238 void
3239 proto_reg_handoff_tcp(void)
3240 {
3241         dissector_handle_t tcp_handle;
3242
3243         tcp_handle = create_dissector_handle(dissect_tcp, proto_tcp);
3244         dissector_add("ip.proto", IP_PROTO_TCP, tcp_handle);
3245         data_handle = find_dissector("data");
3246         tcp_tap = register_tap("tcp");
3247 }