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