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