In the hex dump, generate the offset at the beginning of each line in
[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.144 2002/06/08 21:54:52 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 #ifdef HAVE_SYS_TYPES_H
30 # include <sys/types.h>
31 #endif
32
33 #ifdef HAVE_NETINET_IN_H
34 # include <netinet/in.h>
35 #endif
36
37 #include <stdio.h>
38 #include <string.h>
39 #include <glib.h>
40 #include "in_cksum.h"
41
42 #ifdef NEED_SNPRINTF_H
43 # include "snprintf.h"
44 #endif
45
46 #include <epan/resolv.h>
47 #include "ipproto.h"
48 #include "follow.h"
49 #include "prefs.h"
50 #include "packet-tcp.h"
51 #include "packet-ip.h"
52 #include "packet-frame.h"
53 #include <epan/conversation.h>
54 #include <epan/strutil.h>
55 #include "reassemble.h"
56
57 /* Place TCP summary in proto tree */
58 static gboolean tcp_summary_in_tree = TRUE;
59
60 /*
61  * Flag to control whether to check the TCP checksum.
62  *
63  * In at least some Solaris network traces, there are packets with bad
64  * TCP checksums, but the traffic appears to indicate that the packets
65  * *were* received; the packets were probably sent by the host on which
66  * the capture was being done, on a network interface to which
67  * checksumming was offloaded, so that DLPI supplied an un-checksummed
68  * packet to the capture program but a checksummed packet got put onto
69  * the wire.
70  */
71 static gboolean tcp_check_checksum = TRUE;
72
73 extern FILE* data_out_file;
74
75 static int proto_tcp = -1;
76 static int hf_tcp_srcport = -1;
77 static int hf_tcp_dstport = -1;
78 static int hf_tcp_port = -1;
79 static int hf_tcp_seq = -1;
80 static int hf_tcp_nxtseq = -1;
81 static int hf_tcp_ack = -1;
82 static int hf_tcp_hdr_len = -1;
83 static int hf_tcp_flags = -1;
84 static int hf_tcp_flags_cwr = -1;
85 static int hf_tcp_flags_ecn = -1;
86 static int hf_tcp_flags_urg = -1;
87 static int hf_tcp_flags_ack = -1;
88 static int hf_tcp_flags_push = -1;
89 static int hf_tcp_flags_reset = -1;
90 static int hf_tcp_flags_syn = -1;
91 static int hf_tcp_flags_fin = -1;
92 static int hf_tcp_window_size = -1;
93 static int hf_tcp_checksum = -1;
94 static int hf_tcp_checksum_bad = -1;
95 static int hf_tcp_len = -1;
96 static int hf_tcp_urgent_pointer = -1;
97
98 static gint ett_tcp = -1;
99 static gint ett_tcp_flags = -1;
100 static gint ett_tcp_options = -1;
101 static gint ett_tcp_option_sack = -1;
102 static gint ett_tcp_segments = -1;
103
104 static dissector_table_t subdissector_table;
105 static heur_dissector_list_t heur_subdissector_list;
106 static dissector_handle_t data_handle;
107
108 /* TCP structs and definitions */
109
110 #define TH_FIN  0x01
111 #define TH_SYN  0x02
112 #define TH_RST  0x04
113 #define TH_PUSH 0x08
114 #define TH_ACK  0x10
115 #define TH_URG  0x20
116 #define TH_ECN  0x40
117 #define TH_CWR  0x80
118
119 /* Minimum TCP header length. */
120 #define TCPH_MIN_LEN    20
121
122 /*
123  *      TCP option
124  */
125  
126 #define TCPOPT_NOP              1       /* Padding */
127 #define TCPOPT_EOL              0       /* End of options */
128 #define TCPOPT_MSS              2       /* Segment size negotiating */
129 #define TCPOPT_WINDOW           3       /* Window scaling */
130 #define TCPOPT_SACK_PERM        4       /* SACK Permitted */
131 #define TCPOPT_SACK             5       /* SACK Block */
132 #define TCPOPT_ECHO             6
133 #define TCPOPT_ECHOREPLY        7
134 #define TCPOPT_TIMESTAMP        8       /* Better RTT estimations/PAWS */
135 #define TCPOPT_CC               11
136 #define TCPOPT_CCNEW            12
137 #define TCPOPT_CCECHO           13
138 #define TCPOPT_MD5              19      /* RFC2385 */
139
140 /*
141  *     TCP option lengths
142  */
143
144 #define TCPOLEN_MSS            4
145 #define TCPOLEN_WINDOW         3
146 #define TCPOLEN_SACK_PERM      2
147 #define TCPOLEN_SACK_MIN       2
148 #define TCPOLEN_ECHO           6
149 #define TCPOLEN_ECHOREPLY      6
150 #define TCPOLEN_TIMESTAMP      10
151 #define TCPOLEN_CC             6
152 #define TCPOLEN_CCNEW          6
153 #define TCPOLEN_CCECHO         6
154 #define TCPOLEN_MD5            18
155
156
157
158 /* Desegmentation of TCP streams */
159 /* table to hold defragmented TCP streams */
160 static GHashTable *tcp_fragment_table = NULL;
161 static void
162 tcp_fragment_init(void)
163 {
164         fragment_table_init(&tcp_fragment_table);
165 }
166
167 /* functions to trace tcp segments */
168 /* Enable desegmenting of TCP streams */
169 static gboolean tcp_desegment = FALSE;
170
171 static GHashTable *tcp_segment_table = NULL;
172 static GMemChunk *tcp_segment_key_chunk = NULL;
173 static int tcp_segment_init_count = 200;
174 static GMemChunk *tcp_segment_address_chunk = NULL;
175 static int tcp_segment_address_init_count = 500;
176
177 typedef struct _tcp_segment_key {
178         /* for own bookkeeping inside packet-tcp.c */
179         address *src;
180         address *dst;
181         guint32 seq;
182         /* xxx */
183         guint32 start_seq;
184         guint32 tot_len;
185         guint32 first_frame;
186 } tcp_segment_key;
187
188 static gboolean
189 free_all_segments(gpointer key_arg, gpointer value _U_, gpointer user_data _U_)
190 {
191         tcp_segment_key *key = key_arg;
192
193         if((key->src)&&(key->src->data)){
194                 g_free((gpointer)key->src->data);
195                 key->src->data=NULL;
196         }
197
198         if((key->dst)&&(key->dst->data)){
199                 g_free((gpointer)key->dst->data);
200                 key->dst->data=NULL;
201         }
202
203         return TRUE;
204 }
205
206 static guint
207 tcp_segment_hash(gconstpointer k)
208 {
209         tcp_segment_key *key = (tcp_segment_key *)k;
210
211         return key->seq;
212 }
213
214 static gint
215 tcp_segment_equal(gconstpointer k1, gconstpointer k2)
216 {
217         tcp_segment_key *key1 = (tcp_segment_key *)k1;
218         tcp_segment_key *key2 = (tcp_segment_key *)k2;
219
220         return ( ( (key1->seq==key2->seq)
221                  &&(ADDRESSES_EQUAL(key1->src, key2->src))
222                  &&(ADDRESSES_EQUAL(key1->dst, key2->dst))
223                  ) ? TRUE:FALSE);
224 }
225
226 static void
227 tcp_desegment_init(void)
228 {
229         /*
230          * Free this before freeing any memory chunks; those
231          * chunks contain data we'll look at in "free_all_segments()".
232          */
233         if(tcp_segment_table){
234                 g_hash_table_foreach_remove(tcp_segment_table,
235                         free_all_segments, NULL);
236                 g_hash_table_destroy(tcp_segment_table);
237                 tcp_segment_table = NULL;
238         }
239
240         if(tcp_segment_key_chunk){
241                 g_mem_chunk_destroy(tcp_segment_key_chunk);
242                 tcp_segment_key_chunk = NULL;
243         }
244         if(tcp_segment_address_chunk){
245                 g_mem_chunk_destroy(tcp_segment_address_chunk);
246                 tcp_segment_address_chunk = NULL;
247         }
248
249         /* dont allocate any hash table or memory chunks unless the user
250            really uses this option
251         */
252         if(!tcp_desegment){
253                 return;
254         }
255
256         tcp_segment_table = g_hash_table_new(tcp_segment_hash,
257                 tcp_segment_equal);
258
259         tcp_segment_key_chunk = g_mem_chunk_new("tcp_segment_key_chunk",
260                 sizeof(tcp_segment_key),
261                 tcp_segment_init_count*sizeof(tcp_segment_key),
262                 G_ALLOC_ONLY);
263
264         tcp_segment_address_chunk = g_mem_chunk_new("tcp_segment_address_chunk",
265                 sizeof(address),
266                 tcp_segment_address_init_count*sizeof(address),
267                 G_ALLOC_ONLY);
268 }
269
270 static void
271 desegment_tcp(tvbuff_t *tvb, packet_info *pinfo, int offset,
272                 guint32 seq, guint32 nxtseq,
273                 guint32 sport, guint32 dport,
274                 proto_tree *tree, proto_tree *tcp_tree)
275 {
276         struct tcpinfo *tcpinfo = pinfo->private_data;
277         fragment_data *ipfd_head;
278         tcp_segment_key old_tsk, *tsk;
279         gboolean must_desegment = FALSE;
280         gboolean called_dissector = FALSE;
281         int deseg_offset;
282         guint32 deseg_seq;
283         gint nbytes;
284
285         /*
286          * Initialize these to assume no desegmentation.
287          * If that's not the case, these will be set appropriately
288          * by the subdissector.
289          */
290         pinfo->desegment_offset = 0;
291         pinfo->desegment_len = 0;
292
293         /*
294          * Initialize this to assume that this segment will just be
295          * added to the middle of a desegmented chunk of data, so
296          * that we should show it all as data.
297          * If that's not the case, it will be set appropriately.
298          */
299         deseg_offset = offset;
300
301         /* First we must check if this TCP segment should be desegmented.
302            This is only to check if we should desegment this packet,
303            so we dont spend time doing COPY_ADDRESS/g_free.
304            We just "borrow" some address structures from pinfo instead. Cheaper.
305         */
306         old_tsk.src = &pinfo->src;
307         old_tsk.dst = &pinfo->dst;
308         old_tsk.seq = seq;
309         tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
310
311         if(tsk){
312                 /* OK, this segment was found, which means it continues
313                    a higher-level PDU. This means we must desegment it.
314                    Add it to the defragmentation lists.
315                 */
316                 ipfd_head = fragment_add(tvb, offset, pinfo, tsk->start_seq,
317                         tcp_fragment_table,
318                         seq - tsk->start_seq,
319                         nxtseq - seq,
320                         (nxtseq < (tsk->start_seq + tsk->tot_len)) );
321
322                 if(!ipfd_head){
323                         /* fragment_add() returned NULL, This means that 
324                            desegmentation is not completed yet.
325                            (its like defragmentation but we know we will
326                             always add the segments in order).
327                            XXX - no, we don't; there is no guarantee that
328                            TCP segments are in order on the wire.
329
330                            we must add next segment to our table so we will
331                            find it later.
332                         */
333                         tcp_segment_key *new_tsk;
334
335                         new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
336                         memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
337                         new_tsk->seq=nxtseq;
338                         g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
339                 }
340         } else {
341                 /* This segment was not found in our table, so it doesn't
342                    contain a continuation of a higher-level PDU.
343                    Call the normal subdissector.
344                 */
345                 decode_tcp_ports(tvb, offset, pinfo, tree, 
346                                 sport, dport);
347                 called_dissector = TRUE;
348
349                 /* Did the subdissector ask us to desegment some more data
350                    before it could handle the packet? 
351                    If so we have to create some structures in our table but
352                    this is something we only do the first time we see this 
353                    packet.
354                 */
355                 if(pinfo->desegment_len) {
356                         if (!pinfo->fd->flags.visited)
357                                 must_desegment = TRUE;
358
359                         /*
360                          * Set "deseg_offset" to the offset in "tvb"
361                          * of the first byte of data that the
362                          * subdissector didn't process.
363                          */
364                         deseg_offset = offset + pinfo->desegment_offset;
365                 }
366
367                 /* Either no desegmentation is necessary, or this is
368                    segment contains the beginning but not the end of
369                    a higher-level PDU and thus isn't completely
370                    desegmented.
371                 */
372                 ipfd_head = NULL;
373         }
374
375         /* is it completely desegmented? */
376         if(ipfd_head){
377                 fragment_data *ipfd;
378                 proto_tree *st = NULL;
379                 proto_item *si = NULL;
380
381                 /*
382                  * Yes, we think it is.
383                  * We only call subdissector for the last segment.
384                  * Note that the last segment may include more than what
385                  * we needed.
386                  */
387                 if(nxtseq >= (tsk->start_seq + tsk->tot_len)){
388                         /*
389                          * OK, this is the last segment.
390                          * Let's call the subdissector with the desegmented
391                          * data.
392                          */
393                         tvbuff_t *next_tvb;
394                         int old_len;
395
396                         /* create a new TVB structure for desegmented data */
397                         next_tvb = tvb_new_real_data(ipfd_head->data,
398                                         ipfd_head->datalen, ipfd_head->datalen);
399
400                         /* add this tvb as a child to the original one */
401                         tvb_set_child_real_data_tvbuff(tvb, next_tvb);
402
403                         /* add desegmented data to the data source list */
404                         add_new_data_source(pinfo, next_tvb, "Desegmented");
405
406                         /*
407                          * Supply the sequence number of the first of the
408                          * reassembled bytes.
409                          */
410                         tcpinfo->seq = tsk->start_seq;
411
412                         /* indicate that this is reassembled data */
413                         tcpinfo->is_reassembled = TRUE;
414
415                         /* call subdissector */
416                         decode_tcp_ports(next_tvb, 0, pinfo, tree,
417                                 sport, dport);
418                         called_dissector = TRUE;
419
420                         /*
421                          * OK, did the subdissector think it was completely
422                          * desegmented, or does it think we need even more
423                          * data?
424                          */
425                         old_len=(int)(tvb_reported_length(next_tvb)-tvb_reported_length_remaining(tvb, offset));
426                         if(pinfo->desegment_len &&
427                             pinfo->desegment_offset<=old_len){
428                                 tcp_segment_key *new_tsk;
429
430                                 /*
431                                  * "desegment_len" isn't 0, so it needs more
432                                  * data for something - and "desegment_offset"
433                                  * is before "old_len", so it needs more data
434                                  * to dissect the stuff we thought was
435                                  * completely desegmented (as opposed to the
436                                  * stuff at the beginning being completely
437                                  * desegmented, but the stuff at the end
438                                  * being a new higher-level PDU that also
439                                  * needs desegmentation).
440                                  */
441                                 fragment_set_partial_reassembly(pinfo,tsk->start_seq,tcp_fragment_table);
442                                 tsk->tot_len = tvb_reported_length(next_tvb) + pinfo->desegment_len;
443
444                                 /*
445                                  * Update tsk structure.
446                                  * Can ask ->next->next because at least there's a hdr and one
447                                  * entry in fragment_add()
448                                  */
449                                 for(ipfd=ipfd_head->next; ipfd->next; ipfd=ipfd->next){
450                                         old_tsk.seq = tsk->start_seq + ipfd->offset;
451                                         new_tsk = g_hash_table_lookup(tcp_segment_table, &old_tsk);
452                                         new_tsk->tot_len = tsk->tot_len;
453                                 }
454
455                                 /* this is the next segment in the sequence we want */
456                                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
457                                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
458                                 new_tsk->seq = nxtseq;
459                                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
460                         } else {
461                                 /*
462                                  * Show the stuff in this TCP segment as
463                                  * just raw TCP segment data.
464                                  */
465                                 nbytes =
466                                     tvb_reported_length_remaining(tvb, offset);
467                                 proto_tree_add_text(tcp_tree, tvb, offset, -1,
468                                     "TCP segment data (%u byte%s)", nbytes,
469                                     plurality(nbytes, "", "s"));
470
471                                 /*
472                                  * The subdissector thought it was completely
473                                  * desegmented (although the stuff at the
474                                  * end may, in turn, require desegmentation),
475                                  * so we show a tree with all segments.
476                                  */
477                                 si = proto_tree_add_text(tcp_tree, next_tvb,
478                                                 0, -1, "Segments");
479                                 st = proto_item_add_subtree(si, ett_tcp_segments);
480                                 for(ipfd=ipfd_head->next; ipfd; ipfd=ipfd->next){
481                                         proto_tree_add_text(st, next_tvb,
482                                         ipfd->offset, ipfd->len,
483                                         "Frame:%u seq#:%u-%u [%u-%u]",
484                                         ipfd->frame,
485                                         tsk->start_seq + ipfd->offset,
486                                         tsk->start_seq + ipfd->offset + ipfd->len-1,
487                                         ipfd->offset,
488                                         ipfd->offset + ipfd->len - 1);
489                                 }
490
491                                 /* Did the subdissector ask us to desegment
492                                    some more data?  This means that the data
493                                    at the beginning of this segment completed
494                                    a higher-level PDU, but the data at the
495                                    end of this segment started a higher-level
496                                    PDU but didn't complete it.
497
498                                    If so, we have to create some structures
499                                    in our table, but this is something we
500                                    only do the first time we see this packet.
501                                 */
502                                 if(pinfo->desegment_len) {
503                                         if (!pinfo->fd->flags.visited)
504                                                 must_desegment = TRUE;
505
506                                         /* The stuff we couldn't dissect
507                                            must have come from this segment,
508                                            so it's all in "tvb".
509
510                                            "pinfo->desegment_offset" is
511                                            relative to the beginning of
512                                            "next_tvb"; we want an offset
513                                            relative to the beginning of "tvb".
514
515                                            First, compute the offset relative
516                                            to the *end* of "next_tvb" - i.e.,
517                                            the number of bytes before the end
518                                            of "next_tvb" at which the
519                                            subdissector stopped.  That's the
520                                            length of "next_tvb" minus the
521                                            offset, relative to the beginning
522                                            of "next_tvb, at which the
523                                            subdissector stopped.
524                                         */
525                                         deseg_offset =
526                                             ipfd_head->datalen - pinfo->desegment_offset;
527
528                                         /* "tvb" and "next_tvb" end at the
529                                            same byte of data, so the offset
530                                            relative to the end of "next_tvb"
531                                            of the byte at which we stopped
532                                            is also the offset relative to
533                                            the end of "tvb" of the byte at
534                                            which we stopped.
535
536                                            Convert that back into an offset
537                                            relative to the beginninng of
538                                            "tvb", by taking the length of
539                                            "tvb" and subtracting the offset
540                                            relative to the end.
541                                         */
542                                         deseg_offset=tvb_reported_length(tvb) - deseg_offset;
543                                 }
544                         }
545                 }
546         }
547
548         if (must_desegment) {
549             tcp_segment_key *tsk, *new_tsk;
550
551             /*
552              * The sequence number at which the stuff to be desegmented
553              * starts is the sequence number of the byte at an offset
554              * of "deseg_offset" into "tvb".
555              *
556              * The sequence number of the byte at an offset of "offset"
557              * is "seq", i.e. the starting sequence number of this
558              * segment, so the sequence number of the byte at
559              * "deseg_offset" is "seq + (deseg_offset - offset)".
560              */
561             deseg_seq = seq + (deseg_offset - offset);
562
563             /*
564              * XXX - how do we detect out-of-order transmissions?
565              * We can't just check for "nxtseq" being greater than
566              * "tsk->start_seq"; for now, we check for the difference
567              * being less than a megabyte, but this is a really
568              * gross hack - we really need to handle out-of-order
569              * transmissions correctly.
570              */
571             if ((nxtseq - deseg_seq) <= 1024*1024) {
572                 /* OK, subdissector wants us to desegment
573                    some data before it can process it. Add
574                    what remains of this packet and set
575                    up next packet/sequence number as well.
576
577                    We must remember this segment
578                 */
579                 tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
580                 tsk->src = g_mem_chunk_alloc(tcp_segment_address_chunk);
581                 COPY_ADDRESS(tsk->src, &pinfo->src);
582                 tsk->dst = g_mem_chunk_alloc(tcp_segment_address_chunk);
583                 COPY_ADDRESS(tsk->dst, &pinfo->dst);
584                 tsk->seq = deseg_seq;
585                 tsk->start_seq = tsk->seq;
586                 tsk->tot_len = nxtseq - tsk->start_seq + pinfo->desegment_len;
587                 tsk->first_frame = pinfo->fd->num;
588                 g_hash_table_insert(tcp_segment_table, tsk, tsk);
589
590                 /* Add portion of segment unprocessed by the subdissector
591                    to defragmentation lists */
592                 fragment_add(tvb, deseg_offset, pinfo, tsk->start_seq,
593                     tcp_fragment_table,
594                     tsk->seq - tsk->start_seq,
595                     nxtseq - tsk->start_seq,
596                     (nxtseq < tsk->start_seq + tsk->tot_len));
597
598                 /* this is the next segment in the sequence we want */
599                 new_tsk = g_mem_chunk_alloc(tcp_segment_key_chunk);
600                 memcpy(new_tsk, tsk, sizeof(tcp_segment_key));
601                 new_tsk->seq = nxtseq;
602                 g_hash_table_insert(tcp_segment_table,new_tsk,new_tsk);
603             }
604         }
605
606         if (!called_dissector || pinfo->desegment_len != 0) {
607                 /*
608                  * Either we didn't call the subdissector at all (i.e.,
609                  * this is a segment that contains the middle of a
610                  * higher-level PDU, but contains neither the beginning
611                  * nor the end), or the subdissector couldn't dissect it
612                  * all, as some data was missing (i.e., it set
613                  * "pinfo->desegment_len" to the amount of additional
614                  * data it needs).
615                  */
616                 if (pinfo->desegment_offset == 0) {
617                         /*
618                          * It couldn't, in fact, dissect any of it (the
619                          * first byte it couldn't dissect is at an offset
620                          * of "pinfo->desegment_offset" from the beginning
621                          * of the payload, and that's 0).
622                          * Just mark this as TCP.
623                          */
624                         if (check_col(pinfo->cinfo, COL_PROTOCOL)){
625                                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
626                         }
627                         if (check_col(pinfo->cinfo, COL_INFO)){
628                                 col_set_str(pinfo->cinfo, COL_INFO, "[Desegmented TCP]");
629                         }
630                 }
631
632                 /*
633                  * Show what's left in the packet as just raw TCP segment
634                  * data.
635                  * XXX - remember what protocol the last subdissector
636                  * was, and report it as a continuation of that, instead?
637                  */
638                 nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
639                 proto_tree_add_text(tcp_tree, tvb, deseg_offset, -1,
640                     "TCP segment data (%u byte%s)", nbytes,
641                     plurality(nbytes, "", "s"));
642         }
643         pinfo->can_desegment=0;
644         pinfo->desegment_offset = 0;
645         pinfo->desegment_len = 0;
646 }
647
648 /*
649  * Loop for dissecting PDUs within a TCP stream; assumes that a PDU
650  * consists of a fixed-length chunk of data that contains enough information
651  * to determine the length of the PDU, followed by rest of the PDU.
652  *
653  * The first three arguments are the arguments passed to the dissector
654  * that calls this routine.
655  *
656  * "proto_desegment" is the dissector's flag controlling whether it should
657  * desegment PDUs that cross TCP segment boundaries.
658  *
659  * "fixed_len" is the length of the fixed-length part of the PDU.
660  *
661  * "get_pdu_len()" is a routine called to get the length of the PDU from
662  * the fixed-length part of the PDU; it's passed "tvb" and "offset".
663  *
664  * "dissect_pdu()" is the routine to dissect a PDU.
665  */
666 void
667 tcp_dissect_pdus(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
668                  gboolean proto_desegment, guint fixed_len,
669                  guint (*get_pdu_len)(tvbuff_t *, int),
670                  void (*dissect_pdu)(tvbuff_t *, packet_info *, proto_tree *))
671 {
672   volatile int offset = 0;
673   guint length_remaining;
674   guint plen;
675   guint length;
676   tvbuff_t *next_tvb;
677
678   while (tvb_reported_length_remaining(tvb, offset) != 0) {
679     /*
680      * We use "tvb_ensure_length_remaining()" to make sure there actually
681      * *is* data remaining.  The protocol we're handling could conceivably
682      * consists of a sequence of fixed-length PDUs, and therefore the
683      * "get_pdu_len" routine might not actually fetch anything from
684      * the tvbuff, and thus might not cause an exception to be thrown if
685      * we've run past the end of the tvbuff.
686      *
687      * This means we're guaranteed that "length_remaining" is positive.
688      */
689     length_remaining = tvb_ensure_length_remaining(tvb, offset);
690
691     /*
692      * Can we do reassembly?
693      */
694     if (proto_desegment && pinfo->can_desegment) {
695       /*
696        * Yes - is the fixed-length part of the PDU split across segment
697        * boundaries?
698        */
699       if (length_remaining < fixed_len) {
700         /*
701          * Yes.  Tell the TCP dissector where the data for this message
702          * starts in the data it handed us, and how many more bytes we
703          * need, and return.
704          */
705         pinfo->desegment_offset = offset;
706         pinfo->desegment_len = fixed_len - length_remaining;
707         return;
708       }
709     }
710
711     /*
712      * Get the length of the PDU.
713      */
714     plen = (*get_pdu_len)(tvb, offset);
715
716     /*
717      * Can we do reassembly?
718      */
719     if (proto_desegment && pinfo->can_desegment) {
720       /*
721        * Yes - is the PDU split across segment boundaries?
722        */
723       if (length_remaining < plen) {
724         /*
725          * Yes.  Tell the TCP dissector where the data for this message
726          * starts in the data it handed us, and how many more bytes we
727          * need, and return.
728          */
729         pinfo->desegment_offset = offset;
730         pinfo->desegment_len = plen - length_remaining;
731         return;
732       }
733     }
734
735     /*
736      * Construct a tvbuff containing the amount of the payload we have
737      * available.  Make its reported length the amount of data in the PDU.
738      *
739      * XXX - if reassembly isn't enabled. the subdissector will throw a
740      * BoundsError exception, rather than a ReportedBoundsError exception.
741      * We really want a tvbuff where the length is "length", the reported
742      * length is "plen", and the "if the snapshot length were infinite"
743      * length is the minimum of the reported length of the tvbuff handed
744      * to us and "plen", with a new type of exception thrown if the offset
745      * is within the reported length but beyond that third length, with
746      * that exception getting the "Unreassembled Packet" error.
747      */
748     if (plen < fixed_len) {
749       /*
750        * The PDU length from the fixed-length portion probably didn't
751        * include the fixed-length portion's length, and was probably so
752        * large that the total length overflowed.
753        *
754        * Report this as an error.
755        */
756       show_reported_bounds_error(tvb, pinfo, tree);
757       return;
758     }
759     length = length_remaining;
760     if (length > plen)
761         length = plen;
762     next_tvb = tvb_new_subset(tvb, offset, length, plen);
763
764     /*
765      * Dissect the PDU.
766      *
767      * Catch the ReportedBoundsError exception; if this particular message
768      * happens to get a ReportedBoundsError exception, that doesn't mean
769      * that we should stop dissecting PDUs within this frame or chunk of
770      * reassembled data.
771      *
772      * If it gets a BoundsError, we can stop, as there's nothing more to
773      * see, so we just re-throw it.
774      */
775     TRY {
776       (*dissect_pdu)(next_tvb, pinfo, tree);
777     }
778     CATCH(BoundsError) {
779       RETHROW;
780     }
781     CATCH(ReportedBoundsError) {
782       show_reported_bounds_error(tvb, pinfo, tree);
783     }
784     ENDTRY;
785
786     /*
787      * Step to the next PDU.
788      */
789     offset += plen;
790   }
791 }
792
793 static void
794 tcp_info_append_uint(packet_info *pinfo, const char *abbrev, guint32 val)
795 {
796   if (check_col(pinfo->cinfo, COL_INFO))
797     col_append_fstr(pinfo->cinfo, COL_INFO, " %s=%u", abbrev, val);
798 }
799
800 static void
801 dissect_tcpopt_maxseg(const ip_tcp_opt *optp, tvbuff_t *tvb,
802     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
803 {
804   guint16 mss;
805
806   mss = tvb_get_ntohs(tvb, offset + 2);
807   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
808                         "%s: %u bytes", optp->name, mss);
809   tcp_info_append_uint(pinfo, "MSS", mss);
810 }
811
812 static void
813 dissect_tcpopt_wscale(const ip_tcp_opt *optp, tvbuff_t *tvb,
814     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
815 {
816   guint8 ws;
817
818   ws = tvb_get_guint8(tvb, offset + 2);
819   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
820                         "%s: %u bytes", optp->name, ws);
821   tcp_info_append_uint(pinfo, "WS", ws);
822 }
823
824 static void
825 dissect_tcpopt_sack(const ip_tcp_opt *optp, tvbuff_t *tvb,
826     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
827 {
828   proto_tree *field_tree = NULL;
829   proto_item *tf;
830   guint leftedge, rightedge;
831
832   tf = proto_tree_add_text(opt_tree, tvb, offset,      optlen, "%s:", optp->name);
833   offset += 2;  /* skip past type and length */
834   optlen -= 2;  /* subtract size of type and length */
835   while (optlen > 0) {
836     if (field_tree == NULL) {
837       /* Haven't yet made a subtree out of this option.  Do so. */
838       field_tree = proto_item_add_subtree(tf, *optp->subtree_index);
839     }
840     if (optlen < 4) {
841       proto_tree_add_text(field_tree, tvb, offset,      optlen,
842         "(suboption would go past end of option)");
843       break;
844     }
845     leftedge = tvb_get_ntohl(tvb, offset);
846     optlen -= 4;
847     if (optlen < 4) {
848       proto_tree_add_text(field_tree, tvb, offset,      optlen,
849         "(suboption would go past end of option)");
850       break;
851     }
852     /* XXX - check whether it goes past end of packet */
853     rightedge = tvb_get_ntohl(tvb, offset + 4);
854     optlen -= 4;
855     proto_tree_add_text(field_tree, tvb, offset,      8,
856         "left edge = %u, right edge = %u", leftedge, rightedge);
857     tcp_info_append_uint(pinfo, "SLE", leftedge);
858     tcp_info_append_uint(pinfo, "SRE", rightedge);
859     offset += 8;
860   }
861 }
862
863 static void
864 dissect_tcpopt_echo(const ip_tcp_opt *optp, tvbuff_t *tvb,
865     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
866 {
867   guint32 echo;
868
869   echo = tvb_get_ntohl(tvb, offset + 2);
870   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
871                         "%s: %u", optp->name, echo);
872   tcp_info_append_uint(pinfo, "ECHO", echo);
873 }
874
875 static void
876 dissect_tcpopt_timestamp(const ip_tcp_opt *optp, tvbuff_t *tvb,
877     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
878 {
879   guint32 tsv, tser;
880
881   tsv = tvb_get_ntohl(tvb, offset + 2);
882   tser = tvb_get_ntohl(tvb, offset + 6);
883   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
884     "%s: tsval %u, tsecr %u", optp->name, tsv, tser);
885   tcp_info_append_uint(pinfo, "TSV", tsv);
886   tcp_info_append_uint(pinfo, "TSER", tser);
887 }
888
889 static void
890 dissect_tcpopt_cc(const ip_tcp_opt *optp, tvbuff_t *tvb,
891     int offset, guint optlen, packet_info *pinfo, proto_tree *opt_tree)
892 {
893   guint32 cc;
894
895   cc = tvb_get_ntohl(tvb, offset + 2);
896   proto_tree_add_text(opt_tree, tvb, offset,      optlen,
897                         "%s: %u", optp->name, cc);
898   tcp_info_append_uint(pinfo, "CC", cc);
899 }
900
901 static const ip_tcp_opt tcpopts[] = {
902   {
903     TCPOPT_EOL,
904     "EOL",
905     NULL,
906     NO_LENGTH,
907     0,
908     NULL,
909   },
910   {
911     TCPOPT_NOP,
912     "NOP",
913     NULL,
914     NO_LENGTH,
915     0,
916     NULL,
917   },
918   {
919     TCPOPT_MSS,
920     "Maximum segment size",
921     NULL,
922     FIXED_LENGTH,
923     TCPOLEN_MSS,
924     dissect_tcpopt_maxseg
925   },
926   {
927     TCPOPT_WINDOW,
928     "Window scale",
929     NULL,
930     FIXED_LENGTH,
931     TCPOLEN_WINDOW,
932     dissect_tcpopt_wscale
933   },
934   {
935     TCPOPT_SACK_PERM,
936     "SACK permitted",
937     NULL,
938     FIXED_LENGTH,
939     TCPOLEN_SACK_PERM,
940     NULL,
941   },
942   {
943     TCPOPT_SACK,
944     "SACK",
945     &ett_tcp_option_sack,
946     VARIABLE_LENGTH,
947     TCPOLEN_SACK_MIN,
948     dissect_tcpopt_sack
949   },
950   {
951     TCPOPT_ECHO,
952     "Echo",
953     NULL,
954     FIXED_LENGTH,
955     TCPOLEN_ECHO,
956     dissect_tcpopt_echo
957   },
958   {
959     TCPOPT_ECHOREPLY,
960     "Echo reply",
961     NULL,
962     FIXED_LENGTH,
963     TCPOLEN_ECHOREPLY,
964     dissect_tcpopt_echo
965   },
966   {
967     TCPOPT_TIMESTAMP,
968     "Time stamp",
969     NULL,
970     FIXED_LENGTH,
971     TCPOLEN_TIMESTAMP,
972     dissect_tcpopt_timestamp
973   },
974   {
975     TCPOPT_CC,
976     "CC",
977     NULL,
978     FIXED_LENGTH,
979     TCPOLEN_CC,
980     dissect_tcpopt_cc
981   },
982   {
983     TCPOPT_CCNEW,
984     "CC.NEW",
985     NULL,
986     FIXED_LENGTH,
987     TCPOLEN_CCNEW,
988     dissect_tcpopt_cc
989   },
990   {
991     TCPOPT_CCECHO,
992     "CC.ECHO",
993     NULL,
994     FIXED_LENGTH,
995     TCPOLEN_CCECHO,
996     dissect_tcpopt_cc
997   },
998   {
999     TCPOPT_MD5,
1000     "TCP MD5 signature",
1001     NULL,
1002     FIXED_LENGTH,
1003     TCPOLEN_MD5,
1004     NULL
1005   }
1006 };
1007
1008 #define N_TCP_OPTS      (sizeof tcpopts / sizeof tcpopts[0])
1009
1010 /* TCP flags flag */
1011 static const true_false_string flags_set_truth = {
1012   "Set",
1013   "Not set"
1014 };
1015
1016
1017 /* Determine if there is a sub-dissector and call it.  This has been */
1018 /* separated into a stand alone routine to other protocol dissectors */
1019 /* can call to it, ie. socks    */
1020
1021 void
1022 decode_tcp_ports(tvbuff_t *tvb, int offset, packet_info *pinfo,
1023         proto_tree *tree, int src_port, int dst_port)
1024 {
1025   tvbuff_t *next_tvb;
1026   int low_port, high_port;
1027
1028   next_tvb = tvb_new_subset(tvb, offset, -1, -1);
1029
1030 /* determine if this packet is part of a conversation and call dissector */
1031 /* for the conversation if available */
1032
1033   if (try_conversation_dissector(&pinfo->src, &pinfo->dst, PT_TCP,
1034                 src_port, dst_port, next_tvb, pinfo, tree))
1035     return;
1036
1037   /* Do lookups with the subdissector table.
1038      We try the port number with the lower value first, followed by the
1039      port number with the higher value.  This means that, for packets
1040      where a dissector is registered for *both* port numbers:
1041
1042         1) we pick the same dissector for traffic going in both directions;
1043
1044         2) we prefer the port number that's more likely to be the right
1045            one (as that prefers well-known ports to reserved ports);
1046
1047      although there is, of course, no guarantee that any such strategy
1048      will always pick the right port number.
1049
1050      XXX - we ignore port numbers of 0, as some dissectors use a port
1051      number of 0 to disable the port. */
1052   if (src_port > dst_port) {
1053     low_port = dst_port;
1054     high_port = src_port;
1055   } else {
1056     low_port = src_port;
1057     high_port = dst_port;
1058   }
1059   if (low_port != 0 &&
1060       dissector_try_port(subdissector_table, low_port, next_tvb, pinfo, tree))
1061     return;
1062   if (high_port != 0 &&
1063       dissector_try_port(subdissector_table, high_port, next_tvb, pinfo, tree))
1064     return;
1065
1066   /* do lookup with the heuristic subdissector table */
1067   if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree))
1068     return;
1069
1070   /* Oh, well, we don't know this; dissect it as data. */
1071   call_dissector(data_handle,next_tvb, pinfo, tree);
1072 }
1073
1074
1075 static void
1076 dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1077 {
1078   guint16 th_sport;
1079   guint16 th_dport;
1080   guint32 th_seq;
1081   guint32 th_ack;
1082   guint8  th_off_x2; /* combines th_off and th_x2 */
1083   guint8  th_flags;
1084   guint16 th_win;
1085   guint16 th_sum;
1086   guint16 th_urp;
1087   proto_tree *tcp_tree = NULL, *field_tree = NULL;
1088   proto_item *ti = NULL, *tf;
1089   int        offset = 0;
1090   gchar      flags[64] = "<None>";
1091   gchar     *fstr[] = {"FIN", "SYN", "RST", "PSH", "ACK", "URG", "ECN", "CWR" };
1092   gint       fpos = 0, i;
1093   guint      bpos;
1094   guint      hlen;
1095   guint      optlen;
1096   guint32    seglen;
1097   guint32    nxtseq;
1098   guint      len;
1099   guint      reported_len;
1100   vec_t      cksum_vec[4];
1101   guint32    phdr[2];
1102   guint16    computed_cksum;
1103   guint      length_remaining;
1104   gboolean   desegment_ok;
1105   struct tcpinfo tcpinfo;
1106   gboolean   save_fragmented;
1107
1108   if (check_col(pinfo->cinfo, COL_PROTOCOL))
1109     col_set_str(pinfo->cinfo, COL_PROTOCOL, "TCP");
1110
1111   /* Clear out the Info column. */
1112   if (check_col(pinfo->cinfo, COL_INFO))
1113     col_clear(pinfo->cinfo, COL_INFO);
1114
1115   th_sport = tvb_get_ntohs(tvb, offset);
1116   th_dport = tvb_get_ntohs(tvb, offset + 2);
1117   if (check_col(pinfo->cinfo, COL_INFO)) {
1118     col_append_fstr(pinfo->cinfo, COL_INFO, "%s > %s",
1119       get_tcp_port(th_sport), get_tcp_port(th_dport));
1120   }
1121   
1122   if (tree) {
1123     if (tcp_summary_in_tree) {
1124             ti = proto_tree_add_protocol_format(tree, proto_tcp, tvb, 0, -1,
1125                 "Transmission Control Protocol, Src Port: %s (%u), Dst Port: %s (%u)",
1126                 get_tcp_port(th_sport), th_sport,
1127                 get_tcp_port(th_dport), th_dport);
1128     }
1129     else {
1130             ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, FALSE);
1131     }
1132     tcp_tree = proto_item_add_subtree(ti, ett_tcp);
1133     proto_tree_add_uint_format(tcp_tree, hf_tcp_srcport, tvb, offset, 2, th_sport,
1134         "Source port: %s (%u)", get_tcp_port(th_sport), th_sport);
1135     proto_tree_add_uint_format(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, th_dport,
1136         "Destination port: %s (%u)", get_tcp_port(th_dport), th_dport);
1137     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset, 2, th_sport);
1138     proto_tree_add_uint_hidden(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, th_dport);
1139   }
1140
1141   th_seq = tvb_get_ntohl(tvb, offset + 4);
1142   th_ack = tvb_get_ntohl(tvb, offset + 8);
1143   th_off_x2 = tvb_get_guint8(tvb, offset + 12);
1144   th_flags = tvb_get_guint8(tvb, offset + 13);
1145   th_win = tvb_get_ntohs(tvb, offset + 14);
1146   
1147   if (check_col(pinfo->cinfo, COL_INFO) || tree) {  
1148     for (i = 0; i < 8; i++) {
1149       bpos = 1 << i;
1150       if (th_flags & bpos) {
1151         if (fpos) {
1152           strcpy(&flags[fpos], ", ");
1153           fpos += 2;
1154         }
1155         strcpy(&flags[fpos], fstr[i]);
1156         fpos += 3;
1157       }
1158     }
1159     flags[fpos] = '\0';
1160   }
1161
1162   if (check_col(pinfo->cinfo, COL_INFO)) {
1163     col_append_fstr(pinfo->cinfo, COL_INFO, " [%s] Seq=%u Ack=%u Win=%u",
1164       flags, th_seq, th_ack, th_win);
1165   }
1166
1167   if (tree) {
1168     if (tcp_summary_in_tree)
1169       proto_item_append_text(ti, ", Seq: %u", th_seq);
1170     proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, th_seq);
1171   }
1172
1173   hlen = hi_nibble(th_off_x2) * 4;  /* TCP header length, in bytes */
1174
1175   if (hlen < TCPH_MIN_LEN) {
1176     /* Give up at this point; we put the source and destination port in
1177        the tree, before fetching the header length, so that they'll
1178        show up if this is in the failing packet in an ICMP error packet,
1179        but it's now time to give up if the header length is bogus. */
1180     if (check_col(pinfo->cinfo, COL_INFO))
1181       col_append_fstr(pinfo->cinfo, COL_INFO, ", bogus TCP header length (%u, must be at least %u)",
1182         hlen, TCPH_MIN_LEN);
1183     if (tree) {
1184       proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, hlen,
1185        "Header length: %u bytes (bogus, must be at least %u)", hlen,
1186        TCPH_MIN_LEN);
1187     }
1188     return;
1189   }
1190
1191   reported_len = tvb_reported_length(tvb);
1192   len = tvb_length(tvb);
1193
1194   /* Compute the length of data in this segment. */
1195   seglen = reported_len - hlen;
1196
1197   if (tree) { /* Add the seglen as an invisible field */
1198
1199     proto_tree_add_uint_hidden(ti, hf_tcp_len, tvb, offset, 4, seglen);
1200
1201   }
1202
1203   /* Compute the sequence number of next octet after this segment. */
1204   nxtseq = th_seq + seglen;
1205
1206   if (tree) {
1207     if (tcp_summary_in_tree)
1208       proto_item_append_text(ti, ", Ack: %u, Len: %u", th_ack, seglen);
1209     proto_item_set_len(ti, hlen);
1210     if (nxtseq != th_seq)
1211       proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);
1212     if (th_flags & TH_ACK)
1213       proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, th_ack);
1214     proto_tree_add_uint_format(tcp_tree, hf_tcp_hdr_len, tvb, offset + 12, 1, hlen,
1215         "Header length: %u bytes", hlen);
1216     tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 13, 1,
1217         th_flags, "Flags: 0x%04x (%s)", th_flags, flags);
1218     field_tree = proto_item_add_subtree(tf, ett_tcp_flags);
1219     proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, th_flags);
1220     proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, th_flags);
1221     proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, th_flags);
1222     proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, th_flags);
1223     proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, th_flags);
1224     proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, th_flags);
1225     proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, th_flags);
1226     proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, th_flags);
1227     proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, th_win);
1228   }
1229
1230   /* Supply the sequence number of the first byte. */
1231   tcpinfo.seq = th_seq;
1232
1233   /* Assume we'll pass un-reassembled data to subdissectors. */
1234   tcpinfo.is_reassembled = FALSE;
1235
1236   pinfo->private_data = &tcpinfo;
1237
1238   /*
1239    * Assume, initially, that we can't desegment.
1240    */
1241   pinfo->can_desegment = 0;
1242
1243   th_sum = tvb_get_ntohs(tvb, offset + 16);
1244   if (!pinfo->fragmented && len >= reported_len) {
1245     /* The packet isn't part of an un-reassembled fragmented datagram
1246        and isn't truncated.  This means we have all the data, and thus
1247        can checksum it and, unless it's being returned in an error
1248        packet, are willing to allow subdissectors to request reassembly
1249        on it. */
1250   
1251     if (tcp_check_checksum) {
1252       /* We haven't turned checksum checking off; checksum it. */
1253
1254       /* Set up the fields of the pseudo-header. */
1255       cksum_vec[0].ptr = pinfo->src.data;
1256       cksum_vec[0].len = pinfo->src.len;
1257       cksum_vec[1].ptr = pinfo->dst.data;
1258       cksum_vec[1].len = pinfo->dst.len;
1259       cksum_vec[2].ptr = (const guint8 *)&phdr;
1260       switch (pinfo->src.type) {
1261
1262       case AT_IPv4:
1263         phdr[0] = htonl((IP_PROTO_TCP<<16) + reported_len);
1264         cksum_vec[2].len = 4;
1265         break;
1266
1267       case AT_IPv6:
1268         phdr[0] = htonl(reported_len);
1269         phdr[1] = htonl(IP_PROTO_TCP);
1270         cksum_vec[2].len = 8;
1271         break;
1272
1273       default:
1274         /* TCP runs only atop IPv4 and IPv6.... */
1275         g_assert_not_reached();
1276         break;
1277       }
1278       cksum_vec[3].ptr = tvb_get_ptr(tvb, offset, len);
1279       cksum_vec[3].len = reported_len;
1280       computed_cksum = in_cksum(&cksum_vec[0], 4);
1281       if (computed_cksum == 0) {
1282         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1283           offset + 16, 2, th_sum, "Checksum: 0x%04x (correct)", th_sum);
1284
1285         /* Checksum is valid, so we're willing to desegment it. */
1286         desegment_ok = TRUE;
1287       } else {
1288         proto_tree_add_boolean_hidden(tcp_tree, hf_tcp_checksum_bad, tvb,
1289            offset + 16, 2, TRUE);
1290         proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1291            offset + 16, 2, th_sum,
1292            "Checksum: 0x%04x (incorrect, should be 0x%04x)", th_sum,
1293            in_cksum_shouldbe(th_sum, computed_cksum));
1294
1295         /* Checksum is invalid, so we're not willing to desegment it. */
1296         desegment_ok = FALSE;
1297       }
1298     } else {
1299       proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1300          offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
1301
1302       /* We didn't check the checksum, and don't care if it's valid,
1303          so we're willing to desegment it. */
1304       desegment_ok = TRUE;
1305     }
1306   } else {
1307     /* We don't have all the packet data, so we can't checksum it... */
1308     proto_tree_add_uint_format(tcp_tree, hf_tcp_checksum, tvb,
1309        offset + 16, 2, th_sum, "Checksum: 0x%04x", th_sum);
1310
1311     /* ...and aren't willing to desegment it. */
1312     desegment_ok = FALSE;
1313   }
1314
1315   if (desegment_ok) {
1316     /* We're willing to desegment this.  Is desegmentation enabled? */
1317     if (tcp_desegment) {
1318       /* Yes - is this segment being returned in an error packet? */
1319       if (!pinfo->in_error_pkt) {
1320         /* No - indicate that we will desegment.
1321            We do NOT want to desegment segments returned in error
1322            packets, as they're not part of a TCP connection. */
1323         pinfo->can_desegment = 2;
1324       }
1325     }
1326   }
1327
1328   if (th_flags & TH_URG) {
1329     th_urp = tvb_get_ntohs(tvb, offset + 18);
1330     /* Export the urgent pointer, for the benefit of protocols such as
1331        rlogin. */
1332     tcpinfo.urgent = TRUE;
1333     tcpinfo.urgent_pointer = th_urp;
1334     if (check_col(pinfo->cinfo, COL_INFO))
1335       col_append_fstr(pinfo->cinfo, COL_INFO, " Urg=%u", th_urp);
1336     if (tcp_tree != NULL)
1337       proto_tree_add_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, th_urp);
1338   } else
1339     tcpinfo.urgent = FALSE;
1340
1341   if (check_col(pinfo->cinfo, COL_INFO))
1342     col_append_fstr(pinfo->cinfo, COL_INFO, " Len=%u", seglen);
1343
1344   /* Decode TCP options, if any. */
1345   if (tree && hlen > TCPH_MIN_LEN) {
1346     /* There's more than just the fixed-length header.  Decode the
1347        options. */
1348     optlen = hlen - TCPH_MIN_LEN; /* length of options, in bytes */
1349     tf = proto_tree_add_text(tcp_tree, tvb, offset +  20, optlen,
1350       "Options: (%u bytes)", optlen);
1351     field_tree = proto_item_add_subtree(tf, ett_tcp_options);
1352     dissect_ip_tcp_options(tvb, offset + 20, optlen,
1353       tcpopts, N_TCP_OPTS, TCPOPT_EOL, pinfo, field_tree);
1354   }
1355
1356   /* Skip over header + options */
1357   offset += hlen;
1358
1359   pinfo->ptype = PT_TCP;
1360   pinfo->srcport = th_sport;
1361   pinfo->destport = th_dport;
1362   
1363   /* Check the packet length to see if there's more data
1364      (it could be an ACK-only packet) */
1365   length_remaining = tvb_length_remaining(tvb, offset);
1366
1367   if( data_out_file ) {
1368     reassemble_tcp( th_seq,             /* sequence number */
1369         seglen,                         /* data length */
1370         tvb_get_ptr(tvb, offset, length_remaining),     /* data */
1371         length_remaining,               /* captured data length */
1372         ( th_flags & TH_SYN ),          /* is syn set? */
1373         &pinfo->net_src,
1374         &pinfo->net_dst,
1375         pinfo->srcport,
1376         pinfo->destport);
1377   }
1378
1379   if (length_remaining != 0) {
1380     if (th_flags & TH_RST) {
1381       /*
1382        * RFC1122 says:
1383        *
1384        *        4.2.2.12  RST Segment: RFC-793 Section 3.4
1385        *
1386        *          A TCP SHOULD allow a received RST segment to include data.
1387        *
1388        *          DISCUSSION
1389        *               It has been suggested that a RST segment could contain
1390        *               ASCII text that encoded and explained the cause of the
1391        *               RST.  No standard has yet been established for such
1392        *               data.
1393        *
1394        * so for segments with RST we just display the data as text.
1395        */
1396       proto_tree_add_text(tcp_tree, tvb, offset, length_remaining,
1397                             "Reset cause: %s",
1398                             tvb_format_text(tvb, offset, length_remaining));
1399     } else {
1400       /* Can we desegment this segment? */
1401       if (pinfo->can_desegment) {
1402         /* Yes. */
1403         desegment_tcp(tvb, pinfo, offset, th_seq, nxtseq, th_sport, th_dport, tree, tcp_tree);
1404       } else {
1405         /* No - just call the subdissector.
1406            Mark this as fragmented, so if somebody throws an exception,
1407            we don't report it as a malformed frame. */
1408         save_fragmented = pinfo->fragmented;
1409         pinfo->fragmented = TRUE;
1410         decode_tcp_ports(tvb, offset, pinfo, tree, th_sport, th_dport);
1411         pinfo->fragmented = save_fragmented;
1412       }
1413     }
1414   }
1415 }
1416
1417 void
1418 proto_register_tcp(void)
1419 {
1420         static hf_register_info hf[] = {
1421
1422                 { &hf_tcp_srcport,
1423                 { "Source Port",                "tcp.srcport", FT_UINT16, BASE_DEC, NULL, 0x0,
1424                         "", HFILL }},
1425
1426                 { &hf_tcp_dstport,
1427                 { "Destination Port",           "tcp.dstport", FT_UINT16, BASE_DEC, NULL, 0x0,
1428                         "", HFILL }},
1429
1430                 { &hf_tcp_port,
1431                 { "Source or Destination Port", "tcp.port", FT_UINT16, BASE_DEC, NULL, 0x0,
1432                         "", HFILL }},
1433
1434                 { &hf_tcp_seq,
1435                 { "Sequence number",            "tcp.seq", FT_UINT32, BASE_DEC, NULL, 0x0,
1436                         "", HFILL }},
1437
1438                 { &hf_tcp_nxtseq,
1439                 { "Next sequence number",       "tcp.nxtseq", FT_UINT32, BASE_DEC, NULL, 0x0,
1440                         "", HFILL }},
1441
1442                 { &hf_tcp_ack,
1443                 { "Acknowledgement number",     "tcp.ack", FT_UINT32, BASE_DEC, NULL, 0x0,
1444                         "", HFILL }},
1445
1446                 { &hf_tcp_hdr_len,
1447                 { "Header Length",              "tcp.hdr_len", FT_UINT8, BASE_DEC, NULL, 0x0,
1448                         "", HFILL }},
1449
1450                 { &hf_tcp_flags,
1451                 { "Flags",                      "tcp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
1452                         "", HFILL }},
1453
1454                 { &hf_tcp_flags_cwr,
1455                 { "Congestion Window Reduced (CWR)",                    "tcp.flags.cwr", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_CWR,
1456                         "", HFILL }},
1457
1458                 { &hf_tcp_flags_ecn,
1459                 { "ECN-Echo",                   "tcp.flags.ecn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ECN,
1460                         "", HFILL }},
1461
1462                 { &hf_tcp_flags_urg,
1463                 { "Urgent",                     "tcp.flags.urg", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_URG,
1464                         "", HFILL }},
1465
1466                 { &hf_tcp_flags_ack,
1467                 { "Acknowledgment",             "tcp.flags.ack", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_ACK,
1468                         "", HFILL }},
1469
1470                 { &hf_tcp_flags_push,
1471                 { "Push",                       "tcp.flags.push", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_PUSH,
1472                         "", HFILL }},
1473
1474                 { &hf_tcp_flags_reset,
1475                 { "Reset",                      "tcp.flags.reset", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_RST,
1476                         "", HFILL }},
1477
1478                 { &hf_tcp_flags_syn,
1479                 { "Syn",                        "tcp.flags.syn", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_SYN,
1480                         "", HFILL }},
1481
1482                 { &hf_tcp_flags_fin,
1483                 { "Fin",                        "tcp.flags.fin", FT_BOOLEAN, 8, TFS(&flags_set_truth), TH_FIN,
1484                         "", HFILL }},
1485
1486                 { &hf_tcp_window_size,
1487                 { "Window size",                "tcp.window_size", FT_UINT16, BASE_DEC, NULL, 0x0,
1488                         "", HFILL }},
1489
1490                 { &hf_tcp_checksum,
1491                 { "Checksum",                   "tcp.checksum", FT_UINT16, BASE_HEX, NULL, 0x0,
1492                         "", HFILL }},
1493
1494                 { &hf_tcp_checksum_bad,
1495                 { "Bad Checksum",               "tcp.checksum_bad", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
1496                         "", HFILL }},
1497
1498                 { &hf_tcp_len,
1499                   { "TCP Segment Len",            "tcp.len", FT_UINT32, BASE_DEC, NULL, 0x0, 
1500                     "", HFILL}},
1501
1502                 { &hf_tcp_urgent_pointer,
1503                 { "Urgent pointer",             "tcp.urgent_pointer", FT_UINT16, BASE_DEC, NULL, 0x0,
1504                         "", HFILL }},
1505         };
1506         static gint *ett[] = {
1507                 &ett_tcp,
1508                 &ett_tcp_flags,
1509                 &ett_tcp_options,
1510                 &ett_tcp_option_sack,
1511                 &ett_tcp_segments,
1512         };
1513         module_t *tcp_module;
1514
1515         proto_tcp = proto_register_protocol("Transmission Control Protocol",
1516             "TCP", "tcp");
1517         proto_register_field_array(proto_tcp, hf, array_length(hf));
1518         proto_register_subtree_array(ett, array_length(ett));
1519
1520         /* subdissector code */
1521         subdissector_table = register_dissector_table("tcp.port",
1522             "TCP port", FT_UINT16, BASE_DEC);
1523         register_heur_dissector_list("tcp", &heur_subdissector_list);
1524
1525         /* Register configuration preferences */
1526         tcp_module = prefs_register_protocol(proto_tcp, NULL);
1527         prefs_register_bool_preference(tcp_module, "tcp_summary_in_tree",
1528             "Show TCP summary in protocol tree",
1529 "Whether the TCP summary line should be shown in the protocol tree",
1530             &tcp_summary_in_tree);
1531         prefs_register_bool_preference(tcp_module, "check_checksum",
1532             "Check the validity of the TCP checksum when possible",
1533 "Whether to check the validity of the TCP checksum",
1534             &tcp_check_checksum);
1535         prefs_register_bool_preference(tcp_module, "desegment_tcp_streams",
1536             "Allow subdissector to desegment TCP streams",
1537 "Whether subdissector can request TCP streams to be desegmented",
1538             &tcp_desegment);
1539
1540         register_init_routine(tcp_desegment_init);
1541         register_init_routine(tcp_fragment_init);
1542 }
1543
1544 void
1545 proto_reg_handoff_tcp(void)
1546 {
1547         dissector_handle_t tcp_handle;
1548
1549         tcp_handle = create_dissector_handle(dissect_tcp, proto_tcp);
1550         dissector_add("ip.proto", IP_PROTO_TCP, tcp_handle);
1551         data_handle = find_dissector("data");
1552 }