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