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