epan/dissectors/pidl/drsuapi/drsuapi.cnf unicodePwd, ntPasswdHistory, Newer-Keys
[wireshark-sm.git] / text2pcap.c
blobd128019d0313c5b76e8a5cc6c360aecc52179971
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/clopts_common.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 #define LONGOPT_COMPRESS LONGOPT_BASE_APPLICATION+1
104 /*--- Options --------------------------------------------------------------------*/
107 /* Be quiet */
108 static bool quiet;
110 /* Dummy Ethernet header */
111 static bool hdr_ethernet;
112 #if 0
113 /* XXX: Maybe add custom Ethernet Address options? */
114 static uint8_t hdr_eth_dest_addr[6] = {0x0a, 0x02, 0x02, 0x02, 0x02, 0x02};
115 static uint8_t hdr_eth_src_addr[6] = {0x0a, 0x02, 0x02, 0x02, 0x02, 0x01};
116 #endif
117 static uint32_t hdr_ethernet_proto;
119 /* Dummy IP header */
120 static bool hdr_ip;
121 static bool hdr_ipv6;
122 static bool have_hdr_ip_proto;
123 static uint8_t hdr_ip_proto;
125 /* Destination and source addresses for IP header */
126 static uint32_t hdr_ip_dest_addr;
127 static uint32_t hdr_ip_src_addr;
128 static ws_in6_addr hdr_ipv6_dest_addr = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
129 static ws_in6_addr hdr_ipv6_src_addr = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
131 /* Dummy UDP header */
132 static bool hdr_udp;
133 static uint32_t hdr_dest_port;
134 static uint32_t hdr_src_port;
136 /* Dummy TCP header */
137 static bool hdr_tcp;
139 /* Dummy SCTP header */
140 static bool hdr_sctp;
141 static uint32_t hdr_sctp_src;
142 static uint32_t hdr_sctp_dest;
143 static uint32_t hdr_sctp_tag;
145 /* Dummy DATA chunk header */
146 static bool hdr_data_chunk;
147 static uint32_t hdr_data_chunk_tsn;
148 static uint16_t hdr_data_chunk_sid;
149 static uint16_t hdr_data_chunk_ssn;
150 static uint32_t hdr_data_chunk_ppid;
152 /* Export PDU */
153 static bool hdr_export_pdu;
155 /*--- Local data -----------------------------------------------------------------*/
157 /* This is where we store the packet currently being built */
158 static uint32_t max_offset = WTAP_MAX_PACKET_SIZE_STANDARD;
160 /* Time code of packet, derived from packet_preamble */
161 static int ts_fmt_iso;
163 /* Input file */
164 static char *input_filename;
165 static FILE *input_file;
166 /* Output file */
167 static char *output_filename;
169 static wtap_dumper* wdh;
171 /*----------------------------------------------------------------------
172 * Print usage string and exit
174 static void
175 print_usage (FILE *output)
177 fprintf(output,
178 "\n"
179 "Usage: text2pcap [options] <infile> <outfile>\n"
180 "\n"
181 "where <infile> specifies input filename (use - for standard input)\n"
182 " <outfile> specifies output filename (use - for standard output)\n"
183 "\n"
184 "Input:\n"
185 " -o hex|oct|dec|none parse offsets as (h)ex, (o)ctal, (d)ecimal, or (n)one;\n"
186 " default is hex.\n"
187 " -t <timefmt> treat the text before the packet as a date/time code;\n"
188 " <timefmt> is a format string supported by strptime,\n"
189 " with an optional %%f descriptor for fractional seconds.\n"
190 " Example: The time \"10:15:14.5476\" has the format code\n"
191 " \"%%H:%%M:%%S.%%f\"\n"
192 " The special format string ISO supports ISO-8601 times.\n"
193 " NOTE: Date/time fields from the current date/time are\n"
194 " used as the default for unspecified fields.\n"
195 " -D the text before the packet starts with an I or an O,\n"
196 " indicating that the packet is inbound or outbound.\n"
197 " This is used when generating dummy headers if the\n"
198 " output format supports it (e.g. pcapng).\n"
199 " -a enable ASCII text dump identification.\n"
200 " The start of the ASCII text dump can be identified\n"
201 " and excluded from the packet data, even if it looks\n"
202 " like a HEX dump.\n"
203 " NOTE: Do not enable it if the input file does not\n"
204 " contain the ASCII text dump.\n"
205 " -r <regex> enable regex mode. Scan the input using <regex>, a Perl\n"
206 " compatible regular expression matching a single packet.\n"
207 " Named capturing subgroups are used to identify fields:\n"
208 " <data> (mand.), and <time>, <dir>, and <seqno> (opt.)\n"
209 " The time field format is taken from the -t option\n"
210 " Example: -r '^(?<dir>[<>])\\s(?<time>\\d+:\\d\\d:\\d\\d.\\d+)\\s(?<data>[0-9a-fA-F]+)$'\n"
211 " could match a file with lines like\n"
212 " > 0:00:00.265620 a130368b000000080060\n"
213 " < 0:00:00.295459 a2010800000000000000000800000000\n"
214 " -b 2|8|16|64 encoding base (radix) of the packet data in regex mode\n"
215 " (def: 16: hexadecimal) No effect in hexdump mode.\n"
216 "\n"
217 "Output:\n"
218 " if the output file(s) have the .gz extension, then\n"
219 " gzip compression will be used.\n"
220 " -F <capture type> set the output file type; default is pcapng.\n"
221 " an empty \"-F\" option will list the file types.\n"
222 " -E <encap type> set the output file encapsulation type; default is\n"
223 " ether (Ethernet). An empty \"-E\" option will list\n"
224 " the encapsulation types.\n"
225 " -l <typenum> set the output file encapsulation type via link-layer\n"
226 " type number; default is 1 (Ethernet). See\n"
227 " https://www.tcpdump.org/linktypes.html for a list of\n"
228 " numbers.\n"
229 " Example: -l 7 for ARCNet packets.\n"
230 " -m <max-packet> max packet length in output; default is %u\n"
231 " -N <intf-name> assign name to the interface in the pcapng file.\n"
232 " --compress <type> Compress the output file using the type compression format.\n"
234 "\n"
235 "Prepend dummy header:\n"
236 " -e <ethertype> prepend dummy Ethernet II header with specified EtherType\n"
237 " (in HEX).\n"
238 " Example: -e 0x806 to specify an ARP packet.\n"
239 " -i <proto> prepend dummy IP header with specified IP protocol\n"
240 " (in DECIMAL).\n"
241 " Automatically prepends Ethernet header as well if\n"
242 " link-layer type is Ethernet.\n"
243 " Example: -i 46\n"
244 " -4 <srcip>,<destip> prepend dummy IPv4 header with specified\n"
245 " source and destination addresses.\n"
246 " Example: -4 10.0.0.1,10.0.0.2\n"
247 " -6 <srcip>,<destip> prepend dummy IPv6 header with specified\n"
248 " source and destination addresses.\n"
249 " Example: -6 2001:db8::b3ff:fe1e:8329,2001:0db8:85a3::8a2e:0370:7334\n"
250 " -u <srcp>,<destp> prepend dummy UDP header with specified\n"
251 " source and destination ports (in DECIMAL).\n"
252 " Automatically prepends Ethernet & IP headers as well.\n"
253 " Example: -u 1000,69 to make the packets look like\n"
254 " TFTP/UDP packets.\n"
255 " -T <srcp>,<destp> prepend dummy TCP header with specified\n"
256 " source and destination ports (in DECIMAL).\n"
257 " Automatically prepends Ethernet & IP headers as well.\n"
258 " Example: -T 50,60\n"
259 " -s <srcp>,<dstp>,<tag> prepend dummy SCTP header with specified\n"
260 " source/destination ports and verification tag (in DECIMAL).\n"
261 " Automatically prepends Ethernet & IP headers as well.\n"
262 " Example: -s 30,40,34\n"
263 " -S <srcp>,<dstp>,<ppi> prepend dummy SCTP header with specified\n"
264 " source/destination ports and verification tag 0.\n"
265 " Automatically prepends a dummy SCTP DATA\n"
266 " chunk header with payload protocol identifier ppi.\n"
267 " Example: -S 30,40,34\n"
268 " -P <dissector> prepend EXPORTED_PDU header with specified dissector\n"
269 " as the payload DISSECTOR_NAME tag.\n"
270 " Automatically sets link type to Upper PDU Export.\n"
271 " EXPORTED_PDU payload defaults to \"data\" otherwise.\n"
272 "\n",
273 WTAP_MAX_PACKET_SIZE_STANDARD);
275 ws_log_print_usage(output);
277 fprintf(output, "\n"
278 "Miscellaneous:\n"
279 " -h, --help display this help and exit\n"
280 " -v, --version print version information and exit\n"
281 " -q don't report processed packet counts\n"
282 "");
286 * Set the hdr_ip_proto parameter, and set the flag indicate that the
287 * parameter has been specified.
289 * XXX - catch the case where two different options set it differently?
291 static void
292 set_hdr_ip_proto(uint8_t ip_proto)
294 have_hdr_ip_proto = true;
295 hdr_ip_proto = ip_proto;
298 static void
299 list_capture_types(void) {
300 GArray *writable_type_subtypes;
302 cmdarg_err("The available capture file types for the \"-F\" flag are:\n");
303 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
304 for (unsigned i = 0; i < writable_type_subtypes->len; i++) {
305 int ft = g_array_index(writable_type_subtypes, int, i);
306 fprintf(stderr, " %s - %s\n", wtap_file_type_subtype_name(ft),
307 wtap_file_type_subtype_description(ft));
309 g_array_free(writable_type_subtypes, TRUE);
312 static void
313 list_output_compression_types(void) {
314 GSList *output_compression_types;
316 cmdarg_err("The available output compression type(s) for the \"--compress\" flag are:\n");
317 output_compression_types = wtap_get_all_output_compression_type_names_list();
318 for (GSList *compression_type = output_compression_types;
319 compression_type != NULL;
320 compression_type = g_slist_next(compression_type)) {
321 fprintf(stderr, " %s\n", (const char *)compression_type->data);
324 g_slist_free(output_compression_types);
327 struct string_elem {
328 const char *sstr; /* The short string */
329 const char *lstr; /* The long string */
332 static int
333 string_nat_compare(const void *a, const void *b)
335 return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
336 ((const struct string_elem *)b)->sstr);
339 static void
340 string_elem_print(void *data, void *stream_ptr)
342 fprintf((FILE *) stream_ptr, " %s - %s\n",
343 ((struct string_elem *)data)->sstr,
344 ((struct string_elem *)data)->lstr);
347 static void
348 list_encap_types(void) {
349 int i;
350 struct string_elem *encaps;
351 GSList *list = NULL;
353 encaps = g_new(struct string_elem, wtap_get_num_encap_types());
354 cmdarg_err("The available encapsulation types for the \"-E\" flag are:\n");
355 for (i = 0; i < wtap_get_num_encap_types(); i++) {
356 /* Exclude wtap encapsulations that require a pseudo header,
357 * because we won't setup one from the text we import and
358 * wiretap doesn't allow us to write 'raw' frames
360 if (!wtap_encap_requires_phdr(i)) {
361 encaps[i].sstr = wtap_encap_name(i);
362 if (encaps[i].sstr != NULL) {
363 encaps[i].lstr = wtap_encap_description(i);
364 list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
368 g_slist_foreach(list, string_elem_print, stderr);
369 g_slist_free(list);
370 g_free(encaps);
373 static void
374 cleanup_dump_params(wtap_dump_params *params)
376 wtap_free_idb_info(params->idb_inf);
377 wtap_dump_params_cleanup(params);
380 /*----------------------------------------------------------------------
381 * Parse CLI options
383 static int
384 parse_options(int argc, char *argv[], text_import_info_t * const info, wtap_dump_params * const params)
386 int ret;
387 int c;
388 char *p;
389 static const struct ws_option long_options[] = {
390 {"help", ws_no_argument, NULL, 'h'},
391 {"version", ws_no_argument, NULL, 'v'},
392 {"compress", ws_required_argument, NULL, LONGOPT_COMPRESS},
393 {0, 0, 0, 0 }
395 const char *interface_name = NULL;
396 /* Link-layer type; see https://www.tcpdump.org/linktypes.html for details */
397 uint32_t pcap_link_type = 1; /* Default is LINKTYPE_ETHERNET */
398 int file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_UNKNOWN;
399 int wtap_encap_type = WTAP_ENCAP_ETHERNET;
400 int err;
401 char* err_info;
402 wtap_compression_type compression_type = WTAP_UNKNOWN_COMPRESSION;
403 GError* gerror = NULL;
404 GRegex* regex = NULL;
406 info->mode = TEXT_IMPORT_HEXDUMP;
407 info->hexdump.offset_type = OFFSET_HEX;
408 info->regex.encoding = ENCODING_PLAIN_HEX;
409 info->payload = "data";
411 /* Initialize the version information. */
412 ws_init_version_info("Text2pcap", NULL, NULL);
414 /* Scan CLI parameters */
415 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) {
416 switch (c) {
417 case 'h':
418 show_help_header("Generate a capture file from an ASCII hexdump of packets.");
419 print_usage(stdout);
420 exit(0);
421 break;
422 case 'q': quiet = true; break;
423 case 'a': info->hexdump.identify_ascii = true; break;
424 case 'D': info->hexdump.has_direction = true; break;
425 case 'l':
426 pcap_link_type = (uint32_t)strtol(ws_optarg, NULL, 0);
427 wtap_encap_type = wtap_pcap_encap_to_wtap_encap(pcap_link_type);
428 break;
429 case 'm': max_offset = (uint32_t)strtol(ws_optarg, NULL, 0); break;
430 case 'n': cmdarg_err("'-n' is deprecated; the output format already defaults to pcapng."); break;
431 case 'N': interface_name = ws_optarg; break;
432 case 'b':
434 uint8_t radix;
435 if (!ws_strtou8(ws_optarg, NULL, &radix)) {
436 cmdarg_err("Bad argument for '-b': %s", ws_optarg);
437 print_usage(stderr);
438 return WS_EXIT_INVALID_OPTION;
440 switch (radix) {
441 case 2: info->regex.encoding = ENCODING_PLAIN_BIN; break;
442 case 8: info->regex.encoding = ENCODING_PLAIN_OCT; break;
443 case 16: info->regex.encoding = ENCODING_PLAIN_HEX; break;
444 case 64: info->regex.encoding = ENCODING_BASE64; break;
445 default:
446 cmdarg_err("Bad argument for '-b': %s", ws_optarg);
447 print_usage(stderr);
448 return WS_EXIT_INVALID_OPTION;
450 break;
453 case 'o':
454 if (ws_optarg[0] != 'h' && ws_optarg[0] != 'o' && ws_optarg[0] != 'd' && ws_optarg[0] != 'n') {
455 cmdarg_err("Bad argument for '-o': %s", ws_optarg);
456 print_usage(stderr);
457 return WS_EXIT_INVALID_OPTION;
459 switch (ws_optarg[0]) {
460 case 'o': info->hexdump.offset_type = OFFSET_OCT; break;
461 case 'h': info->hexdump.offset_type = OFFSET_HEX; break;
462 case 'd': info->hexdump.offset_type = OFFSET_DEC; break;
463 case 'n': info->hexdump.offset_type = OFFSET_NONE; break;
465 break;
467 case 'e':
468 hdr_ethernet = true;
469 if (sscanf(ws_optarg, "%x", &hdr_ethernet_proto) < 1) {
470 cmdarg_err("Bad argument for '-e': %s", ws_optarg);
471 print_usage(stderr);
472 return WS_EXIT_INVALID_OPTION;
474 break;
476 case 'E':
477 wtap_encap_type = wtap_name_to_encap(ws_optarg);
478 if (wtap_encap_type < 0) {
479 cmdarg_err("\"%s\" isn't a valid encapsulation type", ws_optarg);
480 list_encap_types();
481 return WS_EXIT_INVALID_OPTION;
483 break;
485 case 'F':
486 file_type_subtype = wtap_name_to_file_type_subtype(ws_optarg);
487 if (file_type_subtype < 0) {
488 cmdarg_err("\"%s\" isn't a valid capture file type", ws_optarg);
489 list_capture_types();
490 return WS_EXIT_INVALID_OPTION;
492 break;
494 case 'i':
496 uint8_t ip_proto;
497 if (!ws_strtou8(ws_optarg, NULL, &ip_proto)) {
498 cmdarg_err("Bad argument for '-i': %s", ws_optarg);
499 print_usage(stderr);
500 return WS_EXIT_INVALID_OPTION;
502 set_hdr_ip_proto(ip_proto);
503 break;
506 case 'P':
507 hdr_export_pdu = true;
508 wtap_encap_type = WTAP_ENCAP_WIRESHARK_UPPER_PDU;
509 info->payload = ws_optarg;
510 break;
512 case 'r':
513 info->mode = TEXT_IMPORT_REGEX;
514 if (regex != NULL) {
515 /* XXX: Used the option twice. Should we warn? */
516 g_regex_unref(regex);
518 regex = g_regex_new(ws_optarg, G_REGEX_DUPNAMES | G_REGEX_OPTIMIZE | G_REGEX_MULTILINE, G_REGEX_MATCH_NOTEMPTY, &gerror);
519 if (gerror) {
520 cmdarg_err("%s", gerror->message);
521 g_error_free(gerror);
522 print_usage(stderr);
523 return WS_EXIT_INVALID_OPTION;
524 } else {
525 if (g_regex_get_string_number(regex, "data") == -1) {
526 cmdarg_err("Regex missing capturing group data (use (?<data>(...)) )");
527 g_regex_unref(regex);
528 print_usage(stderr);
529 return WS_EXIT_INVALID_OPTION;
532 break;
534 case 's':
535 hdr_sctp = true;
536 hdr_data_chunk = false;
537 hdr_tcp = false;
538 hdr_udp = false;
539 hdr_sctp_src = (uint32_t)strtol(ws_optarg, &p, 10);
540 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
541 cmdarg_err("Bad src port for '-%c'", c);
542 print_usage(stderr);
543 return WS_EXIT_INVALID_OPTION;
545 if (*p == '\0') {
546 cmdarg_err("No dest port specified for '-%c'", c);
547 print_usage(stderr);
548 return WS_EXIT_INVALID_OPTION;
550 p++;
551 ws_optarg = p;
552 hdr_sctp_dest = (uint32_t)strtol(ws_optarg, &p, 10);
553 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
554 cmdarg_err("Bad dest port for '-s'");
555 print_usage(stderr);
556 return WS_EXIT_INVALID_OPTION;
558 if (*p == '\0') {
559 cmdarg_err("No tag specified for '-%c'", c);
560 print_usage(stderr);
561 return WS_EXIT_INVALID_OPTION;
563 p++;
564 ws_optarg = p;
565 hdr_sctp_tag = (uint32_t)strtol(ws_optarg, &p, 10);
566 if (p == ws_optarg || *p != '\0') {
567 cmdarg_err("Bad tag for '-%c'", c);
568 print_usage(stderr);
569 return WS_EXIT_INVALID_OPTION;
572 set_hdr_ip_proto(132);
573 break;
575 case 'S':
576 hdr_sctp = true;
577 hdr_data_chunk = true;
578 hdr_tcp = false;
579 hdr_udp = false;
580 hdr_sctp_src = (uint32_t)strtol(ws_optarg, &p, 10);
581 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
582 cmdarg_err("Bad src port for '-%c'", c);
583 print_usage(stderr);
584 return WS_EXIT_INVALID_OPTION;
586 if (*p == '\0') {
587 cmdarg_err("No dest port specified for '-%c'", c);
588 print_usage(stderr);
589 return WS_EXIT_INVALID_OPTION;
591 p++;
592 ws_optarg = p;
593 hdr_sctp_dest = (uint32_t)strtol(ws_optarg, &p, 10);
594 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
595 cmdarg_err("Bad dest port for '-s'");
596 print_usage(stderr);
597 return WS_EXIT_INVALID_OPTION;
599 if (*p == '\0') {
600 cmdarg_err("No ppi specified for '-%c'", c);
601 print_usage(stderr);
602 return WS_EXIT_INVALID_OPTION;
604 p++;
605 ws_optarg = p;
606 hdr_data_chunk_ppid = (uint32_t)strtoul(ws_optarg, &p, 10);
607 if (p == ws_optarg || *p != '\0') {
608 cmdarg_err("Bad ppi for '-%c'", c);
609 print_usage(stderr);
610 return WS_EXIT_INVALID_OPTION;
613 set_hdr_ip_proto(132);
614 break;
616 case 't':
617 info->timestamp_format = ws_optarg;
618 if (!strcmp(ws_optarg, "ISO"))
619 ts_fmt_iso = 1;
620 break;
622 case 'u':
623 hdr_udp = true;
624 hdr_tcp = false;
625 hdr_sctp = false;
626 hdr_data_chunk = false;
627 hdr_src_port = (uint32_t)strtol(ws_optarg, &p, 10);
628 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
629 cmdarg_err("Bad src port for '-u'");
630 print_usage(stderr);
631 return WS_EXIT_INVALID_OPTION;
633 if (*p == '\0') {
634 cmdarg_err("No dest port specified for '-u'");
635 print_usage(stderr);
636 return WS_EXIT_INVALID_OPTION;
638 p++;
639 ws_optarg = p;
640 hdr_dest_port = (uint32_t)strtol(ws_optarg, &p, 10);
641 if (p == ws_optarg || *p != '\0') {
642 cmdarg_err("Bad dest port for '-u'");
643 print_usage(stderr);
644 return WS_EXIT_INVALID_OPTION;
646 set_hdr_ip_proto(17);
647 break;
649 case 'T':
650 hdr_tcp = true;
651 hdr_udp = false;
652 hdr_sctp = false;
653 hdr_data_chunk = false;
654 hdr_src_port = (uint32_t)strtol(ws_optarg, &p, 10);
655 if (p == ws_optarg || (*p != ',' && *p != '\0')) {
656 cmdarg_err("Bad src port for '-T'");
657 print_usage(stderr);
658 return WS_EXIT_INVALID_OPTION;
660 if (*p == '\0') {
661 cmdarg_err("No dest port specified for '-u'");
662 print_usage(stderr);
663 return WS_EXIT_INVALID_OPTION;
665 p++;
666 ws_optarg = p;
667 hdr_dest_port = (uint32_t)strtol(ws_optarg, &p, 10);
668 if (p == ws_optarg || *p != '\0') {
669 cmdarg_err("Bad dest port for '-T'");
670 print_usage(stderr);
671 return WS_EXIT_INVALID_OPTION;
673 set_hdr_ip_proto(6);
674 break;
676 case 'v':
677 show_version();
678 exit(0);
679 break;
681 case '4':
682 case '6':
683 p = strchr(ws_optarg, ',');
685 if (!p) {
686 cmdarg_err("Bad source param addr for '-%c'", c);
687 print_usage(stderr);
688 return WS_EXIT_INVALID_OPTION;
691 *p = '\0';
692 if (c == '6')
694 hdr_ipv6 = true;
695 hdr_ip = false;
697 else
699 hdr_ip = true;
700 hdr_ipv6 = false;
702 hdr_ethernet = true;
704 if (hdr_ipv6 == true) {
705 if (!ws_inet_pton6(ws_optarg, &hdr_ipv6_src_addr)) {
706 cmdarg_err("Bad src addr -%c '%s'", c, p);
707 print_usage(stderr);
708 return WS_EXIT_INVALID_OPTION;
710 } else {
711 if (!ws_inet_pton4(ws_optarg, &hdr_ip_src_addr)) {
712 cmdarg_err("Bad src addr -%c '%s'", c, p);
713 print_usage(stderr);
714 return WS_EXIT_INVALID_OPTION;
718 p++;
719 if (*p == '\0') {
720 cmdarg_err("No dest addr specified for '-%c'", c);
721 print_usage(stderr);
722 return WS_EXIT_INVALID_OPTION;
725 if (hdr_ipv6 == true) {
726 if (!ws_inet_pton6(p, &hdr_ipv6_dest_addr)) {
727 cmdarg_err("Bad dest addr for -%c '%s'", c, p);
728 print_usage(stderr);
729 return WS_EXIT_INVALID_OPTION;
731 } else {
732 if (!ws_inet_pton4(p, &hdr_ip_dest_addr)) {
733 cmdarg_err("Bad dest addr for -%c '%s'", c, p);
734 print_usage(stderr);
735 return WS_EXIT_INVALID_OPTION;
738 break;
740 case LONGOPT_COMPRESS:
741 compression_type = wtap_name_to_compression_type(ws_optarg);
742 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
743 cmdarg_err("\"%s\" isn't a valid output compression mode",
744 ws_optarg);
745 list_output_compression_types();
746 return WS_EXIT_INVALID_OPTION;
748 break;
750 case '?':
751 switch(ws_optopt) {
752 case 'E':
753 list_encap_types();
754 return WS_EXIT_INVALID_OPTION;
755 case 'F':
756 list_capture_types();
757 return WS_EXIT_INVALID_OPTION;
758 case LONGOPT_COMPRESS:
759 list_output_compression_types();
760 return WS_EXIT_INVALID_OPTION;
762 /* FALLTHROUGH */
764 default:
765 print_usage(stderr);
766 return WS_EXIT_INVALID_OPTION;
770 if (ws_optind >= argc || argc-ws_optind < 2) {
771 cmdarg_err("Must specify input and output filename");
772 print_usage(stderr);
773 return WS_EXIT_INVALID_OPTION;
776 if (max_offset > WTAP_MAX_PACKET_SIZE_STANDARD) {
777 cmdarg_err("Maximum packet length cannot be more than %d bytes",
778 WTAP_MAX_PACKET_SIZE_STANDARD);
779 return WS_EXIT_INVALID_OPTION;
782 /* Some validation */
784 if (info->mode == TEXT_IMPORT_REGEX) {
785 info->regex.format = regex;
786 /* need option for data encoding */
787 if (g_regex_get_string_number(regex, "dir") > -1) {
788 /* XXX: Add parameter(s?) to specify these? */
789 info->regex.in_indication = "iI<";
790 info->regex.out_indication = "oO>";
792 if (g_regex_get_string_number(regex, "time") > -1 && info->timestamp_format == NULL) {
793 cmdarg_err("Regex with <time> capturing group requires time format (-t)");
794 return WS_EXIT_INVALID_OPTION;
798 if (have_hdr_ip_proto && !(hdr_ip || hdr_ipv6)) {
800 * If we have an IP protocol to add to the header, but neither an
801 * IPv4 nor an IPv6 header was specified, add an IPv4 header.
803 hdr_ip = true;
806 if (!have_hdr_ip_proto && (hdr_ip || hdr_ipv6)) {
807 /* if -4 or -6 option is specified without an IP protocol then fail */
808 cmdarg_err("IP protocol requires a next layer protocol number");
809 return WS_EXIT_INVALID_OPTION;
812 if ((hdr_tcp || hdr_udp || hdr_sctp) && !(hdr_ip || hdr_ipv6)) {
814 * If TCP (-T), UDP (-u) or SCTP (-s/-S) header options are specified
815 * but none of IPv4 (-4) or IPv6 (-6) options then add an IPv4 header
817 hdr_ip = true;
820 if (hdr_export_pdu && wtap_encap_type != WTAP_ENCAP_WIRESHARK_UPPER_PDU) {
821 cmdarg_err("Export PDU (-P) requires WIRESHARK_UPPER_PDU link type (252)");
822 return WS_EXIT_INVALID_OPTION;
825 /* The other dummy headers require a IPv4 or IPv6 header. Allow
826 * encapsulation types of Ethernet (and add a Ethernet header in that
827 * case if we haven't already), or the appropriate raw IP types.
829 if (hdr_ip) {
830 switch (wtap_encap_type) {
832 case (WTAP_ENCAP_ETHERNET):
833 hdr_ethernet = true;
834 hdr_ethernet_proto = 0x0800;
835 break;
837 case (WTAP_ENCAP_RAW_IP):
838 case (WTAP_ENCAP_RAW_IP4):
839 break;
841 default:
842 cmdarg_err("Dummy IPv4 header not supported with encapsulation %s (%s)", wtap_encap_description(wtap_encap_type), wtap_encap_name(wtap_encap_type));
843 return WS_EXIT_INVALID_OPTION;
845 } else if (hdr_ipv6) {
846 switch (wtap_encap_type) {
848 case (WTAP_ENCAP_ETHERNET):
849 hdr_ethernet = true;
850 hdr_ethernet_proto = 0x86DD;
851 break;
853 case (WTAP_ENCAP_RAW_IP):
854 case (WTAP_ENCAP_RAW_IP6):
855 break;
857 default:
858 cmdarg_err("Dummy IPv6 header not supported with encapsulation %s (%s)", wtap_encap_description(wtap_encap_type), wtap_encap_name(wtap_encap_type));
859 return WS_EXIT_INVALID_OPTION;
863 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
864 /* An explicitly specified compression type overrides filename
865 * magic. (Should we allow specifying "no" compression with, e.g.
866 * a ".gz" extension?) */
867 const char *sfx = strrchr(argv[ws_optind+1], '.');
868 if (sfx) {
869 compression_type = wtap_extension_to_compression_type(sfx + 1);
873 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
874 compression_type = WTAP_UNCOMPRESSED;
877 if (!wtap_can_write_compression_type(compression_type)) {
878 cmdarg_err("Output files can't be written as %s",
879 wtap_compression_type_description(compression_type));
880 return WS_EXIT_INVALID_OPTION;
883 if (compression_type != WTAP_UNCOMPRESSED && !wtap_dump_can_compress(file_type_subtype)) {
884 cmdarg_err("The file format %s can't be written to output compressed format",
885 wtap_file_type_subtype_name(file_type_subtype));
886 return WS_EXIT_INVALID_OPTION;
889 if (strcmp(argv[ws_optind], "-") != 0) {
890 input_filename = argv[ws_optind];
891 if (info->mode == TEXT_IMPORT_REGEX) {
892 info->regex.import_text_GMappedFile = g_mapped_file_new(input_filename, TRUE, &gerror);
893 if (gerror) {
894 cmdarg_err("%s", gerror->message);
895 g_error_free(gerror);
896 return WS_EXIT_OPEN_ERROR;
898 } else {
899 input_file = ws_fopen(input_filename, "rb");
900 if (!input_file) {
901 open_failure_message(input_filename, errno, false);
902 return WS_EXIT_OPEN_ERROR;
905 } else {
906 if (info->mode == TEXT_IMPORT_REGEX) {
907 /* text_import_regex requires a memory mapped file, so this likely
908 * won't work, unless the user has redirected a file (not a FIFO)
909 * to stdin, though that's pretty silly and unnecessary.
910 * XXX: We could read until EOF, write it to a temp file, and then
911 * mmap that (ugh)?
913 info->regex.import_text_GMappedFile = g_mapped_file_new_from_fd(0, TRUE, &gerror);
914 if (gerror) {
915 cmdarg_err("%s", gerror->message);
916 cmdarg_err("regex import requires memory-mapped I/O and cannot be used with terminals or pipes");
917 g_error_free(gerror);
918 return WS_EXIT_INVALID_OPTION;
921 input_filename = "Standard input";
922 input_file = stdin;
925 params->encap = wtap_encap_type;
926 params->snaplen = max_offset;
927 if (file_type_subtype == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN) {
928 file_type_subtype = wtap_pcapng_file_type_subtype();
930 /* Request nanosecond precision. Most file formats only support one time
931 * precision and ignore this parameter (and the related options in the
932 * generated IDB), but it affects pcapng.
934 params->tsprec = WTAP_TSPREC_NSEC;
935 if ((ret = text_import_pre_open(params, file_type_subtype, input_filename, interface_name)) != EXIT_SUCCESS) {
936 cleanup_dump_params(params);
937 return ret;
940 if (strcmp(argv[ws_optind+1], "-") != 0) {
941 /* Write to a file. Open the file. */
942 output_filename = argv[ws_optind+1];
943 wdh = wtap_dump_open(output_filename, file_type_subtype, compression_type, params, &err, &err_info);
944 } else {
945 /* Write to the standard output. */
946 output_filename = "Standard output";
947 wdh = wtap_dump_open_stdout(file_type_subtype, compression_type, params, &err, &err_info);
950 if (!wdh) {
951 cfile_dump_open_failure_message(output_filename, err, err_info,
952 file_type_subtype);
953 cleanup_dump_params(params);
954 return WS_EXIT_OPEN_ERROR;
957 info->import_text_filename = input_filename;
958 info->output_filename = output_filename;
959 info->hexdump.import_text_FILE = input_file;
961 info->encapsulation = wtap_encap_type;
962 info->wdh = wdh;
964 if (hdr_export_pdu) {
965 info->dummy_header_type = HEADER_EXPORT_PDU;
966 } else if (hdr_data_chunk) {
967 info->dummy_header_type = HEADER_SCTP_DATA;
968 } else if (hdr_sctp) {
969 info->dummy_header_type = HEADER_SCTP;
970 } else if (hdr_tcp) {
971 info->dummy_header_type = HEADER_TCP;
972 } else if (hdr_udp) {
973 info->dummy_header_type = HEADER_UDP;
974 } else if (hdr_ip) {
975 info->dummy_header_type = HEADER_IPV4;
976 } else if (hdr_ipv6) {
977 info->dummy_header_type = HEADER_IPV4;
978 } else if (hdr_ethernet) {
979 info->dummy_header_type = HEADER_ETH;
980 } else {
981 info->dummy_header_type = HEADER_NONE;
983 info->pid = hdr_ethernet_proto;
984 if (hdr_ip) {
985 info->ip_src_addr.ipv4 = hdr_ip_src_addr;
986 info->ip_dest_addr.ipv4 = hdr_ip_dest_addr;
987 } else if (hdr_ipv6) {
988 info->ipv6 = true;
989 info->ip_src_addr.ipv6 = hdr_ipv6_src_addr;
990 info->ip_dest_addr.ipv6 = hdr_ipv6_dest_addr;
992 info->protocol = hdr_ip_proto;
993 if (hdr_sctp) {
994 info->src_port = hdr_sctp_src;
995 info->dst_port = hdr_sctp_dest;
996 } else {
997 info->src_port = hdr_src_port;
998 info->dst_port = hdr_dest_port;
1000 info->tag = hdr_sctp_tag;
1001 info->ppi = hdr_data_chunk_ppid;
1003 info->max_frame_length = max_offset;
1005 /* Display summary of our state */
1006 if (!quiet) {
1007 fprintf(stderr, "Input from: %s\n", input_filename);
1008 fprintf(stderr, "Output to: %s\n", output_filename);
1009 fprintf(stderr, "Output format: %s\n", wtap_file_type_subtype_name(file_type_subtype));
1010 if (hdr_ethernet) fprintf(stderr, "Generate dummy Ethernet header: Protocol: 0x%0X\n",
1011 hdr_ethernet_proto);
1012 if (hdr_ip) fprintf(stderr, "Generate dummy IP header: Protocol: %u\n",
1013 hdr_ip_proto);
1014 if (hdr_ipv6) fprintf(stderr, "Generate dummy IPv6 header: Protocol: %u\n",
1015 hdr_ip_proto);
1016 if (hdr_udp) fprintf(stderr, "Generate dummy UDP header: Source port: %u. Dest port: %u\n",
1017 hdr_src_port, hdr_dest_port);
1018 if (hdr_tcp) fprintf(stderr, "Generate dummy TCP header: Source port: %u. Dest port: %u\n",
1019 hdr_src_port, hdr_dest_port);
1020 if (hdr_sctp) fprintf(stderr, "Generate dummy SCTP header: Source port: %u. Dest port: %u. Tag: %u\n",
1021 hdr_sctp_src, hdr_sctp_dest, hdr_sctp_tag);
1022 if (hdr_data_chunk) fprintf(stderr, "Generate dummy DATA chunk header: TSN: %u. SID: %u. SSN: %u. PPID: %u\n",
1023 hdr_data_chunk_tsn, hdr_data_chunk_sid, hdr_data_chunk_ssn, hdr_data_chunk_ppid);
1026 return EXIT_SUCCESS;
1030 * General errors and warnings are reported with an console message
1031 * in text2pcap.
1033 static void
1034 text2pcap_cmdarg_err(const char *msg_format, va_list ap)
1036 fprintf(stderr, "text2pcap: ");
1037 vfprintf(stderr, msg_format, ap);
1038 fprintf(stderr, "\n");
1042 * Report additional information for an error in command-line arguments.
1044 static void
1045 text2pcap_cmdarg_err_cont(const char *msg_format, va_list ap)
1047 vfprintf(stderr, msg_format, ap);
1048 fprintf(stderr, "\n");
1052 main(int argc, char *argv[])
1054 char *configuration_init_error;
1055 int ret = EXIT_SUCCESS;
1056 text_import_info_t info;
1057 wtap_dump_params params;
1058 uint64_t bytes_written;
1060 cmdarg_err_init(text2pcap_cmdarg_err, text2pcap_cmdarg_err_cont);
1062 /* Initialize log handler early so we can have proper logging during startup. */
1063 ws_log_init("text2pcap", vcmdarg_err);
1065 /* Early logging command-line initialization. */
1066 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
1068 ws_noisy("Finished log init and parsing command line log arguments");
1070 #ifdef _WIN32
1071 create_app_running_mutex();
1072 #endif /* _WIN32 */
1074 init_process_policies();
1077 * Make sure our plugin path is initialized for wtap_init.
1079 configuration_init_error = configuration_init(argv[0], NULL);
1080 if (configuration_init_error != NULL) {
1081 cmdarg_err("Can't get pathname of directory containing the text2pcap program: %s.",
1082 configuration_init_error);
1083 g_free(configuration_init_error);
1086 init_report_failure_message("text2pcap");
1087 wtap_init(true);
1089 memset(&info, 0, sizeof(info));
1090 wtap_dump_params_init(&params, NULL);
1091 if ((ret = parse_options(argc, argv, &info, &params)) != EXIT_SUCCESS) {
1092 goto clean_exit;
1095 ws_assert(input_file != NULL || info.regex.import_text_GMappedFile != NULL);
1096 ws_assert(wdh != NULL);
1098 ret = text_import(&info);
1100 if (ws_log_get_level() >= LOG_LEVEL_DEBUG)
1101 fprintf(stderr, "\n-------------------------\n");
1102 if (!quiet) {
1103 bytes_written = wtap_get_bytes_dumped(wdh);
1104 fprintf(stderr, "Read %u potential packet%s, wrote %u packet%s (%" PRIu64 " byte%s including overhead).\n",
1105 info.num_packets_read, plurality(info.num_packets_read, "", "s"),
1106 info.num_packets_written, plurality(info.num_packets_written, "", "s"),
1107 bytes_written, plurality(bytes_written, "", "s"));
1109 clean_exit:
1110 if (input_file) {
1111 fclose(input_file);
1113 if (info.regex.import_text_GMappedFile) {
1114 g_mapped_file_unref(info.regex.import_text_GMappedFile);
1116 if (info.regex.format) {
1117 g_regex_unref(info.regex.format);
1119 if (wdh) {
1120 int err;
1121 char *err_info;
1122 if (!wtap_dump_close(wdh, NULL, &err, &err_info)) {
1123 cfile_close_failure_message(output_filename, err, err_info);
1124 ret = 2;
1127 cleanup_dump_params(&params);
1128 return ret;
1132 * Editor modelines - https://www.wireshark.org/tools/modelines.html
1134 * Local variables:
1135 * c-basic-offset: 4
1136 * tab-width: 8
1137 * indent-tabs-mode: nil
1138 * End:
1140 * vi: set shiftwidth=4 tabstop=8 expandtab:
1141 * :indentSize=4:tabSize=8:noTabs=true: