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