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