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