2 * Synchronisation between Wireshark capture parent and child instances
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 #include <wsutil/unicode-utils.h>
50 #ifdef HAVE_SYS_WAIT_H
51 # include <sys/wait.h>
54 #include "capture-pcap-util.h"
58 * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
59 * macros) on UNIX systems that don't have them.
62 # define WIFEXITED(status) (((status) & 0177) == 0)
65 # define WIFSTOPPED(status) (((status) & 0177) == 0177)
68 # define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
71 # define WEXITSTATUS(status) ((status) >> 8)
74 # define WTERMSIG(status) ((status) & 0177)
77 # define WCOREDUMP(status) ((status) & 0200)
80 # define WSTOPSIG(status) ((status) >> 8)
84 #include <epan/packet.h>
85 #include <epan/prefs.h>
89 #include <epan/filesystem.h>
90 #include <epan/report_err.h>
93 #include "capture_sync.h"
95 #include "sync_pipe.h"
98 #include "capture-wpcap.h"
101 #include "ui/ui_util.h"
103 #include <wsutil/file_util.h>
107 #include <process.h> /* For spawning child process */
113 static const char *sync_pipe_signame(int);
117 static gboolean sync_pipe_input_cb(gint source, gpointer user_data);
118 static int sync_pipe_wait_for_child(int fork_child, gchar **msgp);
119 static void pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len);
120 static int pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
125 /* Append an arg (realloc) to an argc/argv array */
126 /* (add a string pointer to a NULL-terminated array of string pointers) */
128 sync_pipe_add_arg(const char **args, int *argc, const char *arg)
130 /* Grow the array; "*argc" currently contains the number of string
131 pointers, *not* counting the NULL pointer at the end, so we have
132 to add 2 in order to get the new size of the array, including the
133 new pointer and the terminating NULL pointer. */
134 args = g_realloc( (gpointer) args, (*argc + 2) * sizeof (char *));
136 /* Stuff the pointer into the penultimate element of the array, which
137 is the one at the index specified by "*argc". */
138 args[*argc] = g_strdup(arg);
139 /* Now bump the count. */
142 /* We overwrite the NULL pointer; put it back right after the
152 /* Quote the argument element if necessary, so that it will get
153 * reconstructed correctly in the C runtime startup code. Note that
154 * the unquoting algorithm in the C runtime is really weird, and
155 * rather different than what Unix shells do. See stdargv.c in the C
156 * runtime sources (in the Platform SDK, in src/crt).
158 * Stolen from GLib's protect_argv(), an internal routine that quotes
159 * string in an argument list so that they arguments will be handled
160 * correctly in the command-line string passed to CreateProcess()
161 * if that string is constructed by gluing those strings together.
164 protect_arg (const gchar *argv)
167 const gchar *p = argv;
170 gboolean need_dblquotes = FALSE;
173 if (*p == ' ' || *p == '\t')
174 need_dblquotes = TRUE;
177 else if (*p == '\\') {
180 while (*pp && *pp == '\\')
189 q = new_arg = g_malloc (len + need_dblquotes*2 + 1);
198 else if (*p == '\\') {
201 while (*pp && *pp == '\\')
218 * Generate a string for a Win32 error.
220 #define ERRBUF_SIZE 1024
222 win32strerror(DWORD error)
224 static char errbuf[ERRBUF_SIZE+1];
228 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
232 * "FormatMessage()" "helpfully" sticks CR/LF at the end of the
233 * message. Get rid of it.
235 errlen = strlen(errbuf);
237 errbuf[errlen - 1] = '\0';
238 errbuf[errlen - 2] = '\0';
240 p = strchr(errbuf, '\0');
241 g_snprintf(p, (gulong)(sizeof errbuf - (p-errbuf)), " (%lu)", error);
246 * Generate a string for a Win32 exception code.
249 win32strexception(DWORD exception)
251 static char errbuf[ERRBUF_SIZE+1];
252 static const struct exception_msg {
256 { EXCEPTION_ACCESS_VIOLATION, "Access violation" },
257 { EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded" },
258 { EXCEPTION_BREAKPOINT, "Breakpoint" },
259 { EXCEPTION_DATATYPE_MISALIGNMENT, "Data type misalignment" },
260 { EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal floating-point operand" },
261 { EXCEPTION_FLT_DIVIDE_BY_ZERO, "Floating-point divide by zero" },
262 { EXCEPTION_FLT_INEXACT_RESULT, "Floating-point inexact result" },
263 { EXCEPTION_FLT_INVALID_OPERATION, "Invalid floating-point operation" },
264 { EXCEPTION_FLT_OVERFLOW, "Floating-point overflow" },
265 { EXCEPTION_FLT_STACK_CHECK, "Floating-point stack check" },
266 { EXCEPTION_FLT_UNDERFLOW, "Floating-point underflow" },
267 { EXCEPTION_GUARD_PAGE, "Guard page violation" },
268 { EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction" },
269 { EXCEPTION_IN_PAGE_ERROR, "Page-in error" },
270 { EXCEPTION_INT_DIVIDE_BY_ZERO, "Integer divide by zero" },
271 { EXCEPTION_INT_OVERFLOW, "Integer overflow" },
272 { EXCEPTION_INVALID_DISPOSITION, "Invalid disposition" },
273 { EXCEPTION_INVALID_HANDLE, "Invalid handle" },
274 { EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception" },
275 { EXCEPTION_PRIV_INSTRUCTION, "Privileged instruction" },
276 { EXCEPTION_SINGLE_STEP, "Single-step complete" },
277 { EXCEPTION_STACK_OVERFLOW, "Stack overflow" },
280 #define N_EXCEPTIONS (sizeof exceptions / sizeof exceptions[0])
283 for (i = 0; i < N_EXCEPTIONS; i++) {
284 if (exceptions[i].code == exception)
285 return exceptions[i].msg;
287 g_snprintf(errbuf, (gulong)sizeof errbuf, "Exception 0x%08x", exception);
292 /* Initialize an argument list and add dumpcap to it. */
294 init_pipe_args(int *argc) {
296 const char *progfile_dir;
299 progfile_dir = get_progfile_dir();
300 if (progfile_dir == NULL) {
304 /* Allocate the string pointer array with enough space for the
305 terminating NULL pointer. */
307 argv = g_malloc(sizeof (char *));
310 /* take Wireshark's absolute program path and replace "Wireshark" with "dumpcap" */
311 exename = g_strdup_printf("%s" G_DIR_SEPARATOR_S "dumpcap", progfile_dir);
313 /* Make that the first argument in the argument list (argv[0]). */
314 argv = sync_pipe_add_arg(argv, argc, exename);
319 #define ARGV_NUMBER_LEN 24
320 /* a new capture run: start a new dumpcap task and hand over parameters through command line */
322 sync_pipe_start(capture_options *capture_opts) {
323 char ssnap[ARGV_NUMBER_LEN];
324 char sdlt[ARGV_NUMBER_LEN];
325 char scount[ARGV_NUMBER_LEN];
326 char sfilesize[ARGV_NUMBER_LEN];
327 char sfile_duration[ARGV_NUMBER_LEN];
328 char sring_num_files[ARGV_NUMBER_LEN];
329 char sautostop_files[ARGV_NUMBER_LEN];
330 char sautostop_filesize[ARGV_NUMBER_LEN];
331 char sautostop_duration[ARGV_NUMBER_LEN];
332 #ifdef HAVE_PCAP_REMOTE
335 #ifdef HAVE_PCAP_SETSAMPLING
336 char ssampling[ARGV_NUMBER_LEN];
339 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
340 char buffer_size[ARGV_NUMBER_LEN];
344 HANDLE sync_pipe_read; /* pipe used to send messages from child to parent */
345 HANDLE sync_pipe_write; /* pipe used to send messages from child to parent */
346 HANDLE signal_pipe; /* named pipe used to send messages from parent to child (currently only stop) */
347 GString *args = g_string_sized_new(200);
349 SECURITY_ATTRIBUTES sa;
351 PROCESS_INFORMATION pi;
352 char control_id[ARGV_NUMBER_LEN];
353 gchar *signal_pipe_name;
356 int sync_pipe[2]; /* pipe used to send messages from child to parent */
357 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
359 int sync_pipe_read_fd;
364 interface_options interface_opts;
366 if (capture_opts->ifaces->len > 1)
367 capture_opts->use_pcapng = TRUE;
368 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_start");
369 capture_opts_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, capture_opts);
371 capture_opts->fork_child = -1;
373 argv = init_pipe_args(&argc);
375 /* We don't know where to find dumpcap. */
376 report_failure("We don't know where to find dumpcap.");
380 if (capture_opts->ifaces->len > 1)
381 argv = sync_pipe_add_arg(argv, &argc, "-t");
383 if (capture_opts->use_pcapng)
384 argv = sync_pipe_add_arg(argv, &argc, "-n");
386 argv = sync_pipe_add_arg(argv, &argc, "-P");
388 if (capture_opts->multi_files_on) {
389 if (capture_opts->has_autostop_filesize) {
390 argv = sync_pipe_add_arg(argv, &argc, "-b");
391 g_snprintf(sfilesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
392 argv = sync_pipe_add_arg(argv, &argc, sfilesize);
395 if (capture_opts->has_file_duration) {
396 argv = sync_pipe_add_arg(argv, &argc, "-b");
397 g_snprintf(sfile_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->file_duration);
398 argv = sync_pipe_add_arg(argv, &argc, sfile_duration);
401 if (capture_opts->has_ring_num_files) {
402 argv = sync_pipe_add_arg(argv, &argc, "-b");
403 g_snprintf(sring_num_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->ring_num_files);
404 argv = sync_pipe_add_arg(argv, &argc, sring_num_files);
407 if (capture_opts->has_autostop_files) {
408 argv = sync_pipe_add_arg(argv, &argc, "-a");
409 g_snprintf(sautostop_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->autostop_files);
410 argv = sync_pipe_add_arg(argv, &argc, sautostop_files);
413 if (capture_opts->has_autostop_filesize) {
414 argv = sync_pipe_add_arg(argv, &argc, "-a");
415 g_snprintf(sautostop_filesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
416 argv = sync_pipe_add_arg(argv, &argc, sautostop_filesize);
420 if (capture_opts->has_autostop_packets) {
421 argv = sync_pipe_add_arg(argv, &argc, "-c");
422 g_snprintf(scount, ARGV_NUMBER_LEN, "%d",capture_opts->autostop_packets);
423 argv = sync_pipe_add_arg(argv, &argc, scount);
426 if (capture_opts->has_autostop_duration) {
427 argv = sync_pipe_add_arg(argv, &argc, "-a");
428 g_snprintf(sautostop_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->autostop_duration);
429 argv = sync_pipe_add_arg(argv, &argc, sautostop_duration);
432 for (j = 0; j < capture_opts->ifaces->len; j++) {
433 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
435 argv = sync_pipe_add_arg(argv, &argc, "-i");
436 argv = sync_pipe_add_arg(argv, &argc, interface_opts.name);
438 if (interface_opts.cfilter != NULL && strlen(interface_opts.cfilter) != 0) {
439 argv = sync_pipe_add_arg(argv, &argc, "-f");
440 argv = sync_pipe_add_arg(argv, &argc, interface_opts.cfilter);
442 if (interface_opts.snaplen != WTAP_MAX_PACKET_SIZE) {
443 argv = sync_pipe_add_arg(argv, &argc, "-s");
444 g_snprintf(ssnap, ARGV_NUMBER_LEN, "%d", interface_opts.snaplen);
445 argv = sync_pipe_add_arg(argv, &argc, ssnap);
448 if (interface_opts.linktype != -1) {
449 argv = sync_pipe_add_arg(argv, &argc, "-y");
450 g_snprintf(sdlt, ARGV_NUMBER_LEN, "%s", linktype_val_to_name(interface_opts.linktype));
451 argv = sync_pipe_add_arg(argv, &argc, sdlt);
454 if (!interface_opts.promisc_mode) {
455 argv = sync_pipe_add_arg(argv, &argc, "-p");
458 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
459 if (interface_opts.buffer_size != 1) {
460 argv = sync_pipe_add_arg(argv, &argc, "-B");
461 g_snprintf(buffer_size, ARGV_NUMBER_LEN, "%d", interface_opts.buffer_size);
462 argv = sync_pipe_add_arg(argv, &argc, buffer_size);
466 #ifdef HAVE_PCAP_CREATE
467 if (interface_opts.monitor_mode) {
468 argv = sync_pipe_add_arg(argv, &argc, "-I");
472 #ifdef HAVE_PCAP_REMOTE
473 if (interface_opts.datatx_udp)
474 argv = sync_pipe_add_arg(argv, &argc, "-u");
476 if (!interface_opts.nocap_rpcap)
477 argv = sync_pipe_add_arg(argv, &argc, "-r");
479 if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
480 argv = sync_pipe_add_arg(argv, &argc, "-A");
481 g_snprintf(sauth, sizeof(sauth), "%s:%s",
482 interface_opts.auth_username,
483 interface_opts.auth_password);
484 argv = sync_pipe_add_arg(argv, &argc, sauth);
488 #ifdef HAVE_PCAP_SETSAMPLING
489 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
490 argv = sync_pipe_add_arg(argv, &argc, "-m");
491 g_snprintf(ssampling, ARGV_NUMBER_LEN, "%s:%d",
492 interface_opts.sampling_method == CAPTURE_SAMP_BY_COUNT ? "count" :
493 interface_opts.sampling_method == CAPTURE_SAMP_BY_TIMER ? "timer" :
495 interface_opts.sampling_param);
496 argv = sync_pipe_add_arg(argv, &argc, ssampling);
501 /* dumpcap should be running in capture child mode (hidden feature) */
503 argv = sync_pipe_add_arg(argv, &argc, "-Z");
505 g_snprintf(control_id, ARGV_NUMBER_LEN, "%d", GetCurrentProcessId());
506 argv = sync_pipe_add_arg(argv, &argc, control_id);
508 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
512 if (capture_opts->save_file) {
513 argv = sync_pipe_add_arg(argv, &argc, "-w");
514 argv = sync_pipe_add_arg(argv, &argc, capture_opts->save_file);
516 for (i = 0; i < argc; i++) {
517 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", i, argv[i]);
521 /* init SECURITY_ATTRIBUTES */
522 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
523 sa.bInheritHandle = TRUE;
524 sa.lpSecurityDescriptor = NULL;
526 /* Create a pipe for the child process */
527 /* (increase this value if you have trouble while fast capture file switches) */
528 if (! CreatePipe(&sync_pipe_read, &sync_pipe_write, &sa, 5120)) {
529 /* Couldn't create the pipe between parent and child. */
530 report_failure("Couldn't create sync pipe: %s",
531 win32strerror(GetLastError()));
532 for (i = 0; i < argc; i++) {
533 g_free( (gpointer) argv[i]);
535 g_free( (gpointer) argv);
539 /* Create the signal pipe */
540 signal_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, control_id);
541 signal_pipe = CreateNamedPipe(utf_8to16(signal_pipe_name),
542 PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 65535, 65535, 0, NULL);
543 g_free(signal_pipe_name);
545 if (signal_pipe == INVALID_HANDLE_VALUE) {
546 /* Couldn't create the signal pipe between parent and child. */
547 report_failure("Couldn't create signal pipe: %s",
548 win32strerror(GetLastError()));
549 for (i = 0; i < argc; i++) {
550 g_free( (gpointer) argv[i]);
552 g_free( (gpointer) argv);
556 /* init STARTUPINFO */
557 memset(&si, 0, sizeof(si));
560 si.dwFlags = STARTF_USESHOWWINDOW;
561 si.wShowWindow = SW_SHOW;
563 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
564 si.wShowWindow = SW_HIDE; /* this hides the console window */
565 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
566 si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
567 si.hStdError = sync_pipe_write;
568 /*si.hStdError = (HANDLE) _get_osfhandle(2);*/
571 /* convert args array into a single string */
572 /* XXX - could change sync_pipe_add_arg() instead */
573 /* there is a drawback here: the length is internally limited to 1024 bytes */
574 for(i=0; argv[i] != 0; i++) {
575 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
576 quoted_arg = protect_arg(argv[i]);
577 g_string_append(args, quoted_arg);
582 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
583 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
584 report_failure("Couldn't run %s in child process: %s",
585 args->str, win32strerror(GetLastError()));
586 CloseHandle(sync_pipe_read);
587 CloseHandle(sync_pipe_write);
588 for (i = 0; i < argc; i++) {
589 g_free( (gpointer) argv[i]);
591 g_free( (gpointer) argv);
594 capture_opts->fork_child = (int) pi.hProcess;
595 g_string_free(args, TRUE);
597 /* associate the operating system filehandle to a C run-time file handle */
598 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
599 sync_pipe_read_fd = _open_osfhandle( (long) sync_pipe_read, _O_BINARY);
601 /* associate the operating system filehandle to a C run-time file handle */
602 capture_opts->signal_pipe_write_fd = _open_osfhandle( (long) signal_pipe, _O_BINARY);
605 if (pipe(sync_pipe) < 0) {
606 /* Couldn't create the pipe between parent and child. */
607 report_failure("Couldn't create sync pipe: %s", g_strerror(errno));
608 for (i = 0; i < argc; i++) {
609 g_free( (gpointer) argv[i]);
615 if ((capture_opts->fork_child = fork()) == 0) {
617 * Child process - run dumpcap with the right arguments to make
618 * it just capture with the specified capture parameters
620 dup2(sync_pipe[PIPE_WRITE], 2);
621 ws_close(sync_pipe[PIPE_READ]);
622 execv(argv[0], (gpointer)argv);
623 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
624 argv[0], g_strerror(errno));
625 sync_pipe_errmsg_to_parent(2, errmsg, "");
627 /* Exit with "_exit()", so that we don't close the connection
628 to the X server (and cause stuff buffered up by our parent but
629 not yet sent to be sent, as that stuff should only be sent by
630 our parent). We've sent an error message to the parent, so
631 we exit with an exit status of 1 (any exit status other than
632 0 or 1 will cause an additional message to report that exit
633 status, over and above the error message we sent to the parent). */
637 sync_pipe_read_fd = sync_pipe[PIPE_READ];
640 for (i = 0; i < argc; i++) {
641 g_free( (gpointer) argv[i]);
644 /* Parent process - read messages from the child process over the
646 g_free( (gpointer) argv); /* free up arg array */
648 /* Close the write side of the pipe, so that only the child has it
649 open, and thus it completely closes, and thus returns to us
650 an EOF indication, if the child closes it (either deliberately
651 or by exiting abnormally). */
653 CloseHandle(sync_pipe_write);
655 ws_close(sync_pipe[PIPE_WRITE]);
658 if (capture_opts->fork_child == -1) {
659 /* We couldn't even create the child process. */
660 report_failure("Couldn't create child process: %s", g_strerror(errno));
661 ws_close(sync_pipe_read_fd);
663 ws_close(capture_opts->signal_pipe_write_fd);
668 capture_opts->fork_child_status = 0;
670 /* we might wait for a moment till child is ready, so update screen now */
671 main_window_update();
673 /* We were able to set up to read the capture file;
674 arrange that our callback be called whenever it's possible
675 to read from the sync pipe, so that it's called when
676 the child process wants to tell us something. */
678 /* we have a running capture, now wait for the real capture filename */
679 pipe_input_set_handler(sync_pipe_read_fd, (gpointer) capture_opts,
680 &capture_opts->fork_child, sync_pipe_input_cb);
686 * Open two pipes to dumpcap with the supplied arguments, one for its
687 * standard output and one for its standard error.
689 * On success, *msg is unchanged and 0 is returned; data_read_fd,
690 * messsage_read_fd, and fork_child point to the standard output pipe's
691 * file descriptor, the standard error pipe's file descriptor, and
692 * the child's PID/handle, respectively.
694 * On failure, *msg points to an error message for the failure, and -1 is
695 * returned, in which case *msg must be freed with g_free().
697 /* XXX - This duplicates a lot of code in sync_pipe_start() */
698 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
699 #define PIPE_BUF_SIZE 5120
701 sync_pipe_open_command(const char** argv, int *data_read_fd,
702 int *message_read_fd, int *fork_child, gchar **msg)
704 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
706 HANDLE sync_pipe[2]; /* pipe used to send messages from child to parent */
707 HANDLE data_pipe[2]; /* pipe used to send data from child to parent */
708 GString *args = g_string_sized_new(200);
710 SECURITY_ATTRIBUTES sa;
712 PROCESS_INFORMATION pi;
715 int sync_pipe[2]; /* pipe used to send messages from child to parent */
716 int data_pipe[2]; /* pipe used to send data from child to parent */
721 *message_read_fd = -1;
722 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_open_command");
725 /* We can't return anything */
727 g_string_free(args, TRUE);
733 /* init SECURITY_ATTRIBUTES */
734 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
735 sa.bInheritHandle = TRUE;
736 sa.lpSecurityDescriptor = NULL;
738 /* Create a pipe for the child process to send us messages */
739 /* (increase this value if you have trouble while fast capture file switches) */
740 if (! CreatePipe(&sync_pipe[PIPE_READ], &sync_pipe[PIPE_WRITE], &sa, 5120)) {
741 /* Couldn't create the message pipe between parent and child. */
742 *msg = g_strdup_printf("Couldn't create sync pipe: %s",
743 win32strerror(GetLastError()));
744 for (i = 0; argv[i] != NULL; i++) {
745 g_free( (gpointer) argv[i]);
747 g_free( (gpointer) argv);
751 /* Create a pipe for the child process to send us data */
752 /* (increase this value if you have trouble while fast capture file switches) */
753 if (! CreatePipe(&data_pipe[PIPE_READ], &data_pipe[PIPE_WRITE], &sa, 5120)) {
754 /* Couldn't create the message pipe between parent and child. */
755 *msg = g_strdup_printf("Couldn't create data pipe: %s",
756 win32strerror(GetLastError()));
757 CloseHandle(sync_pipe[PIPE_READ]);
758 CloseHandle(sync_pipe[PIPE_WRITE]);
759 for (i = 0; argv[i] != NULL; i++) {
760 g_free( (gpointer) argv[i]);
762 g_free( (gpointer) argv);
766 /* init STARTUPINFO */
767 memset(&si, 0, sizeof(si));
770 si.dwFlags = STARTF_USESHOWWINDOW;
771 si.wShowWindow = SW_SHOW;
773 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
774 si.wShowWindow = SW_HIDE; /* this hides the console window */
776 si.hStdOutput = data_pipe[PIPE_WRITE];
777 si.hStdError = sync_pipe[PIPE_WRITE];
780 /* convert args array into a single string */
781 /* XXX - could change sync_pipe_add_arg() instead */
782 /* there is a drawback here: the length is internally limited to 1024 bytes */
783 for(i=0; argv[i] != 0; i++) {
784 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
785 quoted_arg = protect_arg(argv[i]);
786 g_string_append(args, quoted_arg);
791 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
792 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
793 *msg = g_strdup_printf("Couldn't run %s in child process: %s",
794 args->str, win32strerror(GetLastError()));
795 CloseHandle(data_pipe[PIPE_READ]);
796 CloseHandle(data_pipe[PIPE_WRITE]);
797 CloseHandle(sync_pipe[PIPE_READ]);
798 CloseHandle(sync_pipe[PIPE_WRITE]);
799 for (i = 0; argv[i] != NULL; i++) {
800 g_free( (gpointer) argv[i]);
802 g_free( (gpointer) argv);
805 *fork_child = (int) pi.hProcess;
806 g_string_free(args, TRUE);
808 /* associate the operating system filehandles to C run-time file handles */
809 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
810 *data_read_fd = _open_osfhandle( (long) data_pipe[PIPE_READ], _O_BINARY);
811 *message_read_fd = _open_osfhandle( (long) sync_pipe[PIPE_READ], _O_BINARY);
813 /* Create a pipe for the child process to send us messages */
814 if (pipe(sync_pipe) < 0) {
815 /* Couldn't create the message pipe between parent and child. */
816 *msg = g_strdup_printf("Couldn't create sync pipe: %s", g_strerror(errno));
817 for (i = 0; argv[i] != NULL; i++) {
818 g_free( (gpointer) argv[i]);
824 /* Create a pipe for the child process to send us data */
825 if (pipe(data_pipe) < 0) {
826 /* Couldn't create the data pipe between parent and child. */
827 *msg = g_strdup_printf("Couldn't create data pipe: %s", g_strerror(errno));
828 ws_close(sync_pipe[PIPE_READ]);
829 ws_close(sync_pipe[PIPE_WRITE]);
830 for (i = 0; argv[i] != NULL; i++) {
831 g_free( (gpointer) argv[i]);
837 if ((*fork_child = fork()) == 0) {
839 * Child process - run dumpcap with the right arguments to make
840 * it just capture with the specified capture parameters
842 dup2(data_pipe[PIPE_WRITE], 1);
843 ws_close(data_pipe[PIPE_READ]);
844 ws_close(data_pipe[PIPE_WRITE]);
845 dup2(sync_pipe[PIPE_WRITE], 2);
846 ws_close(sync_pipe[PIPE_READ]);
847 ws_close(sync_pipe[PIPE_WRITE]);
848 execv(argv[0], (gpointer)argv);
849 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
850 argv[0], g_strerror(errno));
851 sync_pipe_errmsg_to_parent(2, errmsg, "");
853 /* Exit with "_exit()", so that we don't close the connection
854 to the X server (and cause stuff buffered up by our parent but
855 not yet sent to be sent, as that stuff should only be sent by
856 our parent). We've sent an error message to the parent, so
857 we exit with an exit status of 1 (any exit status other than
858 0 or 1 will cause an additional message to report that exit
859 status, over and above the error message we sent to the parent). */
863 *data_read_fd = data_pipe[PIPE_READ];
864 *message_read_fd = sync_pipe[PIPE_READ];
867 for (i = 0; argv[i] != NULL; i++) {
868 g_free( (gpointer) argv[i]);
871 /* Parent process - read messages from the child process over the
873 g_free( (gpointer) argv); /* free up arg array */
875 /* Close the write sides of the pipes, so that only the child has them
876 open, and thus they completely close, and thus return to us
877 an EOF indication, if the child closes them (either deliberately
878 or by exiting abnormally). */
880 CloseHandle(data_pipe[PIPE_WRITE]);
881 CloseHandle(sync_pipe[PIPE_WRITE]);
883 ws_close(data_pipe[PIPE_WRITE]);
884 ws_close(sync_pipe[PIPE_WRITE]);
887 if (*fork_child == -1) {
888 /* We couldn't even create the child process. */
889 *msg = g_strdup_printf("Couldn't create child process: %s", g_strerror(errno));
890 ws_close(*data_read_fd);
891 ws_close(*message_read_fd);
895 /* we might wait for a moment till child is ready, so update screen now */
896 main_window_update();
901 * Close the pipes we're using to read from dumpcap, and wait for it
902 * to exit. On success, *msgp is unchanged, and the exit status of
903 * dumpcap is returned. On failure (which includes "dumpcap exited
904 * due to being killed by a signal or an exception"), *msgp points
905 * to an error message for the failure, and -1 is returned. In the
906 * latter case, *msgp must be freed with g_free().
909 sync_pipe_close_command(int *data_read_fd, int *message_read_fd,
910 int *fork_child, gchar **msgp)
912 ws_close(*data_read_fd);
913 if (message_read_fd != NULL)
914 ws_close(*message_read_fd);
917 /* XXX - Should we signal the child somehow? */
918 sync_pipe_kill(*fork_child);
921 return sync_pipe_wait_for_child(*fork_child, msgp);
925 * Run dumpcap with the supplied arguments.
927 * On success, *data points to a buffer containing the dumpcap output,
928 * *primary_msg and *secondary_message are NULL, and 0 is returned; *data
929 * must be freed with g_free().
931 * On failure, *data is NULL, *primary_msg points to an error message,
932 * *secondary_msg either points to an additional error message or is
933 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
934 * must be freed with g_free().
936 /* XXX - This duplicates a lot of code in sync_pipe_start() */
937 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
938 #define PIPE_BUF_SIZE 5120
940 sync_pipe_run_command(const char** argv, gchar **data, gchar **primary_msg,
941 gchar **secondary_msg)
944 int data_pipe_read_fd, sync_pipe_read_fd, fork_child, ret;
946 gchar buffer[PIPE_BUF_SIZE+1];
950 char *primary_msg_text;
951 int secondary_msg_len;
952 char *secondary_msg_text;
954 GString *data_buf = NULL;
957 ret = sync_pipe_open_command(argv, &data_pipe_read_fd, &sync_pipe_read_fd,
961 *secondary_msg = NULL;
967 * We were able to set up to read dumpcap's output. Do so.
969 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
971 nread = pipe_read_block(sync_pipe_read_fd, &indicator, SP_MAX_MSG_LEN,
972 buffer, primary_msg);
974 /* We got a read error from the sync pipe, or we got no data at
975 all from the sync pipe, so we're not going to be getting any
976 data or error message from the child process. Pick up its
977 exit status, and complain.
979 We don't have to worry about killing the child, if the sync pipe
980 returned an error. Usually this error is caused as the child killed
981 itself while going down. Even in the rare cases that this isn't the
982 case, the child will get an error when writing to the broken pipe
983 the next time, cleaning itself up then. */
984 ret = sync_pipe_wait_for_child(fork_child, &wait_msg);
986 /* We got an EOF from the sync pipe. That means that it exited
987 before giving us any data to read. If ret is -1, we report
988 that as a bad exit (e.g., exiting due to a signal); otherwise,
989 we report it as a premature exit. */
991 *primary_msg = wait_msg;
993 *primary_msg = g_strdup("Child dumpcap closed sync pipe prematurely");
995 /* We got an error from the sync pipe. If ret is -1, report
996 both the sync pipe I/O error and the wait error. */
998 combined_msg = g_strdup_printf("%s\n\n%s", *primary_msg, wait_msg);
999 g_free(*primary_msg);
1001 *primary_msg = combined_msg;
1004 *secondary_msg = NULL;
1009 /* we got a valid message block from the child, process it */
1014 * Error from dumpcap; there will be a primary message and a
1015 * secondary message.
1018 /* convert primary message */
1019 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1020 primary_msg_text = buffer+4;
1021 /* convert secondary message */
1022 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1023 &secondary_msg_len);
1024 secondary_msg_text = primary_msg_text + primary_msg_len + 4;
1025 /* the capture child will close the sync_pipe, nothing to do */
1028 * Pick up the child status.
1030 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1034 * Child process failed unexpectedly, or wait failed; msg is the
1038 *secondary_msg = NULL;
1041 * Child process failed, but returned the expected exit status.
1042 * Return the messages it gave us, and indicate failure.
1044 *primary_msg = g_strdup(primary_msg_text);
1045 *secondary_msg = g_strdup(secondary_msg_text);
1052 /* read the output from the command */
1053 data_buf = g_string_new("");
1054 while ((count = ws_read(data_pipe_read_fd, buffer, PIPE_BUF_SIZE)) > 0) {
1055 buffer[count] = '\0';
1056 g_string_append(data_buf, buffer);
1060 * Pick up the child status.
1062 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1066 * Child process failed unexpectedly, or wait failed; msg is the
1070 *secondary_msg = NULL;
1071 g_string_free(data_buf, TRUE);
1075 * Child process succeeded.
1077 *primary_msg = NULL;
1078 *secondary_msg = NULL;
1079 *data = data_buf->str;
1080 g_string_free(data_buf, FALSE);
1086 * Pick up the child status.
1088 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1092 * Child process failed unexpectedly, or wait failed; msg is the
1096 *secondary_msg = NULL;
1099 * Child process returned an unknown status.
1101 *primary_msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1103 *secondary_msg = NULL;
1113 * Get the list of interfaces using dumpcap.
1115 * On success, *data points to a buffer containing the dumpcap output,
1116 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1117 * must be freed with g_free().
1119 * On failure, *data is NULL, *primary_msg points to an error message,
1120 * *secondary_msg either points to an additional error message or is
1121 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1122 * must be freed with g_free().
1125 sync_interface_list_open(gchar **data, gchar **primary_msg,
1126 gchar **secondary_msg)
1131 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_list_open");
1133 argv = init_pipe_args(&argc);
1136 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1137 *secondary_msg = NULL;
1142 /* Ask for the interface list */
1143 argv = sync_pipe_add_arg(argv, &argc, "-D");
1146 /* Run dumpcap in capture child mode */
1147 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1148 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1150 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1154 * Get the capabilities of an interface using dumpcap.
1156 * On success, *data points to a buffer containing the dumpcap output,
1157 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1158 * must be freed with g_free().
1160 * On failure, *data is NULL, *primary_msg points to an error message,
1161 * *secondary_msg either points to an additional error message or is
1162 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1163 * must be freed with g_free().
1166 sync_if_capabilities_open(const gchar *ifname, gboolean monitor_mode,
1167 gchar **data, gchar **primary_msg,
1168 gchar **secondary_msg)
1173 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_linktype_list_open");
1175 argv = init_pipe_args(&argc);
1178 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1179 *secondary_msg = NULL;
1184 /* Ask for the interface capabilities */
1185 argv = sync_pipe_add_arg(argv, &argc, "-i");
1186 argv = sync_pipe_add_arg(argv, &argc, ifname);
1187 argv = sync_pipe_add_arg(argv, &argc, "-L");
1189 argv = sync_pipe_add_arg(argv, &argc, "-I");
1192 /* Run dumpcap in capture child mode */
1193 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1194 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1196 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1200 * Start getting interface statistics using dumpcap. On success, read_fd
1201 * contains the file descriptor for the pipe's stdout, *msg is unchanged,
1202 * and zero is returned. On failure, *msg will point to an error message
1203 * that must be g_free()d, and -1 will be returned.
1206 sync_interface_stats_open(int *data_read_fd, int *fork_child, gchar **msg)
1210 int message_read_fd, ret;
1212 gchar buffer[PIPE_BUF_SIZE+1];
1215 int primary_msg_len;
1216 char *primary_msg_text;
1217 int secondary_msg_len;
1218 /*char *secondary_msg_text;*/
1221 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_stats_open");
1223 argv = init_pipe_args(&argc);
1226 *msg = g_strdup("We don't know where to find dumpcap.");
1230 /* Ask for the interface statistics */
1231 argv = sync_pipe_add_arg(argv, &argc, "-S");
1234 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1235 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1237 ret = sync_pipe_open_command(argv, data_read_fd, &message_read_fd,
1243 * We were able to set up to read dumpcap's output. Do so.
1245 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1247 nread = pipe_read_block(message_read_fd, &indicator, SP_MAX_MSG_LEN,
1250 /* We got a read error from the sync pipe, or we got no data at
1251 all from the sync pipe, so we're not going to be getting any
1252 data or error message from the child process. Pick up its
1253 exit status, and complain.
1255 We don't have to worry about killing the child, if the sync pipe
1256 returned an error. Usually this error is caused as the child killed
1257 itself while going down. Even in the rare cases that this isn't the
1258 case, the child will get an error when writing to the broken pipe
1259 the next time, cleaning itself up then. */
1260 ret = sync_pipe_wait_for_child(*fork_child, &wait_msg);
1262 /* We got an EOF from the sync pipe. That means that it exited
1263 before giving us any data to read. If ret is -1, we report
1264 that as a bad exit (e.g., exiting due to a signal); otherwise,
1265 we report it as a premature exit. */
1269 *msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1271 /* We got an error from the sync pipe. If ret is -1, report
1272 both the sync pipe I/O error and the wait error. */
1274 combined_msg = g_strdup_printf("%s\n\n%s", *msg, wait_msg);
1277 *msg = combined_msg;
1284 /* we got a valid message block from the child, process it */
1289 * Error from dumpcap; there will be a primary message and a
1290 * secondary message.
1293 /* convert primary message */
1294 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1295 primary_msg_text = buffer+4;
1296 /* convert secondary message */
1297 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1298 &secondary_msg_len);
1299 /*secondary_msg_text = primary_msg_text + primary_msg_len + 4;*/
1300 /* the capture child will close the sync_pipe, nothing to do */
1303 * Pick up the child status.
1305 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1309 * Child process failed unexpectedly, or wait failed; msg is the
1314 * Child process failed, but returned the expected exit status.
1315 * Return the messages it gave us, and indicate failure.
1317 *msg = g_strdup(primary_msg_text);
1323 /* Close the message pipe. */
1324 ws_close(message_read_fd);
1329 * Pick up the child status.
1331 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1335 * Child process failed unexpectedly, or wait failed; msg is the
1340 * Child process returned an unknown status.
1342 *msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1351 /* Close down the stats process */
1353 sync_interface_stats_close(int *read_fd, int *fork_child, gchar **msg)
1355 return sync_pipe_close_command(read_fd, NULL, fork_child, msg);
1358 /* read a number of bytes from a pipe */
1359 /* (blocks until enough bytes read or an error occurs) */
1361 pipe_read_bytes(int pipe_fd, char *bytes, int required, char **msg)
1368 newly = read(pipe_fd, &bytes[offset], required);
1371 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1372 "read from pipe %d: EOF (capture closed?)", pipe_fd);
1379 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1380 "read from pipe %d: error(%u): %s", pipe_fd, error,
1382 *msg = g_strdup_printf("Error reading from sync pipe: %s",
1395 static gboolean pipe_data_available(int pipe_fd) {
1396 #ifdef _WIN32 /* PeekNamedPipe */
1397 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
1400 if (hPipe == INVALID_HANDLE_VALUE)
1403 if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
1406 if (bytes_avail > 0)
1411 struct timeval timeout;
1414 FD_SET(pipe_fd, &rfds);
1416 timeout.tv_usec = 0;
1418 if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
1425 /* Read a line from a pipe, similar to fgets */
1427 sync_pipe_gets_nonblock(int pipe_fd, char *bytes, int max) {
1431 while(offset < max - 1) {
1433 if (! pipe_data_available(pipe_fd))
1435 newly = read(pipe_fd, &bytes[offset], 1);
1437 /* EOF - not necessarily an error */
1439 } else if (newly < 0) {
1441 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1442 "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1444 } else if (bytes[offset] == '\n') {
1450 bytes[offset] = '\0';
1456 /* convert header values (indicator and 3-byte length) */
1458 pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len) {
1460 g_assert(header_len == 4);
1462 /* convert header values */
1463 *indicator = header[0];
1464 *block_len = header[1]<<16 | header[2]<<8 | header[3];
1467 /* read a message from the sending pipe in the standard format
1468 (1-byte message indicator, 3-byte message length (excluding length
1469 and indicator field), and the rest is the message) */
1471 pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
1478 /* read header (indicator and 3-byte length) */
1479 newly = pipe_read_bytes(pipe_fd, header, 4, err_msg);
1483 * Immediate EOF; if the capture child exits normally, this
1484 * is an "I'm done" indication, so don't report it as an
1487 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1488 "read %d got an EOF", pipe_fd);
1491 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1492 "read %d failed to read header: %u", pipe_fd, newly);
1495 * Short read, but not an immediate EOF.
1497 *err_msg = g_strdup_printf("Premature EOF reading from sync pipe: got only %d bytes",
1503 /* convert header values */
1504 pipe_convert_header(header, 4, indicator, &required);
1506 /* only indicator with no value? */
1508 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1509 "read %d indicator: %c empty value", pipe_fd, *indicator);
1513 /* does the data fit into the given buffer? */
1514 if(required > len) {
1515 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1516 "read %d length error, required %d > len %d, indicator: %u",
1517 pipe_fd, required, len, *indicator);
1519 /* we have a problem here, try to read some more bytes from the pipe to debug where the problem really is */
1520 memcpy(msg, header, sizeof(header));
1521 newly = read(pipe_fd, &msg[sizeof(header)], len-sizeof(header));
1522 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1528 /* read the actual block data */
1529 newly = pipe_read_bytes(pipe_fd, msg, required, err_msg);
1530 if(newly != required) {
1532 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1538 /* XXX If message is "2part", the msg probably won't be sent to debug log correctly */
1539 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1540 "read %d ok indicator: %c len: %u msg: %s", pipe_fd, *indicator,
1547 /* There's stuff to read from the sync pipe, meaning the child has sent
1548 us a message, or the sync pipe has closed, meaning the child has
1549 closed it (perhaps because it exited). */
1551 sync_pipe_input_cb(gint source, gpointer user_data)
1553 capture_options *capture_opts = (capture_options *)user_data;
1555 char buffer[SP_MAX_MSG_LEN+1];
1561 char *secondary_msg;
1562 char *wait_msg, *combined_msg;
1564 nread = pipe_read_block(source, &indicator, SP_MAX_MSG_LEN, buffer,
1567 /* We got a read error, or a bad message, or an EOF, from the sync pipe.
1569 If we got a read error or a bad message, nread is -1 and
1570 primary_msg is set to point to an error message. We don't
1571 have to worry about killing the child; usually this error
1572 is caused as the child killed itself while going down.
1573 Even in the rare cases that this isn't the case, the child
1574 will get an error when writing to the broken pipe the next time,
1575 cleaning itself up then.
1577 If we got an EOF, nread is 0 and primary_msg isn't set. This
1578 is an indication that the capture is finished. */
1579 ret = sync_pipe_wait_for_child(capture_opts->fork_child, &wait_msg);
1581 /* We got an EOF from the sync pipe. That means that the capture
1582 child exited, and not in the middle of a message; we treat
1583 that as an indication that it's done, and only report an
1584 error if ret is -1, in which case wait_msg is the error
1587 primary_msg = wait_msg;
1589 /* We got an error from the sync pipe. If ret is -1, report
1590 both the sync pipe I/O error and the wait error. */
1592 combined_msg = g_strdup_printf("%s\n\n%s", primary_msg, wait_msg);
1593 g_free(primary_msg);
1595 primary_msg = combined_msg;
1599 /* No more child process. */
1600 capture_opts->fork_child = -1;
1601 capture_opts->fork_child_status = ret;
1604 ws_close(capture_opts->signal_pipe_write_fd);
1606 capture_input_closed(capture_opts, primary_msg);
1607 g_free(primary_msg);
1611 /* we got a valid message block from the child, process it */
1614 if(!capture_input_new_file(capture_opts, buffer)) {
1615 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: file failed, closing capture");
1617 /* We weren't able to open the new capture file; user has been
1618 alerted. Close the sync pipe. */
1621 /* The child has sent us a filename which we couldn't open.
1623 This could mean that the child is creating files faster
1624 than we can handle it. (XXX - why would that result in
1625 a failure to open the file?)
1627 That should only be the case for very fast file switches;
1628 We can't do much more than telling the child to stop.
1629 (This is the "emergency brake" if the user e.g. wants to
1630 switch files every second).
1632 This can also happen if the user specified "-", meaning
1633 "standard output", as the capture file. */
1634 sync_pipe_stop(capture_opts);
1635 capture_input_closed(capture_opts, NULL);
1639 case SP_PACKET_COUNT:
1640 nread = atoi(buffer);
1641 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: new packets %u", nread);
1642 capture_input_new_packets(capture_opts, nread);
1645 /* convert primary message */
1646 pipe_convert_header(buffer, 4, &indicator, &primary_len);
1647 primary_msg = buffer+4;
1648 /* convert secondary message */
1649 pipe_convert_header(primary_msg + primary_len, 4, &indicator, &secondary_len);
1650 secondary_msg = primary_msg + primary_len + 4;
1651 /* message output */
1652 capture_input_error_message(capture_opts, primary_msg, secondary_msg);
1653 /* the capture child will close the sync_pipe, nothing to do for now */
1654 /* (an error message doesn't mean we have to stop capturing) */
1656 case SP_BAD_FILTER: {
1660 ch = strtok(buffer, ":");
1661 index = (int)strtol(ch, NULL, 10);
1662 ch = strtok(NULL, ":");
1663 capture_input_cfilter_error_message(capture_opts, index, ch);
1664 /* the capture child will close the sync_pipe, nothing to do for now */
1668 capture_input_drops(capture_opts, (guint32)strtoul(buffer, NULL, 10));
1671 g_assert_not_reached();
1680 * dumpcap is exiting; wait for it to exit. On success, *msgp is
1681 * unchanged, and the exit status of dumpcap is returned. On
1682 * failure (which includes "dumpcap exited due to being killed by
1683 * a signal or an exception"), *msgp points to an error message
1684 * for the failure, and -1 is returned. In the latter case, *msgp
1685 * must be freed with g_free().
1688 sync_pipe_wait_for_child(int fork_child, gchar **msgp)
1690 int fork_child_status;
1693 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: wait till child closed");
1694 g_assert(fork_child != -1);
1696 *msgp = NULL; /* assume no error */
1698 if (_cwait(&fork_child_status, fork_child, _WAIT_CHILD) == -1) {
1699 *msgp = g_strdup_printf("Error from cwait(): %s", g_strerror(errno));
1703 * The child exited; return its exit status. Do not treat this as
1706 ret = fork_child_status;
1707 if ((fork_child_status & 0xC0000000) == ERROR_SEVERITY_ERROR) {
1708 /* Probably an exception code */
1709 *msgp = g_strdup_printf("Child dumpcap process died: %s",
1710 win32strexception(fork_child_status));
1715 if (waitpid(fork_child, &fork_child_status, 0) != -1) {
1716 if (WIFEXITED(fork_child_status)) {
1718 * The child exited; return its exit status. Do not treat this as
1721 ret = WEXITSTATUS(fork_child_status);
1722 } else if (WIFSTOPPED(fork_child_status)) {
1723 /* It stopped, rather than exiting. "Should not happen." */
1724 *msgp = g_strdup_printf("Child dumpcap process stopped: %s",
1725 sync_pipe_signame(WSTOPSIG(fork_child_status)));
1727 } else if (WIFSIGNALED(fork_child_status)) {
1728 /* It died with a signal. */
1729 *msgp = g_strdup_printf("Child dumpcap process died: %s%s",
1730 sync_pipe_signame(WTERMSIG(fork_child_status)),
1731 WCOREDUMP(fork_child_status) ? " - core dumped" : "");
1734 /* What? It had to either have exited, or stopped, or died with
1735 a signal; what happened here? */
1736 *msgp = g_strdup_printf("Bad status from waitpid(): %#o",
1741 *msgp = g_strdup_printf("Error from waitpid(): %s", g_strerror(errno));
1746 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: capture child closed");
1752 /* convert signal to corresponding name */
1754 sync_pipe_signame(int sig)
1757 static char sigmsg_buf[6+1+3+1];
1766 sigmsg = "Interrupted";
1774 sigmsg = "Illegal instruction";
1778 sigmsg = "Trace trap";
1786 sigmsg = "Arithmetic exception";
1794 sigmsg = "Bus error";
1798 sigmsg = "Segmentation violation";
1801 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1802 Linux is POSIX compliant. These are not POSIX-defined signals ---
1803 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1805 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1806 were omitted from POSIX.1 because their behavior is
1807 implementation dependent and could not be adequately catego-
1808 rized. Conforming implementations may deliver these sig-
1809 nals, but must document the circumstances under which they
1810 are delivered and note any restrictions concerning their
1813 So we only check for SIGSYS on those systems that happen to
1814 implement them (a system can be POSIX-compliant and implement
1815 them, it's just that POSIX doesn't *require* a POSIX-compliant
1816 system to implement them).
1821 sigmsg = "Bad system call";
1826 sigmsg = "Broken pipe";
1830 sigmsg = "Alarm clock";
1834 sigmsg = "Terminated";
1838 /* Returning a static buffer is ok in the context we use it here */
1839 g_snprintf(sigmsg_buf, sizeof sigmsg_buf, "Signal %d", sig);
1840 sigmsg = sigmsg_buf;
1849 /* tell the child through the signal pipe that we want to quit the capture */
1851 signal_pipe_capquit_to_child(capture_options *capture_opts)
1853 const char quit_msg[] = "QUIT";
1857 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "signal_pipe_capquit_to_child");
1859 /* it doesn't matter *what* we send here, the first byte will stop the capture */
1860 /* simply sending a "QUIT" string */
1861 /*pipe_write_block(capture_opts->signal_pipe_write_fd, SP_QUIT, quit_msg);*/
1862 ret = write(capture_opts->signal_pipe_write_fd, quit_msg, sizeof quit_msg);
1864 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1865 "signal_pipe_capquit_to_child: %d header: error %s", capture_opts->signal_pipe_write_fd, g_strerror(errno));
1871 /* user wants to stop the capture run */
1873 sync_pipe_stop(capture_options *capture_opts)
1878 gboolean terminate = TRUE;
1881 if (capture_opts->fork_child != -1) {
1883 /* send the SIGINT signal to close the capture child gracefully. */
1884 int sts = kill(capture_opts->fork_child, SIGINT);
1886 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1887 "Sending SIGINT to child failed: %s\n", g_strerror(errno));
1890 #define STOP_SLEEP_TIME 500 /* ms */
1891 #define STOP_CHECK_TIME 50
1892 /* First, use the special signal pipe to try to close the capture child
1895 signal_pipe_capquit_to_child(capture_opts);
1897 /* Next, wait for the process to exit on its own */
1898 for (count = 0; count < STOP_SLEEP_TIME / STOP_CHECK_TIME; count++) {
1899 if (GetExitCodeProcess((HANDLE) capture_opts->fork_child, &childstatus) &&
1900 childstatus != STILL_ACTIVE) {
1904 Sleep(STOP_CHECK_TIME);
1907 /* Force the issue. */
1909 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1910 "sync_pipe_stop: forcing child to exit");
1911 sync_pipe_kill(capture_opts->fork_child);
1918 /* Wireshark has to exit, force the capture child to close */
1920 sync_pipe_kill(int fork_child)
1922 if (fork_child != -1) {
1924 int sts = kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
1926 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1927 "Sending SIGTERM to child failed: %s\n", g_strerror(errno));
1930 /* Remark: This is not the preferred method of closing a process!
1931 * the clean way would be getting the process id of the child process,
1932 * then getting window handle hWnd of that process (using EnumChildWindows),
1933 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
1935 * Unfortunately, I don't know how to get the process id from the
1936 * handle. OpenProcess will get an handle (not a window handle)
1937 * from the process ID; it will not get a window handle from the
1938 * process ID. (How could it? A process can have more than one
1939 * window. For that matter, a process might have *no* windows,
1940 * as a process running dumpcap, the normal child process program,
1943 * Hint: GenerateConsoleCtrlEvent() will only work if both processes are
1944 * running in the same console; that's not necessarily the case for
1945 * us, as we might not be running in a console.
1946 * And this also will require to have the process id.
1948 TerminateProcess((HANDLE) (fork_child), 0);
1953 #endif /* HAVE_LIBPCAP */