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