-
Notifications
You must be signed in to change notification settings - Fork 0
/
rawshark.c
1524 lines (1332 loc) · 49.3 KB
/
rawshark.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* rawshark.c
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* Rawshark - Raw field extractor by Gerald Combs <[email protected]>
* and Loris Degioanni <[email protected]>
* Based on TShark, by Gilbert Ramirez <[email protected]> and Guy Harris
* <[email protected]>.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* Rawshark does the following:
* - Opens a specified file or named pipe
* - Applies a specfied DLT or "decode as" encapsulation
* - Reads frames prepended with a libpcap packet header.
* - Prints a status line, followed by fields from a specified list.
*/
#include <config.h>
#define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <limits.h>
#ifndef _WIN32
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include <errno.h>
#include <wsutil/ws_getopt.h>
#include <glib.h>
#include <epan/epan.h>
#include <ui/cmdarg_err.h>
#include <ui/exit_codes.h>
#include <wsutil/filesystem.h>
#include <wsutil/file_util.h>
#include <wsutil/socket.h>
#include <wsutil/plugins.h>
#include <wsutil/privileges.h>
#include <wsutil/report_message.h>
#include <wsutil/please_report_bug.h>
#include <wsutil/wslog.h>
#include <ui/clopts_common.h>
#ifdef _WIN32
#include <wsutil/unicode-utils.h>
#endif
#include "globals.h"
#include <epan/packet.h>
#include <epan/ftypes/ftypes.h>
#include "file.h"
#include "frame_tvbuff.h"
#include <epan/disabled_protos.h>
#include <epan/prefs.h>
#include <epan/column.h>
#include <epan/print.h>
#include <epan/addr_resolv.h>
#ifdef HAVE_LIBPCAP
#include "ui/capture_ui_utils.h"
#endif
#include "ui/util.h"
#include "ui/dissect_opts.h"
#include "ui/failure_message.h"
#include <epan/epan_dissect.h>
#include <epan/stat_tap_ui.h>
#include <epan/timestamp.h>
#include "epan/column-utils.h"
#include "epan/proto.h"
#include <epan/tap.h>
#include <wiretap/wtap.h>
#include <wiretap/libpcap.h>
#include <wiretap/pcap-encap.h>
#include <cli_main.h>
#include <ui/version_info.h>
#include "capture/capture-pcap-util.h"
#ifdef HAVE_LIBPCAP
#include <setjmp.h>
#ifdef _WIN32
#include "capture/capture-wpcap.h"
#endif /* _WIN32 */
#endif /* HAVE_LIBPCAP */
#if 0
/*
* This is the template for the decode as option; it is shared between the
* various functions that output the usage for this parameter.
*/
static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
#endif
/* Additional exit codes */
#define INVALID_DFILTER 2
#define FORMAT_ERROR 2
capture_file cfile;
static guint32 cum_bytes;
static frame_data ref_frame;
static frame_data prev_dis_frame;
static frame_data prev_cap_frame;
/*
* The way the packet decode is to be written.
*/
typedef enum {
WRITE_TEXT, /* summary or detail text */
WRITE_XML /* PDML or PSML */
/* Add CSV and the like here */
} output_action_e;
static gboolean line_buffered;
static print_format_e print_format = PR_FMT_TEXT;
static gboolean want_pcap_pkthdr;
cf_status_t raw_cf_open(capture_file *cf, const char *fname);
static gboolean load_cap_file(capture_file *cf);
static gboolean process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset,
wtap_rec *rec, Buffer *buf);
static void show_print_file_io_error(int err);
static void rawshark_cmdarg_err(const char *fmt, va_list ap);
static void rawshark_cmdarg_err_cont(const char *fmt, va_list ap);
static void protocolinfo_init(char *field);
static gboolean parse_field_string_format(char *format);
typedef enum {
SF_NONE, /* No format (placeholder) */
SF_NAME, /* %D Field name / description */
SF_NUMVAL, /* %N Numeric value */
SF_STRVAL /* %S String value */
} string_fmt_e;
typedef struct string_fmt_s {
gchar *plain;
string_fmt_e format; /* Valid if plain is NULL */
} string_fmt_t;
int n_rfilters;
int n_rfcodes;
dfilter_t *rfcodes[64];
int n_rfieldfilters;
dfilter_t *rfieldfcodes[64];
int fd;
int encap;
GPtrArray *string_fmts;
static void
print_usage(FILE *output)
{
fprintf(output, "\n");
fprintf(output, "Usage: rawshark [options] ...\n");
fprintf(output, "\n");
fprintf(output, "Input file:\n");
fprintf(output, " -r <infile> set the pipe or file name to read from\n");
fprintf(output, "\n");
fprintf(output, "Processing:\n");
fprintf(output, " -d <encap:linktype>|<proto:protoname>\n");
fprintf(output, " packet encapsulation or protocol\n");
fprintf(output, " -F <field> field to display\n");
#ifndef _WIN32
fprintf(output, " -m virtual memory limit, in bytes\n");
#endif
fprintf(output, " -n disable all name resolution (def: all enabled)\n");
fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtdv\"\n");
fprintf(output, " -p use the system's packet header format\n");
fprintf(output, " (which may have 64-bit timestamps)\n");
fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
fprintf(output, " -s skip PCAP header on input\n");
fprintf(output, "\n");
fprintf(output, "Output:\n");
fprintf(output, " -l flush output after each packet\n");
fprintf(output, " -S format string for fields\n");
fprintf(output, " (%%D - name, %%S - stringval, %%N numval)\n");
fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
fprintf(output, "\n");
ws_log_print_usage(output);
fprintf(output, "\n");
fprintf(output, "\n");
fprintf(output, "Miscellaneous:\n");
fprintf(output, " -h display this help and exit\n");
fprintf(output, " -o <name>:<value> ... override preference setting\n");
fprintf(output, " -v display version info and exit\n");
}
/**
* Open a pipe for raw input. This is a stripped-down version of
* pcap_loop.c:cap_pipe_open_live().
* We check if "pipe_name" is "-" (stdin) or a FIFO, and open it.
* @param pipe_name The name of the pipe or FIFO.
* @return A POSIX file descriptor on success, or -1 on failure.
*/
static int
raw_pipe_open(const char *pipe_name)
{
#ifndef _WIN32
ws_statb64 pipe_stat;
#else
char *pncopy, *pos = NULL;
DWORD err;
wchar_t *err_str;
HANDLE hPipe = NULL;
#endif
int rfd;
ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, "open_raw_pipe: %s", pipe_name);
/*
* XXX Rawshark blocks until we return
*/
if (strcmp(pipe_name, "-") == 0) {
rfd = 0; /* read from stdin */
#ifdef _WIN32
/*
* This is needed to set the stdin pipe into binary mode, otherwise
* CR/LF are mangled...
*/
_setmode(0, _O_BINARY);
#endif /* _WIN32 */
} else {
#ifndef _WIN32
if (ws_stat64(pipe_name, &pipe_stat) < 0) {
fprintf(stderr, "rawshark: The pipe %s could not be checked: %s\n",
pipe_name, g_strerror(errno));
return -1;
}
if (! S_ISFIFO(pipe_stat.st_mode)) {
if (S_ISCHR(pipe_stat.st_mode)) {
/*
* Assume the user specified an interface on a system where
* interfaces are in /dev. Pretend we haven't seen it.
*/
} else
{
fprintf(stderr, "rawshark: \"%s\" is neither an interface nor a pipe\n",
pipe_name);
}
return -1;
}
rfd = ws_open(pipe_name, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
if (rfd == -1) {
fprintf(stderr, "rawshark: \"%s\" could not be opened: %s\n",
pipe_name, g_strerror(errno));
return -1;
}
#else /* _WIN32 */
#define PIPE_STR "\\pipe\\"
/* Under Windows, named pipes _must_ have the form
* "\\<server>\pipe\<pipe_name>". <server> may be "." for localhost.
*/
pncopy = g_strdup(pipe_name);
if (strstr(pncopy, "\\\\") == pncopy) {
pos = strchr(pncopy + 3, '\\');
if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
pos = NULL;
}
g_free(pncopy);
if (!pos) {
fprintf(stderr, "rawshark: \"%s\" is neither an interface nor a pipe\n",
pipe_name);
return -1;
}
/* Wait for the pipe to appear */
while (1) {
hPipe = CreateFile(utf_8to16(pipe_name), GENERIC_READ, 0, NULL,
OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE)
break;
err = GetLastError();
if (err != ERROR_PIPE_BUSY) {
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, err, 0, (LPTSTR) &err_str, 0, NULL);
fprintf(stderr, "rawshark: \"%s\" could not be opened: %s (error %lu)\n",
pipe_name, utf_16to8(err_str), err);
LocalFree(err_str);
return -1;
}
if (!WaitNamedPipe(utf_8to16(pipe_name), 30 * 1000)) {
err = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, err, 0, (LPTSTR) &err_str, 0, NULL);
fprintf(stderr, "rawshark: \"%s\" could not be waited for: %s (error %lu)\n",
pipe_name, utf_16to8(err_str), err);
LocalFree(err_str);
return -1;
}
}
rfd = _open_osfhandle((intptr_t) hPipe, _O_RDONLY);
if (rfd == -1) {
fprintf(stderr, "rawshark: \"%s\" could not be opened: %s\n",
pipe_name, g_strerror(errno));
return -1;
}
#endif /* _WIN32 */
}
return rfd;
}
/**
* Parse a link-type argument of the form "encap:<pcap linktype>" or
* "proto:<proto name>". "Pcap linktype" must be a name conforming to
* pcap_datalink_name_to_val() or an integer; the integer should be
* a LINKTYPE_ value supported by Wiretap. "Proto name" must be
* a protocol name, e.g. "http".
*/
static gboolean
set_link_type(const char *lt_arg) {
char *spec_ptr = strchr(lt_arg, ':');
char *p;
int dlt_val;
long val;
dissector_handle_t dhandle;
GString *pref_str;
char *errmsg = NULL;
if (!spec_ptr)
return FALSE;
spec_ptr++;
if (strncmp(lt_arg, "encap:", strlen("encap:")) == 0) {
dlt_val = linktype_name_to_val(spec_ptr);
if (dlt_val == -1) {
errno = 0;
val = strtol(spec_ptr, &p, 10);
if (p == spec_ptr || *p != '\0' || errno != 0 || val > INT_MAX) {
return FALSE;
}
dlt_val = (int)val;
}
/*
* In those cases where a given link-layer header type
* has different LINKTYPE_ and DLT_ values, linktype_name_to_val()
* will return the OS's DLT_ value for that link-layer header
* type, not its OS-independent LINKTYPE_ value.
*
* On a given OS, wtap_pcap_encap_to_wtap_encap() should
* be able to map either LINKTYPE_ values or DLT_ values
* for the OS to the appropriate Wiretap encapsulation.
*/
encap = wtap_pcap_encap_to_wtap_encap(dlt_val);
if (encap == WTAP_ENCAP_UNKNOWN) {
return FALSE;
}
return TRUE;
} else if (strncmp(lt_arg, "proto:", strlen("proto:")) == 0) {
dhandle = find_dissector(spec_ptr);
if (dhandle) {
encap = WTAP_ENCAP_USER0;
pref_str = g_string_new("uat:user_dlts:");
/* This must match the format used in the user_dlts file */
g_string_append_printf(pref_str,
"\"User 0 (DLT=147)\",\"%s\",\"0\",\"\",\"0\",\"\"",
spec_ptr);
if (prefs_set_pref(pref_str->str, &errmsg) != PREFS_SET_OK) {
g_string_free(pref_str, TRUE);
g_free(errmsg);
return FALSE;
}
g_string_free(pref_str, TRUE);
return TRUE;
}
}
return FALSE;
}
int
main(int argc, char *argv[])
{
char *err_msg;
int opt, i;
df_error_t *df_err;
#ifndef _WIN32
struct rlimit limit;
#endif /* !_WIN32 */
gchar *pipe_name = NULL;
gchar *rfilters[64];
e_prefs *prefs_p;
char badopt;
GPtrArray *disp_fields = g_ptr_array_new();
guint fc;
gboolean skip_pcap_header = FALSE;
int ret = EXIT_SUCCESS;
static const struct ws_option long_options[] = {
{"help", ws_no_argument, NULL, 'h'},
{"version", ws_no_argument, NULL, 'v'},
{0, 0, 0, 0 }
};
#define OPTSTRING_INIT "d:F:hlm:nN:o:pr:R:sS:t:v"
static const char optstring[] = OPTSTRING_INIT;
static const struct report_message_routines rawshark_report_routines = {
failure_message,
failure_message,
open_failure_message,
read_failure_message,
write_failure_message,
cfile_open_failure_message,
cfile_dump_open_failure_message,
cfile_read_failure_message,
cfile_write_failure_message,
cfile_close_failure_message
};
/*
* Set the C-language locale to the native environment and set the
* code page to UTF-8 on Windows.
*/
#ifdef _WIN32
setlocale(LC_ALL, ".UTF-8");
#else
setlocale(LC_ALL, "");
#endif
cmdarg_err_init(rawshark_cmdarg_err, rawshark_cmdarg_err_cont);
/* Initialize log handler early so we can have proper logging during startup. */
ws_log_init("rawshark", vcmdarg_err);
/* Early logging command-line initialization. */
ws_log_parse_args(&argc, argv, vcmdarg_err, INVALID_OPTION);
ws_noisy("Finished log init and parsing command line log arguments");
/* Initialize the version information. */
ws_init_version_info("Rawshark",
epan_gather_compile_info,
NULL);
#ifdef _WIN32
create_app_running_mutex();
#endif /* _WIN32 */
/*
* Get credential information for later use.
*/
init_process_policies();
/*
* Clear the filters arrays
*/
memset(rfilters, 0, sizeof(rfilters));
memset(rfcodes, 0, sizeof(rfcodes));
n_rfilters = 0;
n_rfcodes = 0;
/*
* Initialize our string format
*/
string_fmts = g_ptr_array_new();
/*
* Attempt to get the pathname of the directory containing the
* executable file.
*/
err_msg = configuration_init(argv[0], NULL);
if (err_msg != NULL) {
fprintf(stderr, "rawshark: Can't get pathname of rawshark program: %s.\n",
err_msg);
}
init_report_message("rawshark", &rawshark_report_routines);
timestamp_set_type(TS_RELATIVE);
timestamp_set_precision(TS_PREC_AUTO);
timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
/*
* XXX - is this necessary, given that we're not reading a
* regular capture file, we're reading rawshark's packet
* stream format?
*
* If it is, note that libwiretap must be initialized before
* libwireshark is, so that dissection-time handlers for
* file-type-dependent blocks can register using the file
* type/subtype value for the file type.
*/
wtap_init(FALSE);
/* Register all dissectors; we must do this before checking for the
"-G" flag, as the "-G" flag dumps information registered by the
dissectors, and we must do it before we read the preferences, in
case any dissectors register preferences. */
if (!epan_init(NULL, NULL, TRUE)) {
ret = INIT_FAILED;
goto clean_exit;
}
/* Load libwireshark settings from the current profile. */
prefs_p = epan_load_settings();
#ifdef _WIN32
ws_init_dll_search_path();
/* Load Wpcap, if possible */
load_wpcap();
#endif
cap_file_init(&cfile);
/* Print format defaults to this. */
print_format = PR_FMT_TEXT;
/* Initialize our encapsulation type */
encap = WTAP_ENCAP_UNKNOWN;
/* Now get our args */
/* XXX - We should probably have an option to dump libpcap link types */
while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
switch (opt) {
case 'd': /* Payload type */
if (!set_link_type(ws_optarg)) {
cmdarg_err("Invalid link type or protocol \"%s\"", ws_optarg);
ret = INVALID_OPTION;
goto clean_exit;
}
break;
case 'F': /* Read field to display */
g_ptr_array_add(disp_fields, g_strdup(ws_optarg));
break;
case 'h': /* Print help and exit */
show_help_header("Dump and analyze network traffic.");
print_usage(stdout);
goto clean_exit;
break;
case 'l': /* "Line-buffer" standard output */
/* This isn't line-buffering, strictly speaking, it's just
flushing the standard output after the information for
each packet is printed; however, that should be good
enough for all the purposes to which "-l" is put (and
is probably actually better for "-V", as it does fewer
writes).
See the comment in "process_packet()" for an explanation of
why we do that, and why we don't just use "setvbuf()" to
make the standard output line-buffered (short version: in
Windows, "line-buffered" is the same as "fully-buffered",
and the output buffer is only flushed when it fills up). */
line_buffered = TRUE;
break;
#ifndef _WIN32
case 'm':
limit.rlim_cur = get_positive_int(ws_optarg, "memory limit");
limit.rlim_max = get_positive_int(ws_optarg, "memory limit");
if(setrlimit(RLIMIT_AS, &limit) != 0) {
cmdarg_err("setrlimit() returned error");
ret = INVALID_OPTION;
goto clean_exit;
}
break;
#endif
case 'n': /* No name resolution */
disable_name_resolution();
break;
case 'N': /* Select what types of addresses/port #s to resolve */
badopt = string_to_name_resolve(ws_optarg, &gbl_resolv_flags);
if (badopt != '\0') {
cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'd', m', 'n', 'N', and 't'",
badopt);
ret = INVALID_OPTION;
goto clean_exit;
}
break;
case 'o': /* Override preference from command line */
{
char *errmsg = NULL;
switch (prefs_set_pref(ws_optarg, &errmsg)) {
case PREFS_SET_OK:
break;
case PREFS_SET_SYNTAX_ERR:
cmdarg_err("Invalid -o flag \"%s\"%s%s", ws_optarg,
errmsg ? ": " : "", errmsg ? errmsg : "");
g_free(errmsg);
ret = INVALID_OPTION;
goto clean_exit;
break;
case PREFS_SET_NO_SUCH_PREF:
cmdarg_err("-o flag \"%s\" specifies unknown preference", ws_optarg);
ret = INVALID_OPTION;
goto clean_exit;
break;
case PREFS_SET_OBSOLETE:
cmdarg_err("-o flag \"%s\" specifies obsolete preference", ws_optarg);
ret = INVALID_OPTION;
goto clean_exit;
break;
}
break;
}
case 'p': /* Expect pcap_pkthdr packet headers, which may have 64-bit timestamps */
want_pcap_pkthdr = TRUE;
break;
case 'r': /* Read capture file xxx */
pipe_name = g_strdup(ws_optarg);
break;
case 'R': /* Read file filter */
if(n_rfilters < (int) sizeof(rfilters) / (int) sizeof(rfilters[0])) {
rfilters[n_rfilters++] = ws_optarg;
}
else {
cmdarg_err("Too many display filters");
ret = INVALID_OPTION;
goto clean_exit;
}
break;
case 's': /* Skip PCAP header */
skip_pcap_header = TRUE;
break;
case 'S': /* Print string representations */
if (!parse_field_string_format(ws_optarg)) {
cmdarg_err("Invalid field string format");
ret = INVALID_OPTION;
goto clean_exit;
}
break;
case 't': /* Time stamp type */
if (strcmp(ws_optarg, "r") == 0)
timestamp_set_type(TS_RELATIVE);
else if (strcmp(ws_optarg, "a") == 0)
timestamp_set_type(TS_ABSOLUTE);
else if (strcmp(ws_optarg, "ad") == 0)
timestamp_set_type(TS_ABSOLUTE_WITH_YMD);
else if (strcmp(ws_optarg, "adoy") == 0)
timestamp_set_type(TS_ABSOLUTE_WITH_YDOY);
else if (strcmp(ws_optarg, "d") == 0)
timestamp_set_type(TS_DELTA);
else if (strcmp(ws_optarg, "dd") == 0)
timestamp_set_type(TS_DELTA_DIS);
else if (strcmp(ws_optarg, "e") == 0)
timestamp_set_type(TS_EPOCH);
else if (strcmp(ws_optarg, "u") == 0)
timestamp_set_type(TS_UTC);
else if (strcmp(ws_optarg, "ud") == 0)
timestamp_set_type(TS_UTC_WITH_YMD);
else if (strcmp(ws_optarg, "udoy") == 0)
timestamp_set_type(TS_UTC_WITH_YDOY);
else {
cmdarg_err("Invalid time stamp type \"%s\"",
ws_optarg);
cmdarg_err_cont(
"It must be \"a\" for absolute, \"ad\" for absolute with YYYY-MM-DD date,");
cmdarg_err_cont(
"\"adoy\" for absolute with YYYY/DOY date, \"d\" for delta,");
cmdarg_err_cont(
"\"dd\" for delta displayed, \"e\" for epoch, \"r\" for relative,");
cmdarg_err_cont(
"\"u\" for absolute UTC, \"ud\" for absolute UTC with YYYY-MM-DD date,");
cmdarg_err_cont(
"or \"udoy\" for absolute UTC with YYYY/DOY date.");
ret = INVALID_OPTION;
goto clean_exit;
}
break;
case 'v': /* Show version and exit */
{
show_version();
goto clean_exit;
}
default:
case '?': /* Bad flag - print usage message */
print_usage(stderr);
ret = INVALID_OPTION;
goto clean_exit;
}
}
/* Notify all registered modules that have had any of their preferences
changed either from one of the preferences file or from the command
line that their preferences have changed.
Initialize preferences before display filters, otherwise modules
like MATE won't work. */
prefs_apply_all();
/* Initialize our display fields */
for (fc = 0; fc < disp_fields->len; fc++) {
protocolinfo_init((char *)g_ptr_array_index(disp_fields, fc));
}
g_ptr_array_free(disp_fields, TRUE);
printf("\n");
fflush(stdout);
/* If no capture filter or read filter has been specified, and there are
still command-line arguments, treat them as the tokens of a capture
filter (if no "-r" flag was specified) or a read filter (if a "-r"
flag was specified. */
if (ws_optind < argc) {
if (pipe_name != NULL) {
if (n_rfilters != 0) {
cmdarg_err("Read filters were specified both with \"-R\" "
"and with additional command-line arguments");
ret = INVALID_OPTION;
goto clean_exit;
}
rfilters[n_rfilters] = get_args_as_string(argc, argv, ws_optind);
}
}
/* Make sure we got a dissector handle for our payload. */
if (encap == WTAP_ENCAP_UNKNOWN) {
cmdarg_err("No valid payload dissector specified.");
ret = INVALID_OPTION;
goto clean_exit;
}
err_msg = ws_init_sockets();
if (err_msg != NULL)
{
cmdarg_err("%s", err_msg);
g_free(err_msg);
cmdarg_err_cont("%s", please_report_bug());
ret = INIT_FAILED;
goto clean_exit;
}
/*
* Enabled and disabled protocols and heuristic dissectors as per
* command-line options.
*/
setup_enabled_and_disabled_protocols();
/* Build the column format array */
build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
if (n_rfilters != 0) {
for (i = 0; i < n_rfilters; i++) {
if (!dfilter_compile(rfilters[i], &rfcodes[n_rfcodes], &df_err)) {
cmdarg_err("%s", df_err->msg);
dfilter_error_free(df_err);
ret = INVALID_DFILTER;
goto clean_exit;
}
n_rfcodes++;
}
}
if (pipe_name) {
/*
* We're reading a pipe (or capture file).
*/
/*
* Immediately relinquish any special privileges we have; we must not
* be allowed to read any capture files the user running Rawshark
* can't open.
*/
relinquish_special_privs_perm();
if (raw_cf_open(&cfile, pipe_name) != CF_OK) {
ret = OPEN_ERROR;
goto clean_exit;
}
/* Do we need to PCAP header and magic? */
if (skip_pcap_header) {
unsigned int bytes_left = (unsigned int) sizeof(struct pcap_hdr) + sizeof(guint32);
gchar buf[sizeof(struct pcap_hdr) + sizeof(guint32)];
while (bytes_left != 0) {
ssize_t bytes = ws_read(fd, buf, bytes_left);
if (bytes <= 0) {
cmdarg_err("Not enough bytes for pcap header.");
ret = FORMAT_ERROR;
goto clean_exit;
}
bytes_left -= (unsigned int)bytes;
}
}
/* Process the packets in the file */
if (!load_cap_file(&cfile)) {
ret = OPEN_ERROR;
goto clean_exit;
}
} else {
/* If you want to capture live packets, use TShark. */
cmdarg_err("Input file or pipe name not specified.");
ret = OPEN_ERROR;
goto clean_exit;
}
clean_exit:
g_free(pipe_name);
epan_free(cfile.epan);
epan_cleanup();
wtap_cleanup();
return ret;
}
/**
* Read data from a raw pipe. The "raw" data consists of a libpcap
* packet header followed by the payload.
* @param buf [IN] A POSIX file descriptor. Because that's _exactly_ the sort
* of thing you want to use in Windows.
* @param err [OUT] Error indicator. Uses wiretap values.
* @param err_info [OUT] Error message.
* @param data_offset [OUT] data offset in the pipe.
* @return TRUE on success, FALSE on failure.
*/
static gboolean
raw_pipe_read(wtap_rec *rec, Buffer *buf, int *err, gchar **err_info, gint64 *data_offset) {
struct pcap_pkthdr mem_hdr;
struct pcaprec_hdr disk_hdr;
ssize_t bytes_read = 0;
unsigned int bytes_needed = (unsigned int) sizeof(disk_hdr);
guchar *ptr = (guchar*) &disk_hdr;
*err = 0;
if (want_pcap_pkthdr) {
bytes_needed = sizeof(mem_hdr);
ptr = (guchar*) &mem_hdr;
}
/*
* Newer versions of the VC runtime do parameter validation. If stdin
* has been closed, calls to _read, _get_osfhandle, et al will trigger
* the invalid parameter handler and crash.
* We could alternatively use ReadFile or set an invalid parameter
* handler.
* We could also tell callers not to close stdin prematurely.
*/
#ifdef _WIN32
DWORD ghi_flags;
if (fd == 0 && GetHandleInformation(GetStdHandle(STD_INPUT_HANDLE), &ghi_flags) == 0) {
*err = 0;
*err_info = NULL;
return FALSE;
}
#endif
/* Copied from capture_loop.c */
while (bytes_needed > 0) {
bytes_read = ws_read(fd, ptr, bytes_needed);
if (bytes_read == 0) {
*err = 0;
*err_info = NULL;
return FALSE;
} else if (bytes_read < 0) {
*err = errno;
*err_info = NULL;
return FALSE;
}
bytes_needed -= (unsigned int)bytes_read;
*data_offset += bytes_read;
ptr += bytes_read;
}
rec->rec_type = REC_TYPE_PACKET;
rec->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
if (want_pcap_pkthdr) {
rec->ts.secs = mem_hdr.ts.tv_sec;
rec->ts.nsecs = (gint32)mem_hdr.ts.tv_usec * 1000;
rec->rec_header.packet_header.caplen = mem_hdr.caplen;
rec->rec_header.packet_header.len = mem_hdr.len;
} else {
rec->ts.secs = disk_hdr.ts_sec;
rec->ts.nsecs = disk_hdr.ts_usec * 1000;
rec->rec_header.packet_header.caplen = disk_hdr.incl_len;
rec->rec_header.packet_header.len = disk_hdr.orig_len;
}
bytes_needed = rec->rec_header.packet_header.caplen;
rec->rec_header.packet_header.pkt_encap = encap;
#if 0
printf("mem_hdr: %lu disk_hdr: %lu\n", sizeof(mem_hdr), sizeof(disk_hdr));
printf("tv_sec: %d (%04x)\n", (unsigned int) rec->ts.secs, (unsigned int) rec->ts.secs);
printf("tv_nsec: %d (%04x)\n", rec->ts.nsecs, rec->ts.nsecs);
printf("caplen: %d (%04x)\n", rec->rec_header.packet_header.caplen, rec->rec_header.packet_header.caplen);
printf("len: %d (%04x)\n", rec->rec_header.packet_header.len, rec->rec_header.packet_header.len);
#endif
if (bytes_needed > WTAP_MAX_PACKET_SIZE_STANDARD) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("Bad packet length: %lu",
(unsigned long) bytes_needed);
return FALSE;
}
ws_buffer_assure_space(buf, bytes_needed);
ptr = ws_buffer_start_ptr(buf);
while (bytes_needed > 0) {
bytes_read = ws_read(fd, ptr, bytes_needed);
if (bytes_read == 0) {
*err = WTAP_ERR_SHORT_READ;
*err_info = NULL;
return FALSE;
} else if (bytes_read < 0) {
*err = errno;
*err_info = NULL;
return FALSE;
}
bytes_needed -= (unsigned int)bytes_read;
*data_offset += bytes_read;
ptr += bytes_read;
}
return TRUE;
}
static gboolean
load_cap_file(capture_file *cf)
{
int err;
gchar *err_info = NULL;
gint64 data_offset = 0;
wtap_rec rec;
Buffer buf;
epan_dissect_t edt;
wtap_rec_init(&rec);
ws_buffer_init(&buf, 1514);
epan_dissect_init(&edt, cf->epan, TRUE, FALSE);
while (raw_pipe_read(&rec, &buf, &err, &err_info, &data_offset)) {
process_packet(cf, &edt, data_offset, &rec, &buf);
}
epan_dissect_cleanup(&edt);
wtap_rec_cleanup(&rec);
ws_buffer_free(&buf);
if (err != 0) {
/* Print a message noting that the read failed somewhere along the line. */
cfile_read_failure_message(cf->filename, err, err_info);
return FALSE;
}
return TRUE;
}
static gboolean
process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset,
wtap_rec *rec, Buffer *buf)
{
frame_data fdata;
gboolean passed;
int i;
if(rec->rec_header.packet_header.len == 0)
{
/* The user sends an empty packet when he wants to get output from us even if we don't currently have
packets to process. We spit out a line with the timestamp and the text "void"
*/
printf("%lu %" PRIu64 " %d void -\n", (unsigned long int)cf->count,
(guint64)rec->ts.secs, rec->ts.nsecs);
fflush(stdout);
return FALSE;
}
/* Count this packet. */
cf->count++;
/* If we're going to print packet information, or we're going to
run a read filter, or we're going to process taps, set up to
do a dissection and do so. */
frame_data_init(&fdata, cf->count, rec, offset, cum_bytes);
passed = TRUE;
/* If we're running a read filter, prime the epan_dissect_t with that
filter. */