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