Put the IGMP type field value into the PIM tree, as is done for other
[obnox/wireshark/wip.git] / text2pcap.c
1 /**-*-C-*-**********************************************************************
2  *
3  * text2pcap.c
4  *
5  * Utility to convert an ASCII hexdump into a libpcap-format capture file
6  *
7  * (c) Copyright 2001 Ashok Narayanan <ashokn@cisco.com>
8  *
9  * $Id: text2pcap.c,v 1.2 2001/05/21 03:17:14 guy Exp $
10  * 
11  * Ethereal - Network traffic analyzer
12  * By Gerald Combs <gerald@ethereal.com>
13  * Copyright 1998 Gerald Combs
14  * 
15  * 
16  * 
17  * This program is free software; you can redistribute it and/or
18  * modify it under the terms of the GNU General Public License
19  * as published by the Free Software Foundation; either version 2
20  * of the License, or (at your option) any later version.
21  * 
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  * 
27  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
30  *
31  *******************************************************************************/
32
33 /*******************************************************************************
34  *
35  * This utility reads in an ASCII hexdump of this common format:
36  *
37  * 00000000  00 E0 1E A7 05 6F 00 10 5A A0 B9 12 08 00 46 00 .....o..Z.....F.
38  * 00000010  03 68 00 00 00 00 0A 2E EE 33 0F 19 08 7F 0F 19 .h.......3...\7f..
39  * 00000020  03 80 94 04 00 00 10 01 16 A2 0A 00 03 50 00 0C .............P..
40  * 00000030  01 01 0F 19 03 80 11 01 1E 61 00 0C 03 01 0F 19 .........a......
41  *
42  * Each bytestring line consists of an offset, one or more bytes, and
43  * text at the end. An offset is defined as a hex string of more than
44  * two characters. A byte is defined as a hex string of exactly two
45  * characters. The text at the end is ignored, as is any text before
46  * the offset. Bytes read from a bytestring line are added to the
47  * current packet only if all the following conditions are satisfied:
48  *
49  * - No text appears between the offset and the bytes (any bytes appearing after
50  *   such text would be ignored)
51  *
52  * - The offset must be arithmetically correct, i.e. if the offset is 00000020, then
53  *   exactly 32 bytes must have been read into this packet before this. If the offset
54  *   is wrong, the packet is immediately terminated
55  *
56  * A packet start is signalled by a zero offset.
57  *
58  * Lines starting with #TEXT2PCAP are directives. These allow the user
59  * to embed instructions into the capture file which allows text2pcap
60  * to take some actions (e.g. specifying the encapsulation
61  * etc.). Currently no directives are implemented.
62  *
63  * Lines beginning with # which are not directives are ignored as
64  * comments. Currently all non-hexdump text is ignored by text2pcap;
65  * in the future, text processing may be added, but lines prefixed
66  * with '#' will still be ignored.
67  *
68  * The output is a libpcap packet containing Ethernet frames by
69  * default. This program takes options which allow the user to add
70  * dummy Ethernet, IP and UDP headers to the packets in order to allow
71  * dumps of L3 or higher protocols to be decoded.
72  *
73  * Considerable flexibility is built into this code to read hexdumps
74  * of slightly different formats. For example, any text prefixing the
75  * hexdump line is dropped (including mail forwarding '>'). The offset
76  * can be any hex number of four digits or greater.
77  *
78  * This converter cannot read a single packet greater than 64K. Packet
79  * snaplength is automatically set to 64K.
80  */
81
82 #ifdef HAVE_CONFIG_H
83 # include "config.h"
84 #endif
85
86 #include <stdio.h>
87 #include <stdlib.h>
88 #include <string.h>
89 #include <sys/types.h>
90 #ifdef HAVE_UNISTD_H
91 # include <unistd.h>
92 #endif
93 #ifdef HAVE_NETINET_IN_H
94 # include <netinet/in.h>
95 #endif
96 #ifdef HAVE_WINSOCK_H
97 # include <winsock.h>
98 #endif
99 #include <errno.h>
100 #include <assert.h>
101
102 #ifdef NEED_GETOPT_H
103 # include "getopt.h"
104 #endif
105
106 #ifndef TRUE
107 #define TRUE 1
108 #endif
109
110 #ifndef FALSE
111 #define FALSE 0
112 #endif
113
114 #include "text2pcap.h"
115
116 /*--- Options --------------------------------------------------------------------*/
117
118 /* Debug level */
119 int debug = 0; 
120 /* Be quiet */
121 int quiet = FALSE;
122
123 /* Dummy Ethernet header */
124 int hdr_ethernet = FALSE;
125 unsigned long hdr_ethernet_proto = 0;
126
127 /* Dummy IP header */
128 int hdr_ip = FALSE;
129 unsigned long hdr_ip_proto = 0;
130
131 /* Dummy UDP header */
132 int hdr_udp = FALSE;
133 unsigned long hdr_udp_dest = 0;
134 unsigned long hdr_udp_src = 0;
135
136 /*--- Local date -----------------------------------------------------------------*/
137
138 /* This is where we store the packet currently being built */
139 #define MAX_PACKET 64000
140 unsigned char   packet_buf[MAX_PACKET];
141 unsigned long curr_offset = 0;
142
143 /* Number of packets read and written */
144 unsigned long num_packets_read = 0;
145 unsigned long num_packets_written = 0;
146
147 /* Input file */
148 char *input_filename;
149 FILE *input_file = NULL;
150 /* Output file */
151 char *output_filename;
152 FILE *output_file = NULL;
153
154 /* Offset base to parse */
155 unsigned long offset_base = 16;
156
157 FILE *yyin;
158
159 /* ----- State machine -----------------------------------------------------------*/
160
161 /* Current state of parser */
162 typedef enum {
163     INIT,             /* Waiting for start of new packet */
164     START_OF_LINE,    /* Starting from beginning of line */
165     READ_OFFSET,      /* Just read the offset */
166     READ_BYTE,        /* Just read a byte */
167     READ_TEXT,        /* Just read text - ignore until EOL */
168 } parser_state_t;
169 parser_state_t state = INIT;
170
171 const char *state_str[] = {"Init", 
172                            "Start-of-line", 
173                            "Offset",
174                            "Byte",
175                            "Text"
176 };
177
178 const char *token_str[] = {"",
179                            "Byte", 
180                            "Offset",
181                            "Directive",
182                            "Text",
183                            "End-of-line"
184 };
185
186 /* ----- Skeleton Packet Headers --------------------------------------------------*/
187
188 typedef struct {
189     unsigned char   src_addr[6];
190     unsigned char   dest_addr[6];
191     unsigned short l3pid;
192 } hdr_ethernet_t;
193
194 hdr_ethernet_t HDR_ETHERNET = {
195     {0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, 
196     {0x02, 0x02, 0x02, 0x02, 0x02, 0x02},
197     0};
198
199 typedef struct {
200     unsigned char   ver_hdrlen;
201     unsigned char   dscp;
202     unsigned short packet_length;
203     unsigned short identification;
204     unsigned char   flags;
205     unsigned char   fragment;
206     unsigned char   ttl;
207     unsigned char   protocol;
208     unsigned short hdr_checksum;
209     unsigned long src_addr;
210     unsigned long dest_addr;
211 } hdr_ip_t;
212
213 hdr_ip_t HDR_IP = {0x45, 0, 0, 0x3412, 0, 0, 0xff, 0, 0, 0x01010101, 0x02020202};
214
215 typedef struct {
216     unsigned short source_port;
217     unsigned short dest_port;
218     unsigned short length;
219     unsigned short checksum;
220 } hdr_udp_t;
221
222 hdr_udp_t HDR_UDP = {0, 0, 0, 0};
223
224 char tempbuf[64];
225
226 /*----------------------------------------------------------------------
227  * Stuff for writing a PCap file
228  */
229 #define PCAP_MAGIC                      0xa1b2c3d4
230
231 /* "libpcap" file header (minus magic number). */
232 struct pcap_hdr {
233     unsigned long    magic;          /* magic */
234     unsigned short      version_major;  /* major version number */
235     unsigned short      version_minor;  /* minor version number */
236     unsigned long       thiszone;       /* GMT to local correction */
237     unsigned long       sigfigs;        /* accuracy of timestamps */
238     unsigned long       snaplen;        /* max length of captured packets, in octets */
239     unsigned long       network;        /* data link type */
240 };
241
242 /* "libpcap" record header. */
243 struct pcaprec_hdr {
244     unsigned long       ts_sec;         /* timestamp seconds */
245     unsigned long       ts_usec;        /* timestamp microseconds */
246     unsigned long       incl_len;       /* number of octets of packet saved in file */
247     unsigned long       orig_len;       /* actual length of packet */
248 };
249
250 /* Link-layer type; see net/bpf.h for details */
251 unsigned long pcap_link_type = 1;   /* Default is DLT-EN10MB */
252
253 /*----------------------------------------------------------------------
254  * Parse a single hex number
255  * Will abort the program if it can't parse the number
256  * Pass in TRUE if this is an offset, FALSE if not
257  */
258 static unsigned long
259 parse_num (char *str, int offset)
260 {
261     unsigned long num;
262     char *c;
263
264     num = strtoul(str, &c, offset ? offset_base : 16);
265     if (c==str) {
266         fprintf(stderr, "FATAL ERROR: Bad hex number? [%s]\n", str);
267         exit(-1);
268     }
269     return num;
270 }
271
272 /*----------------------------------------------------------------------
273  * Write this byte into current packet
274  */
275 static void
276 write_byte (char *str)
277 {
278     unsigned long num;
279
280     num = parse_num(str, FALSE);
281     packet_buf[curr_offset] = num;
282     curr_offset ++;
283 }
284
285 /*----------------------------------------------------------------------
286  * Compute one's complement checksum (from RFC1071)
287  */
288 static unsigned short
289 in_checksum (void *buf, unsigned long count)
290 {
291     unsigned long sum = 0;
292     unsigned short *addr = buf;
293
294     while( count > 1 )  {
295         /*  This is the inner loop */
296         sum += ntohs(* (unsigned short *) addr++);
297         count -= 2;
298     }
299
300     /*  Add left-over byte, if any */
301     if( count > 0 ) 
302         sum += * (unsigned char *) addr;
303
304     /*  Fold 32-bit sum to 16 bits */
305     while (sum>>16)
306         sum = (sum & 0xffff) + (sum >> 16);
307
308     return htons(~sum);
309 }
310
311 /*----------------------------------------------------------------------
312  * Write current packet out 
313  */
314 static void
315 write_current_packet (void)
316 {
317     int length = 0;
318     int udp_length = 0;
319     int ip_length = 0;
320     int eth_trailer_length = 0;
321     struct pcaprec_hdr ph;
322
323     if (curr_offset > 0) {
324         /* Write the packet */
325
326         /* Compute packet length */
327         length = curr_offset;
328         if (hdr_udp) { length += sizeof(HDR_UDP); udp_length = length; }
329         if (hdr_ip) { length += sizeof(HDR_IP); ip_length = length; }
330         if (hdr_ethernet) {
331             length += sizeof(HDR_ETHERNET);
332             /* Pad trailer */
333             if (length < 60) {
334                 eth_trailer_length = 60 - length;
335                 length = 60;
336             }
337         }
338
339         /* Write PCap header */
340         ph.ts_sec = num_packets_written;
341         ph.ts_usec = num_packets_written;
342         ph.incl_len = length;
343         ph.orig_len = length;
344         fwrite(&ph, sizeof(ph), 1, output_file);
345         
346         /* Write Ethernet header */
347         if (hdr_ethernet) {
348             HDR_ETHERNET.l3pid = htons(hdr_ethernet_proto);
349             fwrite(&HDR_ETHERNET, sizeof(HDR_ETHERNET), 1, output_file);
350         }
351
352         /* Write IP header */
353         if (hdr_ip) {
354             HDR_IP.packet_length = htons(ip_length);
355             HDR_IP.protocol = hdr_ip_proto;
356             HDR_IP.hdr_checksum = 0;
357             HDR_IP.hdr_checksum = in_checksum(&HDR_IP, sizeof(HDR_IP));
358             fwrite(&HDR_IP, sizeof(HDR_IP), 1, output_file);
359         }
360
361         /* Write UDP header */
362         if (hdr_udp) {
363             HDR_UDP.source_port = htons(hdr_udp_src);
364             HDR_UDP.dest_port = htons(hdr_udp_dest);
365             HDR_UDP.length = htons(udp_length);
366             
367             fwrite(&HDR_UDP, sizeof(HDR_UDP), 1, output_file);
368         }
369
370         /* Write packet */
371         fwrite(packet_buf, curr_offset, 1, output_file);
372
373         /* Write Ethernet trailer */
374         if (hdr_ethernet && eth_trailer_length > 0) {
375             memset(tempbuf, 0, eth_trailer_length);
376             fwrite(tempbuf, eth_trailer_length, 1, output_file);
377         }
378
379         if (!quiet)
380             fprintf(stderr, "Wrote packet of %lu bytes\n", curr_offset);
381         num_packets_written ++;
382     }
383     curr_offset = 0;
384 }
385
386 /*----------------------------------------------------------------------
387  * Write the PCap file header 
388  */
389 static void
390 write_file_header (void)
391 {
392     struct pcap_hdr fh;
393
394     fh.magic = PCAP_MAGIC;
395     fh.version_major = 2;
396     fh.version_minor = 4;
397     fh.thiszone = 0;
398     fh.sigfigs = 0;
399     fh.snaplen = 102400;
400     fh.network = pcap_link_type;
401
402     fwrite(&fh, sizeof(fh), 1, output_file);
403 }
404
405 /*----------------------------------------------------------------------
406  * Start a new packet 
407  */
408 static void
409 start_new_packet (void)
410 {
411     if (debug>=1) 
412         fprintf(stderr, "Start new packet\n");
413
414     /* Write out the current packet, if required */
415     write_current_packet();
416     curr_offset = 0;
417     num_packets_read ++;
418 }
419
420 /*----------------------------------------------------------------------
421  * Process a directive
422  */
423 static void
424 process_directive (char *str)
425 {
426     fprintf(stderr, "\n--- Directive [%s] currently unsupported ---\n", str+10);
427
428 }
429
430 /*----------------------------------------------------------------------
431  * Parse a single token (called from the scanner)
432  */
433 void 
434 parse_token (token_t token, char *str)
435 {
436     unsigned long num;
437
438     /* 
439      * This is implemented as a simple state machine of five states. 
440      * State transitions are caused by tokens being received from the 
441      * scanner. The code should be self_documenting.
442      */
443
444     if (debug>=2) {
445         /* Sanitize - remove all '\r' */
446         char *c;
447         if (str!=NULL) { while ((c = strchr(str, '\r')) != NULL) *c=' '; }
448         
449         fprintf(stderr, "(%s, %s \"%s\") -> (", 
450                 state_str[state], token_str[token], str ? str : "");
451     }
452
453     switch(state) {
454
455     /* ----- Waiting for new packet -------------------------------------------*/
456     case INIT:
457         switch(token) {
458         case T_DIRECTIVE:
459             process_directive(str);
460             break;
461         case T_OFFSET:
462             num = parse_num(str, TRUE);
463             if (num==0) {
464                 /* New packet starts here */
465                 start_new_packet();
466                 state = READ_OFFSET;
467             }
468             break;
469         default:
470             break;
471         }
472         break;
473
474     /* ----- Processing packet, start of new line -----------------------------*/
475     case START_OF_LINE:
476         switch(token) {
477         case T_DIRECTIVE:
478             process_directive(str);
479             break;
480         case T_OFFSET:
481             num = parse_num(str, TRUE);
482             if (num==0) {
483                 /* New packet starts here */
484                 start_new_packet();
485                 state = READ_OFFSET;
486             } else if (num != curr_offset) {
487                 /* Bad offset; switch to INIT state */
488                 if (debug>=1)
489                     fprintf(stderr, "Inconsistent offset. Expecting %0lX, got %0lX. Ignoring rest of packet\n", 
490                             curr_offset, num);
491                 write_current_packet();
492                 state = INIT;
493             } else 
494                 state = READ_OFFSET;
495             break;
496         default:
497             break;
498         }
499         break;
500
501     /* ----- Processing packet, read offset -----------------------------------*/
502     case READ_OFFSET:
503         switch(token) {
504         case T_BYTE:
505             /* Record the byte */
506             state = READ_BYTE;
507             write_byte(str);
508             break;
509         case T_TEXT:
510         case T_DIRECTIVE:
511         case T_OFFSET:
512             state = READ_TEXT;
513             break;
514         case T_EOL:
515             state = START_OF_LINE;
516             break;
517         default:
518             break;
519         }
520         break;
521
522     /* ----- Processing packet, read byte -------------------------------------*/
523     case READ_BYTE:
524         switch(token) {
525         case T_BYTE:
526             /* Record the byte */
527             write_byte(str);
528             break;
529         case T_TEXT:
530         case T_DIRECTIVE:
531         case T_OFFSET:
532             state = READ_TEXT;
533             break;
534         case T_EOL:
535             state = START_OF_LINE;
536             break;
537         default:
538             break;
539         }
540         break;
541
542     /* ----- Processing packet, read text -------------------------------------*/
543     case READ_TEXT:
544         switch(token) {
545         case T_EOL:
546             state = START_OF_LINE;
547             break;
548         default:
549             break;
550         }
551         break;
552
553     default:
554         fprintf(stderr, "FATAL ERROR: Bad state (%d)", state);
555         exit(-1);
556     }
557
558     if (debug>=2) 
559         fprintf(stderr, ", %s)\n", state_str[state]);
560
561 }
562
563 /*----------------------------------------------------------------------
564  * Print helpstring and exit
565  */
566 static void
567 help (char *progname)
568 {
569     fprintf(stderr, 
570             "\n"
571             "Usage: %s [-d] [-q] [-o h|o] [-l typenum] [-e l3pid] [-i proto] \n"
572             "          [-u srcp destp] <input-filename> <output-filename>\n"
573             "\n"
574             "where <input-filename> specifies input filename (use - for standard input)\n"
575             "      <output-filename> specifies output filename (use - for standard output)\n"
576             "\n"
577             "[options] are one or more of the following \n"
578             "\n"
579             " -w filename  : Write capfile to <filename>. Default is standard output\n"
580             " -h           : Display this help message \n"
581             " -d           : Generate detailed debug of parser states \n"
582             " -o hex|oct   : Parse offsets as (h)ex or (o)ctal. Default is hex\n"
583             " -l typenum   : Specify link-layer type number. Default is 1 (Ethernet). \n"
584             "                See net/bpf.h for list of numbers.\n"
585             " -q           : Generate no output at all (automatically turns off -d)\n"
586             " -e l3pid     : Prepend dummy Ethernet II header with specified L3PID (in HEX)\n"
587             "                Example: -e 0x800\n"
588             " -i proto     : Prepend dummy IP header with specified IP protocol (in DECIMAL). \n"
589             "                Automatically prepends Ethernet header as well. Example: -i 46\n"
590             " -u srcp destp: Prepend dummy UDP header with specified dest and source ports (in DECIMAL).\n"
591             "                Automatically prepends Ethernet and IP headers as well\n"
592             "                Example: -u 30 40"
593             "\n", 
594             progname);
595
596     exit(-1);
597 }
598
599 /*----------------------------------------------------------------------
600  * Parse CLI options 
601  */
602 static void
603 parse_options (int argc, char *argv[])
604 {
605     int c;
606
607     /* Scan CLI parameters */
608     while ((c = getopt(argc, argv, "dqr:w:e:i:l:o:u:")) != -1) {
609         switch(c) {
610         case '?': help(argv[0]); break;
611         case 'h': help(argv[0]); break;
612         case 'd': if (!quiet) debug++; break;
613         case 'q': quiet = TRUE; debug = FALSE; break;
614         case 'l': pcap_link_type = atoi(optarg); break;
615         case 'o': 
616             if (!optarg || (optarg[0]!='h' && optarg[0] != 'o')) {
617                 fprintf(stderr, "Bad argument for '-e': %s\n",
618                         optarg ? optarg : "");
619                 help(argv[0]);
620             }
621             offset_base = (optarg[0]=='o') ? 8 : 16;
622             break;
623         case 'e':
624             hdr_ethernet = TRUE;
625             if (!optarg || sscanf(optarg, "%0lx", &hdr_ethernet_proto) < 1) {
626                 fprintf(stderr, "Bad argument for '-e': %s\n",
627                         optarg ? optarg : "");
628                 help(argv[0]);
629             }
630             break;
631             
632         case 'i':
633             hdr_ip = TRUE;
634             if (!optarg || sscanf(optarg, "%ld", &hdr_ip_proto) < 1) {
635                 fprintf(stderr, "Bad argument for '-i': %s\n",
636                         optarg ? optarg : "");
637                 help(argv[0]);
638             }
639             hdr_ethernet = TRUE;
640             hdr_ethernet_proto = 0x800;
641             break;
642             
643         case 'u':
644             hdr_udp = TRUE;
645             if (!optarg || sscanf(optarg, "%ld", &hdr_udp_src) < 1) {
646                 fprintf(stderr, "Bad src port for '-u'\n");
647                 help(argv[0]);
648             }
649             if (optind >= argc || sscanf(argv[optind], "%ld", &hdr_udp_dest) < 1) {
650                 fprintf(stderr, "Bad dest port for '-u'\n");
651                 help(argv[0]);
652             }
653             hdr_ip = TRUE;
654             hdr_ip_proto = 17;
655             hdr_ethernet = TRUE;
656             hdr_ethernet_proto = 0x800;
657             break;
658             
659         default:
660             help(argv[0]);
661         }
662     }
663
664     if (optind >= argc || argc-optind < 2) {
665         fprintf(stderr, "Must specify input and output filename\n");
666         help(argv[0]);
667     }
668
669     if (strcmp(argv[optind], "-")) {
670         input_filename = strdup(argv[optind]);
671         input_file = fopen(input_filename, "rb");
672         if (!input_file) {
673             fprintf(stderr, "Cannot open file [%s] for reading: %s\n", 
674                     input_filename, strerror(errno));
675             exit(-1);
676         }
677     } else {
678         input_filename = "Standard input";
679         input_file = stdin;
680     }
681
682     if (strcmp(argv[optind+1], "-")) {
683         output_filename = strdup(argv[optind+1]);
684         output_file = fopen(output_filename, "wb");
685         if (!output_file) {
686             fprintf(stderr, "Cannot open file [%s] for writing: %s\n", 
687                     output_filename, strerror(errno));
688             exit(-1);
689         }
690     } else {
691         output_filename = "Standard output";
692         output_file = stdout;
693     }
694
695     /* Some validation */
696     if (pcap_link_type != 1 && hdr_ethernet) {
697         fprintf(stderr, "Dummy headers (-e, -i, -u) cannot be specified with link type override (-l)\n");
698         exit(-1);
699     }
700
701     /* Set up our variables */
702     if (!input_file) {
703         input_file = stdin;
704         input_filename = "Standard input";
705     }
706     if (!output_file) {
707         output_file = stdout;
708         output_filename = "Standard output";
709     }
710     
711     /* Display summary of our state */
712     if (!quiet) {
713         fprintf(stderr, "Input from: %s\n", input_filename);
714         fprintf(stderr, "Output to: %s\n", output_filename);
715
716         if (hdr_ethernet) fprintf(stderr, "Generate dummy Ethernet header: Protocol: 0x%0lX\n", 
717                                  hdr_ethernet_proto); 
718         if (hdr_ip) fprintf(stderr, "Generate dummy IP header: Protocol: %ld\n", 
719                            hdr_ip_proto); 
720         if (hdr_udp) fprintf(stderr, "Generate dummy UDP header: Source port: %ld. Dest port: %ld\n", 
721                             hdr_udp_src, hdr_udp_dest); 
722     }
723 }
724
725 int main(int argc, char *argv[])
726 {
727     parse_options(argc, argv);
728
729     assert(input_file != NULL);
730     assert(output_file != NULL);
731
732     write_file_header();
733
734     yyin = input_file;
735     yylex();
736     write_current_packet();
737     if (debug)
738         fprintf(stderr, "\n-------------------------\n");
739     if (!quiet) {
740     fprintf(stderr, "Read %ld potential packets, wrote %ld packets\n", 
741             num_packets_read, num_packets_written);
742     }
743     return 0;
744 }