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