Have tvbuff's keep track of cap_len and pkt_len ('length' and 'reported_length'
[obnox/wireshark/wip.git] / packet.c
1 /* packet.c
2  * Routines for packet disassembly
3  *
4  * $Id: packet.c,v 1.83 2000/05/16 04:44:13 gram Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@zing.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * 
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  * 
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  * 
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #ifdef HAVE_SYS_TYPES_H
31 # include <sys/types.h>
32 #endif
33
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37
38 #ifdef HAVE_WINSOCK_H
39 #include <winsock.h>
40 #endif
41
42 #include <glib.h>
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdarg.h>
47 #include <string.h>
48 #include <ctype.h>
49 #include <time.h>
50
51 #ifdef NEED_SNPRINTF_H
52 # include "snprintf.h"
53 #endif
54
55 #ifdef HAVE_NETINET_IN_H
56 # include <netinet/in.h>
57 #endif
58
59 #ifdef HAVE_ARPA_INET_H
60 #include <arpa/inet.h>
61 #endif
62
63 #ifdef NEED_INET_V6DEFS_H
64 # include "inet_v6defs.h"
65 #endif
66
67 #include "packet.h"
68 #include "print.h"
69 #include "timestamp.h"
70 #include "file.h"
71
72 #include "packet-ascend.h"
73 #include "packet-atalk.h"
74 #include "packet-atm.h"
75 #include "packet-clip.h"
76 #include "packet-eth.h"
77 #include "packet-fddi.h"
78 #include "packet-ipv6.h"
79 #include "packet-lapb.h"
80 #include "packet-lapd.h"
81 #include "packet-null.h"
82 #include "packet-ppp.h"
83 #include "packet-raw.h"
84 #include "packet-sna.h"
85 #include "packet-tr.h"
86 #include "packet-v120.h"
87 #include "packet-vines.h"
88
89 #ifndef __RESOLV_H__
90 #include "resolv.h"
91 #endif
92
93 #ifndef __TVBUFF_H__
94 #include "tvbuff.h"
95 #endif
96
97 #include "plugins.h"
98
99 extern capture_file  cf;
100
101 static int proto_frame = -1;
102 static int hf_frame_arrival_time = -1;
103 static int hf_frame_time_delta = -1;
104 static int hf_frame_number = -1;
105 static int hf_frame_packet_len = -1;
106 static int hf_frame_capture_len = -1;
107 static int proto_short = -1;
108 static int proto_malformed = -1;
109
110 static gint ett_frame = -1;
111
112 GMemChunk *frame_proto_data_area = NULL;
113
114 /* 
115  * Free up any space allocated for frame proto data areas and then 
116  * allocate a new area.
117  *
118  * We can free the area, as the structures it contains are pointed to by
119  * frames, that will be freed as well.
120  */
121 static void
122 packet_init_protocol(void)
123 {
124
125   if (frame_proto_data_area)
126     g_mem_chunk_destroy(frame_proto_data_area);
127
128   frame_proto_data_area = g_mem_chunk_new("frame_proto_data_area",
129                                           sizeof(frame_proto_data),
130                                           20 * sizeof(frame_proto_data), /* FIXME*/
131                                           G_ALLOC_ONLY);
132
133 }
134
135 /* Wrapper for the most common case of asking
136  * for a string using a colon as the hex-digit separator.
137  */
138 gchar *
139 ether_to_str(const guint8 *ad)
140 {
141         return ether_to_str_punct(ad, ':');
142 }
143
144 /* Places char punct in the string as the hex-digit separator.
145  * If punct is '\0', no punctuation is applied (and thus
146  * the resulting string is 5 bytes shorter)
147  */
148 gchar *
149 ether_to_str_punct(const guint8 *ad, char punct) {
150   static gchar  str[3][18];
151   static gchar *cur;
152   gchar        *p;
153   int          i;
154   guint32      octet;
155   static const gchar hex_digits[16] = "0123456789abcdef";
156
157   if (cur == &str[0][0]) {
158     cur = &str[1][0];
159   } else if (cur == &str[1][0]) {  
160     cur = &str[2][0];
161   } else {  
162     cur = &str[0][0];
163   }
164   p = &cur[18];
165   *--p = '\0';
166   i = 5;
167   for (;;) {
168     octet = ad[i];
169     *--p = hex_digits[octet&0xF];
170     octet >>= 4;
171     *--p = hex_digits[octet&0xF];
172     if (i == 0)
173       break;
174     if (punct)
175       *--p = punct;
176     i--;
177   }
178   return p;
179 }
180
181 gchar *
182 ip_to_str(const guint8 *ad) {
183   static gchar  str[3][16];
184   static gchar *cur;
185   gchar        *p;
186   int           i;
187   guint32       octet;
188   guint32       digit;
189
190   if (cur == &str[0][0]) {
191     cur = &str[1][0];
192   } else if (cur == &str[1][0]) {  
193     cur = &str[2][0];
194   } else {  
195     cur = &str[0][0];
196   }
197   p = &cur[16];
198   *--p = '\0';
199   i = 3;
200   for (;;) {
201     octet = ad[i];
202     *--p = (octet%10) + '0';
203     octet /= 10;
204     digit = octet%10;
205     octet /= 10;
206     if (digit != 0 || octet != 0)
207       *--p = digit + '0';
208     if (octet != 0)
209       *--p = octet + '0';
210     if (i == 0)
211       break;
212     *--p = '.';
213     i--;
214   }
215   return p;
216 }
217
218 gchar *
219 ip6_to_str(struct e_in6_addr *ad) {
220 #ifndef INET6_ADDRSTRLEN
221 #define INET6_ADDRSTRLEN 46
222 #endif
223   static gchar buf[INET6_ADDRSTRLEN];
224
225   inet_ntop(AF_INET6, (u_char*)ad, (gchar*)buf, sizeof(buf));
226   return buf;
227 }
228
229
230 #define PLURALIZE(n)    (((n) > 1) ? "s" : "")
231 #define COMMA(do_it)    ((do_it) ? ", " : "")
232
233 gchar *
234 time_secs_to_str(guint32 time)
235 {
236   static gchar  str[3][8+1+4+2+2+5+2+2+7+2+2+7+1];
237   static gchar *cur, *p;
238   int hours, mins, secs;
239   int do_comma;
240
241   if (cur == &str[0][0]) {
242     cur = &str[1][0];
243   } else if (cur == &str[1][0]) {  
244     cur = &str[2][0];
245   } else {  
246     cur = &str[0][0];
247   }
248
249   if (time == 0) {
250     sprintf(cur, "0 time");
251     return cur;
252   }
253
254   secs = time % 60;
255   time /= 60;
256   mins = time % 60;
257   time /= 60;
258   hours = time % 24;
259   time /= 24;
260
261   p = cur;
262   if (time != 0) {
263     sprintf(p, "%u day%s", time, PLURALIZE(time));
264     p += strlen(p);
265     do_comma = 1;
266   } else
267     do_comma = 0;
268   if (hours != 0) {
269     sprintf(p, "%s%u hour%s", COMMA(do_comma), hours, PLURALIZE(hours));
270     p += strlen(p);
271     do_comma = 1;
272   } else
273     do_comma = 0;
274   if (mins != 0) {
275     sprintf(p, "%s%u minute%s", COMMA(do_comma), mins, PLURALIZE(mins));
276     p += strlen(p);
277     do_comma = 1;
278   } else
279     do_comma = 0;
280   if (secs != 0)
281     sprintf(p, "%s%u second%s", COMMA(do_comma), secs, PLURALIZE(secs));
282   return cur;
283 }
284
285 /* Max string length for displaying byte string.  */
286 #define MAX_BYTE_STR_LEN        32
287
288 /* Turn an array of bytes into a string showing the bytes in hex. */
289 #define N_BYTES_TO_STR_STRINGS  6
290 gchar *
291 bytes_to_str(const guint8 *bd, int bd_len) {
292   static gchar  str[N_BYTES_TO_STR_STRINGS][MAX_BYTE_STR_LEN+3+1];
293   static int    cur_idx;
294   gchar        *cur;
295   gchar        *p;
296   int           len;
297   static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
298                                 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
299
300   cur_idx++;
301   if (cur_idx >= N_BYTES_TO_STR_STRINGS)
302     cur_idx = 0;
303   cur = &str[cur_idx][0];
304   p = cur;
305   len = MAX_BYTE_STR_LEN;
306   while (bd_len > 0 && len > 0) {
307     *p++ = hex[(*bd) >> 4];
308     *p++ = hex[(*bd) & 0xF];
309     len -= 2;
310     bd++;
311     bd_len--;
312   }
313   if (bd_len != 0) {
314     /* Note that we're not showing the full string.  */
315     *p++ = '.';
316     *p++ = '.';
317     *p++ = '.';
318   }
319   *p = '\0';
320   return cur;
321 }
322
323 static const char *mon_names[12] = {
324         "Jan",
325         "Feb",
326         "Mar",
327         "Apr",
328         "May",
329         "Jun",
330         "Jul",
331         "Aug",
332         "Sep",
333         "Oct",
334         "Nov",
335         "Dec"
336 };
337
338 gchar *
339 abs_time_to_str(struct timeval *abs_time)
340 {
341         struct tm *tmp;
342         static gchar *cur;
343         static char str[3][3+1+2+2+4+1+2+1+2+1+2+1+4+1 + 5 /* extra */];
344
345         if (cur == &str[0][0]) {
346                 cur = &str[1][0];
347         } else if (cur == &str[1][0]) {
348                 cur = &str[2][0];
349         } else {
350                 cur = &str[0][0];
351         }
352
353         tmp = localtime(&abs_time->tv_sec);
354         sprintf(cur, "%s %2d, %d %02d:%02d:%02d.%04ld",
355             mon_names[tmp->tm_mon],
356             tmp->tm_mday,
357             tmp->tm_year + 1900,
358             tmp->tm_hour,
359             tmp->tm_min,
360             tmp->tm_sec,
361             (long)abs_time->tv_usec/100);
362
363         return cur;
364 }
365
366 gchar *
367 rel_time_to_str(struct timeval *rel_time)
368 {
369         static gchar *cur;
370         static char str[3][10+1+6+1];
371
372         if (cur == &str[0][0]) {
373                 cur = &str[1][0];
374         } else if (cur == &str[1][0]) {
375                 cur = &str[2][0];
376         } else {
377                 cur = &str[0][0];
378         }
379
380         sprintf(cur, "%ld.%06ld", (long)rel_time->tv_sec,
381                 (long)rel_time->tv_usec);
382
383         return cur;
384 }
385
386 /*
387  * Given a pointer into a data buffer, and to the end of the buffer,
388  * find the end of the (putative) line at that position in the data
389  * buffer.
390  * Return a pointer to the EOL character(s) in "*eol".
391  */
392 const u_char *
393 find_line_end(const u_char *data, const u_char *dataend, const u_char **eol)
394 {
395   const u_char *lineend;
396
397   lineend = memchr(data, '\n', dataend - data);
398   if (lineend == NULL) {
399     /*
400      * No LF - line is probably continued in next TCP segment.
401      */
402     lineend = dataend;
403     *eol = dataend;
404   } else {
405     /*
406      * Is the LF at the beginning of the line?
407      */
408     if (lineend > data) {
409       /*
410        * No - is it preceded by a carriage return?
411        * (Perhaps it's supposed to be, but that's not guaranteed....)
412        */
413       if (*(lineend - 1) == '\r') {
414         /*
415          * Yes.  The EOL starts with the CR.
416          */
417         *eol = lineend - 1;
418       } else {
419         /*
420          * No.  The EOL starts with the LF.
421          */
422         *eol = lineend;
423
424         /*
425          * I seem to remember that we once saw lines ending with LF-CR
426          * in an HTTP request or response, so check if it's *followed*
427          * by a carriage return.
428          */
429         if (lineend < (dataend - 1) && *(lineend + 1) == '\r') {
430           /*
431            * It's <non-LF><LF><CR>; say it ends with the CR.
432            */
433           lineend++;
434         }
435       }
436     }
437
438     /*
439      * Point to the character after the last character.
440      */
441     lineend++;
442   }
443   return lineend;
444 }
445
446 #define MAX_COLUMNS_LINE_DETAIL 62
447
448 /*
449  * Get the length of the next token in a line, and the beginning of the
450  * next token after that (if any).
451  * Return 0 if there is no next token.
452  */
453 int
454 get_token_len(const u_char *linep, const u_char *lineend,
455               const u_char **next_token)
456 {
457   const u_char *tokenp;
458   int token_len;
459
460   tokenp = linep;
461   
462   /*
463    * Search for a blank, a CR or an LF, or the end of the buffer.
464    */
465   while (linep < lineend && *linep != ' ' && *linep != '\r' && *linep != '\n')
466       linep++;
467   token_len = linep - tokenp;
468
469   /*
470    * Skip trailing blanks.
471    */
472   while (linep < lineend && *linep == ' ')
473     linep++;
474
475   *next_token = linep;
476
477   return token_len;
478 }
479
480 /*
481  * Given a string, generate a string from it that shows non-printable
482  * characters as C-style escapes, and return a pointer to it.
483  */
484 gchar *
485 format_text(const u_char *string, int len)
486 {
487   static gchar fmtbuf[MAX_COLUMNS_LINE_DETAIL + 3 + 4 + 1];
488   gchar *fmtbufp;
489   int column;
490   const u_char *stringend = string + len;
491   u_char c;
492   int i;
493
494   column = 0;
495   fmtbufp = &fmtbuf[0];
496   while (string < stringend) {
497     if (column >= MAX_COLUMNS_LINE_DETAIL) {
498       /*
499        * Put "..." and quit.
500        */
501       strcpy(fmtbufp, " ...");
502       fmtbufp += 4;
503       break;
504     }
505     c = *string++;
506     if (isprint(c)) {
507       *fmtbufp++ = c;
508       column++;
509     } else {
510       *fmtbufp++ =  '\\';
511       column++;
512       switch (c) {
513
514       case '\\':
515         *fmtbufp++ = '\\';
516         column++;
517         break;
518
519       case '\a':
520         *fmtbufp++ = 'a';
521         column++;
522         break;
523
524       case '\b':
525         *fmtbufp++ = 'b';
526         column++;
527         break;
528
529       case '\f':
530         *fmtbufp++ = 'f';
531         column++;
532         break;
533
534       case '\n':
535         *fmtbufp++ = 'n';
536         column++;
537         break;
538
539       case '\r':
540         *fmtbufp++ = 'r';
541         column++;
542         break;
543
544       case '\t':
545         *fmtbufp++ = 't';
546         column++;
547         break;
548
549       case '\v':
550         *fmtbufp++ = 'v';
551         column++;
552         break;
553
554       default:
555         i = (c>>6)&03;
556         *fmtbufp++ = i + '0';
557         column++;
558         i = (c>>3)&07;
559         *fmtbufp++ = i + '0';
560         column++;
561         i = (c>>0)&07;
562         *fmtbufp++ = i + '0';
563         column++;
564         break;
565       }
566     }
567   }
568   *fmtbufp = '\0';
569   return fmtbuf;
570 }
571
572
573 /* Tries to match val against each element in the value_string array vs.
574    Returns the associated string ptr on a match.
575    Formats val with fmt, and returns the resulting string, on failure. */
576 gchar*
577 val_to_str(guint32 val, const value_string *vs, const char *fmt) {
578   gchar *ret;
579   static gchar  str[3][64];
580   static gchar *cur;
581
582   ret = match_strval(val, vs);
583   if (ret != NULL)
584     return ret;
585   if (cur == &str[0][0]) {
586     cur = &str[1][0];
587   } else if (cur == &str[1][0]) {  
588     cur = &str[2][0];
589   } else {  
590     cur = &str[0][0];
591   }
592   snprintf(cur, 64, fmt, val);
593   return cur;
594 }
595
596 /* Tries to match val against each element in the value_string array vs.
597    Returns the associated string ptr on a match, or NULL on failure. */
598 gchar*
599 match_strval(guint32 val, const value_string *vs) {
600   gint i = 0;
601   
602   while (vs[i].strptr) {
603     if (vs[i].value == val)
604       return(vs[i].strptr);
605     i++;
606   }
607
608   return(NULL);
609 }
610
611 /* Generate, into "buf", a string showing the bits of a bitfield.
612    Return a pointer to the character after that string. */
613 char *
614 decode_bitfield_value(char *buf, guint32 val, guint32 mask, int width)
615 {
616   int i;
617   guint32 bit;
618   char *p;
619
620   i = 0;
621   p = buf;
622   bit = 1 << (width - 1);
623   for (;;) {
624     if (mask & bit) {
625       /* This bit is part of the field.  Show its value. */
626       if (val & bit)
627         *p++ = '1';
628       else
629         *p++ = '0';
630     } else {
631       /* This bit is not part of the field. */
632       *p++ = '.';
633     }
634     bit >>= 1;
635     i++;
636     if (i >= width)
637       break;
638     if (i % 4 == 0)
639       *p++ = ' ';
640   }
641   strcpy(p, " = ");
642   p += 3;
643   return p;
644 }
645
646 /* Generate a string describing a Boolean bitfield (a one-bit field that
647    says something is either true of false). */
648 const char *
649 decode_boolean_bitfield(guint32 val, guint32 mask, int width,
650     const char *truedesc, const char *falsedesc)
651 {
652   static char buf[1025];
653   char *p;
654
655   p = decode_bitfield_value(buf, val, mask, width);
656   if (val & mask)
657     strcpy(p, truedesc);
658   else
659     strcpy(p, falsedesc);
660   return buf;
661 }
662
663 /* Generate a string describing an enumerated bitfield (an N-bit field
664    with various specific values having particular names). */
665 const char *
666 decode_enumerated_bitfield(guint32 val, guint32 mask, int width,
667     const value_string *tab, const char *fmt)
668 {
669   static char buf[1025];
670   char *p;
671
672   p = decode_bitfield_value(buf, val, mask, width);
673   sprintf(p, fmt, val_to_str(val & mask, tab, "Unknown"));
674   return buf;
675 }
676
677 /* Generate a string describing a numeric bitfield (an N-bit field whose
678    value is just a number). */
679 const char *
680 decode_numeric_bitfield(guint32 val, guint32 mask, int width,
681     const char *fmt)
682 {
683   static char buf[1025];
684   char *p;
685   int shift = 0;
686
687   /* Compute the number of bits we have to shift the bitfield right
688      to extract its value. */
689   while ((mask & (1<<shift)) == 0)
690     shift++;
691
692   p = decode_bitfield_value(buf, val, mask, width);
693   sprintf(p, fmt, (val & mask) >> shift);
694   return buf;
695 }
696
697 /* Checks to see if a particular packet information element is needed for
698    the packet list */
699 gint
700 check_col(frame_data *fd, gint el) {
701   int i;
702
703   if (fd->cinfo) {
704     for (i = 0; i < fd->cinfo->num_cols; i++) {
705       if (fd->cinfo->fmt_matx[i][el])
706         return TRUE;
707     }
708   }
709   return FALSE;
710 }
711
712 /* Adds a vararg list to a packet info string. */
713 void
714 col_add_fstr(frame_data *fd, gint el, gchar *format, ...) {
715   va_list ap;
716   int     i;
717   size_t  max_len;
718   
719   va_start(ap, format);
720   for (i = 0; i < fd->cinfo->num_cols; i++) {
721     if (fd->cinfo->fmt_matx[i][el]) {
722       if (el == COL_INFO)
723         max_len = COL_MAX_INFO_LEN;
724       else
725         max_len = COL_MAX_LEN;
726       vsnprintf(fd->cinfo->col_data[i], max_len, format, ap);
727     }
728   }
729 }
730
731 void
732 col_add_str(frame_data *fd, gint el, const gchar* str) {
733   int    i;
734   size_t max_len;
735
736   for (i = 0; i < fd->cinfo->num_cols; i++) {
737     if (fd->cinfo->fmt_matx[i][el]) {
738       if (el == COL_INFO)
739         max_len = COL_MAX_INFO_LEN;
740       else
741         max_len = COL_MAX_LEN;
742       strncpy(fd->cinfo->col_data[i], str, max_len);
743       fd->cinfo->col_data[i][max_len - 1] = 0;
744     }
745   }
746 }
747
748 /* Appends a vararg list to a packet info string. */
749 void
750 col_append_fstr(frame_data *fd, gint el, gchar *format, ...) {
751   va_list ap;
752   int     i;
753   size_t  len, max_len;
754   
755   va_start(ap, format);
756   for (i = 0; i < fd->cinfo->num_cols; i++) {
757     if (fd->cinfo->fmt_matx[i][el]) {
758       len = strlen(fd->cinfo->col_data[i]);
759       if (el == COL_INFO)
760         max_len = COL_MAX_INFO_LEN;
761       else
762         max_len = COL_MAX_LEN;
763       vsnprintf(&fd->cinfo->col_data[i][len], max_len - len, format, ap);
764     }
765   }
766 }
767
768 void
769 col_append_str(frame_data *fd, gint el, gchar* str) {
770   int    i;
771   size_t len, max_len;
772
773   for (i = 0; i < fd->cinfo->num_cols; i++) {
774     if (fd->cinfo->fmt_matx[i][el]) {
775       len = strlen(fd->cinfo->col_data[i]);
776       if (el == COL_INFO)
777         max_len = COL_MAX_LEN;
778       else
779         max_len = COL_MAX_INFO_LEN;
780       strncat(fd->cinfo->col_data[i], str, max_len - len);
781       fd->cinfo->col_data[i][max_len - 1] = 0;
782     }
783   }
784 }
785
786 /* To do: Add check_col checks to the col_add* routines */
787
788 static void
789 col_set_abs_time(frame_data *fd, int col)
790 {
791   struct tm *tmp;
792   time_t then;
793
794   then = fd->abs_secs;
795   tmp = localtime(&then);
796   snprintf(fd->cinfo->col_data[col], COL_MAX_LEN, "%02d:%02d:%02d.%04ld",
797     tmp->tm_hour,
798     tmp->tm_min,
799     tmp->tm_sec,
800     (long)fd->abs_usecs/100);
801 }
802
803 static void
804 col_set_rel_time(frame_data *fd, int col)
805 {
806   snprintf(fd->cinfo->col_data[col], COL_MAX_LEN, "%d.%06d", fd->rel_secs,
807     fd->rel_usecs);
808 }
809
810 static void
811 col_set_delta_time(frame_data *fd, int col)
812 {
813   snprintf(fd->cinfo->col_data[col], COL_MAX_LEN, "%d.%06d", fd->del_secs,
814     fd->del_usecs);
815 }
816
817 /* Add "command-line-specified" time.
818    XXX - this is called from "file.c" when the user changes the time
819    format they want for "command-line-specified" time; it's a bit ugly
820    that we have to export it, but if we go to a CList-like widget that
821    invokes callbacks to get the text for the columns rather than
822    requiring us to stuff the text into the widget from outside, we
823    might be able to clean this up. */
824 void
825 col_set_cls_time(frame_data *fd, int col)
826 {
827   switch (timestamp_type) {
828     case ABSOLUTE:
829       col_set_abs_time(fd, col);
830       break;
831
832     case RELATIVE:
833       col_set_rel_time(fd, col);
834       break;
835
836     case DELTA:
837       col_set_delta_time(fd, col);
838       break;
839   }
840 }
841
842 static void
843 col_set_addr(frame_data *fd, int col, address *addr, gboolean is_res)
844 {
845   u_int ipv4_addr;
846   struct e_in6_addr ipv6_addr;
847   struct atalk_ddp_addr ddp_addr;
848   struct sna_fid_type_4_addr sna_fid_type_4_addr;
849
850   switch (addr->type) {
851
852   case AT_ETHER:
853     if (is_res)
854       strncpy(fd->cinfo->col_data[col], get_ether_name(addr->data), COL_MAX_LEN);
855     else
856       strncpy(fd->cinfo->col_data[col], ether_to_str(addr->data), COL_MAX_LEN);
857     break;
858
859   case AT_IPv4:
860     memcpy(&ipv4_addr, addr->data, sizeof ipv4_addr);
861     if (is_res)
862       strncpy(fd->cinfo->col_data[col], get_hostname(ipv4_addr), COL_MAX_LEN);
863     else
864       strncpy(fd->cinfo->col_data[col], ip_to_str(addr->data), COL_MAX_LEN);
865     break;
866
867   case AT_IPv6:
868     memcpy(&ipv6_addr.s6_addr, addr->data, sizeof ipv6_addr.s6_addr);
869     if (is_res)
870       strncpy(fd->cinfo->col_data[col], get_hostname6(&ipv6_addr), COL_MAX_LEN);
871     else
872       strncpy(fd->cinfo->col_data[col], ip6_to_str(&ipv6_addr), COL_MAX_LEN);
873     break;
874
875   case AT_IPX:
876     strncpy(fd->cinfo->col_data[col],
877       ipx_addr_to_str(pntohl(&addr->data[0]), &addr->data[4]), COL_MAX_LEN);
878     break;
879
880   case AT_SNA:
881     switch (addr->len) {
882
883     case 1:
884       snprintf(fd->cinfo->col_data[col], COL_MAX_LEN, "%04X", addr->data[0]);
885       break;
886
887     case 2:
888       snprintf(fd->cinfo->col_data[col], COL_MAX_LEN, "%04X",
889         pntohs(&addr->data[0]));
890       break;
891
892     case SNA_FID_TYPE_4_ADDR_LEN:
893       memcpy(&sna_fid_type_4_addr, addr->data, SNA_FID_TYPE_4_ADDR_LEN);
894       strncpy(fd->cinfo->col_data[col],
895         sna_fid_type_4_addr_to_str(&sna_fid_type_4_addr), COL_MAX_LEN);
896       break;
897     }
898     break;
899
900   case AT_ATALK:
901     memcpy(&ddp_addr, addr->data, sizeof ddp_addr);
902     strncpy(fd->cinfo->col_data[col], atalk_addr_to_str(&ddp_addr),
903       COL_MAX_LEN);
904     break;
905
906   case AT_VINES:
907     strncpy(fd->cinfo->col_data[col], vines_addr_to_str(&addr->data[0]),
908       COL_MAX_LEN);
909     break;
910
911   default:
912     break;
913   }
914   fd->cinfo->col_data[col][COL_MAX_LEN - 1] = '\0';
915 }
916
917 static void
918 col_set_port(frame_data *fd, int col, port_type ptype, guint32 port,
919                 gboolean is_res)
920 {
921   switch (ptype) {
922
923   case PT_TCP:
924     if (is_res)
925       strncpy(fd->cinfo->col_data[col], get_tcp_port(port), COL_MAX_LEN);
926     else
927       snprintf(fd->cinfo->col_data[col], COL_MAX_LEN, "%u", port);
928     break;
929
930   case PT_UDP:
931     if (is_res)
932       strncpy(fd->cinfo->col_data[col], get_udp_port(port), COL_MAX_LEN);
933     else
934       snprintf(fd->cinfo->col_data[col], COL_MAX_LEN, "%u", port);
935     break;
936
937   default:
938     break;
939   }
940   fd->cinfo->col_data[col][COL_MAX_LEN - 1] = '\0';
941 }
942
943 void
944 fill_in_columns(frame_data *fd)
945 {
946   int i;
947
948   for (i = 0; i < fd->cinfo->num_cols; i++) {
949     switch (fd->cinfo->col_fmt[i]) {
950
951     case COL_NUMBER:
952       snprintf(fd->cinfo->col_data[i], COL_MAX_LEN, "%u", fd->num);
953       break;
954
955     case COL_CLS_TIME:
956       col_set_cls_time(fd, i);
957       break;
958
959     case COL_ABS_TIME:
960       col_set_abs_time(fd, i);
961       break;
962
963     case COL_REL_TIME:
964       col_set_rel_time(fd, i);
965       break;
966
967     case COL_DELTA_TIME:
968       col_set_delta_time(fd, i);
969       break;
970
971     case COL_DEF_SRC:
972     case COL_RES_SRC:   /* COL_DEF_SRC is currently just like COL_RES_SRC */
973       col_set_addr(fd, i, &pi.src, TRUE);
974       break;
975
976     case COL_UNRES_SRC:
977       col_set_addr(fd, i, &pi.src, FALSE);
978       break;
979
980     case COL_DEF_DL_SRC:
981     case COL_RES_DL_SRC:
982       col_set_addr(fd, i, &pi.dl_src, TRUE);
983       break;
984
985     case COL_UNRES_DL_SRC:
986       col_set_addr(fd, i, &pi.dl_src, FALSE);
987       break;
988
989     case COL_DEF_NET_SRC:
990     case COL_RES_NET_SRC:
991       col_set_addr(fd, i, &pi.net_src, TRUE);
992       break;
993
994     case COL_UNRES_NET_SRC:
995       col_set_addr(fd, i, &pi.net_src, FALSE);
996       break;
997
998     case COL_DEF_DST:
999     case COL_RES_DST:   /* COL_DEF_DST is currently just like COL_RES_DST */
1000       col_set_addr(fd, i, &pi.dst, TRUE);
1001       break;
1002
1003     case COL_UNRES_DST:
1004       col_set_addr(fd, i, &pi.dst, FALSE);
1005       break;
1006
1007     case COL_DEF_DL_DST:
1008     case COL_RES_DL_DST:
1009       col_set_addr(fd, i, &pi.dl_dst, TRUE);
1010       break;
1011
1012     case COL_UNRES_DL_DST:
1013       col_set_addr(fd, i, &pi.dl_dst, FALSE);
1014       break;
1015
1016     case COL_DEF_NET_DST:
1017     case COL_RES_NET_DST:
1018       col_set_addr(fd, i, &pi.net_dst, TRUE);
1019       break;
1020
1021     case COL_UNRES_NET_DST:
1022       col_set_addr(fd, i, &pi.net_dst, FALSE);
1023       break;
1024
1025     case COL_DEF_SRC_PORT:
1026     case COL_RES_SRC_PORT:      /* COL_DEF_SRC_PORT is currently just like COL_RES_SRC_PORT */
1027       col_set_port(fd, i, pi.ptype, pi.srcport, TRUE);
1028       break;
1029
1030     case COL_UNRES_SRC_PORT:
1031       col_set_port(fd, i, pi.ptype, pi.srcport, FALSE);
1032       break;
1033
1034     case COL_DEF_DST_PORT:
1035     case COL_RES_DST_PORT:      /* COL_DEF_DST_PORT is currently just like COL_RES_DST_PORT */
1036       col_set_port(fd, i, pi.ptype, pi.destport, TRUE);
1037       break;
1038
1039     case COL_UNRES_DST_PORT:
1040       col_set_port(fd, i, pi.ptype, pi.destport, FALSE);
1041       break;
1042
1043     case COL_PROTOCOL:  /* currently done by dissectors */
1044     case COL_INFO:      /* currently done by dissectors */
1045       break;
1046
1047     case COL_PACKET_LENGTH:
1048       snprintf(fd->cinfo->col_data[i], COL_MAX_LEN, "%d", fd->pkt_len);
1049       break;
1050
1051     case NUM_COL_FMTS:  /* keep compiler happy - shouldn't get here */
1052       break;
1053     }
1054   }
1055 }
1056         
1057 void blank_packetinfo(void)
1058 {
1059   pi.dl_src.type = AT_NONE;
1060   pi.dl_dst.type = AT_NONE;
1061   pi.net_src.type = AT_NONE;
1062   pi.net_dst.type = AT_NONE;
1063   pi.src.type = AT_NONE;
1064   pi.dst.type = AT_NONE;
1065   pi.ipproto  = 0;
1066   pi.ptype = PT_NONE;
1067   pi.srcport  = 0;
1068   pi.destport = 0;
1069   pi.current_proto = "";
1070 }
1071
1072 /* Do all one-time initialization. */
1073 void
1074 dissect_init(void)
1075 {
1076         except_init();
1077         tvbuff_init();
1078         proto_init();
1079         dfilter_init();
1080 #ifdef HAVE_PLUGINS
1081         init_plugins();
1082 #endif
1083 }
1084
1085 void
1086 dissect_cleanup(void)
1087 {
1088         dfilter_cleanup();
1089         proto_cleanup();
1090         tvbuff_cleanup();
1091         except_deinit();
1092 }
1093
1094 /* Allow protocols to register "init" routines, which are called before
1095    we make a pass through a capture file and dissect all its packets
1096    (e.g., when we read in a new capture file, or run a "filter packets"
1097    or "colorize packets" pass over the current capture file). */
1098 static GSList *init_routines;
1099
1100 void
1101 register_init_routine(void (*func)(void))
1102 {
1103         init_routines = g_slist_append(init_routines, func);
1104 }
1105
1106 /* Call all the registered "init" routines. */
1107 static void
1108 call_init_routine(gpointer routine, gpointer dummy)
1109 {
1110         void (*func)(void) = routine;
1111
1112         (*func)();
1113 }
1114
1115 void
1116 init_all_protocols(void)
1117 {
1118         g_slist_foreach(init_routines, &call_init_routine, NULL);
1119 }
1120
1121 /* this routine checks the frame type from the cf structure */
1122 void
1123 dissect_packet(const u_char *pd, frame_data *fd, proto_tree *tree)
1124 {
1125         proto_tree *fh_tree;
1126         proto_item *ti;
1127         struct timeval tv;
1128         tvbuff_t *tvb;
1129
1130         /* Put in frame header information. */
1131         if (tree) {
1132           ti = proto_tree_add_protocol_format(tree, proto_frame, NullTVB, 0, fd->cap_len,
1133             "Frame %u (%u on wire, %u captured)", fd->num,
1134             fd->pkt_len, fd->cap_len);
1135
1136           fh_tree = proto_item_add_subtree(ti, ett_frame);
1137
1138           tv.tv_sec = fd->abs_secs;
1139           tv.tv_usec = fd->abs_usecs;
1140
1141           proto_tree_add_item(fh_tree, hf_frame_arrival_time, NullTVB,
1142                 0, 0, &tv);
1143
1144           tv.tv_sec = fd->del_secs;
1145           tv.tv_usec = fd->del_usecs;
1146
1147           proto_tree_add_item(fh_tree, hf_frame_time_delta, NullTVB,
1148                 0, 0, &tv);
1149
1150           proto_tree_add_item(fh_tree, hf_frame_number, NullTVB,
1151                 0, 0, fd->num);
1152
1153           proto_tree_add_uint_format(fh_tree, hf_frame_packet_len, NullTVB,
1154                 0, 0, fd->pkt_len, "Packet Length: %d byte%s", fd->pkt_len,
1155                 plurality(fd->pkt_len, "", "s"));
1156                 
1157           proto_tree_add_uint_format(fh_tree, hf_frame_capture_len, NullTVB,
1158                 0, 0, fd->cap_len, "Capture Length: %d byte%s", fd->cap_len,
1159                 plurality(fd->cap_len, "", "s"));
1160         }
1161
1162         blank_packetinfo();
1163
1164         /* Set the initial payload to the packet length, and the initial
1165            captured payload to the capture length (other protocols may
1166            reduce them if their headers say they're less). */
1167         pi.len = fd->pkt_len;
1168         pi.captured_len = fd->cap_len;
1169
1170         tvb = tvb_new_real_data(pd, fd->cap_len, -1);
1171         pi.fd = fd;
1172         pi.compat_top_tvb = tvb;
1173
1174         TRY {
1175                 switch (fd->lnk_t) {
1176                         case WTAP_ENCAP_ETHERNET :
1177                                 /*dissect_eth(tvb, &pi, tree);*/
1178                                 dissect_eth(pd, 0, fd, tree);
1179                                 break;
1180                         case WTAP_ENCAP_FDDI :
1181                                 dissect_fddi(tvb, &pi, tree, FALSE);
1182                                 break;
1183                         case WTAP_ENCAP_FDDI_BITSWAPPED :
1184                                 dissect_fddi(tvb, &pi, tree, TRUE);
1185                                 break;
1186                         case WTAP_ENCAP_TR :
1187                                 dissect_tr(tvb, &pi, tree);
1188                                 break;
1189                         case WTAP_ENCAP_NULL :
1190                                 dissect_null(pd, fd, tree);
1191                                 break;
1192                         case WTAP_ENCAP_PPP :
1193                                 dissect_ppp(pd, 0, fd, tree);
1194                                 break;
1195                         case WTAP_ENCAP_LAPB :
1196                                 dissect_lapb(pd, fd, tree);
1197                                 break;
1198                         case WTAP_ENCAP_RAW_IP :
1199                                 dissect_raw(pd, fd, tree);
1200                                 break;
1201                         case WTAP_ENCAP_LINUX_ATM_CLIP :
1202                                 dissect_clip(pd, fd, tree);
1203                                 break;
1204                         case WTAP_ENCAP_ATM_SNIFFER :
1205                                 dissect_atm(pd, fd, tree);
1206                                 break;
1207                         case WTAP_ENCAP_ASCEND :
1208                                 dissect_ascend(pd, fd, tree);
1209                                 break;
1210                         case WTAP_ENCAP_LAPD :
1211                                 dissect_lapd(pd, fd, tree);
1212                                 break;
1213                         case WTAP_ENCAP_V120 :
1214                                 dissect_v120(pd, fd, tree);
1215                                 break;
1216                 }
1217         }
1218         CATCH(BoundsError) {
1219                 proto_tree_add_protocol_format(tree, proto_short, NullTVB, 0, 0,
1220                                 "[Short Frame: %s]", pi.current_proto );
1221         }
1222         CATCH(ReportedBoundsError) {
1223                 proto_tree_add_protocol_format(tree, proto_malformed, NullTVB, 0, 0,
1224                                 "[Malformed Frame: %s]", pi.current_proto );
1225         }
1226         ENDTRY;
1227
1228         /* Free all tvb's created from this tvb, unless dissector
1229          * wanted to store the pointer (in which case, the dissector
1230          * would have incremented the usage count on that tvbuff_t*) */
1231         tvb_free_chain(tvb);
1232
1233         fd->flags.visited = 1;
1234 }
1235
1236 gint p_compare(gconstpointer a, gconstpointer b)
1237 {
1238
1239   if (((frame_proto_data *)a) -> proto > ((frame_proto_data *)b) -> proto)
1240     return 1;
1241   else if (((frame_proto_data *)a) -> proto == ((frame_proto_data *)b) -> proto)
1242     return 0;
1243   else
1244     return -1;
1245
1246 }
1247
1248 void
1249 p_add_proto_data(frame_data *fd, int proto, void *proto_data)
1250 {
1251   frame_proto_data *p1 = g_mem_chunk_alloc(frame_proto_data_area);
1252  
1253   g_assert(p1 != NULL);
1254
1255   p1 -> proto = proto;
1256   p1 -> proto_data = proto_data;
1257
1258   /* Add it to the GSLIST */
1259
1260   fd -> pfd = g_slist_insert_sorted(fd -> pfd,
1261                                     (gpointer *)p1,
1262                                     p_compare);
1263
1264 }
1265
1266 void *
1267 p_get_proto_data(frame_data *fd, int proto)
1268 {
1269   frame_proto_data temp;
1270   GSList *item;
1271
1272   temp.proto = proto;
1273   temp.proto_data = NULL;
1274
1275   item = g_slist_find_custom(fd->pfd, (gpointer *)&temp, p_compare);
1276
1277   if (item) return (void *)item->data;
1278
1279   return NULL;
1280
1281 }
1282
1283 void
1284 p_rem_proto_data(frame_data *fd, int proto)
1285 {
1286
1287
1288 }
1289
1290 void
1291 proto_register_frame(void)
1292 {
1293         static hf_register_info hf[] = {
1294                 { &hf_frame_arrival_time,
1295                 { "Arrival Time",               "frame.time", FT_ABSOLUTE_TIME, BASE_NONE, NULL, 0x0,
1296                         ""}},
1297
1298                 { &hf_frame_time_delta,
1299                 { "Time delta from previous packet",    "frame.time_delta", FT_RELATIVE_TIME, BASE_NONE, NULL,
1300                         0x0,
1301                         "" }},
1302
1303                 { &hf_frame_number,
1304                 { "Frame Number",               "frame.number", FT_UINT32, BASE_DEC, NULL, 0x0,
1305                         "" }},
1306
1307                 { &hf_frame_packet_len,
1308                 { "Total Frame Length",         "frame.pkt_len", FT_UINT32, BASE_DEC, NULL, 0x0,
1309                         "" }},
1310
1311                 { &hf_frame_capture_len,
1312                 { "Capture Frame Length",       "frame.cap_len", FT_UINT32, BASE_DEC, NULL, 0x0,
1313                         "" }},
1314         };
1315         static gint *ett[] = {
1316                 &ett_frame,
1317         };
1318
1319         proto_frame = proto_register_protocol("Frame", "frame");
1320         proto_register_field_array(proto_frame, hf, array_length(hf));
1321         proto_register_subtree_array(ett, array_length(ett));
1322
1323         proto_short = proto_register_protocol("Short Frame", "short");
1324         proto_malformed = proto_register_protocol("Malformed Frame", "malformed");
1325         register_init_routine(&packet_init_protocol);
1326
1327 }
1328
1329 /*********************** code added for sub-dissector lookup *********************/
1330
1331 static GHashTable *dissector_tables = NULL;
1332
1333 /* Finds a dissector table by field name. */
1334 static dissector_table_t
1335 find_dissector_table(const char *name)
1336 {
1337         g_assert(dissector_tables);
1338         return g_hash_table_lookup( dissector_tables, name );
1339 }
1340
1341 /* lookup a dissector based upon pattern. */
1342 dissector_t
1343 dissector_lookup( dissector_table_t table, guint32 pattern)
1344 {
1345         return g_hash_table_lookup( table, GUINT_TO_POINTER( pattern));
1346 }
1347
1348
1349 /* add an entry, lookup the dissector table for the specified field name,  */
1350 /* if a valid table found, add the subdissector */
1351 void
1352 dissector_add(const char *name, guint32 pattern, dissector_t dissector)
1353 {
1354         dissector_table_t sub_dissectors = find_dissector_table( name);
1355
1356 /* sanity check */
1357         g_assert( sub_dissectors);
1358
1359 /* do the table insertion */
1360         g_hash_table_insert( sub_dissectors, GUINT_TO_POINTER( pattern),
1361          (gpointer)dissector);
1362 }
1363
1364 /* delete the entry for this dissector at this pattern */
1365
1366 /* NOTE: this doesn't use the dissector call variable. It is included to */
1367 /*      be consistant with the dissector_add and more importantly to be used */
1368 /*      if the technique of adding a temporary dissector is implemented.  */
1369 /*      If temporary dissectors are deleted, then the original dissector must */
1370 /*      be available. */
1371 void
1372 dissector_delete(const char *name, guint32 pattern, dissector_t dissector)
1373 {
1374         dissector_table_t sub_dissectors = find_dissector_table( name);
1375
1376 /* sanity check */
1377         g_assert( sub_dissectors);
1378
1379 /* remove the hash table entry */
1380         g_hash_table_remove( sub_dissectors, GUINT_TO_POINTER( pattern));
1381 }
1382
1383 /* Look for a given port in a given dissector table and, if found, call
1384    the dissector with the arguments supplied, and return TRUE, otherwise
1385    return FALSE. */
1386 gboolean
1387 dissector_try_port(dissector_table_t sub_dissectors, guint32 port,
1388     const u_char *pd, int offset, frame_data *fd, proto_tree *tree)
1389 {
1390         dissector_t subdissector;
1391
1392         subdissector = dissector_lookup(sub_dissectors, port);
1393         if (subdissector != NULL) {
1394                 pi.match_port = port;
1395                 (subdissector)(pd, offset, fd, tree);
1396                 return TRUE;
1397         } else
1398                 return FALSE;
1399 }
1400
1401 dissector_table_t
1402 register_dissector_table(const char *name)
1403 {
1404         dissector_table_t       sub_dissectors;
1405
1406         /* Create our hash-of-hashes if it doesn't already exist */
1407         if (!dissector_tables) {
1408                 dissector_tables = g_hash_table_new( g_str_hash, g_str_equal );
1409                 g_assert(dissector_tables);
1410         }
1411
1412         /* Make sure the registration is unique */
1413         g_assert(!g_hash_table_lookup( dissector_tables, name ));
1414
1415         /* Create and register the dissector table for this name; returns */
1416         /* a pointer to the dissector table. */
1417         sub_dissectors = g_hash_table_new( g_direct_hash, g_direct_equal );
1418         g_hash_table_insert( dissector_tables, (gpointer)name, (gpointer) sub_dissectors );
1419         return sub_dissectors;
1420 }
1421
1422 static GHashTable *heur_dissector_lists = NULL;
1423
1424 /* Finds a heuristic dissector table by field name. */
1425 static heur_dissector_list_t *
1426 find_heur_dissector_list(const char *name)
1427 {
1428         g_assert(heur_dissector_lists != NULL);
1429         return g_hash_table_lookup(heur_dissector_lists, name);
1430 }
1431
1432 void
1433 heur_dissector_add(const char *name, heur_dissector_t dissector)
1434 {
1435         heur_dissector_list_t *sub_dissectors = find_heur_dissector_list(name);
1436
1437         /* sanity check */
1438         g_assert(sub_dissectors != NULL);
1439
1440         /* do the table insertion */
1441         *sub_dissectors = g_slist_append(*sub_dissectors, (gpointer)dissector);
1442 }
1443
1444 gboolean
1445 dissector_try_heuristic(heur_dissector_list_t sub_dissectors,
1446     const u_char *pd, int offset, frame_data *fd, proto_tree *tree)
1447 {
1448         heur_dissector_t subdissector;
1449         GSList *entry;
1450
1451         for (entry = sub_dissectors; entry != NULL; entry = g_slist_next(entry)) {
1452                 subdissector = (heur_dissector_t)entry->data;
1453                 if ((subdissector)(pd, offset, fd, tree))
1454                         return TRUE;
1455         }
1456         return FALSE;
1457 }
1458
1459 void
1460 register_heur_dissector_list(const char *name, heur_dissector_list_t *sub_dissectors)
1461 {
1462         /* Create our hash-of-hashes if it doesn't already exist */
1463         if (heur_dissector_lists == NULL) {
1464                 heur_dissector_lists = g_hash_table_new(g_str_hash, g_str_equal);
1465                 g_assert(heur_dissector_lists != NULL);
1466         }
1467
1468         /* Make sure the registration is unique */
1469         g_assert(g_hash_table_lookup(heur_dissector_lists, name) == NULL);
1470
1471         *sub_dissectors = NULL; /* initially empty */
1472         g_hash_table_insert(heur_dissector_lists, (gpointer)name,
1473             (gpointer) sub_dissectors);
1474 }