Qt: Fix leak on CaptureFileDialog preview of file with errors
[wireshark.git] / text2pcap.c
blobfc92bea9b7da61ed9a2519e7769119bab1acf19d
1 /**-*-C-*-**********************************************************************
3 * text2pcap.c
5 * Utility to convert an ASCII hexdump into a libpcap-format capture file
7 * (c) Copyright 2001 Ashok Narayanan <ashokn@cisco.com>
9 * Wireshark - Network traffic analyzer
10 * By Gerald Combs <gerald@wireshark.org>
11 * Copyright 1998 Gerald Combs
13 * SPDX-License-Identifier: GPL-2.0-or-later
15 *******************************************************************************/
17 /*******************************************************************************
19 * This utility reads in an ASCII hexdump of this common format:
21 * 00000000 00 E0 1E A7 05 6F 00 10 5A A0 B9 12 08 00 46 00 .....o..Z.....F.
22 * 00000010 03 68 00 00 00 00 0A 2E EE 33 0F 19 08 7F 0F 19 .h.......3......
23 * 00000020 03 80 94 04 00 00 10 01 16 A2 0A 00 03 50 00 0C .............P..
24 * 00000030 01 01 0F 19 03 80 11 01 1E 61 00 0C 03 01 0F 19 .........a......
26 * Each bytestring line consists of an offset, one or more bytes, and
27 * text at the end. An offset is defined as a hex string of more than
28 * two characters. A byte is defined as a hex string of exactly two
29 * characters. The text at the end is ignored, as is any text before
30 * the offset. Bytes read from a bytestring line are added to the
31 * current packet only if all the following conditions are satisfied:
33 * - No text appears between the offset and the bytes (any bytes appearing after
34 * such text would be ignored)
36 * - The offset must be arithmetically correct, i.e. if the offset is 00000020,
37 * then exactly 32 bytes must have been read into this packet before this.
38 * If the offset is wrong, the packet is immediately terminated
40 * A packet start is signaled by a zero offset.
42 * Lines starting with #TEXT2PCAP are directives. These allow the user
43 * to embed instructions into the capture file which allows text2pcap
44 * to take some actions (e.g. specifying the encapsulation
45 * etc.). Currently no directives are implemented.
47 * Lines beginning with # which are not directives are ignored as
48 * comments. Currently all non-hexdump text is ignored by text2pcap;
49 * in the future, text processing may be added, but lines prefixed
50 * with '#' will still be ignored.
52 * The output is a libpcap packet containing Ethernet frames by
53 * default. This program takes options which allow the user to add
54 * dummy Ethernet, IP and UDP, TCP or SCTP headers to the packets in order
55 * to allow dumps of L3 or higher protocols to be decoded.
57 * Considerable flexibility is built into this code to read hexdumps
58 * of slightly different formats. For example, any text prefixing the
59 * hexdump line is dropped (including mail forwarding '>'). The offset
60 * can be any hex number of four digits or greater.
62 * This converter cannot read a single packet greater than
63 * WTAP_MAX_PACKET_SIZE_STANDARD. The snapshot length is automatically
64 * set to WTAP_MAX_PACKET_SIZE_STANDARD.
67 #include <config.h>
68 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <wsutil/file_util.h>
74 #include <cli_main.h>
75 #include <wsutil/cmdarg_err.h>
76 #include <ui/text_import.h>
77 #include <wsutil/version_info.h>
78 #include <ui/failure_message.h>
79 #include <wsutil/report_message.h>
80 #include <wsutil/inet_addr.h>
81 #include <wsutil/cpu_info.h>
82 #include <wsutil/os_version_info.h>
83 #include <wsutil/privileges.h>
84 #include <wsutil/strtoi.h>
86 #include <glib.h>
88 #include <ws_exit_codes.h>
89 #include <wsutil/filesystem.h>
90 #include <wsutil/str_util.h>
91 #include <wsutil/strnatcmp.h>
92 #include <wsutil/wslog.h>
93 #include <wsutil/ws_getopt.h>
95 #include <errno.h>
97 #include "text2pcap.h"
99 #include "wiretap/wtap.h"
100 #include "wiretap/pcap-encap.h"
102 /*--- Options --------------------------------------------------------------------*/
104 /* Be quiet */
105 static gboolean quiet;
107 /* Dummy Ethernet header */
108 static gboolean hdr_ethernet;
109 #if 0
110 /* XXX: Maybe add custom Ethernet Address options? */
111 static guint8 hdr_eth_dest_addr[6] = {0x0a, 0x02, 0x02, 0x02, 0x02, 0x02};
112 static guint8 hdr_eth_src_addr[6] = {0x0a, 0x02, 0x02, 0x02, 0x02, 0x01};
113 #endif
114 static guint32 hdr_ethernet_proto;
116 /* Dummy IP header */
117 static gboolean hdr_ip;
118 static gboolean hdr_ipv6;
119 static gboolean have_hdr_ip_proto;
120 static guint8 hdr_ip_proto;
122 /* Destination and source addresses for IP header */
123 static guint32 hdr_ip_dest_addr;
124 static guint32 hdr_ip_src_addr;
125 static ws_in6_addr hdr_ipv6_dest_addr = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
126 static ws_in6_addr hdr_ipv6_src_addr = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
128 /* Dummy UDP header */
129 static gboolean hdr_udp;
130 static guint32 hdr_dest_port;
131 static guint32 hdr_src_port;
133 /* Dummy TCP header */
134 static gboolean hdr_tcp;
136 /* Dummy SCTP header */
137 static gboolean hdr_sctp;
138 static guint32 hdr_sctp_src;
139 static guint32 hdr_sctp_dest;
140 static guint32 hdr_sctp_tag;
142 /* Dummy DATA chunk header */
143 static gboolean hdr_data_chunk;
144 static guint32 hdr_data_chunk_tsn;
145 static guint16 hdr_data_chunk_sid;
146 static guint16 hdr_data_chunk_ssn;
147 static guint32 hdr_data_chunk_ppid;
149 /* Export PDU */
150 static gboolean hdr_export_pdu;
152 /*--- Local data -----------------------------------------------------------------*/
154 /* This is where we store the packet currently being built */
155 static guint32 max_offset = WTAP_MAX_PACKET_SIZE_STANDARD;
157 /* Time code of packet, derived from packet_preamble */
158 static int ts_fmt_iso;
160 /* Input file */
161 static char *input_filename;
162 static FILE *input_file;
163 /* Output file */
164 static char *output_filename;
166 static wtap_dumper* wdh;
168 /*----------------------------------------------------------------------
169 * Print usage string and exit
171 static void
172 print_usage (FILE *output)
174 fprintf(output,
175 "\n"
176 "Usage: text2pcap [options] <infile> <outfile>\n"
177 "\n"
178 "where <infile> specifies input filename (use - for standard input)\n"
179 " <outfile> specifies output filename (use - for standard output)\n"
180 "\n"
181 "Input:\n"
182 " -o hex|oct|dec|none parse offsets as (h)ex, (o)ctal, (d)ecimal, or (n)one;\n"
183 " default is hex.\n"
184 " -t <timefmt> treat the text before the packet as a date/time code;\n"
185 " <timefmt> is a format string supported by strptime,\n"
186 " with an optional %%f descriptor for fractional seconds.\n"
187 " Example: The time \"10:15:14.5476\" has the format code\n"
188 " \"%%H:%%M:%%S.%%f\"\n"
189 " The special format string ISO supports ISO-8601 times.\n"
190 " NOTE: Date/time fields from the current date/time are\n"
191 " used as the default for unspecified fields.\n"
192 " -D the text before the packet starts with an I or an O,\n"
193 " indicating that the packet is inbound or outbound.\n"
194 " This is used when generating dummy headers if the\n"
195 " output format supports it (e.g. pcapng).\n"
196 " -a enable ASCII text dump identification.\n"
197 " The start of the ASCII text dump can be identified\n"
198 " and excluded from the packet data, even if it looks\n"
199 " like a HEX dump.\n"
200 " NOTE: Do not enable it if the input file does not\n"
201 " contain the ASCII text dump.\n"
202 " -r <regex> enable regex mode. Scan the input using <regex>, a Perl\n"
203 " compatible regular expression matching a single packet.\n"
204 " Named capturing subgroups are used to identify fields:\n"
205 " <data> (mand.), and <time>, <dir>, and <seqno> (opt.)\n"
206 " The time field format is taken from the -t option\n"
207 " Example: -r '^(?<dir>[<>])\\s(?<time>\\d+:\\d\\d:\\d\\d.\\d+)\\s(?<data>[0-9a-fA-F]+)$'\n"
208 " could match a file with lines like\n"
209 " > 0:00:00.265620 a130368b000000080060\n"
210 " < 0:00:00.295459 a2010800000000000000000800000000\n"
211 " -b 2|8|16|64 encoding base (radix) of the packet data in regex mode\n"
212 " (def: 16: hexadecimal) No effect in hexdump mode.\n"
213 "\n"
214 "Output:\n"
215 " -F <capture type> set the output file type; default is pcapng.\n"
216 " an empty \"-F\" option will list the file types.\n"
217 " -E <encap type> set the output file encapsulation type; default is\n"
218 " ether (Ethernet). An empty \"-E\" option will list\n"
219 " the encapsulation types.\n"
220 " -l <typenum> set the output file encapsulation type via link-layer\n"
221 " type number; default is 1 (Ethernet). See\n"
222 " https://www.tcpdump.org/linktypes.html for a list of\n"
223 " numbers.\n"
224 " Example: -l 7 for ARCNet packets.\n"
225 " -m <max-packet> max packet length in output; default is %u\n"
226 " -N <intf-name> assign name to the interface in the pcapng file.\n"
227 "\n"
228 "Prepend dummy header:\n"
229 " -e <l3pid> prepend dummy Ethernet II header with specified L3PID\n"
230 " (in HEX).\n"
231 " Example: -e 0x806 to specify an ARP packet.\n"
232 " -i <proto> prepend dummy IP header with specified IP protocol\n"
233 " (in DECIMAL).\n"
234 " Automatically prepends Ethernet header as well if\n"
235 " link-layer type is Ethernet.\n"
236 " Example: -i 46\n"
237 " -4 <srcip>,<destip> prepend dummy IPv4 header with specified\n"
238 " dest and source address.\n"
239 " Example: -4 10.0.0.1,10.0.0.2\n"
240 " -6 <srcip>,<destip> prepend dummy IPv6 header with specified\n"
241 " dest and source address.\n"
242 " Example: -6 2001:db8::b3ff:fe1e:8329,2001:0db8:85a3::8a2e:0370:7334\n"
243 " -u <srcp>,<destp> prepend dummy UDP header with specified\n"
244 " source and destination ports (in DECIMAL).\n"
245 " Automatically prepends Ethernet & IP headers as well.\n"
246 " Example: -u 1000,69 to make the packets look like\n"
247 " TFTP/UDP packets.\n"
248 " -T <srcp>,<destp> prepend dummy TCP header with specified\n"
249 " source and destination ports (in DECIMAL).\n"
250 " Automatically prepends Ethernet & IP headers as well.\n"
251 " Example: -T 50,60\n"
252 " -s <srcp>,<dstp>,<tag> prepend dummy SCTP header with specified\n"
253 " source/dest ports and verification tag (in DECIMAL).\n"
254 " Automatically prepends Ethernet & IP headers as well.\n"
255 " Example: -s 30,40,34\n"
256 " -S <srcp>,<dstp>,<ppi> prepend dummy SCTP header with specified\n"
257 " source/dest ports and verification tag 0.\n"
258 " Automatically prepends a dummy SCTP DATA\n"
259 " chunk header with payload protocol identifier ppi.\n"
260 " Example: -S 30,40,34\n"
261 " -P <dissector> prepend EXPORTED_PDU header with specified dissector\n"
262 " as the payload DISSECTOR_NAME tag.\n"
263 " Automatically sets link type to Upper PDU Export.\n"
264 " EXPORTED_PDU payload defaults to \"data\" otherwise.\n"
265 "\n",
266 WTAP_MAX_PACKET_SIZE_STANDARD);
268 ws_log_print_usage(output);
270 fprintf(output, "\n"
271 "Miscellaneous:\n"
272 " -h, --help display this help and exit\n"
273 " -v, --version print version information and exit\n"
274 " -q don't report processed packet counts\n"
275 "");
279 * Set the hdr_ip_proto parameter, and set the flag indicate that the
280 * parameter has been specified.
282 * XXX - catch the case where two different options set it differently?
284 static void
285 set_hdr_ip_proto(guint8 ip_proto)
287 have_hdr_ip_proto = TRUE;
288 hdr_ip_proto = ip_proto;
291 static void
292 list_capture_types(void) {
293 GArray *writable_type_subtypes;
295 cmdarg_err("The available capture file types for the \"-F\" flag are:\n");
296 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
297 for (guint i = 0; i < writable_type_subtypes->len; i++) {
298 int ft = g_array_index(writable_type_subtypes, int, i);
299 fprintf(stderr, " %s - %s\n", wtap_file_type_subtype_name(ft),
300 wtap_file_type_subtype_description(ft));
302 g_array_free(writable_type_subtypes, TRUE);
305 struct string_elem {
306 const char *sstr; /* The short string */
307 const char *lstr; /* The long string */
310 static gint
311 string_nat_compare(gconstpointer a, gconstpointer b)
313 return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
314 ((const struct string_elem *)b)->sstr);
317 static void
318 string_elem_print(gpointer data, gpointer stream_ptr)
320 fprintf((FILE *) stream_ptr, " %s - %s\n",
321 ((struct string_elem *)data)->sstr,
322 ((struct string_elem *)data)->lstr);
325 static void
326 list_encap_types(void) {
327 int i;
328 struct string_elem *encaps;
329 GSList *list = NULL;
331 encaps = g_new(struct string_elem, wtap_get_num_encap_types());
332 cmdarg_err("The available encapsulation types for the \"-E\" flag are:\n");
333 for (i = 0; i < wtap_get_num_encap_types(); i++) {
334 /* Exclude wtap encapsulations that require a pseudo header,
335 * because we won't setup one from the text we import and
336 * wiretap doesn't allow us to write 'raw' frames
338 if (!wtap_encap_requires_phdr(i)) {
339 encaps[i].sstr = wtap_encap_name(i);
340 if (encaps[i].sstr != NULL) {
341 encaps[i].lstr = wtap_encap_description(i);
342 list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
346 g_slist_foreach(list, string_elem_print, stderr);
347 g_slist_free(list);
348 g_free(encaps);
351 static void
352 cleanup_dump_params(wtap_dump_params *params)
354 wtap_free_idb_info(params->idb_inf);
355 wtap_dump_params_cleanup(params);
358 /*----------------------------------------------------------------------
359 * Parse CLI options
361 static int
362 parse_options(int argc, char *argv[], text_import_info_t * const info, wtap_dump_params * const params)
364 int ret;
365 int c;
366 char *p;
367 static const struct ws_option long_options[] = {
368 {"help", ws_no_argument, NULL, 'h'},
369 {"version", ws_no_argument, NULL, 'v'},
370 {0, 0, 0, 0 }
372 const char *interface_name = NULL;
373 /* Link-layer type; see https://www.tcpdump.org/linktypes.html for details */
374 guint32 pcap_link_type = 1; /* Default is LINKTYPE_ETHERNET */
375 int file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_UNKNOWN;
376 int wtap_encap_type = WTAP_ENCAP_ETHERNET;
377 int err;
378 char* err_info;
379 GError* gerror = NULL;
380 GRegex* regex = NULL;
382 info->mode = TEXT_IMPORT_HEXDUMP;
383 info->hexdump.offset_type = OFFSET_HEX;
384 info->regex.encoding = ENCODING_PLAIN_HEX;
385 info->payload = "data";
387 /* Initialize the version information. */
388 ws_init_version_info("Text2pcap", NULL, NULL);
390 /* Scan CLI parameters */
391 while ((c = ws_getopt_long(argc, argv, "hqab:De:E:F:i:l:m:nN:o:u:P:r:s:S:t:T:v4:6:", long_options, NULL)) != -1) {
392 switch (c) {
393 case 'h':
394 show_help_header("Generate a capture file from an ASCII hexdump of packets.");
395 print_usage(stdout);
396 exit(0);
397 break;
398 case 'q': quiet = TRUE; break;
399 case 'a': info->hexdump.identify_ascii = TRUE; break;
400 case 'D': info->hexdump.has_direction = TRUE; break;
401 case 'l':
402 pcap_link_type = (guint32)strtol(ws_optarg, NULL, 0);
403 wtap_encap_type = wtap_pcap_encap_to_wtap_encap(pcap_link_type);
404 break;
405 case 'm': max_offset = (guint32)strtol(ws_optarg, NULL, 0); break;
406 case 'n': cmdarg_err("'-n' is deprecated; the output format already defaults to pcapng."); break;
407 case 'N': interface_name = ws_optarg; break;
408 case 'b':
410 guint8 radix;
411 if (!ws_strtou8(ws_optarg, NULL, &radix)) {
412 cmdarg_err("Bad argument for '-b': %s", ws_optarg);
413 print_usage(stderr);
414 return WS_EXIT_INVALID_OPTION;
416 switch (radix) {
417 case 2: info->regex.encoding = ENCODING_PLAIN_BIN; break;
418 case 8: info->regex.encoding = ENCODING_PLAIN_OCT; break;
419 case 16: info->regex.encoding = ENCODING_PLAIN_HEX; break;
420 case 64: info->regex.encoding = ENCODING_BASE64; break;
421 default:
422 cmdarg_err("Bad argument for '-b': %s", ws_optarg);
423 print_usage(stderr);
424 return WS_EXIT_INVALID_OPTION;
426 break;
429 case 'o':
430 if (ws_optarg[0] != 'h' && ws_optarg[0] != 'o' && ws_optarg[0] != 'd' && ws_optarg[0] != 'n') {
431 cmdarg_err("Bad argument for '-o': %s", ws_optarg);
432 print_usage(stderr);
433 return WS_EXIT_INVALID_OPTION;
435 switch (ws_optarg[0]) {
436 case 'o': info->hexdump.offset_type = OFFSET_OCT; break;
437 case 'h': info->hexdump.offset_type = OFFSET_HEX; break;
438 case 'd': info->hexdump.offset_type = OFFSET_DEC; break;
439 case 'n': info->hexdump.offset_type = OFFSET_NONE; break;
441 break;
443 case 'e':
444 hdr_ethernet = TRUE;
445 if (sscanf(ws_optarg, "%x", &hdr_ethernet_proto) < 1) {
446 cmdarg_err("Bad argument for '-e': %s", ws_optarg);
447 print_usage(stderr);
448 return WS_EXIT_INVALID_OPTION;
450 break;
452 case 'E':
453 wtap_encap_type = wtap_name_to_encap(ws_optarg);
454 if (wtap_encap_type < 0) {
455 cmdarg_err("\"%s\" isn't a valid encapsulation type", ws_optarg);
456 list_encap_types();
457 return WS_EXIT_INVALID_OPTION;
459 break;
461 case 'F':
462 file_type_subtype = wtap_name_to_file_type_subtype(ws_optarg);
463 if (file_type_subtype < 0) {
464 cmdarg_err("\"%s\" isn't a valid capture file type", ws_optarg);
465 list_capture_types();
466 return WS_EXIT_INVALID_OPTION;
468 break;
470 case 'i':
472 guint8 ip_proto;
473 if (!ws_strtou8(ws_optarg, NULL, &ip_proto)) {
474 cmdarg_err("Bad argument for '-i': %s", ws_optarg);
475 print_usage(stderr);
476 return WS_EXIT_INVALID_OPTION;
478 set_hdr_ip_proto(ip_proto);
479 break;
482 case 'P':
483 hdr_export_pdu = TRUE;
484 wtap_encap_type = WTAP_ENCAP_WIRESHARK_UPPER_PDU;
485 info->payload = ws_optarg;
486 break;
488 case 'r':
489 info->mode = TEXT_IMPORT_REGEX;
490 if (regex != NULL) {
491 /* XXX: Used the option twice. Should we warn? */
492 g_regex_unref(regex);
494 regex = g_regex_new(ws_optarg, G_REGEX_DUPNAMES | G_REGEX_OPTIMIZE | G_REGEX_MULTILINE, G_REGEX_MATCH_NOTEMPTY, &gerror);
495 if (gerror) {
496 cmdarg_err("%s", gerror->message);
497 g_error_free(gerror);
498 print_usage(stderr);
499 return WS_EXIT_INVALID_OPTION;
500 } else {
501 if (g_regex_get_string_number(regex, "data") == -1) {
502 cmdarg_err("Regex missing capturing group data (use (?<data>(...)) )");
503 g_regex_unref(regex);
504 print_usage(stderr);
505 return WS_EXIT_INVALID_OPTION;
508 break;
510 case 's':
511 hdr_sctp = TRUE;
512 hdr_data_chunk = FALSE;
513 hdr_tcp = FALSE;
514 hdr_udp = FALSE;
515 hdr_sctp_src = (guint32)strtol(ws_optarg, &p, 10);
516 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
517 cmdarg_err("Bad src port for '-%c'", c);
518 print_usage(stderr);
519 return WS_EXIT_INVALID_OPTION;
521 if (*p == '\0') {
522 cmdarg_err("No dest port specified for '-%c'", c);
523 print_usage(stderr);
524 return WS_EXIT_INVALID_OPTION;
526 p++;
527 ws_optarg = p;
528 hdr_sctp_dest = (guint32)strtol(ws_optarg, &p, 10);
529 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
530 cmdarg_err("Bad dest port for '-s'");
531 print_usage(stderr);
532 return WS_EXIT_INVALID_OPTION;
534 if (*p == '\0') {
535 cmdarg_err("No tag specified for '-%c'", c);
536 print_usage(stderr);
537 return WS_EXIT_INVALID_OPTION;
539 p++;
540 ws_optarg = p;
541 hdr_sctp_tag = (guint32)strtol(ws_optarg, &p, 10);
542 if (p == ws_optarg || *p != '\0') {
543 cmdarg_err("Bad tag for '-%c'", c);
544 print_usage(stderr);
545 return WS_EXIT_INVALID_OPTION;
548 set_hdr_ip_proto(132);
549 break;
551 case 'S':
552 hdr_sctp = TRUE;
553 hdr_data_chunk = TRUE;
554 hdr_tcp = FALSE;
555 hdr_udp = FALSE;
556 hdr_sctp_src = (guint32)strtol(ws_optarg, &p, 10);
557 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
558 cmdarg_err("Bad src port for '-%c'", c);
559 print_usage(stderr);
560 return WS_EXIT_INVALID_OPTION;
562 if (*p == '\0') {
563 cmdarg_err("No dest port specified for '-%c'", c);
564 print_usage(stderr);
565 return WS_EXIT_INVALID_OPTION;
567 p++;
568 ws_optarg = p;
569 hdr_sctp_dest = (guint32)strtol(ws_optarg, &p, 10);
570 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
571 cmdarg_err("Bad dest port for '-s'");
572 print_usage(stderr);
573 return WS_EXIT_INVALID_OPTION;
575 if (*p == '\0') {
576 cmdarg_err("No ppi specified for '-%c'", c);
577 print_usage(stderr);
578 return WS_EXIT_INVALID_OPTION;
580 p++;
581 ws_optarg = p;
582 hdr_data_chunk_ppid = (guint32)strtoul(ws_optarg, &p, 10);
583 if (p == ws_optarg || *p != '\0') {
584 cmdarg_err("Bad ppi for '-%c'", c);
585 print_usage(stderr);
586 return WS_EXIT_INVALID_OPTION;
589 set_hdr_ip_proto(132);
590 break;
592 case 't':
593 info->timestamp_format = ws_optarg;
594 if (!strcmp(ws_optarg, "ISO"))
595 ts_fmt_iso = 1;
596 break;
598 case 'u':
599 hdr_udp = TRUE;
600 hdr_tcp = FALSE;
601 hdr_sctp = FALSE;
602 hdr_data_chunk = FALSE;
603 hdr_src_port = (guint32)strtol(ws_optarg, &p, 10);
604 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
605 cmdarg_err("Bad src port for '-u'");
606 print_usage(stderr);
607 return WS_EXIT_INVALID_OPTION;
609 if (*p == '\0') {
610 cmdarg_err("No dest port specified for '-u'");
611 print_usage(stderr);
612 return WS_EXIT_INVALID_OPTION;
614 p++;
615 ws_optarg = p;
616 hdr_dest_port = (guint32)strtol(ws_optarg, &p, 10);
617 if (p == ws_optarg || *p != '\0') {
618 cmdarg_err("Bad dest port for '-u'");
619 print_usage(stderr);
620 return WS_EXIT_INVALID_OPTION;
622 set_hdr_ip_proto(17);
623 break;
625 case 'T':
626 hdr_tcp = TRUE;
627 hdr_udp = FALSE;
628 hdr_sctp = FALSE;
629 hdr_data_chunk = FALSE;
630 hdr_src_port = (guint32)strtol(ws_optarg, &p, 10);
631 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
632 cmdarg_err("Bad src port for '-T'");
633 print_usage(stderr);
634 return WS_EXIT_INVALID_OPTION;
636 if (*p == '\0') {
637 cmdarg_err("No dest port specified for '-u'");
638 print_usage(stderr);
639 return WS_EXIT_INVALID_OPTION;
641 p++;
642 ws_optarg = p;
643 hdr_dest_port = (guint32)strtol(ws_optarg, &p, 10);
644 if (p == ws_optarg || *p != '\0') {
645 cmdarg_err("Bad dest port for '-T'");
646 print_usage(stderr);
647 return WS_EXIT_INVALID_OPTION;
649 set_hdr_ip_proto(6);
650 break;
652 case 'v':
653 show_version();
654 exit(0);
655 break;
657 case '4':
658 case '6':
659 p = strchr(ws_optarg, ',');
661 if (!p) {
662 cmdarg_err("Bad source param addr for '-%c'", c);
663 print_usage(stderr);
664 return WS_EXIT_INVALID_OPTION;
667 *p = '\0';
668 if (c == '6')
670 hdr_ipv6 = TRUE;
671 hdr_ip = FALSE;
673 else
675 hdr_ip = TRUE;
676 hdr_ipv6 = FALSE;
678 hdr_ethernet = TRUE;
680 if (hdr_ipv6 == TRUE) {
681 if (!ws_inet_pton6(ws_optarg, &hdr_ipv6_src_addr)) {
682 cmdarg_err("Bad src addr -%c '%s'", c, p);
683 print_usage(stderr);
684 return WS_EXIT_INVALID_OPTION;
686 } else {
687 if (!ws_inet_pton4(ws_optarg, &hdr_ip_src_addr)) {
688 cmdarg_err("Bad src addr -%c '%s'", c, p);
689 print_usage(stderr);
690 return WS_EXIT_INVALID_OPTION;
694 p++;
695 if (*p == '\0') {
696 cmdarg_err("No dest addr specified for '-%c'", c);
697 print_usage(stderr);
698 return WS_EXIT_INVALID_OPTION;
701 if (hdr_ipv6 == TRUE) {
702 if (!ws_inet_pton6(p, &hdr_ipv6_dest_addr)) {
703 cmdarg_err("Bad dest addr for -%c '%s'", c, p);
704 print_usage(stderr);
705 return WS_EXIT_INVALID_OPTION;
707 } else {
708 if (!ws_inet_pton4(p, &hdr_ip_dest_addr)) {
709 cmdarg_err("Bad dest addr for -%c '%s'", c, p);
710 print_usage(stderr);
711 return WS_EXIT_INVALID_OPTION;
714 break;
717 case '?':
718 switch(ws_optopt) {
719 case 'E':
720 list_encap_types();
721 return WS_EXIT_INVALID_OPTION;
722 break;
723 case 'F':
724 list_capture_types();
725 return WS_EXIT_INVALID_OPTION;
726 break;
728 /* FALLTHROUGH */
730 default:
731 print_usage(stderr);
732 return WS_EXIT_INVALID_OPTION;
736 if (ws_optind >= argc || argc-ws_optind < 2) {
737 cmdarg_err("Must specify input and output filename");
738 print_usage(stderr);
739 return WS_EXIT_INVALID_OPTION;
742 if (max_offset > WTAP_MAX_PACKET_SIZE_STANDARD) {
743 cmdarg_err("Maximum packet length cannot be more than %d bytes",
744 WTAP_MAX_PACKET_SIZE_STANDARD);
745 return WS_EXIT_INVALID_OPTION;
748 /* Some validation */
750 if (info->mode == TEXT_IMPORT_REGEX) {
751 info->regex.format = regex;
752 /* need option for data encoding */
753 if (g_regex_get_string_number(regex, "dir") > -1) {
754 /* XXX: Add parameter(s?) to specify these? */
755 info->regex.in_indication = "iI<";
756 info->regex.out_indication = "oO>";
758 if (g_regex_get_string_number(regex, "time") > -1 && info->timestamp_format == NULL) {
759 cmdarg_err("Regex with <time> capturing group requires time format (-t)");
760 return WS_EXIT_INVALID_OPTION;
764 if (have_hdr_ip_proto && !(hdr_ip || hdr_ipv6)) {
766 * If we have an IP protocol to add to the header, but neither an
767 * IPv4 nor an IPv6 header was specified, add an IPv4 header.
769 hdr_ip = TRUE;
772 if (!have_hdr_ip_proto && (hdr_ip || hdr_ipv6)) {
773 /* if -4 or -6 option is specified without an IP protocol then fail */
774 cmdarg_err("IP protocol requires a next layer protocol number");
775 return WS_EXIT_INVALID_OPTION;
778 if ((hdr_tcp || hdr_udp || hdr_sctp) && !(hdr_ip || hdr_ipv6)) {
780 * If TCP (-T), UDP (-u) or SCTP (-s/-S) header options are specified
781 * but none of IPv4 (-4) or IPv6 (-6) options then add an IPv4 header
783 hdr_ip = TRUE;
786 if (hdr_export_pdu && wtap_encap_type != WTAP_ENCAP_WIRESHARK_UPPER_PDU) {
787 cmdarg_err("Export PDU (-P) requires WIRESHARK_UPPER_PDU link type (252)");
788 return WS_EXIT_INVALID_OPTION;
791 /* The other dummy headers require a IPv4 or IPv6 header. Allow
792 * encapsulation types of Ethernet (and add a Ethernet header in that
793 * case if we haven't already), or the appropriate raw IP types.
795 if (hdr_ip) {
796 switch (wtap_encap_type) {
798 case (WTAP_ENCAP_ETHERNET):
799 hdr_ethernet = TRUE;
800 hdr_ethernet_proto = 0x0800;
801 break;
803 case (WTAP_ENCAP_RAW_IP):
804 case (WTAP_ENCAP_RAW_IP4):
805 break;
807 default:
808 cmdarg_err("Dummy IPv4 header not supported with encapsulation %s (%s)", wtap_encap_description(wtap_encap_type), wtap_encap_name(wtap_encap_type));
809 return WS_EXIT_INVALID_OPTION;
811 } else if (hdr_ipv6) {
812 switch (wtap_encap_type) {
814 case (WTAP_ENCAP_ETHERNET):
815 hdr_ethernet = TRUE;
816 hdr_ethernet_proto = 0x86DD;
817 break;
819 case (WTAP_ENCAP_RAW_IP):
820 case (WTAP_ENCAP_RAW_IP6):
821 break;
823 default:
824 cmdarg_err("Dummy IPv6 header not supported with encapsulation %s (%s)", wtap_encap_description(wtap_encap_type), wtap_encap_name(wtap_encap_type));
825 return WS_EXIT_INVALID_OPTION;
829 if (strcmp(argv[ws_optind], "-") != 0) {
830 input_filename = argv[ws_optind];
831 if (info->mode == TEXT_IMPORT_REGEX) {
832 info->regex.import_text_GMappedFile = g_mapped_file_new(input_filename, TRUE, &gerror);
833 if (gerror) {
834 cmdarg_err("%s", gerror->message);
835 g_error_free(gerror);
836 return WS_EXIT_OPEN_ERROR;
838 } else {
839 input_file = ws_fopen(input_filename, "rb");
840 if (!input_file) {
841 open_failure_message(input_filename, errno, FALSE);
842 return WS_EXIT_OPEN_ERROR;
845 } else {
846 if (info->mode == TEXT_IMPORT_REGEX) {
847 /* text_import_regex requires a memory mapped file, so this likely
848 * won't work, unless the user has redirected a file (not a FIFO)
849 * to stdin, though that's pretty silly and unnecessary.
850 * XXX: We could read until EOF, write it to a temp file, and then
851 * mmap that (ugh)?
853 info->regex.import_text_GMappedFile = g_mapped_file_new_from_fd(0, TRUE, &gerror);
854 if (gerror) {
855 cmdarg_err("%s", gerror->message);
856 cmdarg_err("regex import requires memory-mapped I/O and cannot be used with terminals or pipes");
857 g_error_free(gerror);
858 return WS_EXIT_INVALID_OPTION;
861 input_filename = "Standard input";
862 input_file = stdin;
865 params->encap = wtap_encap_type;
866 params->snaplen = max_offset;
867 if (file_type_subtype == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN) {
868 file_type_subtype = wtap_pcapng_file_type_subtype();
870 /* Request nanosecond precision. Most file formats only support one time
871 * precision and ignore this parameter (and the related options in the
872 * generated IDB), but it affects pcapng.
874 params->tsprec = WTAP_TSPREC_NSEC;
875 if ((ret = text_import_pre_open(params, file_type_subtype, input_filename, interface_name)) != EXIT_SUCCESS) {
876 cleanup_dump_params(params);
877 return ret;
880 if (strcmp(argv[ws_optind+1], "-") != 0) {
881 /* Write to a file. Open the file. */
882 output_filename = argv[ws_optind+1];
883 wdh = wtap_dump_open(output_filename, file_type_subtype, WTAP_UNCOMPRESSED, params, &err, &err_info);
884 } else {
885 /* Write to the standard output. */
886 output_filename = "Standard output";
887 wdh = wtap_dump_open_stdout(file_type_subtype, WTAP_UNCOMPRESSED, params, &err, &err_info);
890 if (!wdh) {
891 cfile_dump_open_failure_message(output_filename, err, err_info,
892 file_type_subtype);
893 cleanup_dump_params(params);
894 return WS_EXIT_OPEN_ERROR;
897 info->import_text_filename = input_filename;
898 info->output_filename = output_filename;
899 info->hexdump.import_text_FILE = input_file;
901 info->encapsulation = wtap_encap_type;
902 info->wdh = wdh;
904 if (hdr_export_pdu) {
905 info->dummy_header_type = HEADER_EXPORT_PDU;
906 } else if (hdr_data_chunk) {
907 info->dummy_header_type = HEADER_SCTP_DATA;
908 } else if (hdr_sctp) {
909 info->dummy_header_type = HEADER_SCTP;
910 } else if (hdr_tcp) {
911 info->dummy_header_type = HEADER_TCP;
912 } else if (hdr_udp) {
913 info->dummy_header_type = HEADER_UDP;
914 } else if (hdr_ip) {
915 info->dummy_header_type = HEADER_IPV4;
916 } else if (hdr_ipv6) {
917 info->dummy_header_type = HEADER_IPV4;
918 } else if (hdr_ethernet) {
919 info->dummy_header_type = HEADER_ETH;
920 } else {
921 info->dummy_header_type = HEADER_NONE;
923 info->pid = hdr_ethernet_proto;
924 if (hdr_ip) {
925 info->ip_src_addr.ipv4 = hdr_ip_src_addr;
926 info->ip_dest_addr.ipv4 = hdr_ip_dest_addr;
927 } else if (hdr_ipv6) {
928 info->ipv6 = TRUE;
929 info->ip_src_addr.ipv6 = hdr_ipv6_src_addr;
930 info->ip_dest_addr.ipv6 = hdr_ipv6_dest_addr;
932 info->protocol = hdr_ip_proto;
933 if (hdr_sctp) {
934 info->src_port = hdr_sctp_src;
935 info->dst_port = hdr_sctp_dest;
936 } else {
937 info->src_port = hdr_src_port;
938 info->dst_port = hdr_dest_port;
940 info->tag = hdr_sctp_tag;
941 info->ppi = hdr_data_chunk_ppid;
943 info->max_frame_length = max_offset;
945 /* Display summary of our state */
946 if (!quiet) {
947 fprintf(stderr, "Input from: %s\n", input_filename);
948 fprintf(stderr, "Output to: %s\n", output_filename);
949 fprintf(stderr, "Output format: %s\n", wtap_file_type_subtype_name(file_type_subtype));
950 if (hdr_ethernet) fprintf(stderr, "Generate dummy Ethernet header: Protocol: 0x%0X\n",
951 hdr_ethernet_proto);
952 if (hdr_ip) fprintf(stderr, "Generate dummy IP header: Protocol: %u\n",
953 hdr_ip_proto);
954 if (hdr_ipv6) fprintf(stderr, "Generate dummy IPv6 header: Protocol: %u\n",
955 hdr_ip_proto);
956 if (hdr_udp) fprintf(stderr, "Generate dummy UDP header: Source port: %u. Dest port: %u\n",
957 hdr_src_port, hdr_dest_port);
958 if (hdr_tcp) fprintf(stderr, "Generate dummy TCP header: Source port: %u. Dest port: %u\n",
959 hdr_src_port, hdr_dest_port);
960 if (hdr_sctp) fprintf(stderr, "Generate dummy SCTP header: Source port: %u. Dest port: %u. Tag: %u\n",
961 hdr_sctp_src, hdr_sctp_dest, hdr_sctp_tag);
962 if (hdr_data_chunk) fprintf(stderr, "Generate dummy DATA chunk header: TSN: %u. SID: %u. SSN: %u. PPID: %u\n",
963 hdr_data_chunk_tsn, hdr_data_chunk_sid, hdr_data_chunk_ssn, hdr_data_chunk_ppid);
966 return EXIT_SUCCESS;
970 * General errors and warnings are reported with an console message
971 * in text2pcap.
973 static void
974 text2pcap_cmdarg_err(const char *msg_format, va_list ap)
976 fprintf(stderr, "text2pcap: ");
977 vfprintf(stderr, msg_format, ap);
978 fprintf(stderr, "\n");
982 * Report additional information for an error in command-line arguments.
984 static void
985 text2pcap_cmdarg_err_cont(const char *msg_format, va_list ap)
987 vfprintf(stderr, msg_format, ap);
988 fprintf(stderr, "\n");
992 main(int argc, char *argv[])
994 char *configuration_init_error;
995 static const struct report_message_routines text2pcap_report_routines = {
996 failure_message,
997 failure_message,
998 open_failure_message,
999 read_failure_message,
1000 write_failure_message,
1001 cfile_open_failure_message,
1002 cfile_dump_open_failure_message,
1003 cfile_read_failure_message,
1004 cfile_write_failure_message,
1005 cfile_close_failure_message
1007 int ret = EXIT_SUCCESS;
1008 text_import_info_t info;
1009 wtap_dump_params params;
1010 guint64 bytes_written;
1012 cmdarg_err_init(text2pcap_cmdarg_err, text2pcap_cmdarg_err_cont);
1014 /* Initialize log handler early so we can have proper logging during startup. */
1015 ws_log_init("text2pcap", vcmdarg_err);
1017 /* Early logging command-line initialization. */
1018 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
1020 ws_noisy("Finished log init and parsing command line log arguments");
1022 #ifdef _WIN32
1023 create_app_running_mutex();
1024 #endif /* _WIN32 */
1026 init_process_policies();
1029 * Make sure our plugin path is initialized for wtap_init.
1031 configuration_init_error = configuration_init(argv[0], NULL);
1032 if (configuration_init_error != NULL) {
1033 fprintf(stderr,
1034 "text2pcap: Can't get pathname of directory containing the text2pcap program: %s.\n",
1035 configuration_init_error);
1036 g_free(configuration_init_error);
1039 init_report_message("text2pcap", &text2pcap_report_routines);
1040 wtap_init(TRUE);
1042 memset(&info, 0, sizeof(info));
1043 wtap_dump_params_init(&params, NULL);
1044 if ((ret = parse_options(argc, argv, &info, &params)) != EXIT_SUCCESS) {
1045 goto clean_exit;
1048 ws_assert(input_file != NULL || info.regex.import_text_GMappedFile != NULL);
1049 ws_assert(wdh != NULL);
1051 ret = text_import(&info);
1053 if (ws_log_get_level() >= LOG_LEVEL_DEBUG)
1054 fprintf(stderr, "\n-------------------------\n");
1055 if (!quiet) {
1056 bytes_written = wtap_get_bytes_dumped(wdh);
1057 fprintf(stderr, "Read %u potential packet%s, wrote %u packet%s (%" PRIu64 " byte%s including overhead).\n",
1058 info.num_packets_read, plurality(info.num_packets_read, "", "s"),
1059 info.num_packets_written, plurality(info.num_packets_written, "", "s"),
1060 bytes_written, plurality(bytes_written, "", "s"));
1062 clean_exit:
1063 if (input_file) {
1064 fclose(input_file);
1066 if (info.regex.import_text_GMappedFile) {
1067 g_mapped_file_unref(info.regex.import_text_GMappedFile);
1069 if (info.regex.format) {
1070 g_regex_unref(info.regex.format);
1072 if (wdh) {
1073 int err;
1074 char *err_info;
1075 if (!wtap_dump_close(wdh, NULL, &err, &err_info)) {
1076 cfile_close_failure_message(output_filename, err, err_info);
1077 ret = 2;
1080 cleanup_dump_params(&params);
1081 return ret;
1085 * Editor modelines - https://www.wireshark.org/tools/modelines.html
1087 * Local variables:
1088 * c-basic-offset: 4
1089 * tab-width: 8
1090 * indent-tabs-mode: nil
1091 * End:
1093 * vi: set shiftwidth=4 tabstop=8 expandtab:
1094 * :indentSize=4:tabSize=8:noTabs=true: