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 <wsutil/file_util.h>
105 #include <process.h> /* For spawning child process */
111 static const char *sync_pipe_signame(int);
115 static gboolean sync_pipe_input_cb(gint source, gpointer user_data);
116 static int sync_pipe_wait_for_child(int fork_child, gchar **msgp);
117 static void pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len);
118 static int pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
123 /* Append an arg (realloc) to an argc/argv array */
124 /* (add a string pointer to a NULL-terminated array of string pointers) */
126 sync_pipe_add_arg(const char **args, int *argc, const char *arg)
129 /* Grow the array; "*argc" currently contains the number of string
130 pointers, *not* counting the NULL pointer at the end, so we have
131 to add 2 in order to get the new size of the array, including the
132 new pointer and the terminating NULL pointer. */
133 args = g_realloc( (gpointer) args, (*argc + 2) * sizeof (char *));
135 /* Stuff the pointer into the penultimate element of the array, which
136 is the one at the index specified by "*argc". */
137 temparg = g_strdup_printf("%s", arg);
138 args[*argc] = temparg;
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 if (interface_opts.monitor_mode) {
467 argv = sync_pipe_add_arg(argv, &argc, "-I");
470 #ifdef HAVE_PCAP_REMOTE
471 if (interface_opts.datatx_udp)
472 argv = sync_pipe_add_arg(argv, &argc, "-u");
474 if (!interface_opts.nocap_rpcap)
475 argv = sync_pipe_add_arg(argv, &argc, "-r");
477 if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
478 argv = sync_pipe_add_arg(argv, &argc, "-A");
479 g_snprintf(sauth, sizeof(sauth), "%s:%s",
480 interface_opts.auth_username,
481 interface_opts.auth_password);
482 argv = sync_pipe_add_arg(argv, &argc, sauth);
486 #ifdef HAVE_PCAP_SETSAMPLING
487 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
488 argv = sync_pipe_add_arg(argv, &argc, "-m");
489 g_snprintf(ssampling, ARGV_NUMBER_LEN, "%s:%d",
490 interface_opts.sampling_method == CAPTURE_SAMP_BY_COUNT ? "count" :
491 interface_opts.sampling_method == CAPTURE_SAMP_BY_TIMER ? "timer" :
493 interface_opts.sampling_param);
494 argv = sync_pipe_add_arg(argv, &argc, ssampling);
499 /* dumpcap should be running in capture child mode (hidden feature) */
501 argv = sync_pipe_add_arg(argv, &argc, "-Z");
503 g_snprintf(control_id, ARGV_NUMBER_LEN, "%d", GetCurrentProcessId());
504 argv = sync_pipe_add_arg(argv, &argc, control_id);
506 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
510 if (capture_opts->save_file) {
511 argv = sync_pipe_add_arg(argv, &argc, "-w");
512 argv = sync_pipe_add_arg(argv, &argc, capture_opts->save_file);
514 for (i = 0; i < argc; i++) {
515 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", i, argv[i]);
519 /* init SECURITY_ATTRIBUTES */
520 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
521 sa.bInheritHandle = TRUE;
522 sa.lpSecurityDescriptor = NULL;
524 /* Create a pipe for the child process */
525 /* (increase this value if you have trouble while fast capture file switches) */
526 if (! CreatePipe(&sync_pipe_read, &sync_pipe_write, &sa, 5120)) {
527 /* Couldn't create the pipe between parent and child. */
528 report_failure("Couldn't create sync pipe: %s",
529 win32strerror(GetLastError()));
530 for (i = 0; i < argc; i++) {
531 g_free( (gpointer) argv[i]);
533 g_free( (gpointer) argv);
537 /* Create the signal pipe */
538 signal_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, control_id);
539 signal_pipe = CreateNamedPipe(utf_8to16(signal_pipe_name),
540 PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 65535, 65535, 0, NULL);
541 g_free(signal_pipe_name);
543 if (signal_pipe == INVALID_HANDLE_VALUE) {
544 /* Couldn't create the signal pipe between parent and child. */
545 report_failure("Couldn't create signal pipe: %s",
546 win32strerror(GetLastError()));
547 for (i = 0; i < argc; i++) {
548 g_free( (gpointer) argv[i]);
550 g_free( (gpointer) argv);
554 /* init STARTUPINFO */
555 memset(&si, 0, sizeof(si));
558 si.dwFlags = STARTF_USESHOWWINDOW;
559 si.wShowWindow = SW_SHOW;
561 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
562 si.wShowWindow = SW_HIDE; /* this hides the console window */
563 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
564 si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
565 si.hStdError = sync_pipe_write;
566 /*si.hStdError = (HANDLE) _get_osfhandle(2);*/
569 /* convert args array into a single string */
570 /* XXX - could change sync_pipe_add_arg() instead */
571 /* there is a drawback here: the length is internally limited to 1024 bytes */
572 for(i=0; argv[i] != 0; i++) {
573 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
574 quoted_arg = protect_arg(argv[i]);
575 g_string_append(args, quoted_arg);
580 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
581 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
582 report_failure("Couldn't run %s in child process: %s",
583 args->str, win32strerror(GetLastError()));
584 CloseHandle(sync_pipe_read);
585 CloseHandle(sync_pipe_write);
586 for (i = 0; i < argc; i++) {
587 g_free( (gpointer) argv[i]);
589 g_free( (gpointer) argv);
592 capture_opts->fork_child = (int) pi.hProcess;
593 g_string_free(args, TRUE);
595 /* associate the operating system filehandle to a C run-time file handle */
596 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
597 sync_pipe_read_fd = _open_osfhandle( (long) sync_pipe_read, _O_BINARY);
599 /* associate the operating system filehandle to a C run-time file handle */
600 capture_opts->signal_pipe_write_fd = _open_osfhandle( (long) signal_pipe, _O_BINARY);
603 if (pipe(sync_pipe) < 0) {
604 /* Couldn't create the pipe between parent and child. */
605 report_failure("Couldn't create sync pipe: %s", g_strerror(errno));
606 for (i = 0; i < argc; i++) {
607 g_free( (gpointer) argv[i]);
613 if ((capture_opts->fork_child = fork()) == 0) {
615 * Child process - run dumpcap with the right arguments to make
616 * it just capture with the specified capture parameters
618 dup2(sync_pipe[PIPE_WRITE], 2);
619 ws_close(sync_pipe[PIPE_READ]);
620 execv(argv[0], (gpointer)argv);
621 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
622 argv[0], g_strerror(errno));
623 sync_pipe_errmsg_to_parent(2, errmsg, "");
625 /* Exit with "_exit()", so that we don't close the connection
626 to the X server (and cause stuff buffered up by our parent but
627 not yet sent to be sent, as that stuff should only be sent by
628 our parent). We've sent an error message to the parent, so
629 we exit with an exit status of 1 (any exit status other than
630 0 or 1 will cause an additional message to report that exit
631 status, over and above the error message we sent to the parent). */
635 sync_pipe_read_fd = sync_pipe[PIPE_READ];
638 for (i = 0; i < argc; i++) {
639 g_free( (gpointer) argv[i]);
642 /* Parent process - read messages from the child process over the
644 g_free( (gpointer) argv); /* free up arg array */
646 /* Close the write side of the pipe, so that only the child has it
647 open, and thus it completely closes, and thus returns to us
648 an EOF indication, if the child closes it (either deliberately
649 or by exiting abnormally). */
651 CloseHandle(sync_pipe_write);
653 ws_close(sync_pipe[PIPE_WRITE]);
656 if (capture_opts->fork_child == -1) {
657 /* We couldn't even create the child process. */
658 report_failure("Couldn't create child process: %s", g_strerror(errno));
659 ws_close(sync_pipe_read_fd);
661 ws_close(capture_opts->signal_pipe_write_fd);
666 capture_opts->fork_child_status = 0;
668 /* we might wait for a moment till child is ready, so update screen now */
669 main_window_update();
671 /* We were able to set up to read the capture file;
672 arrange that our callback be called whenever it's possible
673 to read from the sync pipe, so that it's called when
674 the child process wants to tell us something. */
676 /* we have a running capture, now wait for the real capture filename */
677 pipe_input_set_handler(sync_pipe_read_fd, (gpointer) capture_opts,
678 &capture_opts->fork_child, sync_pipe_input_cb);
684 * Open two pipes to dumpcap with the supplied arguments, one for its
685 * standard output and one for its standard error.
687 * On success, *msg is unchanged and 0 is returned; data_read_fd,
688 * messsage_read_fd, and fork_child point to the standard output pipe's
689 * file descriptor, the standard error pipe's file descriptor, and
690 * the child's PID/handle, respectively.
692 * On failure, *msg points to an error message for the failure, and -1 is
693 * returned, in which case *msg must be freed with g_free().
695 /* XXX - This duplicates a lot of code in sync_pipe_start() */
696 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
697 #define PIPE_BUF_SIZE 5120
699 sync_pipe_open_command(const char** argv, int *data_read_fd,
700 int *message_read_fd, int *fork_child, gchar **msg)
702 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
704 HANDLE sync_pipe[2]; /* pipe used to send messages from child to parent */
705 HANDLE data_pipe[2]; /* pipe used to send data from child to parent */
706 GString *args = g_string_sized_new(200);
708 SECURITY_ATTRIBUTES sa;
710 PROCESS_INFORMATION pi;
713 int sync_pipe[2]; /* pipe used to send messages from child to parent */
714 int data_pipe[2]; /* pipe used to send data from child to parent */
719 *message_read_fd = -1;
720 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_open_command");
723 /* We can't return anything */
725 g_string_free(args, TRUE);
731 /* init SECURITY_ATTRIBUTES */
732 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
733 sa.bInheritHandle = TRUE;
734 sa.lpSecurityDescriptor = NULL;
736 /* Create a pipe for the child process to send us messages */
737 /* (increase this value if you have trouble while fast capture file switches) */
738 if (! CreatePipe(&sync_pipe[PIPE_READ], &sync_pipe[PIPE_WRITE], &sa, 5120)) {
739 /* Couldn't create the message pipe between parent and child. */
740 *msg = g_strdup_printf("Couldn't create sync pipe: %s",
741 win32strerror(GetLastError()));
742 for (i = 0; i < argc; i++) {
743 g_free( (gpointer) argv[i]);
745 g_free( (gpointer) argv);
749 /* Create a pipe for the child process to send us data */
750 /* (increase this value if you have trouble while fast capture file switches) */
751 if (! CreatePipe(&data_pipe[PIPE_READ], &data_pipe[PIPE_WRITE], &sa, 5120)) {
752 /* Couldn't create the message pipe between parent and child. */
753 *msg = g_strdup_printf("Couldn't create data pipe: %s",
754 win32strerror(GetLastError()));
755 CloseHandle(sync_pipe[PIPE_READ]);
756 CloseHandle(sync_pipe[PIPE_WRITE]);
757 for (i = 0; i < argc; i++) {
758 g_free( (gpointer) argv[i]);
760 g_free( (gpointer) argv);
764 /* init STARTUPINFO */
765 memset(&si, 0, sizeof(si));
768 si.dwFlags = STARTF_USESHOWWINDOW;
769 si.wShowWindow = SW_SHOW;
771 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
772 si.wShowWindow = SW_HIDE; /* this hides the console window */
774 si.hStdOutput = data_pipe[PIPE_WRITE];
775 si.hStdError = sync_pipe[PIPE_WRITE];
778 /* convert args array into a single string */
779 /* XXX - could change sync_pipe_add_arg() instead */
780 /* there is a drawback here: the length is internally limited to 1024 bytes */
781 for(i=0; argv[i] != 0; i++) {
782 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
783 quoted_arg = protect_arg(argv[i]);
784 g_string_append(args, quoted_arg);
789 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
790 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
791 *msg = g_strdup_printf("Couldn't run %s in child process: %s",
792 args->str, win32strerror(GetLastError()));
793 CloseHandle(data_pipe[PIPE_READ]);
794 CloseHandle(data_pipe[PIPE_WRITE]);
795 CloseHandle(sync_pipe[PIPE_READ]);
796 CloseHandle(sync_pipe[PIPE_WRITE]);
797 for (i = 0; i < argc; i++) {
798 g_free( (gpointer) argv[i]);
800 g_free( (gpointer) argv);
803 *fork_child = (int) pi.hProcess;
804 g_string_free(args, TRUE);
806 /* associate the operating system filehandles to C run-time file handles */
807 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
808 *data_read_fd = _open_osfhandle( (long) data_pipe[PIPE_READ], _O_BINARY);
809 *message_read_fd = _open_osfhandle( (long) sync_pipe[PIPE_READ], _O_BINARY);
811 /* Create a pipe for the child process to send us messages */
812 if (pipe(sync_pipe) < 0) {
813 /* Couldn't create the message pipe between parent and child. */
814 *msg = g_strdup_printf("Couldn't create sync pipe: %s", g_strerror(errno));
815 for (i = 0; argv[i] != NULL; i++) {
816 g_free( (gpointer) argv[i]);
822 /* Create a pipe for the child process to send us data */
823 if (pipe(data_pipe) < 0) {
824 /* Couldn't create the data pipe between parent and child. */
825 *msg = g_strdup_printf("Couldn't create data pipe: %s", g_strerror(errno));
826 ws_close(sync_pipe[PIPE_READ]);
827 ws_close(sync_pipe[PIPE_WRITE]);
828 for (i = 0; argv[i] != NULL; i++) {
829 g_free( (gpointer) argv[i]);
835 if ((*fork_child = fork()) == 0) {
837 * Child process - run dumpcap with the right arguments to make
838 * it just capture with the specified capture parameters
840 dup2(data_pipe[PIPE_WRITE], 1);
841 ws_close(data_pipe[PIPE_READ]);
842 ws_close(data_pipe[PIPE_WRITE]);
843 dup2(sync_pipe[PIPE_WRITE], 2);
844 ws_close(sync_pipe[PIPE_READ]);
845 ws_close(sync_pipe[PIPE_WRITE]);
846 execv(argv[0], (gpointer)argv);
847 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
848 argv[0], g_strerror(errno));
849 sync_pipe_errmsg_to_parent(2, errmsg, "");
851 /* Exit with "_exit()", so that we don't close the connection
852 to the X server (and cause stuff buffered up by our parent but
853 not yet sent to be sent, as that stuff should only be sent by
854 our parent). We've sent an error message to the parent, so
855 we exit with an exit status of 1 (any exit status other than
856 0 or 1 will cause an additional message to report that exit
857 status, over and above the error message we sent to the parent). */
861 *data_read_fd = data_pipe[PIPE_READ];
862 *message_read_fd = sync_pipe[PIPE_READ];
865 for (i = 0; argv[i] != NULL; i++) {
866 g_free( (gpointer) argv[i]);
869 /* Parent process - read messages from the child process over the
871 g_free( (gpointer) argv); /* free up arg array */
873 /* Close the write sides of the pipes, so that only the child has them
874 open, and thus they completely close, and thus return to us
875 an EOF indication, if the child closes them (either deliberately
876 or by exiting abnormally). */
878 CloseHandle(data_pipe[PIPE_WRITE]);
879 CloseHandle(sync_pipe[PIPE_WRITE]);
881 ws_close(data_pipe[PIPE_WRITE]);
882 ws_close(sync_pipe[PIPE_WRITE]);
885 if (*fork_child == -1) {
886 /* We couldn't even create the child process. */
887 *msg = g_strdup_printf("Couldn't create child process: %s", g_strerror(errno));
888 ws_close(*data_read_fd);
889 ws_close(*message_read_fd);
893 /* we might wait for a moment till child is ready, so update screen now */
894 main_window_update();
899 * Wait for dumpcap to finish. On success, *msg is unchanged, and 0 is
900 * returned. On failure, *msg points to an error message for the
901 * failure, and -1 is returned. In the latter case, *msg must be
902 * freed with g_free().
905 sync_pipe_close_command(int *data_read_fd, int *message_read_fd,
906 int *fork_child, gchar **msg)
908 ws_close(*data_read_fd);
909 if (message_read_fd != NULL)
910 ws_close(*message_read_fd);
913 /* XXX - Should we signal the child somehow? */
914 sync_pipe_kill(*fork_child);
917 return sync_pipe_wait_for_child(*fork_child, msg);
921 * Run dumpcap with the supplied arguments.
923 * On success, *data points to a buffer containing the dumpcap output,
924 * *primary_msg and *secondary_message are NULL, and 0 is returned; *data
925 * must be freed with g_free().
927 * On failure, *data is NULL, *primary_msg points to an error message,
928 * *secondary_msg either points to an additional error message or is
929 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
930 * must be freed with g_free().
932 /* XXX - This duplicates a lot of code in sync_pipe_start() */
933 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
934 #define PIPE_BUF_SIZE 5120
936 sync_pipe_run_command(const char** argv, gchar **data, gchar **primary_msg,
937 gchar **secondary_msg)
940 int data_pipe_read_fd, sync_pipe_read_fd, fork_child, ret;
942 gchar buffer[PIPE_BUF_SIZE+1];
946 char *primary_msg_text;
947 int secondary_msg_len;
948 char *secondary_msg_text;
950 GString *data_buf = NULL;
953 ret = sync_pipe_open_command(argv, &data_pipe_read_fd, &sync_pipe_read_fd,
957 *secondary_msg = NULL;
963 * We were able to set up to read dumpcap's output. Do so.
965 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
967 nread = pipe_read_block(sync_pipe_read_fd, &indicator, SP_MAX_MSG_LEN,
968 buffer, primary_msg);
970 /* We got a read error from the sync pipe, or we got no data at
971 all from the sync pipe, so we're not going to be getting any
972 data or error message from the child process. Pick up its
973 exit status, and complain.
975 We don't have to worry about killing the child, if the sync pipe
976 returned an error. Usually this error is caused as the child killed
977 itself while going down. Even in the rare cases that this isn't the
978 case, the child will get an error when writing to the broken pipe
979 the next time, cleaning itself up then. */
980 ret = sync_pipe_wait_for_child(fork_child, &wait_msg);
982 /* We got an EOF from the sync pipe. That means that it exited
983 before giving us any data to read. If ret is -1, we report
984 that as a bad exit (e.g., exiting due to a signal); otherwise,
985 we report it as a premature exit. */
987 *primary_msg = wait_msg;
989 *primary_msg = g_strdup("Child dumpcap closed sync pipe prematurely");
991 /* We got an error from the sync pipe. If ret is -1, report
992 both the sync pipe I/O error and the wait error. */
994 combined_msg = g_strdup_printf("%s\n\n%s", *primary_msg, wait_msg);
995 g_free(*primary_msg);
997 *primary_msg = combined_msg;
1000 *secondary_msg = NULL;
1005 /* we got a valid message block from the child, process it */
1010 * Error from dumpcap; there will be a primary message and a
1011 * secondary message.
1014 /* convert primary message */
1015 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1016 primary_msg_text = buffer+4;
1017 /* convert secondary message */
1018 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1019 &secondary_msg_len);
1020 secondary_msg_text = primary_msg_text + primary_msg_len + 4;
1021 /* the capture child will close the sync_pipe, nothing to do */
1024 * Pick up the child status.
1026 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1030 * Child process failed unexpectedly, or wait failed; msg is the
1034 *secondary_msg = NULL;
1037 * Child process failed, but returned the expected exit status.
1038 * Return the messages it gave us, and indicate failure.
1040 *primary_msg = g_strdup(primary_msg_text);
1041 *secondary_msg = g_strdup(secondary_msg_text);
1048 /* read the output from the command */
1049 data_buf = g_string_new("");
1050 while ((count = ws_read(data_pipe_read_fd, buffer, PIPE_BUF_SIZE)) > 0) {
1051 buffer[count] = '\0';
1052 g_string_append(data_buf, buffer);
1056 * Pick up the child status.
1058 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1062 * Child process failed unexpectedly, or wait failed; msg is the
1066 *secondary_msg = NULL;
1067 g_string_free(data_buf, TRUE);
1071 * Child process succeeded.
1073 *primary_msg = NULL;
1074 *secondary_msg = NULL;
1075 *data = data_buf->str;
1076 g_string_free(data_buf, FALSE);
1082 * Pick up the child status.
1084 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1088 * Child process failed unexpectedly, or wait failed; msg is the
1092 *secondary_msg = NULL;
1095 * Child process returned an unknown status.
1097 *primary_msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1099 *secondary_msg = NULL;
1109 * Get the list of interfaces using dumpcap.
1111 * On success, *data points to a buffer containing the dumpcap output,
1112 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1113 * must be freed with g_free().
1115 * On failure, *data is NULL, *primary_msg points to an error message,
1116 * *secondary_msg either points to an additional error message or is
1117 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1118 * must be freed with g_free().
1121 sync_interface_list_open(gchar **data, gchar **primary_msg,
1122 gchar **secondary_msg)
1127 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_list_open");
1129 argv = init_pipe_args(&argc);
1132 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1133 *secondary_msg = NULL;
1138 /* Ask for the interface list */
1139 argv = sync_pipe_add_arg(argv, &argc, "-D");
1142 /* Run dumpcap in capture child mode */
1143 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1144 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1146 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1150 * Get the capabilities of an interface using dumpcap.
1152 * On success, *data points to a buffer containing the dumpcap output,
1153 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1154 * must be freed with g_free().
1156 * On failure, *data is NULL, *primary_msg points to an error message,
1157 * *secondary_msg either points to an additional error message or is
1158 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1159 * must be freed with g_free().
1162 sync_if_capabilities_open(const gchar *ifname, gboolean monitor_mode,
1163 gchar **data, gchar **primary_msg,
1164 gchar **secondary_msg)
1169 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_linktype_list_open");
1171 argv = init_pipe_args(&argc);
1174 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1175 *secondary_msg = NULL;
1180 /* Ask for the interface capabilities */
1181 argv = sync_pipe_add_arg(argv, &argc, "-i");
1182 argv = sync_pipe_add_arg(argv, &argc, ifname);
1183 argv = sync_pipe_add_arg(argv, &argc, "-L");
1185 argv = sync_pipe_add_arg(argv, &argc, "-I");
1188 /* Run dumpcap in capture child mode */
1189 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1190 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1192 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1196 * Start getting interface statistics using dumpcap. On success, read_fd
1197 * contains the file descriptor for the pipe's stdout, *msg is unchanged,
1198 * and zero is returned. On failure, *msg will point to an error message
1199 * that must be g_free()d, and -1 will be returned.
1202 sync_interface_stats_open(int *data_read_fd, int *fork_child, gchar **msg)
1206 int message_read_fd, ret;
1208 gchar buffer[PIPE_BUF_SIZE+1];
1211 int primary_msg_len;
1212 char *primary_msg_text;
1213 int secondary_msg_len;
1214 /*char *secondary_msg_text;*/
1217 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_stats_open");
1219 argv = init_pipe_args(&argc);
1222 *msg = g_strdup("We don't know where to find dumpcap.");
1226 /* Ask for the interface statistics */
1227 argv = sync_pipe_add_arg(argv, &argc, "-S");
1230 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1231 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1233 ret = sync_pipe_open_command(argv, data_read_fd, &message_read_fd,
1239 * We were able to set up to read dumpcap's output. Do so.
1241 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1243 nread = pipe_read_block(message_read_fd, &indicator, SP_MAX_MSG_LEN,
1246 /* We got a read error from the sync pipe, or we got no data at
1247 all from the sync pipe, so we're not going to be getting any
1248 data or error message from the child process. Pick up its
1249 exit status, and complain.
1251 We don't have to worry about killing the child, if the sync pipe
1252 returned an error. Usually this error is caused as the child killed
1253 itself while going down. Even in the rare cases that this isn't the
1254 case, the child will get an error when writing to the broken pipe
1255 the next time, cleaning itself up then. */
1256 ret = sync_pipe_wait_for_child(*fork_child, &wait_msg);
1258 /* We got an EOF from the sync pipe. That means that it exited
1259 before giving us any data to read. If ret is -1, we report
1260 that as a bad exit (e.g., exiting due to a signal); otherwise,
1261 we report it as a premature exit. */
1265 *msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1267 /* We got an error from the sync pipe. If ret is -1, report
1268 both the sync pipe I/O error and the wait error. */
1270 combined_msg = g_strdup_printf("%s\n\n%s", *msg, wait_msg);
1273 *msg = combined_msg;
1280 /* we got a valid message block from the child, process it */
1285 * Error from dumpcap; there will be a primary message and a
1286 * secondary message.
1289 /* convert primary message */
1290 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1291 primary_msg_text = buffer+4;
1292 /* convert secondary message */
1293 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1294 &secondary_msg_len);
1295 /*secondary_msg_text = primary_msg_text + primary_msg_len + 4;*/
1296 /* the capture child will close the sync_pipe, nothing to do */
1299 * Pick up the child status.
1301 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1305 * Child process failed unexpectedly, or wait failed; msg is the
1310 * Child process failed, but returned the expected exit status.
1311 * Return the messages it gave us, and indicate failure.
1313 *msg = g_strdup(primary_msg_text);
1319 /* Close the message pipe. */
1320 ws_close(message_read_fd);
1325 * Pick up the child status.
1327 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1331 * Child process failed unexpectedly, or wait failed; msg is the
1336 * Child process returned an unknown status.
1338 *msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1347 /* Close down the stats process */
1349 sync_interface_stats_close(int *read_fd, int *fork_child, gchar **msg)
1351 return sync_pipe_close_command(read_fd, NULL, fork_child, msg);
1354 /* read a number of bytes from a pipe */
1355 /* (blocks until enough bytes read or an error occurs) */
1357 pipe_read_bytes(int pipe_fd, char *bytes, int required, char **msg)
1364 newly = read(pipe_fd, &bytes[offset], required);
1367 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1368 "read from pipe %d: EOF (capture closed?)", pipe_fd);
1375 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1376 "read from pipe %d: error(%u): %s", pipe_fd, error,
1378 *msg = g_strdup_printf("Error reading from sync pipe: %s",
1391 static gboolean pipe_data_available(int pipe_fd) {
1392 #ifdef _WIN32 /* PeekNamedPipe */
1393 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
1396 if (hPipe == INVALID_HANDLE_VALUE)
1399 if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
1402 if (bytes_avail > 0)
1407 struct timeval timeout;
1410 FD_SET(pipe_fd, &rfds);
1412 timeout.tv_usec = 0;
1414 if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
1421 /* Read a line from a pipe, similar to fgets */
1423 sync_pipe_gets_nonblock(int pipe_fd, char *bytes, int max) {
1427 while(offset < max - 1) {
1429 if (! pipe_data_available(pipe_fd))
1431 newly = read(pipe_fd, &bytes[offset], 1);
1433 /* EOF - not necessarily an error */
1435 } else if (newly < 0) {
1437 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1438 "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1440 } else if (bytes[offset] == '\n') {
1446 bytes[offset] = '\0';
1452 /* convert header values (indicator and 3-byte length) */
1454 pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len) {
1456 g_assert(header_len == 4);
1458 /* convert header values */
1459 *indicator = header[0];
1460 *block_len = header[1]<<16 | header[2]<<8 | header[3];
1463 /* read a message from the sending pipe in the standard format
1464 (1-byte message indicator, 3-byte message length (excluding length
1465 and indicator field), and the rest is the message) */
1467 pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
1474 /* read header (indicator and 3-byte length) */
1475 newly = pipe_read_bytes(pipe_fd, header, 4, err_msg);
1479 * Immediate EOF; if the capture child exits normally, this
1480 * is an "I'm done" indication, so don't report it as an
1483 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1484 "read %d got an EOF", pipe_fd);
1487 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1488 "read %d failed to read header: %u", pipe_fd, newly);
1491 * Short read, but not an immediate EOF.
1493 *err_msg = g_strdup_printf("Premature EOF reading from sync pipe: got only %d bytes",
1499 /* convert header values */
1500 pipe_convert_header(header, 4, indicator, &required);
1502 /* only indicator with no value? */
1504 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1505 "read %d indicator: %c empty value", pipe_fd, *indicator);
1509 /* does the data fit into the given buffer? */
1510 if(required > len) {
1511 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1512 "read %d length error, required %d > len %d, indicator: %u",
1513 pipe_fd, required, len, *indicator);
1515 /* we have a problem here, try to read some more bytes from the pipe to debug where the problem really is */
1516 memcpy(msg, header, sizeof(header));
1517 newly = read(pipe_fd, &msg[sizeof(header)], len-sizeof(header));
1518 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1524 /* read the actual block data */
1525 newly = pipe_read_bytes(pipe_fd, msg, required, err_msg);
1526 if(newly != required) {
1528 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1534 /* XXX If message is "2part", the msg probably won't be sent to debug log correctly */
1535 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1536 "read %d ok indicator: %c len: %u msg: %s", pipe_fd, *indicator,
1543 /* There's stuff to read from the sync pipe, meaning the child has sent
1544 us a message, or the sync pipe has closed, meaning the child has
1545 closed it (perhaps because it exited). */
1547 sync_pipe_input_cb(gint source, gpointer user_data)
1549 capture_options *capture_opts = (capture_options *)user_data;
1551 char buffer[SP_MAX_MSG_LEN+1];
1557 char *secondary_msg;
1558 char *wait_msg, *combined_msg;
1560 nread = pipe_read_block(source, &indicator, SP_MAX_MSG_LEN, buffer,
1563 /* We got a read error, or a bad message, or an EOF, from the sync pipe.
1565 If we got a read error or a bad message, nread is -1 and
1566 primary_msg is set to point to an error message. We don't
1567 have to worry about killing the child; usually this error
1568 is caused as the child killed itself while going down.
1569 Even in the rare cases that this isn't the case, the child
1570 will get an error when writing to the broken pipe the next time,
1571 cleaning itself up then.
1573 If we got an EOF, nread is 0 and primary_msg isn't set. This
1574 is an indication that the capture is finished. */
1575 ret = sync_pipe_wait_for_child(capture_opts->fork_child, &wait_msg);
1577 /* We got an EOF from the sync pipe. That means that the capture
1578 child exited, and not in the middle of a message; we treat
1579 that as an indication that it's done, and only report an
1580 error if ret is -1, in which case wait_msg is the error
1583 primary_msg = wait_msg;
1585 /* We got an error from the sync pipe. If ret is -1, report
1586 both the sync pipe I/O error and the wait error. */
1588 combined_msg = g_strdup_printf("%s\n\n%s", primary_msg, wait_msg);
1589 g_free(primary_msg);
1591 primary_msg = combined_msg;
1595 /* No more child process. */
1596 capture_opts->fork_child = -1;
1597 capture_opts->fork_child_status = ret;
1600 ws_close(capture_opts->signal_pipe_write_fd);
1602 capture_input_closed(capture_opts, primary_msg);
1603 g_free(primary_msg);
1607 /* we got a valid message block from the child, process it */
1610 if(!capture_input_new_file(capture_opts, buffer)) {
1611 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: file failed, closing capture");
1613 /* We weren't able to open the new capture file; user has been
1614 alerted. Close the sync pipe. */
1617 /* the child has send us a filename which we couldn't open.
1618 this probably means, the child is creating files faster than we can handle it.
1619 this should only be the case for very fast file switches
1620 we can't do much more than telling the child to stop
1621 (this is the "emergency brake" if user e.g. wants to switch files every second) */
1622 sync_pipe_stop(capture_opts);
1625 case SP_PACKET_COUNT:
1626 nread = atoi(buffer);
1627 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: new packets %u", nread);
1628 capture_input_new_packets(capture_opts, nread);
1631 /* convert primary message */
1632 pipe_convert_header(buffer, 4, &indicator, &primary_len);
1633 primary_msg = buffer+4;
1634 /* convert secondary message */
1635 pipe_convert_header(primary_msg + primary_len, 4, &indicator, &secondary_len);
1636 secondary_msg = primary_msg + primary_len + 4;
1637 /* message output */
1638 capture_input_error_message(capture_opts, primary_msg, secondary_msg);
1639 /* the capture child will close the sync_pipe, nothing to do for now */
1640 /* (an error message doesn't mean we have to stop capturing) */
1642 case SP_BAD_FILTER: {
1646 ch = strtok(buffer, ":");
1647 index = (int)strtol(ch, NULL, 10);
1648 ch = strtok(NULL, ":");
1649 capture_input_cfilter_error_message(capture_opts, index, ch);
1650 /* the capture child will close the sync_pipe, nothing to do for now */
1654 capture_input_drops(capture_opts, (guint32)strtoul(buffer, NULL, 10));
1657 g_assert_not_reached();
1665 /* the child process is going down, wait until it's completely terminated */
1667 sync_pipe_wait_for_child(int fork_child, gchar **msgp)
1669 int fork_child_status;
1672 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: wait till child closed");
1673 g_assert(fork_child != -1);
1675 *msgp = NULL; /* assume no error */
1678 if (_cwait(&fork_child_status, fork_child, _WAIT_CHILD) == -1) {
1679 *msgp = g_strdup_printf("Error from cwait(): %s", g_strerror(errno));
1683 * The child exited; return its exit status. Do not treat this as
1686 ret = fork_child_status;
1687 if ((fork_child_status & 0xC0000000) == ERROR_SEVERITY_ERROR) {
1688 /* Probably an exception code */
1689 *msgp = g_strdup_printf("Child dumpcap process died: %s",
1690 win32strexception(fork_child_status));
1695 if (waitpid(fork_child, &fork_child_status, 0) != -1) {
1696 if (WIFEXITED(fork_child_status)) {
1698 * The child exited; return its exit status. Do not treat this as
1701 ret = WEXITSTATUS(fork_child_status);
1702 } else if (WIFSTOPPED(fork_child_status)) {
1703 /* It stopped, rather than exiting. "Should not happen." */
1704 *msgp = g_strdup_printf("Child dumpcap process stopped: %s",
1705 sync_pipe_signame(WSTOPSIG(fork_child_status)));
1707 } else if (WIFSIGNALED(fork_child_status)) {
1708 /* It died with a signal. */
1709 *msgp = g_strdup_printf("Child dumpcap process died: %s%s",
1710 sync_pipe_signame(WTERMSIG(fork_child_status)),
1711 WCOREDUMP(fork_child_status) ? " - core dumped" : "");
1714 /* What? It had to either have exited, or stopped, or died with
1715 a signal; what happened here? */
1716 *msgp = g_strdup_printf("Bad status from waitpid(): %#o",
1721 *msgp = g_strdup_printf("Error from waitpid(): %s", g_strerror(errno));
1726 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: capture child closed");
1732 /* convert signal to corresponding name */
1734 sync_pipe_signame(int sig)
1737 static char sigmsg_buf[6+1+3+1];
1746 sigmsg = "Interrupted";
1754 sigmsg = "Illegal instruction";
1758 sigmsg = "Trace trap";
1766 sigmsg = "Arithmetic exception";
1774 sigmsg = "Bus error";
1778 sigmsg = "Segmentation violation";
1781 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1782 Linux is POSIX compliant. These are not POSIX-defined signals ---
1783 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1785 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1786 were omitted from POSIX.1 because their behavior is
1787 implementation dependent and could not be adequately catego-
1788 rized. Conforming implementations may deliver these sig-
1789 nals, but must document the circumstances under which they
1790 are delivered and note any restrictions concerning their
1793 So we only check for SIGSYS on those systems that happen to
1794 implement them (a system can be POSIX-compliant and implement
1795 them, it's just that POSIX doesn't *require* a POSIX-compliant
1796 system to implement them).
1801 sigmsg = "Bad system call";
1806 sigmsg = "Broken pipe";
1810 sigmsg = "Alarm clock";
1814 sigmsg = "Terminated";
1818 /* Returning a static buffer is ok in the context we use it here */
1819 g_snprintf(sigmsg_buf, sizeof sigmsg_buf, "Signal %d", sig);
1820 sigmsg = sigmsg_buf;
1829 /* tell the child through the signal pipe that we want to quit the capture */
1831 signal_pipe_capquit_to_child(capture_options *capture_opts)
1833 const char quit_msg[] = "QUIT";
1837 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "signal_pipe_capquit_to_child");
1839 /* it doesn't matter *what* we send here, the first byte will stop the capture */
1840 /* simply sending a "QUIT" string */
1841 /*pipe_write_block(capture_opts->signal_pipe_write_fd, SP_QUIT, quit_msg);*/
1842 ret = write(capture_opts->signal_pipe_write_fd, quit_msg, sizeof quit_msg);
1844 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1845 "signal_pipe_capquit_to_child: %d header: error %s", capture_opts->signal_pipe_write_fd, g_strerror(errno));
1851 /* user wants to stop the capture run */
1853 sync_pipe_stop(capture_options *capture_opts)
1858 gboolean terminate = TRUE;
1861 if (capture_opts->fork_child != -1) {
1863 /* send the SIGINT signal to close the capture child gracefully. */
1864 int sts = kill(capture_opts->fork_child, SIGINT);
1866 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1867 "Sending SIGINT to child failed: %s\n", g_strerror(errno));
1870 #define STOP_SLEEP_TIME 500 /* ms */
1871 #define STOP_CHECK_TIME 50
1872 /* First, use the special signal pipe to try to close the capture child
1875 signal_pipe_capquit_to_child(capture_opts);
1877 /* Next, wait for the process to exit on its own */
1878 for (count = 0; count < STOP_SLEEP_TIME / STOP_CHECK_TIME; count++) {
1879 if (GetExitCodeProcess((HANDLE) capture_opts->fork_child, &childstatus) &&
1880 childstatus != STILL_ACTIVE) {
1884 Sleep(STOP_CHECK_TIME);
1887 /* Force the issue. */
1889 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1890 "sync_pipe_stop: forcing child to exit");
1891 sync_pipe_kill(capture_opts->fork_child);
1898 /* Wireshark has to exit, force the capture child to close */
1900 sync_pipe_kill(int fork_child)
1902 if (fork_child != -1) {
1904 int sts = kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
1906 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1907 "Sending SIGTERM to child failed: %s\n", g_strerror(errno));
1910 /* Remark: This is not the preferred method of closing a process!
1911 * the clean way would be getting the process id of the child process,
1912 * then getting window handle hWnd of that process (using EnumChildWindows),
1913 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
1915 * Unfortunately, I don't know how to get the process id from the
1916 * handle. OpenProcess will get an handle (not a window handle)
1917 * from the process ID; it will not get a window handle from the
1918 * process ID. (How could it? A process can have more than one
1919 * window. For that matter, a process might have *no* windows,
1920 * as a process running dumpcap, the normal child process program,
1923 * Hint: GenerateConsoleCtrlEvent() will only work if both processes are
1924 * running in the same console; that's not necessarily the case for
1925 * us, as we might not be running in a console.
1926 * And this also will require to have the process id.
1928 TerminateProcess((HANDLE) (fork_child), 0);
1933 #endif /* HAVE_LIBPCAP */