2 * Synchronisation between Wireshark capture parent and child instances
4 * Wireshark - Network traffic analyzer
5 * By Gerald Combs <gerald@wireshark.org>
6 * Copyright 1998 Gerald Combs
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
35 #include <wsutil/unicode-utils.h>
38 #ifdef HAVE_SYS_WAIT_H
39 # include <sys/wait.h>
42 #include "caputils/capture-pcap-util.h"
46 * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
47 * macros) on UNIX systems that don't have them.
50 # define WIFEXITED(status) (((status) & 0177) == 0)
53 # define WIFSTOPPED(status) (((status) & 0177) == 0177)
56 # define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
59 # define WEXITSTATUS(status) ((status) >> 8)
62 # define WTERMSIG(status) ((status) & 0177)
65 # define WCOREDUMP(status) ((status) & 0200)
68 # define WSTOPSIG(status) ((status) >> 8)
72 #include <epan/packet.h>
73 #include <epan/prefs.h>
78 #include "ui/capture.h"
79 #include <capchild/capture_sync.h>
81 #include "sync_pipe.h"
84 #include "caputils/capture-wpcap.h"
87 #include "ui/ui_util.h"
89 #include <wsutil/filesystem.h>
90 #include <wsutil/file_util.h>
91 #include <wsutil/report_err.h>
98 #include <process.h> /* For spawning child process */
104 static void create_dummy_signal_pipe();
105 static HANDLE dummy_signal_pipe; /* Dummy named pipe which lets the child check for a dropped connection */
106 static gchar *dummy_control_id;
108 static const char *sync_pipe_signame(int);
112 static gboolean sync_pipe_input_cb(gint source, gpointer user_data);
113 static int sync_pipe_wait_for_child(ws_process_id fork_child, gchar **msgp);
114 static void pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len);
115 static ssize_t pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
118 static void (*fetch_dumpcap_pid)(ws_process_id) = NULL;
122 capture_session_init(capture_session *cap_session, struct _capture_file *cf)
124 cap_session->cf = cf;
125 cap_session->fork_child = WS_INVALID_PID; /* invalid process handle */
127 cap_session->signal_pipe_write_fd = -1;
129 cap_session->state = CAPTURE_STOPPED;
131 cap_session->owner = getuid();
132 cap_session->group = getgid();
134 cap_session->count = 0;
135 cap_session->session_started = FALSE;
138 /* Append an arg (realloc) to an argc/argv array */
139 /* (add a string pointer to a NULL-terminated array of string pointers) */
141 sync_pipe_add_arg(char **args, int *argc, const char *arg)
143 /* Grow the array; "*argc" currently contains the number of string
144 pointers, *not* counting the NULL pointer at the end, so we have
145 to add 2 in order to get the new size of the array, including the
146 new pointer and the terminating NULL pointer. */
147 args = (char **)g_realloc( (gpointer) args, (*argc + 2) * sizeof (char *));
149 /* Stuff the pointer into the penultimate element of the array, which
150 is the one at the index specified by "*argc". */
151 args[*argc] = g_strdup(arg);
152 /* Now bump the count. */
155 /* We overwrite the NULL pointer; put it back right after the
165 /* Quote the argument element if necessary, so that it will get
166 * reconstructed correctly in the C runtime startup code. Note that
167 * the unquoting algorithm in the C runtime is really weird, and
168 * rather different than what Unix shells do. See stdargv.c in the C
169 * runtime sources (in the Platform SDK, in src/crt).
171 * Stolen from GLib's protect_argv(), an internal routine that quotes
172 * string in an argument list so that they arguments will be handled
173 * correctly in the command-line string passed to CreateProcess()
174 * if that string is constructed by gluing those strings together.
177 protect_arg (const gchar *argv)
180 const gchar *p = argv;
183 gboolean need_dblquotes = FALSE;
186 if (*p == ' ' || *p == '\t')
187 need_dblquotes = TRUE;
190 else if (*p == '\\') {
193 while (*pp && *pp == '\\')
202 q = new_arg = g_malloc (len + need_dblquotes*2 + 1);
211 else if (*p == '\\') {
214 while (*pp && *pp == '\\')
231 * Generate a string for a Win32 error.
233 #define ERRBUF_SIZE 1024
235 win32strerror(DWORD error)
237 static char errbuf[ERRBUF_SIZE+1];
241 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
242 NULL, error, 0, errbuf, ERRBUF_SIZE, NULL);
245 * "FormatMessage()" "helpfully" sticks CR/LF at the end of the
246 * message. Get rid of it.
248 errlen = strlen(errbuf);
250 errbuf[errlen - 1] = '\0';
251 errbuf[errlen - 2] = '\0';
253 p = strchr(errbuf, '\0');
254 g_snprintf(p, (gulong)(sizeof errbuf - (p-errbuf)), " (%lu)", error);
259 * Generate a string for a Win32 exception code.
262 win32strexception(DWORD exception)
264 static char errbuf[ERRBUF_SIZE+1];
265 static const struct exception_msg {
269 { EXCEPTION_ACCESS_VIOLATION, "Access violation" },
270 { EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded" },
271 { EXCEPTION_BREAKPOINT, "Breakpoint" },
272 { EXCEPTION_DATATYPE_MISALIGNMENT, "Data type misalignment" },
273 { EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal floating-point operand" },
274 { EXCEPTION_FLT_DIVIDE_BY_ZERO, "Floating-point divide by zero" },
275 { EXCEPTION_FLT_INEXACT_RESULT, "Floating-point inexact result" },
276 { EXCEPTION_FLT_INVALID_OPERATION, "Invalid floating-point operation" },
277 { EXCEPTION_FLT_OVERFLOW, "Floating-point overflow" },
278 { EXCEPTION_FLT_STACK_CHECK, "Floating-point stack check" },
279 { EXCEPTION_FLT_UNDERFLOW, "Floating-point underflow" },
280 { EXCEPTION_GUARD_PAGE, "Guard page violation" },
281 { EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction" },
282 { EXCEPTION_IN_PAGE_ERROR, "Page-in error" },
283 { EXCEPTION_INT_DIVIDE_BY_ZERO, "Integer divide by zero" },
284 { EXCEPTION_INT_OVERFLOW, "Integer overflow" },
285 { EXCEPTION_INVALID_DISPOSITION, "Invalid disposition" },
286 { EXCEPTION_INVALID_HANDLE, "Invalid handle" },
287 { EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception" },
288 { EXCEPTION_PRIV_INSTRUCTION, "Privileged instruction" },
289 { EXCEPTION_SINGLE_STEP, "Single-step complete" },
290 { EXCEPTION_STACK_OVERFLOW, "Stack overflow" },
293 #define N_EXCEPTIONS (sizeof exceptions / sizeof exceptions[0])
296 for (i = 0; i < N_EXCEPTIONS; i++) {
297 if (exceptions[i].code == exception)
298 return exceptions[i].msg;
300 g_snprintf(errbuf, (gulong)sizeof errbuf, "Exception 0x%08x", exception);
305 /* Initialize an argument list and add dumpcap to it. */
307 init_pipe_args(int *argc) {
309 const char *progfile_dir;
312 progfile_dir = get_progfile_dir();
313 if (progfile_dir == NULL) {
317 /* Allocate the string pointer array with enough space for the
318 terminating NULL pointer. */
320 argv = (char **)g_malloc(sizeof (char *));
323 /* take Wireshark's absolute program path and replace "Wireshark" with "dumpcap" */
325 exename = g_strdup_printf("%s\\dumpcap.exe", progfile_dir);
327 exename = g_strdup_printf("%s/dumpcap", progfile_dir);
330 /* Make that the first argument in the argument list (argv[0]). */
331 argv = sync_pipe_add_arg(argv, argc, exename);
333 /* sync_pipe_add_arg strdupes exename, so we should free our copy */
339 #define ARGV_NUMBER_LEN 24
340 /* a new capture run: start a new dumpcap task and hand over parameters through command line */
342 sync_pipe_start(capture_options *capture_opts, capture_session *cap_session, info_data_t* cap_data, void (*update_cb)(void))
344 char ssnap[ARGV_NUMBER_LEN];
345 char scount[ARGV_NUMBER_LEN];
346 char sfilesize[ARGV_NUMBER_LEN];
347 char sfile_duration[ARGV_NUMBER_LEN];
348 char sring_num_files[ARGV_NUMBER_LEN];
349 char sautostop_files[ARGV_NUMBER_LEN];
350 char sautostop_filesize[ARGV_NUMBER_LEN];
351 char sautostop_duration[ARGV_NUMBER_LEN];
352 #ifdef HAVE_PCAP_REMOTE
355 #ifdef HAVE_PCAP_SETSAMPLING
356 char ssampling[ARGV_NUMBER_LEN];
359 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
360 char buffer_size[ARGV_NUMBER_LEN];
364 HANDLE sync_pipe_read; /* pipe used to send messages from child to parent */
365 HANDLE sync_pipe_write; /* pipe used to send messages from child to parent */
366 int signal_pipe_write_fd;
367 HANDLE signal_pipe; /* named pipe used to send messages from parent to child (currently only stop) */
368 GString *args = g_string_sized_new(200);
370 SECURITY_ATTRIBUTES sa;
372 PROCESS_INFORMATION pi;
373 char control_id[ARGV_NUMBER_LEN];
374 gchar *signal_pipe_name;
377 int sync_pipe[2]; /* pipe used to send messages from child to parent */
378 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
380 int sync_pipe_read_fd;
385 interface_options interface_opts;
387 if (capture_opts->ifaces->len > 1)
388 capture_opts->use_pcapng = TRUE;
389 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_start");
390 capture_opts_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, capture_opts);
392 cap_session->fork_child = WS_INVALID_PID;
395 if (!extcaps_init_initerfaces(capture_opts)) {
396 report_failure("Unable to init extcaps. (tmp fifo already exists?)");
402 argv = init_pipe_args(&argc);
404 /* We don't know where to find dumpcap. */
405 report_failure("We don't know where to find dumpcap.");
409 if (capture_opts->ifaces->len > 1)
410 argv = sync_pipe_add_arg(argv, &argc, "-t");
412 if (capture_opts->use_pcapng)
413 argv = sync_pipe_add_arg(argv, &argc, "-n");
415 argv = sync_pipe_add_arg(argv, &argc, "-P");
417 if (capture_opts->capture_comment) {
418 argv = sync_pipe_add_arg(argv, &argc, "--capture-comment");
419 argv = sync_pipe_add_arg(argv, &argc, capture_opts->capture_comment);
422 if (capture_opts->multi_files_on) {
423 if (capture_opts->has_autostop_filesize) {
424 argv = sync_pipe_add_arg(argv, &argc, "-b");
425 g_snprintf(sfilesize, ARGV_NUMBER_LEN, "filesize:%u",capture_opts->autostop_filesize);
426 argv = sync_pipe_add_arg(argv, &argc, sfilesize);
429 if (capture_opts->has_file_duration) {
430 argv = sync_pipe_add_arg(argv, &argc, "-b");
431 g_snprintf(sfile_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->file_duration);
432 argv = sync_pipe_add_arg(argv, &argc, sfile_duration);
435 if (capture_opts->has_ring_num_files) {
436 argv = sync_pipe_add_arg(argv, &argc, "-b");
437 g_snprintf(sring_num_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->ring_num_files);
438 argv = sync_pipe_add_arg(argv, &argc, sring_num_files);
441 if (capture_opts->has_autostop_files) {
442 argv = sync_pipe_add_arg(argv, &argc, "-a");
443 g_snprintf(sautostop_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->autostop_files);
444 argv = sync_pipe_add_arg(argv, &argc, sautostop_files);
447 if (capture_opts->has_autostop_filesize) {
448 argv = sync_pipe_add_arg(argv, &argc, "-a");
449 g_snprintf(sautostop_filesize, ARGV_NUMBER_LEN, "filesize:%u",capture_opts->autostop_filesize);
450 argv = sync_pipe_add_arg(argv, &argc, sautostop_filesize);
454 if (capture_opts->has_autostop_packets) {
455 argv = sync_pipe_add_arg(argv, &argc, "-c");
456 g_snprintf(scount, ARGV_NUMBER_LEN, "%d",capture_opts->autostop_packets);
457 argv = sync_pipe_add_arg(argv, &argc, scount);
460 if (capture_opts->has_autostop_duration) {
461 argv = sync_pipe_add_arg(argv, &argc, "-a");
462 g_snprintf(sautostop_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->autostop_duration);
463 argv = sync_pipe_add_arg(argv, &argc, sautostop_duration);
466 if (capture_opts->group_read_access) {
467 argv = sync_pipe_add_arg(argv, &argc, "-g");
470 for (j = 0; j < capture_opts->ifaces->len; j++) {
471 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
473 argv = sync_pipe_add_arg(argv, &argc, "-i");
475 if (interface_opts.extcap_fifo != NULL)
476 argv = sync_pipe_add_arg(argv, &argc, interface_opts.extcap_fifo);
479 argv = sync_pipe_add_arg(argv, &argc, interface_opts.name);
481 if (interface_opts.cfilter != NULL && strlen(interface_opts.cfilter) != 0) {
482 argv = sync_pipe_add_arg(argv, &argc, "-f");
483 argv = sync_pipe_add_arg(argv, &argc, interface_opts.cfilter);
485 if (interface_opts.snaplen != WTAP_MAX_PACKET_SIZE) {
486 argv = sync_pipe_add_arg(argv, &argc, "-s");
487 g_snprintf(ssnap, ARGV_NUMBER_LEN, "%d", interface_opts.snaplen);
488 argv = sync_pipe_add_arg(argv, &argc, ssnap);
491 if (interface_opts.linktype != -1) {
492 const char *linktype = linktype_val_to_name(interface_opts.linktype);
493 if ( linktype != NULL )
495 argv = sync_pipe_add_arg(argv, &argc, "-y");
496 argv = sync_pipe_add_arg(argv, &argc, linktype);
500 if (!interface_opts.promisc_mode) {
501 argv = sync_pipe_add_arg(argv, &argc, "-p");
504 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
505 if (interface_opts.buffer_size != DEFAULT_CAPTURE_BUFFER_SIZE) {
506 argv = sync_pipe_add_arg(argv, &argc, "-B");
507 if(interface_opts.buffer_size == 0x00)
508 interface_opts.buffer_size = DEFAULT_CAPTURE_BUFFER_SIZE;
509 g_snprintf(buffer_size, ARGV_NUMBER_LEN, "%d", interface_opts.buffer_size);
510 argv = sync_pipe_add_arg(argv, &argc, buffer_size);
514 #ifdef HAVE_PCAP_CREATE
515 if (interface_opts.monitor_mode) {
516 argv = sync_pipe_add_arg(argv, &argc, "-I");
520 #ifdef HAVE_PCAP_REMOTE
521 if (interface_opts.datatx_udp)
522 argv = sync_pipe_add_arg(argv, &argc, "-u");
524 if (!interface_opts.nocap_rpcap)
525 argv = sync_pipe_add_arg(argv, &argc, "-r");
527 if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
528 argv = sync_pipe_add_arg(argv, &argc, "-A");
529 g_snprintf(sauth, sizeof(sauth), "%s:%s",
530 interface_opts.auth_username,
531 interface_opts.auth_password);
532 argv = sync_pipe_add_arg(argv, &argc, sauth);
536 #ifdef HAVE_PCAP_SETSAMPLING
537 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
538 argv = sync_pipe_add_arg(argv, &argc, "-m");
539 g_snprintf(ssampling, ARGV_NUMBER_LEN, "%s:%d",
540 interface_opts.sampling_method == CAPTURE_SAMP_BY_COUNT ? "count" :
541 interface_opts.sampling_method == CAPTURE_SAMP_BY_TIMER ? "timer" :
543 interface_opts.sampling_param);
544 argv = sync_pipe_add_arg(argv, &argc, ssampling);
549 /* dumpcap should be running in capture child mode (hidden feature) */
551 argv = sync_pipe_add_arg(argv, &argc, "-Z");
553 g_snprintf(control_id, ARGV_NUMBER_LEN, "%d", GetCurrentProcessId());
554 argv = sync_pipe_add_arg(argv, &argc, control_id);
556 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
560 if (capture_opts->save_file) {
561 argv = sync_pipe_add_arg(argv, &argc, "-w");
562 argv = sync_pipe_add_arg(argv, &argc, capture_opts->save_file);
564 for (i = 0; i < argc; i++) {
565 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", i, argv[i]);
569 /* init SECURITY_ATTRIBUTES */
570 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
571 sa.bInheritHandle = TRUE;
572 sa.lpSecurityDescriptor = NULL;
574 /* Create a pipe for the child process */
575 /* (increase this value if you have trouble while fast capture file switches) */
576 if (! CreatePipe(&sync_pipe_read, &sync_pipe_write, &sa, 5120)) {
577 /* Couldn't create the pipe between parent and child. */
578 report_failure("Couldn't create sync pipe: %s",
579 win32strerror(GetLastError()));
580 for (i = 0; i < argc; i++) {
581 g_free( (gpointer) argv[i]);
583 g_free( (gpointer) argv);
588 * Associate a C run-time file handle with the Windows HANDLE for the
589 * read side of the message pipe.
591 * (See http://www.flounder.com/handles.htm for information on various
592 * types of file handle in C/C++ on Windows.)
594 sync_pipe_read_fd = _open_osfhandle( (intptr_t) sync_pipe_read, _O_BINARY);
595 if (sync_pipe_read_fd == -1) {
596 /* Couldn't create the pipe between parent and child. */
597 report_failure("Couldn't get C file handle for sync pipe: %s", g_strerror(errno));
598 CloseHandle(sync_pipe_read);
599 CloseHandle(sync_pipe_write);
600 for (i = 0; i < argc; i++) {
601 g_free( (gpointer) argv[i]);
607 /* Create the signal pipe */
608 signal_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, control_id);
609 signal_pipe = CreateNamedPipe(utf_8to16(signal_pipe_name),
610 PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 65535, 65535, 0, NULL);
611 g_free(signal_pipe_name);
613 if (signal_pipe == INVALID_HANDLE_VALUE) {
614 /* Couldn't create the signal pipe between parent and child. */
615 report_failure("Couldn't create signal pipe: %s",
616 win32strerror(GetLastError()));
617 ws_close(sync_pipe_read_fd); /* Should close sync_pipe_read */
618 CloseHandle(sync_pipe_write);
619 for (i = 0; i < argc; i++) {
620 g_free( (gpointer) argv[i]);
622 g_free( (gpointer) argv);
627 * Associate a C run-time file handle with the Windows HANDLE for the
628 * read side of the message pipe.
630 * (See http://www.flounder.com/handles.htm for information on various
631 * types of file handle in C/C++ on Windows.)
633 signal_pipe_write_fd = _open_osfhandle( (intptr_t) signal_pipe, _O_BINARY);
634 if (sync_pipe_read_fd == -1) {
635 /* Couldn't create the pipe between parent and child. */
636 report_failure("Couldn't get C file handle for sync pipe: %s", g_strerror(errno));
637 ws_close(sync_pipe_read_fd); /* Should close sync_pipe_read */
638 CloseHandle(sync_pipe_write);
639 CloseHandle(signal_pipe);
640 for (i = 0; i < argc; i++) {
641 g_free( (gpointer) argv[i]);
647 /* init STARTUPINFO */
648 memset(&si, 0, sizeof(si));
651 si.dwFlags = STARTF_USESHOWWINDOW;
652 si.wShowWindow = SW_SHOW;
654 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
655 si.wShowWindow = SW_HIDE; /* this hides the console window */
657 /* needs first a check if NULL *
658 * otherwise wouldn't work with non extcap interfaces */
659 if(interface_opts.extcap_fifo != NULL)
661 if(strncmp(interface_opts.extcap_fifo,"\\\\.\\pipe\\",9)== 0)
663 si.hStdInput = extcap_get_win32_handle();
668 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
670 si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
671 si.hStdError = sync_pipe_write;
672 /*si.hStdError = (HANDLE) _get_osfhandle(2);*/
675 /* convert args array into a single string */
676 /* XXX - could change sync_pipe_add_arg() instead */
677 /* there is a drawback here: the length is internally limited to 1024 bytes */
678 for(i=0; argv[i] != 0; i++) {
679 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
680 quoted_arg = protect_arg(argv[i]);
681 g_string_append(args, quoted_arg);
686 if(!CreateProcess(utf_8to16(argv[0]), utf_8to16(args->str), NULL, NULL, TRUE,
687 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
688 report_failure("Couldn't run %s in child process: %s",
689 args->str, win32strerror(GetLastError()));
690 ws_close(sync_pipe_read_fd); /* Should close sync_pipe_read */
691 CloseHandle(sync_pipe_write);
692 CloseHandle(signal_pipe);
693 for (i = 0; i < argc; i++) {
694 g_free( (gpointer) argv[i]);
696 g_free( (gpointer) argv);
699 cap_session->fork_child = pi.hProcess;
700 /* We may need to store this and close it later */
701 CloseHandle(pi.hThread);
702 g_string_free(args, TRUE);
704 cap_session->signal_pipe_write_fd = signal_pipe_write_fd;
707 if (pipe(sync_pipe) < 0) {
708 /* Couldn't create the pipe between parent and child. */
709 report_failure("Couldn't create sync pipe: %s", g_strerror(errno));
710 for (i = 0; i < argc; i++) {
711 g_free( (gpointer) argv[i]);
717 if ((cap_session->fork_child = fork()) == 0) {
719 * Child process - run dumpcap with the right arguments to make
720 * it just capture with the specified capture parameters
722 dup2(sync_pipe[PIPE_WRITE], 2);
723 ws_close(sync_pipe[PIPE_READ]);
724 execv(argv[0], argv);
725 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
726 argv[0], g_strerror(errno));
727 sync_pipe_errmsg_to_parent(2, errmsg, "");
729 /* Exit with "_exit()", so that we don't close the connection
730 to the X server (and cause stuff buffered up by our parent but
731 not yet sent to be sent, as that stuff should only be sent by
732 our parent). We've sent an error message to the parent, so
733 we exit with an exit status of 1 (any exit status other than
734 0 or 1 will cause an additional message to report that exit
735 status, over and above the error message we sent to the parent). */
739 if (fetch_dumpcap_pid && cap_session->fork_child > 0)
740 fetch_dumpcap_pid(cap_session->fork_child);
742 sync_pipe_read_fd = sync_pipe[PIPE_READ];
745 for (i = 0; i < argc; i++) {
746 g_free( (gpointer) argv[i]);
749 /* Parent process - read messages from the child process over the
751 g_free( (gpointer) argv); /* free up arg array */
753 /* Close the write side of the pipe, so that only the child has it
754 open, and thus it completely closes, and thus returns to us
755 an EOF indication, if the child closes it (either deliberately
756 or by exiting abnormally). */
758 CloseHandle(sync_pipe_write);
760 ws_close(sync_pipe[PIPE_WRITE]);
763 if (cap_session->fork_child == WS_INVALID_PID) {
764 /* We couldn't even create the child process. */
765 report_failure("Couldn't create child process: %s", g_strerror(errno));
766 ws_close(sync_pipe_read_fd);
768 ws_close(cap_session->signal_pipe_write_fd);
773 cap_session->fork_child_status = 0;
774 cap_session->capture_opts = capture_opts;
775 cap_session->cap_data_info = cap_data;
777 /* we might wait for a moment till child is ready, so update screen now */
778 if (update_cb) update_cb();
780 /* We were able to set up to read the capture file;
781 arrange that our callback be called whenever it's possible
782 to read from the sync pipe, so that it's called when
783 the child process wants to tell us something. */
785 /* we have a running capture, now wait for the real capture filename */
786 pipe_input_set_handler(sync_pipe_read_fd, (gpointer) cap_session,
787 &cap_session->fork_child, sync_pipe_input_cb);
793 * Open two pipes to dumpcap with the supplied arguments, one for its
794 * standard output and one for its standard error.
796 * On success, *msg is unchanged and 0 is returned; data_read_fd,
797 * message_read_fd, and fork_child point to the standard output pipe's
798 * file descriptor, the standard error pipe's file descriptor, and
799 * the child's PID/handle, respectively.
801 * On failure, *msg points to an error message for the failure, and -1 is
802 * returned, in which case *msg must be freed with g_free().
804 /* XXX - This duplicates a lot of code in sync_pipe_start() */
805 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
806 #define PIPE_BUF_SIZE 5120
808 sync_pipe_open_command(char** argv, int *data_read_fd,
809 int *message_read_fd, ws_process_id *fork_child, gchar **msg, void(*update_cb)(void))
811 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
813 HANDLE sync_pipe[2]; /* pipe used to send messages from child to parent */
814 HANDLE data_pipe[2]; /* pipe used to send data from child to parent */
815 GString *args = g_string_sized_new(200);
817 SECURITY_ATTRIBUTES sa;
819 PROCESS_INFORMATION pi;
822 int sync_pipe[2]; /* pipe used to send messages from child to parent */
823 int data_pipe[2]; /* pipe used to send data from child to parent */
826 *fork_child = WS_INVALID_PID;
828 *message_read_fd = -1;
829 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_open_command");
832 /* We can't return anything */
834 g_string_free(args, TRUE);
840 /* init SECURITY_ATTRIBUTES */
841 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
842 sa.bInheritHandle = TRUE;
843 sa.lpSecurityDescriptor = NULL;
845 /* Create a pipe for the child process to send us messages */
846 /* (increase this value if you have trouble while fast capture file switches) */
847 if (! CreatePipe(&sync_pipe[PIPE_READ], &sync_pipe[PIPE_WRITE], &sa, 5120)) {
848 /* Couldn't create the message pipe between parent and child. */
849 *msg = g_strdup_printf("Couldn't create sync pipe: %s",
850 win32strerror(GetLastError()));
851 for (i = 0; argv[i] != NULL; i++) {
852 g_free( (gpointer) argv[i]);
854 g_free( (gpointer) argv);
859 * Associate a C run-time file handle with the Windows HANDLE for the
860 * read side of the message pipe.
862 * (See http://www.flounder.com/handles.htm for information on various
863 * types of file handle in C/C++ on Windows.)
865 *message_read_fd = _open_osfhandle( (intptr_t) sync_pipe[PIPE_READ], _O_BINARY);
866 if (*message_read_fd == -1) {
867 *msg = g_strdup_printf("Couldn't get C file handle for message read pipe: %s", g_strerror(errno));
868 CloseHandle(sync_pipe[PIPE_READ]);
869 CloseHandle(sync_pipe[PIPE_WRITE]);
870 for (i = 0; argv[i] != NULL; i++) {
871 g_free( (gpointer) argv[i]);
873 g_free( (gpointer) argv);
877 /* Create a pipe for the child process to send us data */
878 /* (increase this value if you have trouble while fast capture file switches) */
879 if (! CreatePipe(&data_pipe[PIPE_READ], &data_pipe[PIPE_WRITE], &sa, 5120)) {
880 /* Couldn't create the message pipe between parent and child. */
881 *msg = g_strdup_printf("Couldn't create data pipe: %s",
882 win32strerror(GetLastError()));
883 ws_close(*message_read_fd); /* Should close sync_pipe[PIPE_READ] */
884 CloseHandle(sync_pipe[PIPE_WRITE]);
885 for (i = 0; argv[i] != NULL; i++) {
886 g_free( (gpointer) argv[i]);
888 g_free( (gpointer) argv);
893 * Associate a C run-time file handle with the Windows HANDLE for the
894 * read side of the data pipe.
896 * (See http://www.flounder.com/handles.htm for information on various
897 * types of file handle in C/C++ on Windows.)
899 *data_read_fd = _open_osfhandle( (intptr_t) data_pipe[PIPE_READ], _O_BINARY);
900 if (*data_read_fd == -1) {
901 *msg = g_strdup_printf("Couldn't get C file handle for data read pipe: %s", g_strerror(errno));
902 CloseHandle(data_pipe[PIPE_READ]);
903 CloseHandle(data_pipe[PIPE_WRITE]);
904 ws_close(*message_read_fd); /* Should close sync_pipe[PIPE_READ] */
905 CloseHandle(sync_pipe[PIPE_WRITE]);
906 for (i = 0; argv[i] != NULL; i++) {
907 g_free( (gpointer) argv[i]);
909 g_free( (gpointer) argv);
913 /* init STARTUPINFO */
914 memset(&si, 0, sizeof(si));
917 si.dwFlags = STARTF_USESHOWWINDOW;
918 si.wShowWindow = SW_SHOW;
920 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
921 si.wShowWindow = SW_HIDE; /* this hides the console window */
922 si.hStdInput = NULL; /* handle for named pipe*/
924 si.hStdOutput = data_pipe[PIPE_WRITE];
925 si.hStdError = sync_pipe[PIPE_WRITE];
928 /* convert args array into a single string */
929 /* XXX - could change sync_pipe_add_arg() instead */
930 /* there is a drawback here: the length is internally limited to 1024 bytes */
931 for(i=0; argv[i] != 0; i++) {
932 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
933 quoted_arg = protect_arg(argv[i]);
934 g_string_append(args, quoted_arg);
939 if(!CreateProcess(utf_8to16(argv[0]), utf_8to16(args->str), NULL, NULL, TRUE,
940 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
941 *msg = g_strdup_printf("Couldn't run %s in child process: %s",
942 args->str, win32strerror(GetLastError()));
943 ws_close(*data_read_fd); /* Should close data_pipe[PIPE_READ] */
944 CloseHandle(data_pipe[PIPE_WRITE]);
945 ws_close(*message_read_fd); /* Should close sync_pipe[PIPE_READ] */
946 CloseHandle(sync_pipe[PIPE_WRITE]);
947 for (i = 0; argv[i] != NULL; i++) {
948 g_free( (gpointer) argv[i]);
950 g_free( (gpointer) argv);
953 *fork_child = pi.hProcess;
954 /* We may need to store this and close it later */
955 CloseHandle(pi.hThread);
956 g_string_free(args, TRUE);
958 /* Create a pipe for the child process to send us messages */
959 if (pipe(sync_pipe) < 0) {
960 /* Couldn't create the message pipe between parent and child. */
961 *msg = g_strdup_printf("Couldn't create sync pipe: %s", g_strerror(errno));
962 for (i = 0; argv[i] != NULL; i++) {
963 g_free( (gpointer) argv[i]);
969 /* Create a pipe for the child process to send us data */
970 if (pipe(data_pipe) < 0) {
971 /* Couldn't create the data pipe between parent and child. */
972 *msg = g_strdup_printf("Couldn't create data pipe: %s", g_strerror(errno));
973 ws_close(sync_pipe[PIPE_READ]);
974 ws_close(sync_pipe[PIPE_WRITE]);
975 for (i = 0; argv[i] != NULL; i++) {
976 g_free( (gpointer) argv[i]);
982 if ((*fork_child = fork()) == 0) {
984 * Child process - run dumpcap with the right arguments to make
985 * it just capture with the specified capture parameters
987 dup2(data_pipe[PIPE_WRITE], 1);
988 ws_close(data_pipe[PIPE_READ]);
989 ws_close(data_pipe[PIPE_WRITE]);
990 dup2(sync_pipe[PIPE_WRITE], 2);
991 ws_close(sync_pipe[PIPE_READ]);
992 ws_close(sync_pipe[PIPE_WRITE]);
993 execv(argv[0], argv);
994 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
995 argv[0], g_strerror(errno));
996 sync_pipe_errmsg_to_parent(2, errmsg, "");
998 /* Exit with "_exit()", so that we don't close the connection
999 to the X server (and cause stuff buffered up by our parent but
1000 not yet sent to be sent, as that stuff should only be sent by
1001 our parent). We've sent an error message to the parent, so
1002 we exit with an exit status of 1 (any exit status other than
1003 0 or 1 will cause an additional message to report that exit
1004 status, over and above the error message we sent to the parent). */
1008 if (fetch_dumpcap_pid && *fork_child > 0)
1009 fetch_dumpcap_pid(*fork_child);
1011 *data_read_fd = data_pipe[PIPE_READ];
1012 *message_read_fd = sync_pipe[PIPE_READ];
1015 for (i = 0; argv[i] != NULL; i++) {
1016 g_free( (gpointer) argv[i]);
1019 /* Parent process - read messages from the child process over the
1021 g_free( (gpointer) argv); /* free up arg array */
1023 /* Close the write sides of the pipes, so that only the child has them
1024 open, and thus they completely close, and thus return to us
1025 an EOF indication, if the child closes them (either deliberately
1026 or by exiting abnormally). */
1028 CloseHandle(data_pipe[PIPE_WRITE]);
1029 CloseHandle(sync_pipe[PIPE_WRITE]);
1031 ws_close(data_pipe[PIPE_WRITE]);
1032 ws_close(sync_pipe[PIPE_WRITE]);
1035 if (*fork_child == WS_INVALID_PID) {
1036 /* We couldn't even create the child process. */
1037 *msg = g_strdup_printf("Couldn't create child process: %s", g_strerror(errno));
1038 ws_close(*data_read_fd);
1039 ws_close(*message_read_fd);
1043 /* we might wait for a moment till child is ready, so update screen now */
1044 if (update_cb) update_cb();
1049 * Close the pipes we're using to read from dumpcap, and wait for it
1050 * to exit. On success, *msgp is unchanged, and the exit status of
1051 * dumpcap is returned. On failure (which includes "dumpcap exited
1052 * due to being killed by a signal or an exception"), *msgp points
1053 * to an error message for the failure, and -1 is returned. In the
1054 * latter case, *msgp must be freed with g_free().
1057 sync_pipe_close_command(int *data_read_fd, int *message_read_fd,
1058 ws_process_id *fork_child, gchar **msgp)
1060 ws_close(*data_read_fd);
1061 if (message_read_fd != NULL)
1062 ws_close(*message_read_fd);
1065 /* XXX - Should we signal the child somehow? */
1066 sync_pipe_kill(*fork_child);
1069 return sync_pipe_wait_for_child(*fork_child, msgp);
1073 * Run dumpcap with the supplied arguments.
1075 * On success, *data points to a buffer containing the dumpcap output,
1076 * *primary_msg and *secondary_message are NULL, and 0 is returned; *data
1077 * must be freed with g_free().
1079 * On failure, *data is NULL, *primary_msg points to an error message,
1080 * *secondary_msg either points to an additional error message or is
1081 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1082 * must be freed with g_free().
1084 /* XXX - This duplicates a lot of code in sync_pipe_start() */
1085 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
1086 #define PIPE_BUF_SIZE 5120
1088 sync_pipe_run_command_actual(char** argv, gchar **data, gchar **primary_msg,
1089 gchar **secondary_msg, void(*update_cb)(void))
1092 int data_pipe_read_fd, sync_pipe_read_fd, ret;
1093 ws_process_id fork_child;
1095 gchar buffer[PIPE_BUF_SIZE+1] = {0};
1098 int primary_msg_len;
1099 char *primary_msg_text;
1100 int secondary_msg_len;
1101 char *secondary_msg_text;
1103 GString *data_buf = NULL;
1106 ret = sync_pipe_open_command(argv, &data_pipe_read_fd, &sync_pipe_read_fd,
1107 &fork_child, &msg, update_cb);
1110 *secondary_msg = NULL;
1116 * We were able to set up to read dumpcap's output. Do so.
1118 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1120 nread = pipe_read_block(sync_pipe_read_fd, &indicator, SP_MAX_MSG_LEN,
1121 buffer, primary_msg);
1123 /* We got a read error from the sync pipe, or we got no data at
1124 all from the sync pipe, so we're not going to be getting any
1125 data or error message from the child process. Pick up its
1126 exit status, and complain.
1128 We don't have to worry about killing the child, if the sync pipe
1129 returned an error. Usually this error is caused as the child killed
1130 itself while going down. Even in the rare cases that this isn't the
1131 case, the child will get an error when writing to the broken pipe
1132 the next time, cleaning itself up then. */
1133 ret = sync_pipe_wait_for_child(fork_child, &wait_msg);
1135 /* We got an EOF from the sync pipe. That means that it exited
1136 before giving us any data to read. If ret is -1, we report
1137 that as a bad exit (e.g., exiting due to a signal); otherwise,
1138 we report it as a premature exit. */
1140 *primary_msg = wait_msg;
1142 *primary_msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1144 /* We got an error from the sync pipe. If ret is -1, report
1145 both the sync pipe I/O error and the wait error. */
1147 combined_msg = g_strdup_printf("%s\n\n%s", *primary_msg, wait_msg);
1148 g_free(*primary_msg);
1150 *primary_msg = combined_msg;
1153 *secondary_msg = NULL;
1159 /* we got a valid message block from the child, process it */
1164 * Error from dumpcap; there will be a primary message and a
1165 * secondary message.
1168 /* convert primary message */
1169 pipe_convert_header((guchar*)buffer, 4, &indicator, &primary_msg_len);
1170 primary_msg_text = buffer+4;
1171 /* convert secondary message */
1172 pipe_convert_header((guchar*)primary_msg_text + primary_msg_len, 4, &indicator,
1173 &secondary_msg_len);
1174 secondary_msg_text = primary_msg_text + primary_msg_len + 4;
1175 /* the capture child will close the sync_pipe, nothing to do */
1178 * Pick up the child status.
1180 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1184 * Child process failed unexpectedly, or wait failed; msg is the
1188 *secondary_msg = NULL;
1191 * Child process failed, but returned the expected exit status.
1192 * Return the messages it gave us, and indicate failure.
1194 *primary_msg = g_strdup(primary_msg_text);
1195 *secondary_msg = g_strdup(secondary_msg_text);
1202 /* read the output from the command */
1203 data_buf = g_string_new("");
1204 while ((count = ws_read(data_pipe_read_fd, buffer, PIPE_BUF_SIZE)) > 0) {
1205 buffer[count] = '\0';
1206 g_string_append(data_buf, buffer);
1210 * Pick up the child status.
1212 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1216 * Child process failed unexpectedly, or wait failed; msg is the
1220 *secondary_msg = NULL;
1221 g_string_free(data_buf, TRUE);
1225 * Child process succeeded.
1227 *primary_msg = NULL;
1228 *secondary_msg = NULL;
1229 *data = g_string_free(data_buf, FALSE);
1235 * Pick up the child status.
1237 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1241 * Child process failed unexpectedly, or wait failed; msg is the
1245 *secondary_msg = NULL;
1248 * Child process returned an unknown status.
1250 *primary_msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1252 *secondary_msg = NULL;
1261 /* centralised logging and timing for sync_pipe_run_command_actual(),
1262 * redirects to sync_pipe_run_command_actual()
1265 sync_pipe_run_command(char** argv, gchar **data, gchar **primary_msg,
1266 gchar **secondary_msg, void (*update_cb)(void))
1269 GTimeVal start_time;
1272 int logging_enabled;
1274 /* check if logging is actually enabled, otherwise don't expend the CPU generating logging */
1275 logging_enabled=( (G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO) & G_LOG_LEVEL_MASK & prefs.console_log_level);
1276 if(logging_enabled){
1277 g_get_current_time(&start_time);
1278 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_INFO, "sync_pipe_run_command() starts");
1279 for(i=0; argv[i] != 0; i++) {
1280 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, " argv[%d]: %s", i, argv[i]);
1283 /* do the actual sync pipe run command */
1284 ret=sync_pipe_run_command_actual(argv, data, primary_msg, secondary_msg, update_cb);
1286 if(logging_enabled){
1287 g_get_current_time(&end_time);
1288 elapsed = (float) ((end_time.tv_sec - start_time.tv_sec) +
1289 ((end_time.tv_usec - start_time.tv_usec) / 1e6));
1291 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_INFO, "sync_pipe_run_command() ends, taking %.3fs, result=%d", elapsed, ret);
1299 sync_interface_set_80211_chan(const gchar *iface, const char *freq, const gchar *type,
1300 gchar **data, gchar **primary_msg,
1301 gchar **secondary_msg, void (*update_cb)(void))
1307 argv = init_pipe_args(&argc);
1310 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1311 *secondary_msg = NULL;
1316 argv = sync_pipe_add_arg(argv, &argc, "-i");
1317 argv = sync_pipe_add_arg(argv, &argc, iface);
1320 opt = g_strdup_printf("%s,%s", freq, type);
1322 opt = g_strdup_printf("%s", freq);
1325 *primary_msg = g_strdup("Out of mem.");
1326 *secondary_msg = NULL;
1331 argv = sync_pipe_add_arg(argv, &argc, "-k");
1332 argv = sync_pipe_add_arg(argv, &argc, opt);
1335 /* Run dumpcap in capture child mode */
1336 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1337 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1340 ret = sync_pipe_run_command(argv, data, primary_msg, secondary_msg, update_cb);
1346 * Get the list of interfaces using dumpcap.
1348 * On success, *data points to a buffer containing the dumpcap output,
1349 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1350 * must be freed with g_free().
1352 * On failure, *data is NULL, *primary_msg points to an error message,
1353 * *secondary_msg either points to an additional error message or is
1354 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1355 * must be freed with g_free().
1358 sync_interface_list_open(gchar **data, gchar **primary_msg,
1359 gchar **secondary_msg, void (*update_cb)(void))
1364 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_list_open");
1366 argv = init_pipe_args(&argc);
1369 *primary_msg = g_strdup("We don't know where to find dumpcap..");
1370 *secondary_msg = NULL;
1375 /* Ask for the interface list */
1376 argv = sync_pipe_add_arg(argv, &argc, "-D");
1379 /* Run dumpcap in capture child mode */
1380 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1381 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1383 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg, update_cb);
1387 * Get the capabilities of an interface using dumpcap.
1389 * On success, *data points to a buffer containing the dumpcap output,
1390 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1391 * must be freed with g_free().
1393 * On failure, *data is NULL, *primary_msg points to an error message,
1394 * *secondary_msg either points to an additional error message or is
1395 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1396 * must be freed with g_free().
1399 sync_if_capabilities_open(const gchar *ifname, gboolean monitor_mode, const gchar* auth,
1400 gchar **data, gchar **primary_msg,
1401 gchar **secondary_msg, void (*update_cb)(void))
1406 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_if_capabilities_open");
1408 argv = init_pipe_args(&argc);
1411 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1412 *secondary_msg = NULL;
1417 /* Ask for the interface capabilities */
1418 argv = sync_pipe_add_arg(argv, &argc, "-i");
1419 argv = sync_pipe_add_arg(argv, &argc, ifname);
1420 argv = sync_pipe_add_arg(argv, &argc, "-L");
1422 argv = sync_pipe_add_arg(argv, &argc, "-I");
1424 argv = sync_pipe_add_arg(argv, &argc, "-A");
1425 argv = sync_pipe_add_arg(argv, &argc, auth);
1429 /* Run dumpcap in capture child mode */
1430 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1431 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1433 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg, update_cb);
1437 * Start getting interface statistics using dumpcap. On success, read_fd
1438 * contains the file descriptor for the pipe's stdout, *msg is unchanged,
1439 * and zero is returned. On failure, *msg will point to an error message
1440 * that must be g_free()d, and -1 will be returned.
1443 sync_interface_stats_open(int *data_read_fd, ws_process_id *fork_child, gchar **msg, void (*update_cb)(void))
1447 int message_read_fd, ret;
1449 gchar buffer[PIPE_BUF_SIZE+1] = {0};
1452 int primary_msg_len;
1453 char *primary_msg_text;
1454 int secondary_msg_len;
1455 /*char *secondary_msg_text;*/
1458 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_stats_open");
1460 argv = init_pipe_args(&argc);
1463 *msg = g_strdup("We don't know where to find dumpcap.");
1467 /* Ask for the interface statistics */
1468 argv = sync_pipe_add_arg(argv, &argc, "-S");
1471 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1473 create_dummy_signal_pipe();
1474 argv = sync_pipe_add_arg(argv, &argc, dummy_control_id);
1476 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1479 ret = sync_pipe_open_command(argv, data_read_fd, &message_read_fd,
1480 fork_child, msg, update_cb);
1485 * We were able to set up to read dumpcap's output. Do so.
1487 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1489 nread = pipe_read_block(message_read_fd, &indicator, SP_MAX_MSG_LEN,
1492 /* We got a read error from the sync pipe, or we got no data at
1493 all from the sync pipe, so we're not going to be getting any
1494 data or error message from the child process. Pick up its
1495 exit status, and complain.
1497 We don't have to worry about killing the child, if the sync pipe
1498 returned an error. Usually this error is caused as the child killed
1499 itself while going down. Even in the rare cases that this isn't the
1500 case, the child will get an error when writing to the broken pipe
1501 the next time, cleaning itself up then. */
1502 ret = sync_pipe_wait_for_child(*fork_child, &wait_msg);
1503 ws_close(message_read_fd);
1504 ws_close(*data_read_fd);
1506 /* We got an EOF from the sync pipe. That means that it exited
1507 before giving us any data to read. If ret is -1, we report
1508 that as a bad exit (e.g., exiting due to a signal); otherwise,
1509 we report it as a premature exit. */
1513 *msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1515 /* We got an error from the sync pipe. If ret is -1, report
1516 both the sync pipe I/O error and the wait error. */
1518 combined_msg = g_strdup_printf("%s\n\n%s", *msg, wait_msg);
1521 *msg = combined_msg;
1528 /* we got a valid message block from the child, process it */
1533 * Error from dumpcap; there will be a primary message and a
1534 * secondary message.
1537 /* convert primary message */
1538 pipe_convert_header((guchar*)buffer, 4, &indicator, &primary_msg_len);
1539 primary_msg_text = buffer+4;
1540 /* convert secondary message */
1541 pipe_convert_header((guchar*)primary_msg_text + primary_msg_len, 4, &indicator,
1542 &secondary_msg_len);
1543 /*secondary_msg_text = primary_msg_text + primary_msg_len + 4;*/
1544 /* the capture child will close the sync_pipe, nothing to do */
1547 * Pick up the child status.
1549 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1553 * Child process failed unexpectedly, or wait failed; msg is the
1558 * Child process failed, but returned the expected exit status.
1559 * Return the messages it gave us, and indicate failure.
1561 *msg = g_strdup(primary_msg_text);
1567 /* Close the message pipe. */
1568 ws_close(message_read_fd);
1573 * Pick up the child status.
1575 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1579 * Child process failed unexpectedly, or wait failed; msg is the
1584 * Child process returned an unknown status.
1586 *msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1595 /* Close down the stats process */
1597 sync_interface_stats_close(int *read_fd, ws_process_id *fork_child, gchar **msg)
1601 * Don't bother waiting for the child. sync_pipe_close_command
1602 * does this for us on Windows.
1604 sync_pipe_kill(*fork_child);
1606 return sync_pipe_close_command(read_fd, NULL, fork_child, msg);
1609 /* read a number of bytes from a pipe */
1610 /* (blocks until enough bytes read or an error occurs) */
1612 pipe_read_bytes(int pipe_fd, char *bytes, int required, char **msg)
1619 newly = read(pipe_fd, &bytes[offset], required);
1622 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1623 "read from pipe %d: EOF (capture closed?)", pipe_fd);
1630 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1631 "read from pipe %d: error(%u): %s", pipe_fd, error,
1633 *msg = g_strdup_printf("Error reading from sync pipe: %s",
1638 required -= (int)newly;
1646 static gboolean pipe_data_available(int pipe_fd) {
1647 #ifdef _WIN32 /* PeekNamedPipe */
1648 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
1651 if (hPipe == INVALID_HANDLE_VALUE)
1654 if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
1657 if (bytes_avail > 0)
1662 struct timeval timeout;
1665 FD_SET(pipe_fd, &rfds);
1667 timeout.tv_usec = 0;
1669 if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
1676 /* Read a line from a pipe, similar to fgets */
1678 sync_pipe_gets_nonblock(int pipe_fd, char *bytes, int max) {
1682 while(offset < max - 1) {
1684 if (! pipe_data_available(pipe_fd))
1686 newly = read(pipe_fd, &bytes[offset], 1);
1688 /* EOF - not necessarily an error */
1690 } else if (newly == -1) {
1692 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1693 "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1695 } else if (bytes[offset] == '\n') {
1701 bytes[offset] = '\0';
1707 /* convert header values (indicator and 3-byte length) */
1709 pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len) {
1711 g_assert(header_len == 4);
1713 /* convert header values */
1714 *indicator = header[0];
1715 *block_len = (header[1]&0xFF)<<16 | (header[2]&0xFF)<<8 | (header[3]&0xFF);
1718 /* read a message from the sending pipe in the standard format
1719 (1-byte message indicator, 3-byte message length (excluding length
1720 and indicator field), and the rest is the message) */
1722 pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
1729 /* read header (indicator and 3-byte length) */
1730 newly = pipe_read_bytes(pipe_fd, header, 4, err_msg);
1734 * Immediate EOF; if the capture child exits normally, this
1735 * is an "I'm done" indication, so don't report it as an
1738 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1739 "read %d got an EOF", pipe_fd);
1742 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1743 "read %d failed to read header: %lu", pipe_fd, (long)newly);
1746 * Short read, but not an immediate EOF.
1748 *err_msg = g_strdup_printf("Premature EOF reading from sync pipe: got only %ld bytes",
1754 /* convert header values */
1755 pipe_convert_header((guchar*)header, 4, indicator, &required);
1757 /* only indicator with no value? */
1759 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1760 "read %d indicator: %c empty value", pipe_fd, *indicator);
1764 /* does the data fit into the given buffer? */
1765 if(required > len) {
1766 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1767 "read %d length error, required %d > len %d, header: 0x%02x 0x%02x 0x%02x 0x%02x",
1768 pipe_fd, required, len,
1769 header[0], header[1], header[2], header[3]);
1771 /* we have a problem here, try to read some more bytes from the pipe to debug where the problem really is */
1772 memcpy(msg, header, sizeof(header));
1773 newly = read(pipe_fd, &msg[sizeof(header)], len-sizeof(header));
1774 if (newly < 0) { /* error */
1775 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1776 "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1778 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1784 /* read the actual block data */
1785 newly = pipe_read_bytes(pipe_fd, msg, required, err_msg);
1786 if(newly != required) {
1788 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1794 /* XXX If message is "2part", the msg probably won't be sent to debug log correctly */
1795 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1796 "read %d ok indicator: %c len: %u msg: %s", pipe_fd, *indicator,
1803 /* There's stuff to read from the sync pipe, meaning the child has sent
1804 us a message, or the sync pipe has closed, meaning the child has
1805 closed it (perhaps because it exited). */
1807 sync_pipe_input_cb(gint source, gpointer user_data)
1809 capture_session *cap_session = (capture_session *)user_data;
1811 char buffer[SP_MAX_MSG_LEN+1] = {0};
1817 char *secondary_msg;
1818 char *wait_msg, *combined_msg;
1821 nread = pipe_read_block(source, &indicator, SP_MAX_MSG_LEN, buffer,
1824 /* We got a read error, or a bad message, or an EOF, from the sync pipe.
1826 If we got a read error or a bad message, nread is -1 and
1827 primary_msg is set to point to an error message. We don't
1828 have to worry about killing the child; usually this error
1829 is caused as the child killed itself while going down.
1830 Even in the rare cases that this isn't the case, the child
1831 will get an error when writing to the broken pipe the next time,
1832 cleaning itself up then.
1834 If we got an EOF, nread is 0 and primary_msg isn't set. This
1835 is an indication that the capture is finished. */
1836 ret = sync_pipe_wait_for_child(cap_session->fork_child, &wait_msg);
1838 /* We got an EOF from the sync pipe. That means that the capture
1839 child exited, and not in the middle of a message; we treat
1840 that as an indication that it's done, and only report an
1841 error if ret is -1, in which case wait_msg is the error
1844 primary_msg = wait_msg;
1846 /* We got an error from the sync pipe. If ret is -1, report
1847 both the sync pipe I/O error and the wait error. */
1849 combined_msg = g_strdup_printf("%s\n\n%s", primary_msg, wait_msg);
1850 g_free(primary_msg);
1852 primary_msg = combined_msg;
1856 /* No more child process. */
1857 cap_session->fork_child = WS_INVALID_PID;
1858 cap_session->fork_child_status = ret;
1861 ws_close(cap_session->signal_pipe_write_fd);
1864 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: cleaning extcap pipe");
1865 extcap_cleanup(cap_session->capture_opts);
1867 capture_input_closed(cap_session, primary_msg);
1868 g_free(primary_msg);
1872 /* we got a valid message block from the child, process it */
1875 if(!capture_input_new_file(cap_session, buffer)) {
1876 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: file failed, closing capture");
1878 /* We weren't able to open the new capture file; user has been
1879 alerted. Close the sync pipe. */
1882 /* The child has sent us a filename which we couldn't open.
1884 This could mean that the child is creating and deleting files
1885 (ring buffer mode) faster than we can handle it.
1887 That should only be the case for very fast file switches;
1888 We can't do much more than telling the child to stop.
1889 (This is the "emergency brake" if the user e.g. wants to
1890 switch files every second).
1892 This can also happen if the user specified "-", meaning
1893 "standard output", as the capture file. */
1894 sync_pipe_stop(cap_session);
1895 capture_input_closed(cap_session, NULL);
1899 case SP_PACKET_COUNT:
1900 npackets = atoi(buffer);
1901 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: new packets %u", npackets);
1902 cap_session->count += npackets;
1903 capture_input_new_packets(cap_session, npackets);
1906 /* convert primary message */
1907 pipe_convert_header((guchar*)buffer, 4, &indicator, &primary_len);
1908 primary_msg = buffer+4;
1909 /* convert secondary message */
1910 pipe_convert_header((guchar*)primary_msg + primary_len, 4, &indicator, &secondary_len);
1911 secondary_msg = primary_msg + primary_len + 4;
1912 /* message output */
1913 capture_input_error_message(cap_session, primary_msg, secondary_msg);
1914 /* the capture child will close the sync_pipe, nothing to do for now */
1915 /* (an error message doesn't mean we have to stop capturing) */
1917 case SP_BAD_FILTER: {
1921 ch = strtok(buffer, ":");
1923 indx = (int)strtol(ch, NULL, 10);
1924 ch = strtok(NULL, ":");
1926 capture_input_cfilter_error_message(cap_session, indx, ch);
1927 /* the capture child will close the sync_pipe, nothing to do for now */
1931 capture_input_drops(cap_session, (guint32)strtoul(buffer, NULL, 10));
1934 g_assert_not_reached();
1943 * dumpcap is exiting; wait for it to exit. On success, *msgp is
1944 * unchanged, and the exit status of dumpcap is returned. On
1945 * failure (which includes "dumpcap exited due to being killed by
1946 * a signal or an exception"), *msgp points to an error message
1947 * for the failure, and -1 is returned. In the latter case, *msgp
1948 * must be freed with g_free().
1951 sync_pipe_wait_for_child(ws_process_id fork_child, gchar **msgp)
1953 int fork_child_status;
1955 int retry_waitpid = 3;
1958 GTimeVal start_time;
1963 * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
1966 g_get_current_time(&start_time);
1968 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: wait till child closed");
1969 g_assert(fork_child != WS_INVALID_PID);
1971 *msgp = NULL; /* assume no error */
1973 if (_cwait(&fork_child_status, (intptr_t) fork_child, _WAIT_CHILD) == -1) {
1974 *msgp = g_strdup_printf("Error from cwait(): %s", g_strerror(errno));
1978 * The child exited; return its exit status. Do not treat this as
1981 ret = fork_child_status;
1982 if ((fork_child_status & 0xC0000000) == ERROR_SEVERITY_ERROR) {
1983 /* Probably an exception code */
1984 *msgp = g_strdup_printf("Child dumpcap process died: %s",
1985 win32strexception(fork_child_status));
1990 while (--retry_waitpid >= 0) {
1991 if (waitpid(fork_child, &fork_child_status, 0) != -1) {
1992 /* waitpid() succeeded */
1993 if (WIFEXITED(fork_child_status)) {
1995 * The child exited; return its exit status. Do not treat this as
1998 ret = WEXITSTATUS(fork_child_status);
1999 } else if (WIFSTOPPED(fork_child_status)) {
2000 /* It stopped, rather than exiting. "Should not happen." */
2001 *msgp = g_strdup_printf("Child dumpcap process stopped: %s",
2002 sync_pipe_signame(WSTOPSIG(fork_child_status)));
2004 } else if (WIFSIGNALED(fork_child_status)) {
2005 /* It died with a signal. */
2006 *msgp = g_strdup_printf("Child dumpcap process died: %s%s",
2007 sync_pipe_signame(WTERMSIG(fork_child_status)),
2008 WCOREDUMP(fork_child_status) ? " - core dumped" : "");
2011 /* What? It had to either have exited, or stopped, or died with
2012 a signal; what happened here? */
2013 *msgp = g_strdup_printf("Bad status from waitpid(): %#o",
2018 /* waitpid() failed */
2019 if (errno == EINTR) {
2021 * Signal interrupted waitpid().
2023 * If it's SIGALRM, we just want to keep waiting, in case
2024 * there's some timer using it (e.g., in a GUI toolkit).
2026 * If you ^C TShark (or Wireshark), that should deliver
2027 * SIGINT to dumpcap as well. dumpcap catches SIGINT,
2028 * and should clean up and exit, so we should eventually
2029 * see that and clean up and terminate.
2031 * If we're sent a SIGTERM, we should (and do) catch it,
2032 * and TShark, at least, calls sync_pipe_stop(). which
2033 * kills dumpcap, so we should eventually see that and
2034 * clean up and terminate.
2036 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_WARNING, "sync_pipe_wait_for_child: waitpid returned EINTR. retrying.");
2038 } else if (errno == ECHILD) {
2040 * The process identified by fork_child either doesn't
2041 * exist any more or isn't our child process (anymore?).
2043 * echld might have already reaped the child.
2045 ret = fetch_dumpcap_pid ? 0 : -1;
2047 /* Unknown error. */
2048 *msgp = g_strdup_printf("Error from waitpid(): %s", g_strerror(errno));
2056 g_get_current_time(&end_time);
2057 elapsed = (float) ((end_time.tv_sec - start_time.tv_sec) +
2058 ((end_time.tv_usec - start_time.tv_usec) / 1e6));
2059 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: capture child closed after %.3fs", elapsed);
2065 /* convert signal to corresponding name */
2067 sync_pipe_signame(int sig)
2070 static char sigmsg_buf[6+1+3+1];
2079 sigmsg = "Interrupted";
2087 sigmsg = "Illegal instruction";
2091 sigmsg = "Trace trap";
2099 sigmsg = "Arithmetic exception";
2107 sigmsg = "Bus error";
2111 sigmsg = "Segmentation violation";
2114 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
2115 Linux is POSIX compliant. These are not POSIX-defined signals ---
2116 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
2118 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
2119 were omitted from POSIX.1 because their behavior is
2120 implementation dependent and could not be adequately catego-
2121 rized. Conforming implementations may deliver these sig-
2122 nals, but must document the circumstances under which they
2123 are delivered and note any restrictions concerning their
2126 So we only check for SIGSYS on those systems that happen to
2127 implement them (a system can be POSIX-compliant and implement
2128 them, it's just that POSIX doesn't *require* a POSIX-compliant
2129 system to implement them).
2134 sigmsg = "Bad system call";
2139 sigmsg = "Broken pipe";
2143 sigmsg = "Alarm clock";
2147 sigmsg = "Terminated";
2151 /* Returning a static buffer is ok in the context we use it here */
2152 g_snprintf(sigmsg_buf, sizeof sigmsg_buf, "Signal %d", sig);
2153 sigmsg = sigmsg_buf;
2163 static void create_dummy_signal_pipe() {
2164 gchar *dummy_signal_pipe_name;
2166 if (dummy_signal_pipe != NULL) return;
2168 if (!dummy_control_id) {
2169 dummy_control_id = g_strdup_printf("%d.dummy", GetCurrentProcessId());
2172 /* Create the signal pipe */
2173 dummy_signal_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, dummy_control_id);
2174 dummy_signal_pipe = CreateNamedPipe(utf_8to16(dummy_signal_pipe_name),
2175 PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 65535, 65535, 0, NULL);
2176 g_free(dummy_signal_pipe_name);
2179 /* tell the child through the signal pipe that we want to quit the capture */
2181 signal_pipe_capquit_to_child(capture_session *cap_session)
2183 const char quit_msg[] = "QUIT";
2186 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "signal_pipe_capquit_to_child");
2188 /* it doesn't matter *what* we send here, the first byte will stop the capture */
2189 /* simply sending a "QUIT" string */
2190 /*pipe_write_block(cap_session->signal_pipe_write_fd, SP_QUIT, quit_msg);*/
2191 ret = write(cap_session->signal_pipe_write_fd, quit_msg, sizeof quit_msg);
2193 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
2194 "signal_pipe_capquit_to_child: %d header: error %s", cap_session->signal_pipe_write_fd, g_strerror(errno));
2200 /* user wants to stop the capture run */
2202 sync_pipe_stop(capture_session *cap_session)
2207 gboolean terminate = TRUE;
2209 if (cap_session->fork_child != WS_INVALID_PID) {
2211 /* send the SIGINT signal to close the capture child gracefully. */
2212 int sts = kill(cap_session->fork_child, SIGINT);
2214 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
2215 "Sending SIGINT to child failed: %s\n", g_strerror(errno));
2218 #define STOP_SLEEP_TIME 500 /* ms */
2219 #define STOP_CHECK_TIME 50
2220 /* First, use the special signal pipe to try to close the capture child
2223 signal_pipe_capquit_to_child(cap_session);
2225 /* Next, wait for the process to exit on its own */
2226 for (count = 0; count < STOP_SLEEP_TIME / STOP_CHECK_TIME; count++) {
2227 if (GetExitCodeProcess((HANDLE) cap_session->fork_child, &childstatus) &&
2228 childstatus != STILL_ACTIVE) {
2232 Sleep(STOP_CHECK_TIME);
2235 /* Force the issue. */
2237 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
2238 "sync_pipe_stop: forcing child to exit");
2239 sync_pipe_kill(cap_session->fork_child);
2246 /* Wireshark has to exit, force the capture child to close */
2248 sync_pipe_kill(ws_process_id fork_child)
2250 if (fork_child != WS_INVALID_PID) {
2252 int sts = kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
2254 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
2255 "Sending SIGTERM to child failed: %s\n", g_strerror(errno));
2258 /* Remark: This is not the preferred method of closing a process!
2259 * the clean way would be getting the process id of the child process,
2260 * then getting window handle hWnd of that process (using EnumChildWindows),
2261 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
2263 * Unfortunately, I don't know how to get the process id from the
2264 * handle. OpenProcess will get an handle (not a window handle)
2265 * from the process ID; it will not get a window handle from the
2266 * process ID. (How could it? A process can have more than one
2267 * window. For that matter, a process might have *no* windows,
2268 * as a process running dumpcap, the normal child process program,
2271 * Hint: GenerateConsoleCtrlEvent() will only work if both processes are
2272 * running in the same console; that's not necessarily the case for
2273 * us, as we might not be running in a console.
2274 * And this also will require to have the process id.
2276 TerminateProcess((HANDLE) (fork_child), 0);
2282 void capture_sync_set_fetch_dumpcap_pid_cb(void(*cb)(ws_process_id pid)) {
2283 fetch_dumpcap_pid = cb;
2286 #endif /* HAVE_LIBPCAP */