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