f9a7532790efafe55337881aa2d82bda241a57ed
[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.156 2002/08/22 19:47:15 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  * 
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  * 
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  * 
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <glib.h>
32 #include "in_cksum.h"
33
34 #include <epan/resolv.h>
35 #include "ipproto.h"
36 #include "follow.h"
37 #include "prefs.h"
38 #include "packet-tcp.h"
39 #include "packet-ip.h"
40 #include "packet-frame.h"
41 #include <epan/conversation.h>
42 #include <epan/strutil.h>
43 #include "reassemble.h"
44
45 /* Place TCP summary in proto tree */
46 static gboolean tcp_summary_in_tree = TRUE;
47
48 /*
49  * Flag to control whether to check the TCP checksum.
50  *
51  * In at least some Solaris network traces, there are packets with bad
52  * TCP checksums, but the traffic appears to indicate that the packets
53  * *were* received; the packets were probably sent by the host on which
54  * the capture was being done, on a network interface to which
55  * checksumming was offloaded, so that DLPI supplied an un-checksummed
56  * packet to the capture program but a checksummed packet got put onto
57  * the wire.
58  */
59 static gboolean tcp_check_checksum = TRUE;
60
61 extern FILE* data_out_file;
62
63 static int proto_tcp = -1;
64 static int hf_tcp_srcport = -1;
65 static int hf_tcp_dstport = -1;
66 static int hf_tcp_port = -1;
67 static int hf_tcp_seq = -1;
68 static int hf_tcp_nxtseq = -1;
69 static int hf_tcp_ack = -1;
70 static int hf_tcp_hdr_len = -1;
71 static int hf_tcp_flags = -1;
72 static int hf_tcp_flags_cwr = -1;
73 static int hf_tcp_flags_ecn = -1;
74 static int hf_tcp_flags_urg = -1;
75 static int hf_tcp_flags_ack = -1;
76 static int hf_tcp_flags_push = -1;
77 static int hf_tcp_flags_reset = -1;
78 static int hf_tcp_flags_syn = -1;
79 static int hf_tcp_flags_fin = -1;
80 static int hf_tcp_window_size = -1;
81 static int hf_tcp_checksum = -1;
82 static int hf_tcp_checksum_bad = -1;
83 static int hf_tcp_len = -1;
84 static int hf_tcp_urgent_pointer = -1;
85 static int hf_tcp_analysis_flags = -1;
86 static int hf_tcp_analysis_acks_frame = -1;
87 static int hf_tcp_analysis_ack_rtt = -1;
88 static int hf_tcp_analysis_retransmission = -1;
89 static int hf_tcp_analysis_lost_packet = -1;
90 static int hf_tcp_analysis_ack_lost_packet = -1;
91 static int hf_tcp_analysis_keep_alive = -1;
92
93 static gint ett_tcp = -1;
94 static gint ett_tcp_flags = -1;
95 static gint ett_tcp_options = -1;
96 static gint ett_tcp_option_sack = -1;
97 static gint ett_tcp_segments = -1;
98 static gint ett_tcp_analysis = -1;
99 static gint ett_tcp_analysis_faults = -1;
100
101 static dissector_table_t subdissector_table;
102 static heur_dissector_list_t heur_subdissector_list;
103 static dissector_handle_t data_handle;
104
105 /* TCP structs and definitions */
106
107 #define TH_FIN  0x01
108 #define TH_SYN  0x02
109 #define TH_RST  0x04
110 #define TH_PUSH 0x08
111 #define TH_ACK  0x10
112 #define TH_URG  0x20
113 #define TH_ECN  0x40
114 #define TH_CWR  0x80
115
116
117
118
119 /* ************************************************************************** 
120  * stuff to analyze TCP sequencenumbers for retransmissions, missing segments,
121  * RTT and reltive sequence numbers.
122  * **************************************************************************/
123 static gboolean tcp_analyze_seq = FALSE;
124 static gboolean tcp_relative_seq = FALSE;
125
126 static GMemChunk *tcp_unacked_chunk = NULL;
127 static int tcp_unacked_count = 500;     /* one for each packet until it is acked*/
128 struct tcp_unacked {
129         struct tcp_unacked *next;
130         guint32 frame;
131         guint32 seq;
132         guint32 nextseq;
133         nstime_t ts;
134 };
135
136 /* Idea for gt: either x > y, or y is much bigger (assume wrap) */
137 #define GT_SEQ(x, y) ((x > y) || ((y - x) > 0x80000000))
138 #define LT_SEQ(x, y) ((x < y) || ((x - y) > 0x80000000))
139 #define GE_SEQ(x, y) ((x >= y) || ((y - x) > 0x80000000))
140 #define LE_SEQ(x, y) ((x <= y) || ((x - y) > 0x80000000))
141 #define EQ_SEQ(x, y) (x == y)
142
143 static GMemChunk *tcp_acked_chunk = NULL;
144 static int tcp_acked_count = 5000;      /* one for almost every other segment in the capture */
145 #define TCP_A_RETRANSMISSION    0x01
146 #define TCP_A_LOST_PACKET       0x02
147 #define TCP_A_ACK_LOST_PACKET   0x04
148 #define TCP_A_KEEP_ALIVE        0x08
149 struct tcp_acked {
150         guint32 frame_acked;
151         nstime_t ts;
152         guint8 flags;
153 };
154 static GHashTable *tcp_analyze_acked_table = NULL;
155
156 static GMemChunk *tcp_rel_seq_chunk = NULL;
157 static int tcp_rel_seq_count = 10000; /* one for each segment in the capture */
158 struct tcp_rel_seq {
159         guint32 seq_base;
160         guint32 ack_base;
161 };
162 static GHashTable *tcp_rel_seq_table = NULL;
163
164 static GMemChunk *tcp_analysis_chunk = NULL;
165 static int tcp_analysis_count = 20;     /* one for each conversation */
166 struct tcp_analysis {
167         /* These two structs are managed based on comparing the source
168          * and destination addresses and, if they're equal, comparing
169          * the source and destination ports.
170          *
171          * If the source is greater than the destination, then stuff
172          * sent from src is in ual1.
173          *
174          * If the source is less than the destination, then stuff
175          * sent from src is in ual2.
176          *
177          * XXX - if the addresses and ports are equal, we don't guarantee
178          * the behavior.
179          */
180         struct tcp_unacked *ual1;       /* UnAcked List 1*/
181         guint32 base_seq1;
182         struct tcp_unacked *ual2;       /* UnAcked List 2*/
183         guint32 base_seq2;
184 };
185
186 static void
187 tcp_get_relative_seq_ack(guint32 frame, guint32 *seq, guint32 *ack)
188 {
189         struct tcp_rel_seq *trs;
190
191         trs=g_hash_table_lookup(tcp_rel_seq_table, (void *)frame);
192         if(!trs){
193                 return;
194         }
195
196         (*seq) -= trs->seq_base;
197         (*ack) -= trs->ack_base;
198 }
199
200 static struct tcp_acked *
201 tcp_analyze_get_acked_struct(guint32 frame, gboolean createflag)
202 {
203         struct tcp_acked *ta;
204
205         ta=g_hash_table_lookup(tcp_analyze_acked_table, (void *)frame);
206         if((!ta) && createflag){
207                 ta=g_mem_chunk_alloc(tcp_acked_chunk);
208                 ta->frame_acked=0;
209                 ta->ts.secs=0;
210                 ta->ts.nsecs=0;
211                 ta->flags=0;
212                 g_hash_table_insert(tcp_analyze_acked_table, (void *)frame, ta);
213         }
214         return ta;
215 }
216
217 static void
218 tcp_analyze_sequence_number(packet_info *pinfo, guint32 seq, guint32 ack, guint32 seglen, guint8 flags)
219 {
220         conversation_t *conv=NULL;
221         struct tcp_analysis *tcpd=NULL;
222         int direction;
223         struct tcp_unacked *ual1=NULL;
224         struct tcp_unacked *ual2=NULL;
225         struct tcp_unacked *ual=NULL;
226         guint32 base_seq;
227         guint32 base_ack;
228
229         /* Have we seen this conversation before? */
230         if( (conv=find_conversation(&pinfo->src, &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport, 0)) == NULL){
231                 /* No this is a new conversation. */
232                 conv=conversation_new(&pinfo->src, &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
233         }
234
235         /* check if we have any data for this conversation */
236         tcpd=conversation_get_proto_data(conv, proto_tcp);
237         if(!tcpd){
238                 /* No no such data yet. Allocate and init it */
239                 tcpd=g_mem_chunk_alloc(tcp_analysis_chunk);
240                 tcpd->ual1=NULL;
241                 tcpd->base_seq1=0;
242                 tcpd->ual2=NULL;
243                 tcpd->base_seq2=0;
244                 conversation_add_proto_data(conv, proto_tcp, tcpd);
245         }
246
247         /* check direction and get ua lists */
248         direction=CMP_ADDRESS(&pinfo->src, &pinfo->dst);
249         if(direction==0)
250                 direction=pinfo->srcport - pinfo->destport;
251         if(direction>=0){
252                 /*
253                  * XXX - if direction == 0, that'll be true for packets
254                  * from both sides of the connection, so this won't
255                  * work.
256                  *
257                  * That'd be a connection from a given port on a machine
258                  * to that same port on the same machine; does that ever
259                  * happen?
260                  */
261                 ual1=tcpd->ual1;
262                 ual2=tcpd->ual2;
263                 base_seq=tcpd->base_seq1;
264                 base_ack=tcpd->base_seq2;
265         } else {
266                 ual1=tcpd->ual2;
267                 ual2=tcpd->ual1;
268                 base_seq=tcpd->base_seq2;
269                 base_ack=tcpd->base_seq1;
270         }
271
272         if(base_seq==0){
273                 base_seq=seq;
274         }
275         if(base_ack==0){
276                 base_ack=ack;
277         }
278
279         /* handle the sequence numbers */
280         /* if this was a SYN packet, then remove existing list and 
281          * put SEQ+1 first the list */
282         if(flags&TH_SYN){
283                 for(ual=ual1;ual1;ual1=ual){
284                         ual=ual1->next;
285                         g_mem_chunk_free(tcp_unacked_chunk, ual1);
286                 }
287                 ual1=g_mem_chunk_alloc(tcp_unacked_chunk);
288                 ual1->next=NULL;
289                 ual1->frame=pinfo->fd->num;
290                 ual1->seq=seq+1;
291                 ual1->nextseq=seq+1;
292                 ual1->ts.secs=pinfo->fd->abs_secs;
293                 ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
294                 base_seq=seq;
295                 base_ack=ack;
296                 goto seq_finished;
297         }
298
299         /* if this is the first segment we see then just add it */
300         if( !ual1 ){
301                 ual1=g_mem_chunk_alloc(tcp_unacked_chunk);
302                 ual1->next=NULL;
303                 ual1->frame=pinfo->fd->num;
304                 ual1->seq=seq;
305                 ual1->nextseq=seq+seglen;
306                 ual1->ts.secs=pinfo->fd->abs_secs;
307                 ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
308                 base_seq=seq;
309                 goto seq_finished;
310         }
311
312         /* if we get past here we know that ual1 points to a segment */
313
314         /* To handle FIN, just pretend they have a length of 1. 
315            else the ACK following the FIN-ACK will look like it was
316            outside the window. */
317         if( (!seglen) && (flags&TH_FIN) ){
318                 seglen=1;
319         }
320
321         /* if seq is beyond ual1->nextseq we have lost a segment */
322         if (GT_SEQ(seq, ual1->nextseq)) {
323                 struct tcp_acked *ta;
324
325                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
326                 ta->flags|=TCP_A_LOST_PACKET;
327
328                 /* just add the segment to the beginning of the list */
329                 ual=g_mem_chunk_alloc(tcp_unacked_chunk);
330                 ual->next=ual1;
331                 ual->frame=pinfo->fd->num;
332                 ual->seq=seq;
333                 ual->nextseq=seq+seglen;
334                 ual->ts.secs=pinfo->fd->abs_secs;
335                 ual->ts.nsecs=pinfo->fd->abs_usecs*1000;
336                 ual1=ual;
337                 goto seq_finished;
338         }
339
340         /* keep-alives are empty semgents with a sequence number -1 of what
341          * we would expect.
342          */
343         if( (!seglen) && EQ_SEQ(seq, (ual1->nextseq-1)) ){
344                 struct tcp_acked *ta;
345
346                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
347                 ta->flags|=TCP_A_KEEP_ALIVE;
348                 goto seq_finished;
349         }
350
351
352         /* if this is an empty segment, just skip it all */
353         if( !seglen ){
354                 goto seq_finished;
355         }
356
357         /* check if the sequence number is lower than expected, i.e. retransmission */
358         if( LT_SEQ(seq, ual1->nextseq )){
359                 struct tcp_acked *ta;
360
361                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
362                 ta->flags|=TCP_A_RETRANSMISSION;
363
364                 /* did this segment contain any more data we havent seen yet?
365                  * if so we can just increase nextseq
366                  */
367                 if(GT_SEQ((seq+seglen), ual1->nextseq)){
368                         ual1->nextseq=seq+seglen;
369                         ual1->frame=pinfo->fd->num;
370                         ual1->ts.secs=pinfo->fd->abs_secs;
371                         ual1->ts.nsecs=pinfo->fd->abs_usecs*1000;
372                 }
373                 goto seq_finished;
374         }
375
376         /* just add the segment to the beginning of the list */
377         ual=g_mem_chunk_alloc(tcp_unacked_chunk);
378         ual->next=ual1;
379         ual->frame=pinfo->fd->num;
380         ual->seq=seq;
381         ual->nextseq=seq+seglen;
382         ual->ts.secs=pinfo->fd->abs_secs;
383         ual->ts.nsecs=pinfo->fd->abs_usecs*1000;
384         ual1=ual;
385
386 seq_finished:
387
388
389         /* handle the ack numbers */
390
391         /* if we dont have the ack flag its not much we can do */
392         if( !(flags&TH_ACK)){
393                 goto ack_finished;
394         }
395
396         /* if we havent seen anything yet in the other direction we dont
397          * know what this one acks */
398         if( !ual2 ){
399                 goto ack_finished;
400         }
401
402         /* if we dont have any real segments in the other direction not 
403          * acked yet (as we see from the magic frame==0 entry)
404          * then there is no point in continuing
405          */
406         if( !ual2->frame ){
407                 goto ack_finished;
408         }
409
410         /* if we get here we know ual2 is valid */
411
412         /* if we are acking beyong what we have seen in the other direction
413          * we must have lost packets. Not much point in keeping the segments
414          * in the other direction either.
415          */
416         if( GT_SEQ(ack, ual2->nextseq )){
417                 struct tcp_acked *ta;
418
419                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
420                 ta->flags|=TCP_A_ACK_LOST_PACKET;
421                 for(ual=ual2;ual2;ual2=ual){
422                         ual=ual2->next;
423                         g_mem_chunk_free(tcp_unacked_chunk, ual2);
424                 }
425                 goto ack_finished;
426         }
427
428
429         /* does this ACK ack all semgents we have seen in the other direction?*/
430         if( EQ_SEQ(ack, ual2->nextseq )){
431                 struct tcp_acked *ta;
432
433                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
434                 ta->frame_acked=ual2->frame;
435                 ta->ts.secs=pinfo->fd->abs_secs-ual2->ts.secs;
436                 ta->ts.nsecs=pinfo->fd->abs_usecs*1000-ual2->ts.nsecs;
437                 if(ta->ts.nsecs<0){
438                         ta->ts.nsecs+=1000000000;
439                         ta->ts.secs--;
440                 }
441
442                 /* its all been ACKed so we dont need to keep them anymore */
443                 for(ual=ual2;ual2;ual2=ual){
444                         ual=ual2->next;
445                         g_mem_chunk_free(tcp_unacked_chunk, ual2);
446                 }
447                 goto ack_finished;
448         }
449
450         /* ok it only ACKs part of what we have seen. Find out how much
451          * update and remove the ACKed segments
452          */
453         for(ual=ual2;ual->next;ual=ual->next){
454                 if( GE_SEQ(ack, ual->next->nextseq)){
455                         break;
456                 }
457         }
458         if(ual->next){
459                 struct tcp_unacked *tmpual=NULL;
460                 struct tcp_unacked *ackedual=NULL;
461                 struct tcp_acked *ta;
462
463                 /* XXX normal ACK*/
464                 ackedual=ual->next;
465
466                 ta=tcp_analyze_get_acked_struct(pinfo->fd->num, TRUE);
467                 ta->frame_acked=ackedual->frame;
468                 ta->ts.secs=pinfo->fd->abs_secs-ackedual->ts.secs;
469                 ta->ts.nsecs=pinfo->fd->abs_usecs*1000-ackedual->ts.nsecs;
470                 if(ta->ts.nsecs<0){
471                         ta->ts.nsecs+=1000000000;
472                         ta->ts.secs--;
473                 }
474
475                 /* just delete all ACKed segments */
476                 tmpual=ual->next;
477                 ual->next=NULL;
478                 for(ual=tmpual;ual;ual=tmpual){
479                         tmpual=ual->next;
480                         g_mem_chunk_free(tcp_unacked_chunk, ual);
481                 }
482
483         }
484
485
486 ack_finished:
487         /* we might have deleted the entire ual2 list, if this is an ACK, 
488            make sure ual2 at least has a dummy entry for the current ACK */
489         if( (!ual2) && (flags&TH_ACK) ){
490                 ual2=g_mem_chunk_alloc(tcp_unacked_chunk);
491                 ual2->next=NULL;
492                 ual2->frame=0;
493                 ual2->seq=ack;
494                 ual2->nextseq=ack;
495                 ual2->ts.secs=0;
496                 ual2->ts.nsecs=0;
497         }
498
499
500         /* store the lists back in our struct */
501         if(direction>=0){
502                 /*
503                  * XXX - if direction == 0, that'll be true for packets
504                  * from both sides of the connection, so this won't
505                  * work.
506                  *
507                  * That'd be a connection from a given port on a machine
508                  * to that same port on the same machine; does that ever
509                  * happen?
510                  */
511                 tcpd->ual1=ual1;
512                 tcpd->ual2=ual2;
513                 tcpd->base_seq1=base_seq;
514         } else {
515                 tcpd->ual1=ual2;
516                 tcpd->ual2=ual1;
517                 tcpd->base_seq2=base_seq;
518         }
519
520         if(tcp_relative_seq){
521                 struct tcp_rel_seq *trs;
522                 /* remember relative seq/ack number base for this packet */
523                 trs=g_mem_chunk_alloc(tcp_rel_seq_chunk);
524                 trs->seq_base=base_seq;
525                 trs->ack_base=base_ack;
526                 g_hash_table_insert(tcp_rel_seq_table, (void *)pinfo->fd->num, trs);
527         }
528 }
529
530 static void
531 tcp_print_sequence_number_analysis(packet_info *pinfo, tvbuff_t *tvb, proto_tree *parent_tree)
532 {
533         struct tcp_acked *ta;
534         proto_item *item;
535         proto_tree *tree;
536
537         ta=tcp_analyze_get_acked_struct(pinfo->fd->num, FALSE);
538         if(!ta){
539                 return;
540         }
541
542         item=proto_tree_add_text(parent_tree, tvb, 0, 0, "SEQ/ACK analysis");
543         tree=proto_item_add_subtree(item, ett_tcp_analysis);
544
545         /* encapsulate all proto_tree_add_xxx in ifs so we only print what 
546            data we actually have */
547         if(ta->frame_acked){
548                 proto_tree_add_uint(tree, hf_tcp_analysis_acks_frame, 
549                         tvb, 0, 0, ta->frame_acked);
550         }
551         if( ta->ts.secs || ta->ts.nsecs ){
552                 proto_tree_add_time(tree, hf_tcp_analysis_ack_rtt, 
553                 tvb, 0, 0, &ta->ts);
554         }
555
556         if(ta->flags){
557                 proto_item *flags_item=NULL;
558                 proto_tree *flags_tree=NULL;
559
560                 flags_item = proto_tree_add_item(tree, hf_tcp_analysis_flags, tvb, 0, -1, FALSE);
561                 flags_tree=proto_item_add_subtree(flags_item, ett_tcp_analysis);
562                 if( ta->flags&TCP_A_RETRANSMISSION ){
563                         proto_tree_add_boolean_format(flags_tree, hf_tcp_analysis_retransmission, tvb, 0, 0, TRUE, "This frame is a (suspected) retransmission");
564                         if(check_col(pinfo->cinfo, COL_INFO)){
565                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Retransmission] ");
566                         }
567                 }
568                 if( ta->flags&TCP_A_LOST_PACKET ){
569                         proto_tree_add_boolean_format(flags_tree, hf_tcp_analysis_lost_packet, tvb, 0, 0, TRUE, "A segment before this frame was lost");
570                         if(check_col(pinfo->cinfo, COL_INFO)){
571                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Previous segment lost] ");
572                         }
573                 }
574                 if( ta->flags&TCP_A_ACK_LOST_PACKET ){
575                         proto_tree_add_boolean_format(flags_tree, hf_tcp_analysis_ack_lost_packet, tvb, 0, 0, TRUE, "This frame ACKs a segment we have not seen (lost?)");
576                         if(check_col(pinfo->cinfo, COL_INFO)){
577                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP ACKed lost segment] ");
578                         }
579                 }
580                 if( ta->flags&TCP_A_KEEP_ALIVE ){
581                         proto_tree_add_boolean_format(flags_tree, hf_tcp_analysis_keep_alive, tvb, 0, 0, TRUE, "This is a TCP keep-alive segment");
582                         if(check_col(pinfo->cinfo, COL_INFO)){
583                                 col_prepend_fstr(pinfo->cinfo, COL_INFO, "[TCP Keep-Alive] ");
584                         }
585                 }
586         }
587
588 }
589
590
591 /* Do we still need to do this ...remove_all() even though we dont need
592  * to do anything special?  The glib docs are not clear on this and
593  * its better safe than sorry
594  */
595 static gboolean
596 free_all_acked(gpointer key_arg _U_, gpointer value _U_, gpointer user_data _U_)
597 {
598         return TRUE;
599 }
600
601 static guint
602 tcp_acked_hash(gconstpointer k)
603 {
604         guint32 frame = (guint32)k;
605
606         return frame;
607 }
608 static gint
609 tcp_acked_equal(gconstpointer k1, gconstpointer k2)
610 {
611         guint32 frame1 = (guint32)k1;
612         guint32 frame2 = (guint32)k2;
613
614         return frame1==frame2;
615 }
616
617 static void
618 tcp_analyze_seq_init(void)
619 {
620         /* first destroy the tables */
621         if( tcp_analyze_acked_table ){
622                 g_hash_table_foreach_remove(tcp_analyze_acked_table,
623                         free_all_acked, NULL);
624                 g_hash_table_destroy(tcp_analyze_acked_table);
625                 tcp_analyze_acked_table = NULL;
626         }
627         if( tcp_rel_seq_table ){
628                 g_hash_table_foreach_remove(tcp_rel_seq_table,
629                         free_all_acked, NULL);
630                 g_hash_table_destroy(tcp_rel_seq_table);
631                 tcp_rel_seq_table = NULL;
632         }
633                 
634         /*
635          * Now destroy the chunk from which the conversation table
636          * structures were allocated.
637          */
638         if (tcp_analysis_chunk) {
639                 g_mem_chunk_destroy(tcp_analysis_chunk);
640                 tcp_analysis_chunk = NULL;
641         }
642         if (tcp_unacked_chunk) {
643                 g_mem_chunk_destroy(tcp_unacked_chunk);
644                 tcp_unacked_chunk = NULL;
645         }
646         if (tcp_acked_chunk) {
647                 g_mem_chunk_destroy(tcp_acked_chunk);
648                 tcp_acked_chunk = NULL;
649         }
650         if (tcp_rel_seq_chunk) {
651                 g_mem_chunk_destroy(tcp_rel_seq_chunk);
652                 tcp_rel_seq_chunk = NULL;
653         }
654
655         if(tcp_analyze_seq){
656                 tcp_analyze_acked_table = g_hash_table_new(tcp_acked_hash,
657                         tcp_acked_equal);
658                 tcp_rel_seq_table = g_hash_table_new(tcp_acked_hash,
659                         tcp_acked_equal);
660                 tcp_analysis_chunk = g_mem_chunk_new("tcp_analysis_chunk",
661                         sizeof(struct tcp_analysis),
662                         tcp_analysis_count * sizeof(struct tcp_analysis),
663                         G_ALLOC_ONLY);
664                 tcp_unacked_chunk = g_mem_chunk_new("tcp_unacked_chunk",
665                         sizeof(struct tcp_unacked),
666                         tcp_unacked_count * sizeof(struct tcp_unacked),
667                         G_ALLOC_ONLY);
668                 tcp_acked_chunk = g_mem_chunk_new("tcp_acked_chunk",
669                         sizeof(struct tcp_acked),
670                         tcp_acked_count * sizeof(struct tcp_acked),
671                         G_ALLOC_ONLY);
672                 if(tcp_relative_seq){
673                         tcp_rel_seq_chunk = g_mem_chunk_new("tcp_rel_seq_chunk",
674                                 sizeof(struct tcp_rel_seq),
675                                 tcp_rel_seq_count * sizeof(struct tcp_rel_seq),
676                                 G_ALLOC_ONLY);
677                 }
678         }
679
680 }
681
682 /* **************************************************************************
683  * End of tcp sequence number analysis 
684  * **************************************************************************/
685
686
687
688
689 /* Minimum TCP header length. */
690 #define TCPH_MIN_LEN    20
691
692 /*
693  *      TCP option
694  */
695  
696 #define TCPOPT_NOP              1       /* Padding */
697 #define TCPOPT_EOL              0       /* End of options */
698 #define TCPOPT_MSS              2       /* Segment size negotiating */
699 #define TCPOPT_WINDOW           3       /* Window scaling */
700 #define TCPOPT_SACK_PERM        4       /* SACK Permitted */
701 #define TCPOPT_SACK             5       /* SACK Block */
702 #define TCPOPT_ECHO             6
703 #define TCPOPT_ECHOREPLY        7
704 #define TCPOPT_TIMESTAMP        8       /* Better RTT estimations/PAWS */
705 #define TCPOPT_CC               11
706 #define TCPOPT_CCNEW            12
707 #define TCPOPT_CCECHO           13
708 #define TCPOPT_MD5              19      /* RFC2385 */
709
710 /*
711  *     TCP option lengths
712  */
713
714 #define TCPOLEN_MSS            4
715 #define TCPOLEN_WINDOW         3
716 #define TCPOLEN_SACK_PERM      2
717 #define TCPOLEN_SACK_MIN       2
718 #define TCPOLEN_ECHO           6
719 #define TCPOLEN_ECHOREPLY      6
720 #define TCPOLEN_TIMESTAMP      10
721 #define TCPOLEN_CC             6
722 #define TCPOLEN_CCNEW          6
723 #define TCPOLEN_CCECHO         6
724 #define TCPOLEN_MD5            18
725
726
727
728 /* Desegmentation of TCP streams */
729 /* table to hold defragmented TCP streams */
730 static GHashTable *tcp_fragment_table = NULL;
731 static void
732 tcp_fragment_init(void)
733 {
734         fragment_table_init(&tcp_fragment_table);
735 }
736
737 /* functions to trace tcp segments */
738 /* Enable desegmenting of TCP streams */
739 static gboolean tcp_desegment = FALSE;
740
741 static GHashTable *tcp_segment_table = NULL;
742 static GMemChunk *tcp_segment_key_chunk = NULL;
743 static int tcp_segment_init_count = 200;
744 static GMemChunk *tcp_segment_address_chunk = NULL;
745 static int tcp_segment_address_init_count = 500;
746
747 typedef struct _tcp_segment_key {
748         /* for own bookkeeping inside packet-tcp.c */
749         address *src;
750         address *dst;
751         guint32 seq;
752         /* xxx */
753         guint32 start_seq;
754         guint32 tot_len;
755         guint32 first_frame;
756 } tcp_segment_key;
757
758 static gboolean
759 free_all_segments(gpointer key_arg, gpointer value _U_, gpointer user_data _U_)
760 {
761         tcp_segment_key *key = key_arg;
762
763         if((key->src)&&(key->src->data)){
764                 g_free((gpointer)key->src->data);
765                 key->src->data=NULL;
766         }
767
768         if((key->dst)&&(key->dst->data)){
769                 g_free((gpointer)key->dst->data);
770                 key->dst->data=NULL;
771         }
772
773         return TRUE;
774 }
775
776 static guint
777 tcp_segment_hash(gconstpointer k)
778 {
779         tcp_segment_key *key = (tcp_segment_key *)k;
780
781         return key->seq;
782 }
783
784 static gint
785 tcp_segment_equal(gconstpointer k1, gconstpointer k2)
786 {
787         tcp_segment_key *key1 = (tcp_segment_key *)k1;
788         tcp_segment_key *key2 = (tcp_segment_key *)k2;
789
790         return ( ( (key1->seq==key2->seq)
791                  &&(ADDRESSES_EQUAL(key1->src, key2->src))
792                  &&(ADDRESSES_EQUAL(key1->dst, key2->dst))
793                  ) ? TRUE:FALSE);
794 }
795
796 static void
797 tcp_desegment_init(void)
798 {
799         /*
800          * Free this before freeing any memory chunks; those
801          * chunks contain data we'll look at in "free_all_segments()".
802          */
803         if(tcp_segment_table){
804                 g_hash_table_foreach_remove(tcp_segment_table,
805                         free_all_segments, NULL);
806                 g_hash_table_destroy(tcp_segment_table);
807                 tcp_segment_table = NULL;
808         }
809
810         if(tcp_segment_key_chunk){
811                 g_mem_chunk_destroy(tcp_segment_key_chunk);
812                 tcp_segment_key_chunk = NULL;
813         }
814         if(tcp_segment_address_chunk){
815                 g_mem_chunk_destroy(tcp_segment_address_chunk);
816                 tcp_segment_address_chunk = NULL;
817         }
818
819         /* dont allocate any hash table or memory chunks unless the user
820            really uses this option
821         */
822         if(!tcp_desegment){
823                 return;
824         }
825
826         tcp_segment_table = g_hash_table_new(tcp_segment_hash,
827                 tcp_segment_equal);
828
829         tcp_segment_key_chunk = g_mem_chunk_new("tcp_segment_key_chunk",
830                 sizeof(tcp_segment_key),
831                 tcp_segment_init_count*sizeof(tcp_segment_key),
832                 G_ALLOC_ONLY);
833
834         tcp_segment_address_chunk = g_mem_chunk_new("tcp_segment_address_chunk",
835                 sizeof(address),
836                 tcp_segment_address_init_count*sizeof(address),
837                 G_ALLOC_ONLY);
838 }
839
840 static void
841 desegment_tcp(tvbuff_t *tvb, packet_info *pinfo, int offset,
842                 guint32 seq, guint32 nxtseq,
843                 guint32 sport, guint32 dport,
844                 proto_tree *tree, proto_tree *tcp_tree)
845 {
846         struct tcpinfo *tcpinfo = pinfo->private_data;
847         fragment_data *ipfd_head;
848         tcp_segment_key old_tsk, *tsk;
849         gboolean must_desegment = FALSE;
850         gboolean called_dissector = FALSE;
851         int deseg_offset;
852         guint32 deseg_seq;
853         gint nbytes;
854
855         /*
856          * Initialize these to assume no desegmentation.
857          * If that's not the case, these will be set appropriately
858          * by the subdissector.
859          */
860         pinfo->desegment_offset = 0;
861         pinfo->desegment_len = 0;
862
863         /*
864          * Initialize this to assume that this segment will just be
865          * added to the middle of a desegmented chunk of data, so
866          * that we should show it all as data.
867          * If that's not the case, it will be set appropriately.
868          */
869         deseg_offset = offset;
870
871         /* First we must check if this TCP segment should be desegmented.
872            This is only to check if we should desegment this packet,
873            so we dont spend time doing COPY_ADDRESS/g_free.
874            We just "borrow" some address structures from pinfo instead. Cheaper.
875         */
876         old_tsk.src = &pinfo->src;
877         old_tsk.dst = &pinfo->dst;
878         old_tsk.seq = seq;
879         tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
880
881         if(tsk){
882                 /* OK, this segment was found, which means it continues
883                    a higher-level PDU. This means we must desegment it.
884                    Add it to the defragmentation lists.
885                 */
886                 ipfd_head = fragment_add(tvb, offset, pinfo, tsk->start_seq,
887                         tcp_fragment_table,
888                         seq - tsk->start_seq,
889                         nxtseq - seq,
890                         (nxtseq < (tsk->start_seq + tsk->tot_len)) );
891
892                 if(!ipfd_head){
893                         /* fragment_add() returned NULL, This means that 
894                            desegmentation is not completed yet.
895                            (its like defragmentation but we know we will
896                             always add the segments in order).
897                            XXX - no, we don't; there is no guarantee that
898                            TCP segments are in order on the wire.
899
900                            we must add next segment to our table so we will
901                            find it later.
902                         */
903                         tcp_segment_key *new_tsk;
904
905                         new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
906                         memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
907                         new_tsk->seq=nxtseq;
908                         g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
909                 }
910         } else {
911                 /* This segment was not found in our table, so it doesn't
912                    contain a continuation of a higher-level PDU.
913                    Call the normal subdissector.
914                 */
915                 decode_tcp_ports(tvb, offset, pinfo, tree, 
916                                 sport, dport);
917                 called_dissector = TRUE;
918
919                 /* Did the subdissector ask us to desegment some more data
920                    before it could handle the packet? 
921                    If so we have to create some structures in our table but
922                    this is something we only do the first time we see this 
923                    packet.
924                 */
925                 if(pinfo->desegment_len) {
926                         if (!pinfo->fd->flags.visited)
927                                 must_desegment = TRUE;
928
929                         /*
930                          * Set "deseg_offset" to the offset in "tvb"
931                          * of the first byte of data that the
932                          * subdissector didn't process.
933                          */
934                         deseg_offset = offset + pinfo->desegment_offset;
935                 }
936
937                 /* Either no desegmentation is necessary, or this is
938                    segment contains the beginning but not the end of
939                    a higher-level PDU and thus isn't completely
940                    desegmented.
941                 */
942                 ipfd_head = NULL;
943         }
944
945         /* is it completely desegmented? */
946         if(ipfd_head){
947                 fragment_data *ipfd;
948                 proto_tree *st = NULL;
949                 proto_item *si = NULL;
950
951                 /*
952                  * Yes, we think it is.
953                  * We only call subdissector for the last segment.
954                  * Note that the last segment may include more than what
955                  * we needed.
956                  */
957                 if(nxtseq >= (tsk->start_seq + tsk->tot_len)){
958                         /*
959                          * OK, this is the last segment.
960                          * Let's call the subdissector with the desegmented
961                          * data.
962                          */
963                         tvbuff_t *next_tvb;
964                         int old_len;
965
966                         /* create a new TVB structure for desegmented data */
967                         next_tvb = tvb_new_real_data(ipfd_head->data,
968                                         ipfd_head->datalen, ipfd_head->datalen);
969
970                         /* add this tvb as a child to the original one */
971                         tvb_set_child_real_data_tvbuff(tvb, next_tvb);
972
973                         /* add desegmented data to the data source list */
974                         add_new_data_source(pinfo, next_tvb, "Desegmented");
975
976                         /*
977                          * Supply the sequence number of the first of the
978                          * reassembled bytes.
979                          */
980                         tcpinfo->seq = tsk->start_seq;
981
982                         /* indicate that this is reassembled data */
983                         tcpinfo->is_reassembled = TRUE;
984
985                         /* call subdissector */
986                         decode_tcp_ports(next_tvb, 0, pinfo, tree,
987                                 sport, dport);
988                         called_dissector = TRUE;
989
990                         /*
991                          * OK, did the subdissector think it was completely
992                          * desegmented, or does it think we need even more
993                          * data?
994                          */
995                         old_len=(int)(tvb_reported_length(next_tvb)-tvb_reported_length_remaining(tvb, offset));
996                         if(pinfo->desegment_len &&
997                             pinfo->desegment_offset<=old_len){
998                                 tcp_segment_key *new_tsk;
999
1000                                 /*
1001                                  * "desegment_len" isn't 0, so it needs more
1002                                  * data for something - and "desegment_offset"
1003                                  * is before "old_len", so it needs more data
1004                                  * to dissect the stuff we thought was
1005                                  * completely desegmented (as opposed to the
1006                                  * stuff at the beginning being completely
1007                                  * desegmented, but the stuff at the end
1008                                  * being a new higher-level PDU that also
1009                                  * needs desegmentation).
1010                                  */
1011                                 fragment_set_partial_reassembly(pinfo,tsk->start_seq,tcp_fragment_table);
1012                                 tsk->tot_len = tvb_reported_length(next_tvb) + pinfo->desegment_len;
1013
1014                                 /*
1015                                  * Update tsk structure.
1016                                  * Can ask ->next->next because at least there's a hdr and one
1017                                  * entry in fragment_add()
1018                                  */
1019                                 for(ipfd=ipfd_head->next; ipfd->next; ipfd=ipfd->next){
1020                                         old_tsk.seq = tsk->start_seq + ipfd->offset;
1021                                         new_tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
1022                                         new_tsk->tot_len = tsk->tot_len;
1023                                 }
1024
1025                                 /* this is the next segment in the sequence we want */
1026                                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1027                                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1028                                 new_tsk->seq = nxtseq;
1029                                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1030                         } else {
1031                                 /*
1032                                  * Show the stuff in this TCP segment as
1033                                  * just raw TCP segment data.
1034                                  */
1035                                 nbytes =
1036                                     tvb_reported_length_remaining(tvb, offset);
1037                                 proto_tree_add_text(tcp_tree, tvb, offset, -1,
1038                                     "TCP segment data (%u byte%s)", nbytes,
1039                                     plurality(nbytes, "", "s"));
1040
1041                                 /*
1042                                  * The subdissector thought it was completely
1043                                  * desegmented (although the stuff at the
1044                                  * end may, in turn, require desegmentation),
1045                                  * so we show a tree with all segments.
1046                                  */
1047                                 si = proto_tree_add_text(tcp_tree, next_tvb,
1048                                                 0, -1, "Segments");
1049                                 st = proto_item_add_subtree(si, ett_tcp_segments);
1050                                 for(ipfd=ipfd_head->next; ipfd; ipfd=ipfd->next){
1051                                         proto_tree_add_text(st, next_tvb,
1052                                         ipfd->offset, ipfd->len,
1053                                         "Frame:%u seq#:%u-%u [%u-%u]",
1054                                         ipfd->frame,
1055                                         tsk->start_seq + ipfd->offset,
1056                                         tsk->start_seq + ipfd->offset + ipfd->len-1,
1057                                         ipfd->offset,
1058                                         ipfd->offset + ipfd->len - 1);
1059                                 }
1060
1061                                 /* Did the subdissector ask us to desegment
1062                                    some more data?  This means that the data
1063                                    at the beginning of this segment completed
1064                                    a higher-level PDU, but the data at the
1065                                    end of this segment started a higher-level
1066                                    PDU but didn't complete it.
1067
1068                                    If so, we have to create some structures
1069                                    in our table, but this is something we
1070                                    only do the first time we see this packet.
1071                                 */
1072                                 if(pinfo->desegment_len) {
1073                                         if (!pinfo->fd->flags.visited)
1074                                                 must_desegment = TRUE;
1075
1076                                         /* The stuff we couldn't dissect
1077                                            must have come from this segment,
1078                                            so it's all in "tvb".
1079
1080                                            "pinfo->desegment_offset" is
1081                                            relative to the beginning of
1082                                            "next_tvb"; we want an offset
1083                                            relative to the beginning of "tvb".
1084
1085                                            First, compute the offset relative
1086                                            to the *end* of "next_tvb" - i.e.,
1087                                            the number of bytes before the end
1088                                            of "next_tvb" at which the
1089                                            subdissector stopped.  That's the
1090                                            length of "next_tvb" minus the
1091                                            offset, relative to the beginning
1092                                            of "next_tvb, at which the
1093                                            subdissector stopped.
1094                                         */
1095                                         deseg_offset =
1096                                             ipfd_head->datalen - pinfo->desegment_offset;
1097
1098                                         /* "tvb" and "next_tvb" end at the
1099                                            same byte of data, so the offset
1100                                            relative to the end of "next_tvb"
1101                                            of the byte at which we stopped
1102                                            is also the offset relative to
1103                                            the end of "tvb" of the byte at
1104                                            which we stopped.
1105
1106                                            Convert that back into an offset
1107                                            relative to the beginninng of
1108                                            "tvb", by taking the length of
1109                                            "tvb" and subtracting the offset
1110                                            relative to the end.
1111                                         */
1112                                         deseg_offset=tvb_reported_length(tvb) - deseg_offset;
1113                                 }
1114                         }
1115                 }
1116         }
1117
1118         if (must_desegment) {
1119             tcp_segment_key *tsk, *new_tsk;
1120
1121             /*
1122              * The sequence number at which the stuff to be desegmented
1123              * starts is the sequence number of the byte at an offset
1124              * of "deseg_offset" into "tvb".
1125              *
1126              * The sequence number of the byte at an offset of "offset"
1127              * is "seq", i.e. the starting sequence number of this
1128              * segment, so the sequence number of the byte at
1129              * "deseg_offset" is "seq + (deseg_offset - offset)".
1130              */
1131             deseg_seq = seq + (deseg_offset - offset);
1132
1133             /*
1134              * XXX - how do we detect out-of-order transmissions?
1135              * We can't just check for "nxtseq" being greater than
1136              * "tsk->start_seq"; for now, we check for the difference
1137              * being less than a megabyte, but this is a really
1138              * gross hack - we really need to handle out-of-order
1139              * transmissions correctly.
1140              */
1141             if ((nxtseq - deseg_seq) <= 1024*1024) {
1142                 /* OK, subdissector wants us to desegment
1143                    some data before it can process it. Add
1144                    what remains of this packet and set
1145                    up next packet/sequence number as well.
1146
1147                    We must remember this segment
1148                 */
1149                 tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1150                 tsk->src = g_mem_chunk_alloc(tcp_segment_address_chunk);
1151                 COPY_ADDRESS(tsk->src, &pinfo->src);
1152                 tsk->dst = g_mem_chunk_alloc(tcp_segment_address_chunk);
1153                 COPY_ADDRESS(tsk->dst, &pinfo->dst);
1154                 tsk->seq = deseg_seq;
1155                 tsk->start_seq = tsk->seq;
1156                 tsk->tot_len = nxtseq - tsk->start_seq + pinfo->desegment_len;
1157                 tsk->first_frame = pinfo->fd->num;
1158                 g_hash_table_insert(tcp_segment_table, tsk, tsk);
1159
1160                 /* Add portion of segment unprocessed by the subdissector
1161                    to defragmentation lists */
1162                 fragment_add(tvb, deseg_offset, pinfo, tsk->start_seq,
1163                     tcp_fragment_table,
1164                     tsk->seq - tsk->start_seq,
1165                     nxtseq - tsk->start_seq,
1166                     (nxtseq < tsk->start_seq + tsk->tot_len));
1167
1168                 /* this is the next segment in the sequence we want */
1169                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
1170                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
1171                 new_tsk->seq = nxtseq;
1172                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
1173             }
1174         }
1175
1176         if (!called_dissector || pinfo->desegment_len != 0) {
1177                 /*
1178                  * Either we didn't call the subdissector at all (i.e.,
1179                  * this is a segment that contains the middle of a
1180                  * higher-level PDU, but contains neither the beginning
1181                  * nor the end), or the subdissector couldn't dissect it
1182                  * all, as some data was missing (i.e., it set
1183                  * "pinfo->desegment_len" to the amount of additional
1184                  * data it needs).
1185                  */
1186                 if (pinfo->desegment_offset == 0) {
1187                         /*
1188                          * It couldn't, in fact, dissect any of it (the
1189                          * first byte it couldn't dissect is at an offset
1190                          * of "pinfo->desegment_offset" from the beginning
1191                          * of the payload, and that's 0).
1192                          * Just mark this as TCP.
1193                          */
1194                         if (check_col(pinfo->cinfo, COL_PROTOCOL)){
1195                                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
1196                         }
1197                         if (check_col(pinfo->cinfo, COL_INFO)){
1198                                 col_set_str(pinfo->cinfo, COL_INFO, "[Desegmented TCP]");
1199                         }
1200                 }
1201
1202                 /*
1203                  * Show what's left in the packet as just raw TCP segment
1204                  * data.
1205                  * XXX - remember what protocol the last subdissector
1206                  * was, and report it as a continuation of that, instead?
1207                  */
1208                 nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
1209                 proto_tree_add_text(tcp_tree, tvb, deseg_offset, -1,
1210                     "TCP segment data (%u byte%s)", nbytes,
1211                     plurality(nbytes, "", "s"));
1212         }
1213         pinfo->can_desegment=0;
1214         pinfo->desegment_offset = 0;
1215         pinfo->desegment_len = 0;
1216 }
1217
1218 /*
1219  * Loop for dissecting PDUs within a TCP stream; assumes that a PDU
1220  * consists of a fixed-length chunk of data that contains enough information
1221  * to determine the length of the PDU, followed by rest of the PDU.
1222  *
1223  * The first three arguments are the arguments passed to the dissector
1224  * that calls this routine.
1225  *
1226  * "proto_desegment" is the dissector's flag controlling whether it should
1227  * desegment PDUs that cross TCP segment boundaries.
1228  *
1229  * "fixed_len" is the length of the fixed-length part of the PDU.
1230  *
1231  * "get_pdu_len()" is a routine called to get the length of the PDU from
1232  * the fixed-length part of the PDU; it's passed "tvb" and "offset".
1233  *
1234  * "dissect_pdu()" is the routine to dissect a PDU.
1235  */
1236 void
1237 tcp_dissect_pdus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
1238                  gboolean proto_desegment, guint fixed_len,
1239                  guint (*get_pdu_len)(tvbuff_t *, int),
1240                  void (*dissect_pdu)(tvbuff_t *, packet_info *, proto_tree *))
1241 {
1242   volatile int offset = 0;
1243   guint length_remaining;
1244   guint plen;
1245   guint length;
1246   tvbuff_t *next_tvb;
1247
1248   while (tvb_reported_length_remaining(tvb, offset) != 0) {
1249     /*
1250      * We use "tvb_ensure_length_remaining()" to make sure there actually
1251      * *is* data remaining.  The protocol we're handling could conceivably
1252      * consists of a sequence of fixed-length PDUs, and therefore the
1253      * "get_pdu_len" routine might not actually fetch anything from
1254      * the tvbuff, and thus might not cause an exception to be thrown if
1255      * we've run past the end of the tvbuff.
1256      *
1257      * This means we're guaranteed that "length_remaining" is positive.
1258      */
1259     length_remaining = tvb_ensure_length_remaining(tvb, offset);
1260
1261     /*
1262      * Can we do reassembly?
1263      */
1264     if (proto_desegment && pinfo->can_desegment) {
1265       /*
1266        * Yes - is the fixed-length part of the PDU split across segment
1267        * boundaries?
1268        */
1269       if (length_remaining < fixed_len) {
1270         /*
1271          * Yes.  Tell the TCP dissector where the data for this message
1272          * starts in the data it handed us, and how many more bytes we
1273          * need, and return.
1274          */
1275         pinfo->desegment_offset = offset;
1276         pinfo->desegment_len = fixed_len - length_remaining;
1277         return;
1278       }
1279     }
1280
1281     /*
1282      * Get the length of the PDU.
1283      */
1284     plen = (*get_pdu_len)(tvb, offset);
1285
1286     /*
1287      * Can we do reassembly?
1288      */
1289     if (proto_desegment && pinfo->can_desegment) {
1290       /*
1291        * Yes - is the PDU split across segment boundaries?
1292        */
1293       if (length_remaining < plen) {
1294         /*
1295          * Yes.  Tell the TCP dissector where the data for this message
1296          * starts in the data it handed us, and how many more bytes we
1297          * need, and return.
1298          */
1299         pinfo->desegment_offset = offset;
1300         pinfo->desegment_len = plen - length_remaining;
1301         return;
1302       }
1303     }
1304
1305     /*
1306      * Construct a tvbuff containing the amount of the payload we have
1307      * available.  Make its reported length the amount of data in the PDU.
1308      *
1309      * XXX - if reassembly isn't enabled. the subdissector will throw a
1310      * BoundsError exception, rather than a ReportedBoundsError exception.
1311      * We really want a tvbuff where the length is "length", the reported
1312      * length is "plen", and the "if the snapshot length were infinite"
1313      * length is the minimum of the reported length of the tvbuff handed
1314      * to us and "plen", with a new type of exception thrown if the offset
1315      * is within the reported length but beyond that third length, with
1316      * that exception getting the "Unreassembled Packet" error.
1317      */
1318     if (plen < fixed_len) {
1319       /*
1320        * The PDU length from the fixed-length portion probably didn't
1321        * include the fixed-length portion's length, and was probably so
1322        * large that the total length overflowed.
1323        *
1324        * Report this as an error.
1325        */
1326       show_reported_bounds_error(tvb, pinfo, tree);
1327       return;
1328     }
1329     length = length_remaining;
1330     if (length > plen)
1331         length = plen;
1332     next_tvb = tvb_new_subset(tvb, offset, length, plen);
1333
1334     /*
1335      * Dissect the PDU.
1336      *
1337      * Catch the ReportedBoundsError exception; if this particular message
1338      * happens to get a ReportedBoundsError exception, that doesn't mean
1339      * that we should stop dissecting PDUs within this frame or chunk of
1340      * reassembled data.
1341      *
1342      * If it gets a BoundsError, we can stop, as there's nothing more to
1343      * see, so we just re-throw it.
1344      */
1345     TRY {
1346       (*dissect_pdu)(next_tvb, pinfo, tree);
1347     }
1348     CATCH(BoundsError) {
1349       RETHROW;
1350     }
1351     CATCH(ReportedBoundsError) {
1352       show_reported_bounds_error(tvb, pinfo, tree);
1353     }
1354     ENDTRY;
1355
1356     /*
1357      * Step to the next PDU.
1358      */
1359     offset += plen;
1360   }
1361 }
1362
1363 static void
1364 tcp_info_append_uint(packet_info *pinfo, const char *abbrev, guint32 val)
1365 {
1366   if (check_col(pinfo->cinfo, COL_INFO))
1367     col_append_fstr(pinfo->cinfo, COL_INFO, " %s=%u", abbrev, val);
1368 }
1369
1370 static void
1371 dissect_tcpopt_maxseg(const ip_tcp_opt *optp, tvbuff_t *tvb,
1372     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
1373 {
1374   guint16 mss;
1375
1376   mss = tvb_get_ntohs(tvb, offset + 2);
1377   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
1378                         "%s: %u bytes", optp->name, mss);
1379   tcp_info_append_uint(pinfo, "MSS", mss);
1380 }
1381
1382 static void
1383 dissect_tcpopt_wscale(const ip_tcp_opt *optp, tvbuff_t *tvb,
1384     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
1385 {
1386   guint8 ws;
1387
1388   ws = tvb_get_guint8(tvb, offset + 2);
1389   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
1390                         "%s: %u (multiply by %u)", optp->name, ws, 1 << ws);
1391   tcp_info_append_uint(pinfo, "WS", ws);
1392 }
1393
1394 static void
1395 dissect_tcpopt_sack(const ip_tcp_opt *optp, tvbuff_t *tvb,
1396     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
1397 {
1398   proto_tree *field_tree = NULL;
1399   proto_item *tf;
1400   guint leftedge, rightedge;
1401
1402   tf = proto_tree_add_text(opt_tree, tvb, offset,      optlen, "%s:", optp->name);
1403   offset += 2;  /* skip past type and length */
1404   optlen -= 2;  /* subtract size of type and length */
1405   while (optlen > 0) {
1406     if (field_tree == NULL) {
1407       /* Haven't yet made a subtree out of this option.  Do so. */
1408       field_tree = proto_item_add_subtree(tf, *optp->subtree_index);
1409     }
1410     if (optlen < 4) {
1411       proto_tree_add_text(field_tree, tvb, offset,      optlen,
1412         "(suboption would go past end of option)");
1413       break;
1414     }
1415     leftedge = tvb_get_ntohl(tvb, offset);
1416     optlen -= 4;
1417     if (optlen < 4) {
1418       proto_tree_add_text(field_tree, tvb, offset,      optlen,
1419         "(suboption would go past end of option)");
1420       break;
1421     }
1422     /* XXX - check whether it goes past end of packet */
1423     rightedge = tvb_get_ntohl(tvb, offset + 4);
1424     optlen -= 4;
1425     proto_tree_add_text(field_tree, tvb, offset,      8,
1426         "left edge = %u, right edge = %u", leftedge, rightedge);
1427     tcp_info_append_uint(pinfo, "SLE", leftedge);
1428     tcp_info_append_uint(pinfo, "SRE", rightedge);
1429     offset += 8;
1430   }
1431 }
1432
1433 static void
1434 dissect_tcpopt_echo(const ip_tcp_opt *optp, tvbuff_t *tvb,
1435     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
1436 {
1437   guint32 echo;
1438
1439   echo = tvb_get_ntohl(tvb, offset + 2);
1440   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
1441                         "%s: %u", optp->name, echo);
1442   tcp_info_append_uint(pinfo, "ECHO", echo);
1443 }
1444
1445 static void
1446 dissect_tcpopt_timestamp(const ip_tcp_opt *optp, tvbuff_t *tvb,
1447     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
1448 {
1449   guint32 tsv, tser;
1450
1451   tsv = tvb_get_ntohl(tvb, offset + 2);
1452   tser = tvb_get_ntohl(tvb, offset + 6);
1453   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
1454     "%s: tsval %u, tsecr %u", optp->name, tsv, tser);
1455   tcp_info_append_uint(pinfo, "TSV", tsv);
1456   tcp_info_append_uint(pinfo, "TSER", tser);
1457 }
1458
1459 static void
1460 dissect_tcpopt_cc(const ip_tcp_opt *optp, tvbuff_t *tvb,
1461     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
1462 {
1463   guint32 cc;
1464
1465   cc = tvb_get_ntohl(tvb, offset + 2);
1466   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
1467                         "%s: %u", optp->name, cc);
1468   tcp_info_append_uint(pinfo, "CC", cc);
1469 }
1470
1471 static const ip_tcp_opt tcpopts[] = {
1472   {
1473     TCPOPT_EOL,
1474     "EOL",
1475     NULL,
1476     NO_LENGTH,
1477     0,
1478     NULL,
1479   },
1480   {
1481     TCPOPT_NOP,
1482     "NOP",
1483     NULL,
1484     NO_LENGTH,
1485     0,
1486     NULL,
1487   },
1488   {
1489     TCPOPT_MSS,
1490     "Maximum segment size",
1491     NULL,
1492     FIXED_LENGTH,
1493     TCPOLEN_MSS,
1494     dissect_tcpopt_maxseg
1495   },
1496   {
1497     TCPOPT_WINDOW,
1498     "Window scale",
1499     NULL,
1500     FIXED_LENGTH,
1501     TCPOLEN_WINDOW,
1502     dissect_tcpopt_wscale
1503   },
1504   {
1505     TCPOPT_SACK_PERM,
1506     "SACK permitted",
1507     NULL,
1508     FIXED_LENGTH,
1509     TCPOLEN_SACK_PERM,
1510     NULL,
1511   },
1512   {
1513     TCPOPT_SACK,
1514     "SACK",
1515     &ett_tcp_option_sack,
1516     VARIABLE_LENGTH,
1517     TCPOLEN_SACK_MIN,
1518     dissect_tcpopt_sack
1519   },
1520   {
1521     TCPOPT_ECHO,
1522     "Echo",
1523     NULL,
1524     FIXED_LENGTH,
1525     TCPOLEN_ECHO,
1526     dissect_tcpopt_echo
1527   },
1528   {
1529     TCPOPT_ECHOREPLY,
1530     "Echo reply",
1531     NULL,
1532     FIXED_LENGTH,
1533     TCPOLEN_ECHOREPLY,
1534     dissect_tcpopt_echo
1535   },
1536   {
1537     TCPOPT_TIMESTAMP,
1538     "Time stamp",
1539     NULL,
1540     FIXED_LENGTH,
1541     TCPOLEN_TIMESTAMP,
1542     dissect_tcpopt_timestamp
1543   },
1544   {
1545     TCPOPT_CC,
1546     "CC",
1547     NULL,
1548     FIXED_LENGTH,
1549     TCPOLEN_CC,
1550     dissect_tcpopt_cc
1551   },
1552   {
1553     TCPOPT_CCNEW,
1554     "CC.NEW",
1555     NULL,
1556     FIXED_LENGTH,
1557     TCPOLEN_CCNEW,
1558     dissect_tcpopt_cc
1559   },
1560   {
1561     TCPOPT_CCECHO,
1562     "CC.ECHO",
1563     NULL,
1564     FIXED_LENGTH,
1565     TCPOLEN_CCECHO,
1566     dissect_tcpopt_cc
1567   },
1568   {
1569     TCPOPT_MD5,
1570     "TCP MD5 signature",
1571     NULL,
1572     FIXED_LENGTH,
1573     TCPOLEN_MD5,
1574     NULL
1575   }
1576 };
1577
1578 #define N_TCP_OPTS      (sizeof tcpopts / sizeof tcpopts[0])
1579
1580 /* Determine if there is a sub-dissector and call it.  This has been */
1581 /* separated into a stand alone routine to other protocol dissectors */
1582 /* can call to it, ie. socks    */
1583
1584 void
1585 decode_tcp_ports(tvbuff_t *tvb, int offset, packet_info *pinfo,
1586         proto_tree *tree, int src_port, int dst_port)
1587 {
1588   tvbuff_t *next_tvb;
1589   int low_port, high_port;
1590
1591   next_tvb = tvb_new_subset(tvb, offset, -1, -1);
1592
1593 /* determine if this packet is part of a conversation and call dissector */
1594 /* for the conversation if available */
1595
1596   if (try_conversation_dissector(&pinfo->src, &pinfo->dst, PT_TCP,
1597                 src_port, dst_port, next_tvb, pinfo, tree))
1598     return;
1599
1600   /* Do lookups with the subdissector table.
1601      We try the port number with the lower value first, followed by the
1602      port number with the higher value.  This means that, for packets
1603      where a dissector is registered for *both* port numbers:
1604
1605         1) we pick the same dissector for traffic going in both directions;
1606
1607         2) we prefer the port number that's more likely to be the right
1608            one (as that prefers well-known ports to reserved ports);
1609
1610      although there is, of course, no guarantee that any such strategy
1611      will always pick the right port number.
1612
1613      XXX - we ignore port numbers of 0, as some dissectors use a port
1614      number of 0 to disable the port. */
1615   if (src_port > dst_port) {
1616     low_port = dst_port;
1617     high_port = src_port;
1618   } else {
1619     low_port = src_port;
1620     high_port = dst_port;
1621   }
1622   if (low_port != 0 &&
1623       dissector_try_port(subdissector_table, low_port, next_tvb, pinfo, tree))
1624     return;
1625   if (high_port != 0 &&
1626       dissector_try_port(subdissector_table, high_port, next_tvb, pinfo, tree))
1627     return;
1628
1629   /* do lookup with the heuristic subdissector table */
1630   if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree))
1631     return;
1632
1633   /* Oh, well, we don't know this; dissect it as data. */
1634   call_dissector(data_handle,next_tvb, pinfo, tree);
1635 }
1636
1637
1638 static void
1639 dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1640 {
1641   guint16 th_sport;
1642   guint16 th_dport;
1643   guint32 th_seq;
1644   guint32 th_ack;
1645   guint8  th_off_x2; /* combines th_off and th_x2 */
1646   guint8  th_flags;
1647   guint16 th_win;
1648   guint16 th_sum;
1649   guint16 th_urp;
1650   proto_tree *tcp_tree = NULL, *field_tree = NULL;
1651   proto_item *ti = NULL, *tf;
1652   int        offset = 0;
1653   gchar      flags[64] = "<None>";
1654   gchar     *fstr[] = {"FIN", "SYN", "RST", "PSH", "ACK", "URG", "ECN", "CWR" };
1655   gint       fpos = 0, i;
1656   guint      bpos;
1657   guint      hlen;
1658   guint      optlen;
1659   guint32    seglen;
1660   guint32    nxtseq;
1661   guint      len;
1662   guint      reported_len;
1663   vec_t      cksum_vec[4];
1664   guint32    phdr[2];
1665   guint16    computed_cksum;
1666   guint      length_remaining;
1667   gboolean   desegment_ok;
1668   struct tcpinfo tcpinfo;
1669   gboolean   save_fragmented;
1670
1671   if (check_col(pinfo->cinfo, COL_PROTOCOL))
1672     col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
1673
1674   /* Clear out the Info column. */
1675   if (check_col(pinfo->cinfo, COL_INFO))
1676     col_clear(pinfo->cinfo, COL_INFO);
1677
1678   th_sport = tvb_get_ntohs(tvb, offset);
1679   th_dport = tvb_get_ntohs(tvb, offset + 2);
1680   if (check_col(pinfo->cinfo, COL_INFO)) {
1681     col_append_fstr(pinfo->cinfo, COL_INFO, "%s > %s",
1682       get_tcp_port(th_sport), get_tcp_port(th_dport));
1683   }
1684   if (tree) {
1685     if (tcp_summary_in_tree) {
1686             ti = proto_tree_add_protocol_format(tree, proto_tcp, tvb, 0, -1,
1687                 "Transmission Control Protocol, Src Port: %s (%u), Dst Port: %s (%u)",
1688                 get_tcp_port(th_sport), th_sport,
1689                 get_tcp_port(th_dport), th_dport);
1690     }
1691     else {
1692             ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, FALSE);
1693     }
1694     tcp_tree = proto_item_add_subtree(ti, ett_tcp);
1695     proto_tree_add_uint_format(tcp_tree, hf_tcp_srcport, tvb, offset, 2, th_sport,
1696         "Source port: %s (%u)", get_tcp_port(th_sport), th_sport);
1697     proto_tree_add_uint_format(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, th_dport,
1698         "Destination port: %s (%u)", get_tcp_port(th_dport), th_dport);
1699     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset, 2, th_sport);
1700     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, th_dport);
1701   }
1702
1703   /* Set the source and destination port numbers as soon as we get them,
1704      so that they're available to the "Follow TCP Stream" code even if
1705      we throw an exception dissecting the rest of the TCP header. */
1706   pinfo->ptype = PT_TCP;
1707   pinfo->srcport = th_sport;
1708   pinfo->destport = th_dport;
1709   
1710   th_seq = tvb_get_ntohl(tvb, offset + 4);
1711   th_ack = tvb_get_ntohl(tvb, offset + 8);
1712   th_off_x2 = tvb_get_guint8(tvb, offset + 12);
1713   th_flags = tvb_get_guint8(tvb, offset + 13);
1714   th_win = tvb_get_ntohs(tvb, offset + 14);
1715   hlen = hi_nibble(th_off_x2) * 4;  /* TCP header length, in bytes */
1716
1717   reported_len = tvb_reported_length(tvb);
1718   len = tvb_length(tvb);
1719
1720   /* Compute the length of data in this segment. */
1721   seglen = reported_len - hlen;
1722
1723   if (tree) { /* Add the seglen as an invisible field */
1724
1725     proto_tree_add_uint_hidden(ti, hf_tcp_len, tvb, offset, 4, seglen);
1726
1727   }
1728
1729   /* handle TCP seq# analysis parse all new segments we see */
1730   if(tcp_analyze_seq){
1731       if(!(pinfo->fd->flags.visited)){
1732           tcp_analyze_sequence_number(pinfo, th_seq, th_ack, seglen, th_flags);
1733       }
1734       if(tcp_relative_seq){
1735           tcp_get_relative_seq_ack(pinfo->fd->num, &th_seq, &th_ack);
1736       }
1737   }
1738
1739
1740   /* Compute the sequence number of next octet after this segment. */
1741   nxtseq = th_seq + seglen;
1742
1743   if (check_col(pinfo->cinfo, COL_INFO) || tree) {  
1744     for (i = 0; i < 8; i++) {
1745       bpos = 1 << i;
1746       if (th_flags & bpos) {
1747         if (fpos) {
1748           strcpy(&flags[fpos], ", ");
1749           fpos += 2;
1750         }
1751         strcpy(&flags[fpos], fstr[i]);
1752         fpos += 3;
1753       }
1754     }
1755     flags[fpos] = '\0';
1756   }
1757
1758   if (check_col(pinfo->cinfo, COL_INFO)) {
1759     col_append_fstr(pinfo->cinfo, COL_INFO, " [%s] Seq=%u Ack=%u Win=%u",
1760       flags, th_seq, th_ack, th_win);
1761   }
1762
1763   if (tree) {
1764     if (tcp_summary_in_tree)
1765       proto_item_append_text(ti, ", Seq: %u", th_seq);
1766     proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, th_seq);
1767   }
1768
1769   if (hlen < TCPH_MIN_LEN) {
1770     /* Give up at this point; we put the source and destination port in
1771        the tree, before fetching the header length, so that they'll
1772        show up if this is in the failing packet in an ICMP error packet,
1773        but it's now time to give up if the header length is bogus. */
1774     if (check_col(pinfo->cinfo, COL_INFO))
1775       col_append_fstr(pinfo->cinfo, COL_INFO, ", bogus TCP header length (%u, must be at least %u)",
1776         hlen, TCPH_MIN_LEN);
1777     if (tree) {
1778       proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, hlen,
1779        "Header length: %u bytes (bogus, must be at least %u)", hlen,
1780        TCPH_MIN_LEN);
1781     }
1782     return;
1783   }
1784
1785   if (tree) {
1786     if (tcp_summary_in_tree)
1787       proto_item_append_text(ti, ", Ack: %u, Len: %u", th_ack, seglen);
1788     proto_item_set_len(ti, hlen);
1789     if (nxtseq != th_seq)
1790       proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);
1791     if (th_flags & TH_ACK)
1792       proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, th_ack);
1793     proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, hlen,
1794         "Header length: %u bytes", hlen);
1795     tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 13, 1,
1796         th_flags, "Flags: 0x%04x (%s)", th_flags, flags);
1797     field_tree = proto_item_add_subtree(tf, ett_tcp_flags);
1798     proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, th_flags);
1799     proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, th_flags);
1800     proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, th_flags);
1801     proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, th_flags);
1802     proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, th_flags);
1803     proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, th_flags);
1804     proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, th_flags);
1805     proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, th_flags);
1806     proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, th_win);
1807   }
1808
1809   /* Supply the sequence number of the first byte. */
1810   tcpinfo.seq = th_seq;
1811
1812   /* Assume we'll pass un-reassembled data to subdissectors. */
1813   tcpinfo.is_reassembled = FALSE;
1814
1815   pinfo->private_data = &tcpinfo;
1816
1817   /*
1818    * Assume, initially, that we can't desegment.
1819    */
1820   pinfo->can_desegment = 0;
1821
1822   th_sum = tvb_get_ntohs(tvb, offset + 16);
1823   if (!pinfo->fragmented && len >= reported_len) {
1824     /* The packet isn't part of an un-reassembled fragmented datagram
1825        and isn't truncated.  This means we have all the data, and thus
1826        can checksum it and, unless it's being returned in an error
1827        packet, are willing to allow subdissectors to request reassembly
1828        on it. */
1829   
1830     if (tcp_check_checksum) {
1831       /* We haven't turned checksum checking off; checksum it. */
1832
1833       /* Set up the fields of the pseudo-header. */
1834       cksum_vec[0].ptr = pinfo->src.data;
1835       cksum_vec[0].len = pinfo->src.len;
1836       cksum_vec[1].ptr = pinfo->dst.data;
1837       cksum_vec[1].len = pinfo->dst.len;
1838       cksum_vec[2].ptr = (const guint8 *)&phdr;
1839       switch (pinfo->src.type) {
1840
1841       case AT_IPv4:
1842         phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);
1843         cksum_vec[2].len = 4;
1844         break;
1845
1846       case AT_IPv6:
1847         phdr[0] = g_htonl(reported_len);
1848         phdr[1] = g_htonl(IP_PROTO_TCP);
1849         cksum_vec[2].len = 8;
1850         break;
1851
1852       default:
1853         /* TCP runs only atop IPv4 and IPv6.... */
1854         g_assert_not_reached();
1855         break;
1856       }
1857       cksum_vec[3].ptr = tvb_get_ptr(tvb, offset, len);
1858       cksum_vec[3].len = reported_len;
1859       computed_cksum = in_cksum(&cksum_vec[0], 4);
1860       if (computed_cksum == 0) {
1861         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1862           offset + 16, 2, th_sum, "Checksum: 0x%04x (correct)", th_sum);
1863
1864         /* Checksum is valid, so we're willing to desegment it. */
1865         desegment_ok = TRUE;
1866       } else {
1867         proto_tree_add_boolean_hidden(tcp_tree, hf_tcp_checksum_bad, tvb,
1868            offset + 16, 2, TRUE);
1869         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1870            offset + 16, 2, th_sum,
1871            "Checksum: 0x%04x (incorrect, should be 0x%04x)", th_sum,
1872            in_cksum_shouldbe(th_sum, computed_cksum));
1873
1874         /* Checksum is invalid, so we're not willing to desegment it. */
1875         desegment_ok = FALSE;
1876       }
1877     } else {
1878       proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1879          offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
1880
1881       /* We didn't check the checksum, and don't care if it's valid,
1882          so we're willing to desegment it. */
1883       desegment_ok = TRUE;
1884     }
1885   } else {
1886     /* We don't have all the packet data, so we can't checksum it... */
1887     proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1888        offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
1889
1890     /* ...and aren't willing to desegment it. */
1891     desegment_ok = FALSE;
1892   }
1893
1894   if (desegment_ok) {
1895     /* We're willing to desegment this.  Is desegmentation enabled? */
1896     if (tcp_desegment) {
1897       /* Yes - is this segment being returned in an error packet? */
1898       if (!pinfo->in_error_pkt) {
1899         /* No - indicate that we will desegment.
1900            We do NOT want to desegment segments returned in error
1901            packets, as they're not part of a TCP connection. */
1902         pinfo->can_desegment = 2;
1903       }
1904     }
1905   }
1906
1907   if (th_flags & TH_URG) {
1908     th_urp = tvb_get_ntohs(tvb, offset + 18);
1909     /* Export the urgent pointer, for the benefit of protocols such as
1910        rlogin. */
1911     tcpinfo.urgent = TRUE;
1912     tcpinfo.urgent_pointer = th_urp;
1913     if (check_col(pinfo->cinfo, COL_INFO))
1914       col_append_fstr(pinfo->cinfo, COL_INFO, " Urg=%u", th_urp);
1915     if (tcp_tree != NULL)
1916       proto_tree_add_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, th_urp);
1917   } else
1918     tcpinfo.urgent = FALSE;
1919
1920   if (check_col(pinfo->cinfo, COL_INFO))
1921     col_append_fstr(pinfo->cinfo, COL_INFO, " Len=%u", seglen);
1922
1923   /* Decode TCP options, if any. */
1924   if (tree && hlen > TCPH_MIN_LEN) {
1925     /* There's more than just the fixed-length header.  Decode the
1926        options. */
1927     optlen = hlen - TCPH_MIN_LEN; /* length of options, in bytes */
1928     tf = proto_tree_add_text(tcp_tree, tvb, offset +  20, optlen,
1929       "Options: (%u bytes)", optlen);
1930     field_tree = proto_item_add_subtree(tf, ett_tcp_options);
1931     dissect_ip_tcp_options(tvb, offset + 20, optlen,
1932       tcpopts, N_TCP_OPTS, TCPOPT_EOL, pinfo, field_tree);
1933   }
1934
1935   /* Skip over header + options */
1936   offset += hlen;
1937
1938   /* Check the packet length to see if there's more data
1939      (it could be an ACK-only packet) */
1940   length_remaining = tvb_length_remaining(tvb, offset);
1941
1942   if( data_out_file ) {
1943     reassemble_tcp( th_seq,             /* sequence number */
1944         seglen,                         /* data length */
1945         tvb_get_ptr(tvb, offset, length_remaining),     /* data */
1946         length_remaining,               /* captured data length */
1947         ( th_flags & TH_SYN ),          /* is syn set? */
1948         &pinfo->net_src,
1949         &pinfo->net_dst,
1950         pinfo->srcport,
1951         pinfo->destport);
1952   }
1953
1954   if (length_remaining != 0) {
1955     if (th_flags & TH_RST) {
1956       /*
1957        * RFC1122 says:
1958        *
1959        *        4.2.2.12  RST Segment: RFC-793 Section 3.4
1960        *
1961        *          A TCP SHOULD allow a received RST segment to include data.
1962        *
1963        *          DISCUSSION
1964        *               It has been suggested that a RST segment could contain
1965        *               ASCII text that encoded and explained the cause of the
1966        *               RST.  No standard has yet been established for such
1967        *               data.
1968        *
1969        * so for segments with RST we just display the data as text.
1970        */
1971       proto_tree_add_text(tcp_tree, tvb, offset, length_remaining,
1972                             "Reset cause: %s",
1973                             tvb_format_text(tvb, offset, length_remaining));
1974     } else {
1975       /* Can we desegment this segment? */
1976       if (pinfo->can_desegment) {
1977         /* Yes. */
1978         desegment_tcp(tvb, pinfo, offset, th_seq, nxtseq, th_sport, th_dport, tree, tcp_tree);
1979       } else {
1980         /* No - just call the subdissector.
1981            Mark this as fragmented, so if somebody throws an exception,
1982            we don't report it as a malformed frame. */
1983         save_fragmented = pinfo->fragmented;
1984         pinfo->fragmented = TRUE;
1985         decode_tcp_ports(tvb, offset, pinfo, tree, th_sport, th_dport);
1986         pinfo->fragmented = save_fragmented;
1987       }
1988     }
1989   }
1990
1991   /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/
1992   if(tcp_analyze_seq){
1993       tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree);
1994   }
1995 }
1996
1997 void
1998 proto_register_tcp(void)
1999 {
2000         static hf_register_info hf[] = {
2001
2002                 { &hf_tcp_srcport,
2003                 { "Source Port",                "tcp.srcport", FT_UINT16, BASE_DEC, NULL, 0x0,
2004                         "", HFILL }},
2005
2006                 { &hf_tcp_dstport,
2007                 { "Destination Port",           "tcp.dstport", FT_UINT16, BASE_DEC, NULL, 0x0,
2008                         "", HFILL }},
2009
2010                 { &hf_tcp_port,
2011                 { "Source or Destination Port", "tcp.port", FT_UINT16, BASE_DEC, NULL, 0x0,
2012                         "", HFILL }},
2013
2014                 { &hf_tcp_seq,
2015                 { "Sequence number",            "tcp.seq", FT_UINT32, BASE_DEC, NULL, 0x0,
2016                         "", HFILL }},
2017
2018                 { &hf_tcp_nxtseq,
2019                 { "Next sequence number",       "tcp.nxtseq", FT_UINT32, BASE_DEC, NULL, 0x0,
2020                         "", HFILL }},
2021
2022                 { &hf_tcp_ack,
2023                 { "Acknowledgement number",     "tcp.ack", FT_UINT32, BASE_DEC, NULL, 0x0,
2024                         "", HFILL }},
2025
2026                 { &hf_tcp_hdr_len,
2027                 { "Header Length",              "tcp.hdr_len", FT_UINT8, BASE_DEC, NULL, 0x0,
2028                         "", HFILL }},
2029
2030                 { &hf_tcp_flags,
2031                 { "Flags",                      "tcp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
2032                         "", HFILL }},
2033
2034                 { &hf_tcp_flags_cwr,
2035                 { "Congestion Window Reduced (CWR)",                    "tcp.flags.cwr", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_CWR,
2036                         "", HFILL }},
2037
2038                 { &hf_tcp_flags_ecn,
2039                 { "ECN-Echo",                   "tcp.flags.ecn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ECN,
2040                         "", HFILL }},
2041
2042                 { &hf_tcp_flags_urg,
2043                 { "Urgent",                     "tcp.flags.urg", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_URG,
2044                         "", HFILL }},
2045
2046                 { &hf_tcp_flags_ack,
2047                 { "Acknowledgment",             "tcp.flags.ack", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ACK,
2048                         "", HFILL }},
2049
2050                 { &hf_tcp_flags_push,
2051                 { "Push",                       "tcp.flags.push", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_PUSH,
2052                         "", HFILL }},
2053
2054                 { &hf_tcp_flags_reset,
2055                 { "Reset",                      "tcp.flags.reset", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_RST,
2056                         "", HFILL }},
2057
2058                 { &hf_tcp_flags_syn,
2059                 { "Syn",                        "tcp.flags.syn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_SYN,
2060                         "", HFILL }},
2061
2062                 { &hf_tcp_flags_fin,
2063                 { "Fin",                        "tcp.flags.fin", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_FIN,
2064                         "", HFILL }},
2065
2066                 { &hf_tcp_window_size,
2067                 { "Window size",                "tcp.window_size", FT_UINT16, BASE_DEC, NULL, 0x0,
2068                         "", HFILL }},
2069
2070                 { &hf_tcp_checksum,
2071                 { "Checksum",                   "tcp.checksum", FT_UINT16, BASE_HEX, NULL, 0x0,
2072                         "", HFILL }},
2073
2074                 { &hf_tcp_checksum_bad,
2075                 { "Bad Checksum",               "tcp.checksum_bad", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2076                         "", HFILL }},
2077
2078                 { &hf_tcp_analysis_flags,
2079                 { "TCP Analysis Flags",         "tcp.analysis.flags", FT_NONE, BASE_NONE, NULL, 0x0,
2080                         "This frame has some of the TCP analysis flags set", HFILL }},
2081
2082                 { &hf_tcp_analysis_retransmission,
2083                 { "",           "tcp.analysis.retransmission", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2084                         "This frame is a suspected TCP retransmission", HFILL }},
2085
2086                 { &hf_tcp_analysis_lost_packet,
2087                 { "",           "tcp.analysis.lost_segment", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2088                         "A segment before this one was lost from the capture", HFILL }},
2089
2090                 { &hf_tcp_analysis_ack_lost_packet,
2091                 { "",           "tcp.analysis.ack_lost_segment", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2092                         "This frame ACKs a lost segment", HFILL }},
2093
2094                 { &hf_tcp_analysis_keep_alive,
2095                 { "",           "tcp.analysis.keep_alive", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2096                         "This is a keep-alive segment", HFILL }},
2097
2098                 { &hf_tcp_len,
2099                   { "TCP Segment Len",            "tcp.len", FT_UINT32, BASE_DEC, NULL, 0x0, 
2100                     "", HFILL}},
2101
2102                 { &hf_tcp_analysis_acks_frame,
2103                   { "This is an ACK to the segment in frame",            "tcp.analysis.acks_frame", FT_UINT32, BASE_DEC, NULL, 0x0, 
2104                     "Which previous segment is this an ACK for", HFILL}},
2105
2106                 { &hf_tcp_analysis_ack_rtt,
2107                   { "The RTT to ACK the segment was",            "tcp.analysis.ack_rtt", FT_RELATIVE_TIME, BASE_NONE, NULL, 0x0, 
2108                     "How long time it took to ACK the segment (RTT)", HFILL}},
2109
2110                 { &hf_tcp_urgent_pointer,
2111                 { "Urgent pointer",             "tcp.urgent_pointer", FT_UINT16, BASE_DEC, NULL, 0x0,
2112                         "", HFILL }},
2113         };
2114         static gint *ett[] = {
2115                 &ett_tcp,
2116                 &ett_tcp_flags,
2117                 &ett_tcp_options,
2118                 &ett_tcp_option_sack,
2119                 &ett_tcp_segments,
2120                 &ett_tcp_analysis_faults,
2121                 &ett_tcp_analysis
2122         };
2123         module_t *tcp_module;
2124
2125         proto_tcp = proto_register_protocol("Transmission Control Protocol",
2126             "TCP", "tcp");
2127         proto_register_field_array(proto_tcp, hf, array_length(hf));
2128         proto_register_subtree_array(ett, array_length(ett));
2129
2130         /* subdissector code */
2131         subdissector_table = register_dissector_table("tcp.port",
2132             "TCP port", FT_UINT16, BASE_DEC);
2133         register_heur_dissector_list("tcp", &heur_subdissector_list);
2134
2135         /* Register configuration preferences */
2136         tcp_module = prefs_register_protocol(proto_tcp, NULL);
2137         prefs_register_bool_preference(tcp_module, "tcp_summary_in_tree",
2138             "Show TCP summary in protocol tree",
2139 "Whether the TCP summary line should be shown in the protocol tree",
2140             &tcp_summary_in_tree);
2141         prefs_register_bool_preference(tcp_module, "check_checksum",
2142             "Check the validity of the TCP checksum when possible",
2143 "Whether to check the validity of the TCP checksum",
2144             &tcp_check_checksum);
2145         prefs_register_bool_preference(tcp_module, "desegment_tcp_streams",
2146             "Allow subdissector to desegment TCP streams",
2147 "Whether subdissector can request TCP streams to be desegmented",
2148             &tcp_desegment);
2149         prefs_register_bool_preference(tcp_module, "tcp_analyze_sequence_numbers",
2150             "Analyze TCP sequence numbers",
2151             "Make the TCP dissector analyze TCP sequence numbers to find and flag segment retransmissions, missing segments and RTT",
2152             &tcp_analyze_seq);
2153         prefs_register_bool_preference(tcp_module, "tcp_relative_sequence_numbers",
2154             "Use relative sequence numbers",
2155             "Make the TCP dissector use relative sequence numbers instead of absolute ones. To use this option you must also enable \"Analyze TCP sequence numbers\".",
2156             &tcp_relative_seq);
2157
2158         register_init_routine(tcp_analyze_seq_init);
2159         register_init_routine(tcp_desegment_init);
2160         register_init_routine(tcp_fragment_init);
2161 }
2162
2163 void
2164 proto_reg_handoff_tcp(void)
2165 {
2166         dissector_handle_t tcp_handle;
2167
2168         tcp_handle = create_dissector_handle(dissect_tcp, proto_tcp);
2169         dissector_add("ip.proto", IP_PROTO_TCP, tcp_handle);
2170         data_handle = find_dissector("data");
2171 }