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