Get rid of some GTK+-only stuff.
[metze/wireshark/wip.git] / ui / text_import.c
1 /* text_import.c
2  * State machine for text import
3  * November 2010, Jaap Keuter <jaap.keuter@xs4all.nl>
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * Based on text2pcap.c by Ashok Narayanan <ashokn@cisco.com>
10  *
11  * SPDX-License-Identifier: GPL-2.0-or-later
12  */
13
14 /*******************************************************************************
15  *
16  * This utility reads in an ASCII hexdump of this common format:
17  *
18  * 00000000  00 E0 1E A7 05 6F 00 10 5A A0 B9 12 08 00 46 00 .....o..Z.....F.
19  * 00000010  03 68 00 00 00 00 0A 2E EE 33 0F 19 08 7F 0F 19 .h.......3......
20  * 00000020  03 80 94 04 00 00 10 01 16 A2 0A 00 03 50 00 0C .............P..
21  * 00000030  01 01 0F 19 03 80 11 01 1E 61 00 0C 03 01 0F 19 .........a......
22  *
23  * Each bytestring line consists of an offset, one or more bytes, and
24  * text at the end. An offset is defined as a hex string of more than
25  * two characters. A byte is defined as a hex string of exactly two
26  * characters. The text at the end is ignored, as is any text before
27  * the offset. Bytes read from a bytestring line are added to the
28  * current packet only if all the following conditions are satisfied:
29  *
30  * - No text appears between the offset and the bytes (any bytes appearing after
31  *   such text would be ignored)
32  *
33  * - The offset must be arithmetically correct, i.e. if the offset is 00000020, then
34  *   exactly 32 bytes must have been read into this packet before this. If the offset
35  *   is wrong, the packet is immediately terminated
36  *
37  * A packet start is signalled by a zero offset.
38  *
39  * Lines starting with #TEXT2PCAP are directives. These allow the user
40  * to embed instructions into the capture file which allows text2pcap
41  * to take some actions (e.g. specifying the encapsulation
42  * etc.). Currently no directives are implemented.
43  *
44  * Lines beginning with # which are not directives are ignored as
45  * comments. Currently all non-hexdump text is ignored by text2pcap;
46  * in the future, text processing may be added, but lines prefixed
47  * with '#' will still be ignored.
48  *
49  * The output is a libpcap packet containing Ethernet frames by
50  * default. This program takes options which allow the user to add
51  * dummy Ethernet, IP and UDP or TCP headers to the packets in order
52  * to allow dumps of L3 or higher protocols to be decoded.
53  *
54  * Considerable flexibility is built into this code to read hexdumps
55  * of slightly different formats. For example, any text prefixing the
56  * hexdump line is dropped (including mail forwarding '>'). The offset
57  * can be any hex number of four digits or greater.
58  *
59  * This converter cannot read a single packet greater than 64KiB-1. Packet
60  * snaplength is automatically set to 64KiB-1.
61  */
62
63 #include "config.h"
64
65 /*
66  * Just make sure we include the prototype for strptime as well
67  * (needed for glibc 2.2) but make sure we do this only if not
68  * yet defined.
69  */
70 #ifndef __USE_XOPEN
71 #  define __USE_XOPEN
72 #endif
73 #ifndef _XOPEN_SOURCE
74 #  ifndef __sun
75 #    define _XOPEN_SOURCE 600
76 #  endif
77 #endif
78
79 /*
80  * Defining _XOPEN_SOURCE is needed on some platforms, e.g. platforms
81  * using glibc, to expand the set of things system header files define.
82  *
83  * Unfortunately, on other platforms, such as some versions of Solaris
84  * (including Solaris 10), it *reduces* that set as well, causing
85  * strptime() not to be declared, presumably because the version of the
86  * X/Open spec that _XOPEN_SOURCE implies doesn't include strptime() and
87  * blah blah blah namespace pollution blah blah blah.
88  *
89  * So we define __EXTENSIONS__ so that "strptime()" is declared.
90  */
91 #ifndef __EXTENSIONS__
92 #  define __EXTENSIONS__
93 #endif
94
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <wsutil/file_util.h>
99
100 #include <time.h>
101 #include <glib.h>
102
103 #include <errno.h>
104 #include <assert.h>
105
106 #include <epan/tvbuff.h>
107 #include <wsutil/crc32.h>
108 #include <epan/in_cksum.h>
109
110 #ifndef HAVE_STRPTIME
111 # include "wsutil/strptime.h"
112 #endif
113
114 #include "text_import.h"
115 #include "text_import_scanner.h"
116 #include "text_import_scanner_lex.h"
117
118 /*--- Options --------------------------------------------------------------------*/
119
120 /* Debug level */
121 static int debug = 0;
122
123 /* Dummy Ethernet header */
124 static int hdr_ethernet = FALSE;
125 static guint32 hdr_ethernet_proto = 0;
126
127 /* Dummy IP header */
128 static int hdr_ip = FALSE;
129 static guint hdr_ip_proto = 0;
130
131 /* Dummy UDP header */
132 static int hdr_udp = FALSE;
133 static guint32 hdr_dest_port = 0;
134 static guint32 hdr_src_port = 0;
135
136 /* Dummy TCP header */
137 static int hdr_tcp = FALSE;
138
139 /* Dummy SCTP header */
140 static int hdr_sctp = FALSE;
141 static guint32 hdr_sctp_src  = 0;
142 static guint32 hdr_sctp_dest = 0;
143 static guint32 hdr_sctp_tag  = 0;
144
145 /* Dummy DATA chunk header */
146 static int hdr_data_chunk = FALSE;
147 static guint8  hdr_data_chunk_type = 0;
148 static guint8  hdr_data_chunk_bits = 3;
149 static guint32 hdr_data_chunk_tsn  = 0;
150 static guint16 hdr_data_chunk_sid  = 0;
151 static guint16 hdr_data_chunk_ssn  = 0;
152 static guint32 hdr_data_chunk_ppid = 0;
153
154 static gboolean has_direction = FALSE;
155 static guint32 direction = 0;
156
157 /*--- Local data -----------------------------------------------------------------*/
158
159 /* This is where we store the packet currently being built */
160 static guint8 *packet_buf;
161 static guint32 curr_offset = 0;
162 static guint32 max_offset = IMPORT_MAX_PACKET;
163 static guint32 packet_start = 0;
164 static void start_new_packet (void);
165
166 /* This buffer contains strings present before the packet offset 0 */
167 #define PACKET_PREAMBLE_MAX_LEN    2048
168 static guint8 packet_preamble[PACKET_PREAMBLE_MAX_LEN+1];
169 static int packet_preamble_len = 0;
170
171 /* Time code of packet, derived from packet_preamble */
172 static time_t ts_sec = 0;
173 static guint32 ts_usec = 0;
174 static char *ts_fmt = NULL;
175 static struct tm timecode_default;
176
177 static wtap_dumper* wdh;
178
179 /* HDR_ETH Offset base to parse */
180 static guint32 offset_base = 16;
181
182 /* ----- State machine -----------------------------------------------------------*/
183
184 /* Current state of parser */
185 typedef enum {
186     INIT,             /* Waiting for start of new packet */
187     START_OF_LINE,    /* Starting from beginning of line */
188     READ_OFFSET,      /* Just read the offset */
189     READ_BYTE,        /* Just read a byte */
190     READ_TEXT         /* Just read text - ignore until EOL */
191 } parser_state_t;
192 static parser_state_t state = INIT;
193
194 static const char *state_str[] = {"Init",
195                            "Start-of-line",
196                            "Offset",
197                            "Byte",
198                            "Text"
199 };
200
201 static const char *token_str[] = {"",
202                            "Byte",
203                            "Offset",
204                            "Directive",
205                            "Text",
206                            "End-of-line"
207 };
208
209 /* ----- Skeleton Packet Headers --------------------------------------------------*/
210
211 typedef struct {
212     guint8  dest_addr[6];
213     guint8  src_addr[6];
214     guint16 l3pid;
215 } hdr_ethernet_t;
216
217 static hdr_ethernet_t HDR_ETHERNET = {
218     {0x20, 0x52, 0x45, 0x43, 0x56, 0x00},
219     {0x20, 0x53, 0x45, 0x4E, 0x44, 0x00},
220     0};
221
222 typedef struct {
223     guint8  ver_hdrlen;
224     guint8  dscp;
225     guint16 packet_length;
226     guint16 identification;
227     guint8  flags;
228     guint8  fragment;
229     guint8  ttl;
230     guint8  protocol;
231     guint16 hdr_checksum;
232     guint32 src_addr;
233     guint32 dest_addr;
234 } hdr_ip_t;
235
236 static hdr_ip_t HDR_IP =
237   {0x45, 0, 0, 0x3412, 0, 0, 0xff, 0, 0, 0x01010101, 0x02020202};
238
239 static struct {         /* pseudo header for checksum calculation */
240     guint32 src_addr;
241     guint32 dest_addr;
242     guint8  zero;
243     guint8  protocol;
244     guint16 length;
245 } pseudoh;
246
247 typedef struct {
248     guint16 source_port;
249     guint16 dest_port;
250     guint16 length;
251     guint16 checksum;
252 } hdr_udp_t;
253
254 static hdr_udp_t HDR_UDP = {0, 0, 0, 0};
255
256 typedef struct {
257     guint16 source_port;
258     guint16 dest_port;
259     guint32 seq_num;
260     guint32 ack_num;
261     guint8  hdr_length;
262     guint8  flags;
263     guint16 window;
264     guint16 checksum;
265     guint16 urg;
266 } hdr_tcp_t;
267
268 static hdr_tcp_t HDR_TCP = {0, 0, 0, 0, 0x50, 0, 0, 0, 0};
269
270 typedef struct {
271     guint16 src_port;
272     guint16 dest_port;
273     guint32 tag;
274     guint32 checksum;
275 } hdr_sctp_t;
276
277 static hdr_sctp_t HDR_SCTP = {0, 0, 0, 0};
278
279 typedef struct {
280     guint8  type;
281     guint8  bits;
282     guint16 length;
283     guint32 tsn;
284     guint16 sid;
285     guint16 ssn;
286     guint32 ppid;
287 } hdr_data_chunk_t;
288
289 static hdr_data_chunk_t HDR_DATA_CHUNK = {0, 0, 0, 0, 0, 0, 0};
290
291 /* Link-layer type; see net/bpf.h for details */
292 static guint pcap_link_type = 1;   /* Default is DLT_EN10MB */
293
294 /*----------------------------------------------------------------------
295  * Parse a single hex number
296  * Will abort the program if it can't parse the number
297  * Pass in TRUE if this is an offset, FALSE if not
298  */
299 static guint32
300 parse_num (const char *str, int offset)
301 {
302     unsigned long num;
303     char *c;
304
305     if (str == NULL) {
306         fprintf(stderr, "FATAL ERROR: str is NULL\n");
307         exit(1);
308     }
309
310     num = strtoul(str, &c, offset ? offset_base : 16);
311     if (c==str) {
312         fprintf(stderr, "FATAL ERROR: Bad hex number? [%s]\n", str);
313     }
314     return (guint32)num;
315 }
316
317 /*----------------------------------------------------------------------
318  * Write this byte into current packet
319  */
320 static void
321 write_byte (const char *str)
322 {
323     guint32 num;
324
325     num = parse_num(str, FALSE);
326     packet_buf[curr_offset] = (guint8) num;
327     curr_offset ++;
328     if (curr_offset >= max_offset) /* packet full */
329         start_new_packet();
330 }
331
332 /*----------------------------------------------------------------------
333  * Remove bytes from the current packet
334  */
335 static void
336 unwrite_bytes (guint32 nbytes)
337 {
338     curr_offset -= nbytes;
339 }
340
341 /*----------------------------------------------------------------------
342  * Determin SCTP chunk padding length
343  */
344 static guint32
345 number_of_padding_bytes (guint32 length)
346 {
347   guint32 remainder;
348
349   remainder = length % 4;
350
351   if (remainder == 0)
352     return 0;
353   else
354     return 4 - remainder;
355 }
356
357 /*----------------------------------------------------------------------
358  * Write current packet out
359  */
360 void
361 write_current_packet (void)
362 {
363     int prefix_length = 0;
364     int proto_length = 0;
365     int ip_length = 0;
366     int eth_trailer_length = 0;
367     int prefix_index = 0;
368     int i, padding_length;
369
370     if (curr_offset > 0) {
371         /* Write the packet */
372
373         /* Compute packet length */
374         prefix_length = 0;
375         if (hdr_data_chunk) { prefix_length += (int)sizeof(HDR_DATA_CHUNK); }
376         if (hdr_sctp) { prefix_length += (int)sizeof(HDR_SCTP); }
377         if (hdr_udp) { prefix_length += (int)sizeof(HDR_UDP); proto_length = prefix_length + curr_offset; }
378         if (hdr_tcp) { prefix_length += (int)sizeof(HDR_TCP); proto_length = prefix_length + curr_offset; }
379         if (hdr_ip) {
380             prefix_length += (int)sizeof(HDR_IP);
381             ip_length = prefix_length + curr_offset + ((hdr_data_chunk) ? number_of_padding_bytes(curr_offset) : 0);
382         }
383         if (hdr_ethernet) { prefix_length += (int)sizeof(HDR_ETHERNET); }
384
385         /* Make room for dummy header */
386         memmove(&packet_buf[prefix_length], packet_buf, curr_offset);
387
388         if (hdr_ethernet) {
389             /* Pad trailer */
390             if (prefix_length + curr_offset < 60) {
391                 eth_trailer_length = 60 - (prefix_length + curr_offset);
392             }
393         }
394
395         /* Write Ethernet header */
396         if (hdr_ethernet) {
397             HDR_ETHERNET.l3pid = g_htons(hdr_ethernet_proto);
398             memcpy(&packet_buf[prefix_index], &HDR_ETHERNET, sizeof(HDR_ETHERNET));
399             prefix_index += (int)sizeof(HDR_ETHERNET);
400         }
401
402         /* Write IP header */
403         if (hdr_ip) {
404             vec_t cksum_vector[1];
405
406             HDR_IP.packet_length = g_htons(ip_length);
407             HDR_IP.protocol = (guint8) hdr_ip_proto;
408             HDR_IP.hdr_checksum = 0;
409             cksum_vector[0].ptr = (guint8 *)&HDR_IP; cksum_vector[0].len = sizeof(HDR_IP);
410             HDR_IP.hdr_checksum = in_cksum(cksum_vector, 1);
411
412             memcpy(&packet_buf[prefix_index], &HDR_IP, sizeof(HDR_IP));
413             prefix_index += (int)sizeof(HDR_IP);
414         }
415
416         /* initialize pseudo header for checksum calculation */
417         pseudoh.src_addr    = HDR_IP.src_addr;
418         pseudoh.dest_addr   = HDR_IP.dest_addr;
419         pseudoh.zero        = 0;
420         pseudoh.protocol    = (guint8) hdr_ip_proto;
421         pseudoh.length      = g_htons(proto_length);
422
423         /* Write UDP header */
424         if (hdr_udp) {
425             vec_t cksum_vector[3];
426
427             HDR_UDP.source_port = g_htons(hdr_src_port);
428             HDR_UDP.dest_port = g_htons(hdr_dest_port);
429             HDR_UDP.length = g_htons(proto_length);
430
431             HDR_UDP.checksum = 0;
432             cksum_vector[0].ptr = (guint8 *)&pseudoh; cksum_vector[0].len = sizeof(pseudoh);
433             cksum_vector[1].ptr = (guint8 *)&HDR_UDP; cksum_vector[1].len = sizeof(HDR_UDP);
434             cksum_vector[2].ptr = &packet_buf[prefix_length]; cksum_vector[2].len = curr_offset;
435             HDR_UDP.checksum = in_cksum(cksum_vector, 3);
436
437             memcpy(&packet_buf[prefix_index], &HDR_UDP, sizeof(HDR_UDP));
438             prefix_index += (int)sizeof(HDR_UDP);
439         }
440
441         /* Write TCP header */
442         if (hdr_tcp) {
443             vec_t cksum_vector[3];
444
445             HDR_TCP.source_port = g_htons(hdr_src_port);
446             HDR_TCP.dest_port = g_htons(hdr_dest_port);
447             /* HDR_TCP.seq_num already correct */
448             HDR_TCP.window = g_htons(0x2000);
449
450             HDR_TCP.checksum = 0;
451             cksum_vector[0].ptr = (guint8 *)&pseudoh; cksum_vector[0].len = sizeof(pseudoh);
452             cksum_vector[1].ptr = (guint8 *)&HDR_TCP; cksum_vector[1].len = sizeof(HDR_TCP);
453             cksum_vector[2].ptr = &packet_buf[prefix_length]; cksum_vector[2].len = curr_offset;
454             HDR_TCP.checksum = in_cksum(cksum_vector, 3);
455
456             memcpy(&packet_buf[prefix_index], &HDR_TCP, sizeof(HDR_TCP));
457             prefix_index += (int)sizeof(HDR_TCP);
458         }
459
460         /* Compute DATA chunk header and append padding */
461         if (hdr_data_chunk) {
462             HDR_DATA_CHUNK.type   = hdr_data_chunk_type;
463             HDR_DATA_CHUNK.bits   = hdr_data_chunk_bits;
464             HDR_DATA_CHUNK.length = g_htons(curr_offset + sizeof(HDR_DATA_CHUNK));
465             HDR_DATA_CHUNK.tsn    = g_htonl(hdr_data_chunk_tsn);
466             HDR_DATA_CHUNK.sid    = g_htons(hdr_data_chunk_sid);
467             HDR_DATA_CHUNK.ssn    = g_htons(hdr_data_chunk_ssn);
468             HDR_DATA_CHUNK.ppid   = g_htonl(hdr_data_chunk_ppid);
469
470             padding_length = number_of_padding_bytes(curr_offset);
471             for (i=0; i<padding_length; i++)
472                 packet_buf[prefix_length+curr_offset+i] = 0;
473             curr_offset += padding_length;
474         }
475
476         /* Write SCTP header */
477         if (hdr_sctp) {
478             HDR_SCTP.src_port  = g_htons(hdr_sctp_src);
479             HDR_SCTP.dest_port = g_htons(hdr_sctp_dest);
480             HDR_SCTP.tag       = g_htonl(hdr_sctp_tag);
481             HDR_SCTP.checksum  = g_htonl(0);
482
483             HDR_SCTP.checksum  = crc32c_calculate(&HDR_SCTP, sizeof(HDR_SCTP), CRC32C_PRELOAD);
484             if (hdr_data_chunk)
485                 HDR_SCTP.checksum  = crc32c_calculate(&HDR_DATA_CHUNK, sizeof(HDR_DATA_CHUNK), HDR_SCTP.checksum);
486             HDR_SCTP.checksum  = g_htonl(~crc32c_calculate(&packet_buf[prefix_length], curr_offset, HDR_SCTP.checksum));
487
488             memcpy(&packet_buf[prefix_index], &HDR_SCTP, sizeof(HDR_SCTP));
489             prefix_index += (int)sizeof(HDR_SCTP);
490         }
491
492         /* Write DATA chunk header */
493         if (hdr_data_chunk) {
494             memcpy(&packet_buf[prefix_index], &HDR_DATA_CHUNK, sizeof(HDR_DATA_CHUNK));
495             /*prefix_index += (int)sizeof(HDR_DATA_CHUNK);*/
496         }
497
498         /* Write Ethernet trailer */
499         if (hdr_ethernet && eth_trailer_length > 0) {
500             memset(&packet_buf[prefix_length+curr_offset], 0, eth_trailer_length);
501         }
502
503         HDR_TCP.seq_num = g_ntohl(HDR_TCP.seq_num) + curr_offset;
504         HDR_TCP.seq_num = g_htonl(HDR_TCP.seq_num);
505
506         {
507             /* Write the packet */
508             wtap_rec rec;
509             int err;
510             gchar *err_info;
511
512             memset(&rec, 0, sizeof rec);
513
514             rec.rec_type = REC_TYPE_PACKET;
515             rec.ts.secs = (guint32)ts_sec;
516             rec.ts.nsecs = ts_usec * 1000;
517             if (ts_fmt == NULL) { ts_usec++; }  /* fake packet counter */
518             rec.rec_header.packet_header.caplen = rec.rec_header.packet_header.len = prefix_length + curr_offset + eth_trailer_length;
519             rec.rec_header.packet_header.pkt_encap = pcap_link_type;
520             rec.rec_header.packet_header.pack_flags |= direction;
521             rec.presence_flags = WTAP_HAS_CAP_LEN|WTAP_HAS_INTERFACE_ID|WTAP_HAS_TS|WTAP_HAS_PACK_FLAGS;
522
523             /* XXX - report errors! */
524             if (!wtap_dump(wdh, &rec, packet_buf, &err, &err_info)) {
525                 switch (err) {
526
527                 case WTAP_ERR_UNWRITABLE_REC_DATA:
528                     g_free(err_info);
529                     break;
530
531                 default:
532                     break;
533                 }
534             }
535         }
536     }
537
538     packet_start += curr_offset;
539     curr_offset = 0;
540 }
541
542
543 /*----------------------------------------------------------------------
544  * Append a token to the packet preamble.
545  */
546 static void
547 append_to_preamble(char *str)
548 {
549     size_t toklen;
550
551     if (packet_preamble_len != 0) {
552         if (packet_preamble_len == PACKET_PREAMBLE_MAX_LEN)
553             return;    /* no room to add more preamble */
554         /* Add a blank separator between the previous token and this token. */
555         packet_preamble[packet_preamble_len++] = ' ';
556     }
557     if(str == NULL){
558         fprintf(stderr, "FATAL ERROR: str is NULL\n");
559         exit(1);
560     }
561     toklen = strlen(str);
562     if (toklen != 0) {
563         if (packet_preamble_len + toklen > PACKET_PREAMBLE_MAX_LEN)
564             return;    /* no room to add the token to the preamble */
565         g_strlcpy(&packet_preamble[packet_preamble_len], str, PACKET_PREAMBLE_MAX_LEN);
566         packet_preamble_len += (int) toklen;
567         if (debug >= 2) {
568             char *c;
569             char xs[PACKET_PREAMBLE_MAX_LEN];
570             g_strlcpy(xs, packet_preamble, PACKET_PREAMBLE_MAX_LEN);
571             while ((c = strchr(xs, '\r')) != NULL) *c=' ';
572             fprintf (stderr, "[[append_to_preamble: \"%s\"]]", xs);
573         }
574     }
575 }
576
577 /*----------------------------------------------------------------------
578  * Parse the preamble to get the timecode.
579  */
580
581 static void
582 parse_preamble (void)
583 {
584     struct tm timecode;
585     char *subsecs;
586     char *p;
587     int  subseclen;
588     int  i;
589
590     /*
591      * Null-terminate the preamble.
592      */
593     packet_preamble[packet_preamble_len] = '\0';
594
595     if (has_direction) {
596         switch (packet_preamble[0]) {
597         case 'i':
598         case 'I':
599             direction = 0x00000001;
600             packet_preamble[0] = ' ';
601             break;
602         case 'o':
603         case 'O':
604             direction = 0x00000002;
605             packet_preamble[0] = ' ';
606             break;
607         default:
608             direction = 0x00000000;
609             break;
610         }
611         i = 0;
612         while (packet_preamble[i] == ' ' ||
613                packet_preamble[i] == '\r' ||
614                packet_preamble[i] == '\t') {
615             i++;
616         }
617         packet_preamble_len -= i;
618         /* Also move the trailing '\0'. */
619         memmove(packet_preamble, packet_preamble + i, packet_preamble_len + 1);
620     }
621
622     /*
623      * If no "-t" flag was specified, don't attempt to parse a packet
624      * preamble to extract a time stamp.
625      */
626     if (ts_fmt == NULL)
627         return;
628
629     /*
630      * Initialize to today localtime, just in case not all fields
631      * of the date and time are specified.
632      */
633
634     timecode = timecode_default;
635     ts_usec = 0;
636
637     /* Ensure preamble has more than two chars before attempting to parse.
638      * This should cover line breaks etc that get counted.
639      */
640     if ( strlen(packet_preamble) > 2 ) {
641         /* Get Time leaving subseconds */
642         subsecs = strptime( packet_preamble, ts_fmt, &timecode );
643         if (subsecs != NULL) {
644             /* Get the long time from the tm structure */
645             /*  (will return -1 if failure)            */
646             ts_sec  = mktime( &timecode );
647         } else
648             ts_sec = -1;    /* we failed to parse it */
649
650         /* This will ensure incorrectly parsed dates get set to zero */
651         if ( -1 == ts_sec )
652         {
653             /* Sanitize - remove all '\r' */
654             char *c;
655             while ((c = strchr(packet_preamble, '\r')) != NULL) *c=' ';
656             fprintf (stderr, "Failure processing time \"%s\" using time format \"%s\"\n   (defaulting to Jan 1,1970 00:00:00 GMT)\n",
657                  packet_preamble, ts_fmt);
658             if (debug >= 2) {
659                 fprintf(stderr, "timecode: %02d/%02d/%d %02d:%02d:%02d %d\n",
660                     timecode.tm_mday, timecode.tm_mon, timecode.tm_year,
661                     timecode.tm_hour, timecode.tm_min, timecode.tm_sec, timecode.tm_isdst);
662             }
663             ts_sec  = 0;  /* Jan 1,1970: 00:00 GMT; tshark/wireshark will display date/time as adjusted by timezone */
664             ts_usec = 0;
665         }
666         else
667         {
668             /* Parse subseconds */
669             ts_usec = (guint32)strtol(subsecs, &p, 10);
670             if (subsecs == p) {
671                 /* Error */
672                 ts_usec = 0;
673             } else {
674                 /*
675                  * Convert that number to a number
676                  * of microseconds; if it's N digits
677                  * long, it's in units of 10^(-N) seconds,
678                  * so, to convert it to units of
679                  * 10^-6 seconds, we multiply by
680                  * 10^(6-N).
681                  */
682                 subseclen = (int) (p - subsecs);
683                 if (subseclen > 6) {
684                     /*
685                      * *More* than 6 digits; 6-N is
686                      * negative, so we divide by
687                      * 10^(N-6).
688                      */
689                     for (i = subseclen - 6; i != 0; i--)
690                         ts_usec /= 10;
691                 } else if (subseclen < 6) {
692                     for (i = 6 - subseclen; i != 0; i--)
693                         ts_usec *= 10;
694                 }
695             }
696         }
697     }
698     if (debug >= 2) {
699         char *c;
700         while ((c = strchr(packet_preamble, '\r')) != NULL) *c=' ';
701         fprintf(stderr, "[[parse_preamble: \"%s\"]]\n", packet_preamble);
702         fprintf(stderr, "Format(%s), time(%u), subsecs(%u)\n", ts_fmt, (guint32)ts_sec, ts_usec);
703     }
704
705
706     /* Clear Preamble */
707     packet_preamble_len = 0;
708 }
709
710 /*----------------------------------------------------------------------
711  * Start a new packet
712  */
713 static void
714 start_new_packet (void)
715 {
716     if (debug>=1)
717         fprintf(stderr, "Start new packet\n");
718
719     /* Write out the current packet, if required */
720     write_current_packet();
721
722     /* Ensure we parse the packet preamble as it may contain the time */
723     parse_preamble();
724 }
725
726 /*----------------------------------------------------------------------
727  * Process a directive
728  */
729 static void
730 process_directive (char *str)
731 {
732     fprintf(stderr, "\n--- Directive [%s] currently unsupported ---\n", str+10);
733
734 }
735
736 /*----------------------------------------------------------------------
737  * Parse a single token (called from the scanner)
738  */
739 void
740 parse_token (token_t token, char *str)
741 {
742     guint32 num;
743
744     /*
745      * This is implemented as a simple state machine of five states.
746      * State transitions are caused by tokens being received from the
747      * scanner. The code should be self_documenting.
748      */
749
750     if (debug>=2) {
751         /* Sanitize - remove all '\r' */
752         char *c;
753         if (str!=NULL) { while ((c = strchr(str, '\r')) != NULL) *c=' '; }
754
755         fprintf(stderr, "(%s, %s \"%s\") -> (",
756                 state_str[state], token_str[token], str ? str : "");
757     }
758
759     switch(state) {
760
761     /* ----- Waiting for new packet -------------------------------------------*/
762     case INIT:
763         switch(token) {
764         case T_TEXT:
765             append_to_preamble(str);
766             break;
767         case T_DIRECTIVE:
768             process_directive(str);
769             break;
770         case T_OFFSET:
771             num = parse_num(str, TRUE);
772             if (num==0) {
773                 /* New packet starts here */
774                 start_new_packet();
775                 state = READ_OFFSET;
776             }
777             break;
778         case T_BYTE:
779             if (offset_base == 0) {
780                 start_new_packet();
781                 write_byte(str);
782                 state = READ_BYTE;
783             }
784             break;
785         default:
786             break;
787         }
788         break;
789
790     /* ----- Processing packet, start of new line -----------------------------*/
791     case START_OF_LINE:
792         switch(token) {
793         case T_TEXT:
794             append_to_preamble(str);
795             break;
796         case T_DIRECTIVE:
797             process_directive(str);
798             break;
799         case T_OFFSET:
800             num = parse_num(str, TRUE);
801             if (num==0) {
802                 /* New packet starts here */
803                 start_new_packet();
804                 packet_start = 0;
805                 state = READ_OFFSET;
806             } else if ((num - packet_start) != curr_offset) {
807                 /*
808                  * The offset we read isn't the one we expected.
809                  * This may only mean that we mistakenly interpreted
810                  * some text as byte values (e.g., if the text dump
811                  * of packet data included a number with spaces around
812                  * it).  If the offset is less than what we expected,
813                  * assume that's the problem, and throw away the putative
814                  * extra byte values.
815                  */
816                 if (num < curr_offset) {
817                     unwrite_bytes(curr_offset - num);
818                     state = READ_OFFSET;
819                 } else {
820                     /* Bad offset; switch to INIT state */
821                     if (debug>=1)
822                         fprintf(stderr, "Inconsistent offset. Expecting %0X, got %0X. Ignoring rest of packet\n",
823                                 curr_offset, num);
824                     write_current_packet();
825                     state = INIT;
826                 }
827             } else
828                 state = READ_OFFSET;
829             break;
830         case T_BYTE:
831             if (offset_base == 0) {
832                 write_byte(str);
833                 state = READ_BYTE;
834             }
835             break;
836         default:
837             break;
838         }
839         break;
840
841     /* ----- Processing packet, read offset -----------------------------------*/
842     case READ_OFFSET:
843         switch(token) {
844         case T_BYTE:
845             /* Record the byte */
846             state = READ_BYTE;
847             write_byte(str);
848             break;
849         case T_TEXT:
850         case T_DIRECTIVE:
851         case T_OFFSET:
852             state = READ_TEXT;
853             break;
854         case T_EOL:
855             state = START_OF_LINE;
856             break;
857         default:
858             break;
859         }
860         break;
861
862     /* ----- Processing packet, read byte -------------------------------------*/
863     case READ_BYTE:
864         switch(token) {
865         case T_BYTE:
866             /* Record the byte */
867             write_byte(str);
868             break;
869         case T_TEXT:
870         case T_DIRECTIVE:
871         case T_OFFSET:
872             state = READ_TEXT;
873             break;
874         case T_EOL:
875             state = START_OF_LINE;
876             break;
877         default:
878             break;
879         }
880         break;
881
882     /* ----- Processing packet, read text -------------------------------------*/
883     case READ_TEXT:
884         switch(token) {
885         case T_EOL:
886             state = START_OF_LINE;
887             break;
888         default:
889             break;
890         }
891         break;
892
893     default:
894         fprintf(stderr, "FATAL ERROR: Bad state (%d)", state);
895         exit(-1);
896     }
897
898     if (debug>=2)
899         fprintf(stderr, ", %s)\n", state_str[state]);
900
901 }
902
903 /*----------------------------------------------------------------------
904  * Import a text file.
905  */
906 int
907 text_import(text_import_info_t *info)
908 {
909     int ret;
910     struct tm *now_tm;
911
912     packet_buf = (guint8 *)g_malloc(sizeof(HDR_ETHERNET) + sizeof(HDR_IP) +
913                                     sizeof(HDR_SCTP) + sizeof(HDR_DATA_CHUNK) +
914                                     IMPORT_MAX_PACKET);
915
916     if (!packet_buf)
917     {
918         fprintf(stderr, "FATAL ERROR: no memory for packet buffer");
919         exit(-1);
920     }
921
922     /* Lets start from the beginning */
923     state = INIT;
924     curr_offset = 0;
925     packet_start = 0;
926     packet_preamble_len = 0;
927     ts_sec = time(0);            /* initialize to current time */
928     now_tm = localtime(&ts_sec);
929     if (now_tm == NULL) {
930         /*
931          * This shouldn't happen - on UN*X, this should Just Work, and
932          * on Windows, it won't work if ts_sec is before the Epoch,
933          * but it's long after 1970, so....
934          */
935         fprintf(stderr, "localtime(right now) failed\n");
936         exit(-1);
937     }
938     timecode_default = *now_tm;
939     timecode_default.tm_isdst = -1;     /* Unknown for now, depends on time given to the strptime() function */
940     ts_usec = 0;
941
942     /* Dummy headers */
943     hdr_ethernet = FALSE;
944     hdr_ip = FALSE;
945     hdr_udp = FALSE;
946     hdr_tcp = FALSE;
947     hdr_sctp = FALSE;
948     hdr_data_chunk = FALSE;
949
950     offset_base = (info->offset_type == OFFSET_NONE) ? 0 :
951                   (info->offset_type == OFFSET_HEX) ? 16 :
952                   (info->offset_type == OFFSET_OCT) ? 8 :
953                   (info->offset_type == OFFSET_DEC) ? 10 :
954                   16;
955
956     has_direction = info->has_direction;
957
958     if (info->date_timestamp)
959     {
960         ts_fmt = info->date_timestamp_format;
961     }
962
963     pcap_link_type = info->encapsulation;
964
965     wdh = info->wdh;
966
967     switch (info->dummy_header_type)
968     {
969         case HEADER_ETH:
970             hdr_ethernet = TRUE;
971             hdr_ethernet_proto = info->pid;
972             break;
973
974         case HEADER_IPV4:
975             hdr_ip = TRUE;
976             hdr_ip_proto = info->protocol;
977             hdr_ethernet = TRUE;
978             hdr_ethernet_proto = 0x800;
979             break;
980
981         case HEADER_UDP:
982             hdr_udp = TRUE;
983             hdr_tcp = FALSE;
984             hdr_src_port = info->src_port;
985             hdr_dest_port = info->dst_port;
986             hdr_ip = TRUE;
987             hdr_ip_proto = 17;
988             hdr_ethernet = TRUE;
989             hdr_ethernet_proto = 0x800;
990             break;
991
992         case HEADER_TCP:
993             hdr_tcp = TRUE;
994             hdr_udp = FALSE;
995             hdr_src_port = info->src_port;
996             hdr_dest_port = info->dst_port;
997             hdr_ip = TRUE;
998             hdr_ip_proto = 6;
999             hdr_ethernet = TRUE;
1000             hdr_ethernet_proto = 0x800;
1001             break;
1002
1003         case HEADER_SCTP:
1004             hdr_sctp = TRUE;
1005             hdr_sctp_src = info->src_port;
1006             hdr_sctp_dest = info->dst_port;
1007             hdr_sctp_tag = info->tag;
1008             hdr_ip = TRUE;
1009             hdr_ip_proto = 132;
1010             hdr_ethernet = TRUE;
1011             hdr_ethernet_proto = 0x800;
1012             break;
1013
1014         case HEADER_SCTP_DATA:
1015             hdr_sctp = TRUE;
1016             hdr_data_chunk = TRUE;
1017             hdr_sctp_src = info->src_port;
1018             hdr_sctp_dest = info->dst_port;
1019             hdr_data_chunk_ppid = info->ppi;
1020             hdr_ip = TRUE;
1021             hdr_ip_proto = 132;
1022             hdr_ethernet = TRUE;
1023             hdr_ethernet_proto = 0x800;
1024             break;
1025
1026         default:
1027             break;
1028     }
1029
1030     max_offset = info->max_frame_length;
1031
1032     ret = text_import_scan(info->import_text_file);
1033     g_free(packet_buf);
1034     return ret;
1035 }
1036
1037 /*
1038  * Editor modelines
1039  *
1040  * Local Variables:
1041  * c-basic-offset: 4
1042  * tab-width: 8
1043  * indent-tabs-mode: nil
1044  * End:
1045  *
1046  * ex: set shiftwidth=4 tabstop=8 expandtab:
1047  * :indentSize=4:tabSize=8:noTabs=true:
1048  */