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