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