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)
128 /* Grow the array; "*argc" currently contains the number of string
129 pointers, *not* counting the NULL pointer at the end, so we have
130 to add 2 in order to get the new size of the array, including the
131 new pointer and the terminating NULL pointer. */
132 args = g_realloc( (gpointer) args, (*argc + 2) * sizeof (char *));
134 /* Stuff the pointer into the penultimate element of the array, which
135 is the one at the index specified by "*argc". */
138 /* Now bump the count. */
141 /* We overwrite the NULL pointer; put it back right after the
151 /* Quote the argument element if necessary, so that it will get
152 * reconstructed correctly in the C runtime startup code. Note that
153 * the unquoting algorithm in the C runtime is really weird, and
154 * rather different than what Unix shells do. See stdargv.c in the C
155 * runtime sources (in the Platform SDK, in src/crt).
157 * Stolen from GLib's protect_argv(), an internal routine that quotes
158 * string in an argument list so that they arguments will be handled
159 * correctly in the command-line string passed to CreateProcess()
160 * if that string is constructed by gluing those strings together.
163 protect_arg (const gchar *argv)
166 const gchar *p = argv;
169 gboolean need_dblquotes = FALSE;
172 if (*p == ' ' || *p == '\t')
173 need_dblquotes = TRUE;
176 else if (*p == '\\') {
179 while (*pp && *pp == '\\')
188 q = new_arg = g_malloc (len + need_dblquotes*2 + 1);
197 else if (*p == '\\') {
200 while (*pp && *pp == '\\')
217 * Generate a string for a Win32 error.
219 #define ERRBUF_SIZE 1024
221 win32strerror(DWORD error)
223 static char errbuf[ERRBUF_SIZE+1];
227 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
231 * "FormatMessage()" "helpfully" sticks CR/LF at the end of the
232 * message. Get rid of it.
234 errlen = strlen(errbuf);
236 errbuf[errlen - 1] = '\0';
237 errbuf[errlen - 2] = '\0';
239 p = strchr(errbuf, '\0');
240 g_snprintf(p, (gulong)(sizeof errbuf - (p-errbuf)), " (%lu)", error);
245 * Generate a string for a Win32 exception code.
248 win32strexception(DWORD exception)
250 static char errbuf[ERRBUF_SIZE+1];
251 static const struct exception_msg {
255 { EXCEPTION_ACCESS_VIOLATION, "Access violation" },
256 { EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded" },
257 { EXCEPTION_BREAKPOINT, "Breakpoint" },
258 { EXCEPTION_DATATYPE_MISALIGNMENT, "Data type misalignment" },
259 { EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal floating-point operand" },
260 { EXCEPTION_FLT_DIVIDE_BY_ZERO, "Floating-point divide by zero" },
261 { EXCEPTION_FLT_INEXACT_RESULT, "Floating-point inexact result" },
262 { EXCEPTION_FLT_INVALID_OPERATION, "Invalid floating-point operation" },
263 { EXCEPTION_FLT_OVERFLOW, "Floating-point overflow" },
264 { EXCEPTION_FLT_STACK_CHECK, "Floating-point stack check" },
265 { EXCEPTION_FLT_UNDERFLOW, "Floating-point underflow" },
266 { EXCEPTION_GUARD_PAGE, "Guard page violation" },
267 { EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction" },
268 { EXCEPTION_IN_PAGE_ERROR, "Page-in error" },
269 { EXCEPTION_INT_DIVIDE_BY_ZERO, "Integer divide by zero" },
270 { EXCEPTION_INT_OVERFLOW, "Integer overflow" },
271 { EXCEPTION_INVALID_DISPOSITION, "Invalid disposition" },
272 { EXCEPTION_INVALID_HANDLE, "Invalid handle" },
273 { EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception" },
274 { EXCEPTION_PRIV_INSTRUCTION, "Privileged instruction" },
275 { EXCEPTION_SINGLE_STEP, "Single-step complete" },
276 { EXCEPTION_STACK_OVERFLOW, "Stack overflow" },
279 #define N_EXCEPTIONS (sizeof exceptions / sizeof exceptions[0])
282 for (i = 0; i < N_EXCEPTIONS; i++) {
283 if (exceptions[i].code == exception)
284 return exceptions[i].msg;
286 g_snprintf(errbuf, (gulong)sizeof errbuf, "Exception 0x%08x", exception);
291 /* Initialize an argument list and add dumpcap to it. */
293 init_pipe_args(int *argc) {
295 const char *progfile_dir;
298 progfile_dir = get_progfile_dir();
299 if (progfile_dir == NULL) {
303 /* Allocate the string pointer array with enough space for the
304 terminating NULL pointer. */
306 argv = g_malloc(sizeof (char *));
309 /* take Wireshark's absolute program path and replace "Wireshark" with "dumpcap" */
310 exename = g_strdup_printf("%s" G_DIR_SEPARATOR_S "dumpcap", progfile_dir);
312 /* Make that the first argument in the argument list (argv[0]). */
313 argv = sync_pipe_add_arg(argv, argc, exename);
318 #define ARGV_NUMBER_LEN 24
319 /* a new capture run: start a new dumpcap task and hand over parameters through command line */
321 sync_pipe_start(capture_options *capture_opts) {
322 char ssnap[ARGV_NUMBER_LEN];
323 char sdlt[ARGV_NUMBER_LEN];
324 char scount[ARGV_NUMBER_LEN];
325 char sfilesize[ARGV_NUMBER_LEN];
326 char sfile_duration[ARGV_NUMBER_LEN];
327 char sring_num_files[ARGV_NUMBER_LEN];
328 char sautostop_files[ARGV_NUMBER_LEN];
329 char sautostop_filesize[ARGV_NUMBER_LEN];
330 char sautostop_duration[ARGV_NUMBER_LEN];
331 #ifdef HAVE_PCAP_REMOTE
334 #ifdef HAVE_PCAP_SETSAMPLING
335 char ssampling[ARGV_NUMBER_LEN];
338 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
339 char buffer_size[ARGV_NUMBER_LEN];
343 HANDLE sync_pipe_read; /* pipe used to send messages from child to parent */
344 HANDLE sync_pipe_write; /* pipe used to send messages from child to parent */
345 HANDLE signal_pipe; /* named pipe used to send messages from parent to child (currently only stop) */
346 GString *args = g_string_sized_new(200);
348 SECURITY_ATTRIBUTES sa;
350 PROCESS_INFORMATION pi;
351 char control_id[ARGV_NUMBER_LEN];
352 gchar *signal_pipe_name;
355 int sync_pipe[2]; /* pipe used to send messages from child to parent */
356 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
358 int sync_pipe_read_fd;
363 interface_options interface_opts;
365 if (capture_opts->ifaces->len > 1)
366 capture_opts->use_pcapng = TRUE;
367 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_start");
368 capture_opts_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, capture_opts);
370 capture_opts->fork_child = -1;
372 argv = init_pipe_args(&argc);
374 /* We don't know where to find dumpcap. */
375 report_failure("We don't know where to find dumpcap.");
379 if (capture_opts->ifaces->len > 1)
380 argv = sync_pipe_add_arg(argv, &argc, "-t");
382 if (capture_opts->use_pcapng)
383 argv = sync_pipe_add_arg(argv, &argc, "-n");
385 argv = sync_pipe_add_arg(argv, &argc, "-P");
387 if (capture_opts->multi_files_on) {
388 if (capture_opts->has_autostop_filesize) {
389 argv = sync_pipe_add_arg(argv, &argc, "-b");
390 g_snprintf(sfilesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
391 argv = sync_pipe_add_arg(argv, &argc, sfilesize);
394 if (capture_opts->has_file_duration) {
395 argv = sync_pipe_add_arg(argv, &argc, "-b");
396 g_snprintf(sfile_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->file_duration);
397 argv = sync_pipe_add_arg(argv, &argc, sfile_duration);
400 if (capture_opts->has_ring_num_files) {
401 argv = sync_pipe_add_arg(argv, &argc, "-b");
402 g_snprintf(sring_num_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->ring_num_files);
403 argv = sync_pipe_add_arg(argv, &argc, sring_num_files);
406 if (capture_opts->has_autostop_files) {
407 argv = sync_pipe_add_arg(argv, &argc, "-a");
408 g_snprintf(sautostop_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->autostop_files);
409 argv = sync_pipe_add_arg(argv, &argc, sautostop_files);
412 if (capture_opts->has_autostop_filesize) {
413 argv = sync_pipe_add_arg(argv, &argc, "-a");
414 g_snprintf(sautostop_filesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
415 argv = sync_pipe_add_arg(argv, &argc, sautostop_filesize);
419 if (capture_opts->has_autostop_packets) {
420 argv = sync_pipe_add_arg(argv, &argc, "-c");
421 g_snprintf(scount, ARGV_NUMBER_LEN, "%d",capture_opts->autostop_packets);
422 argv = sync_pipe_add_arg(argv, &argc, scount);
425 if (capture_opts->has_autostop_duration) {
426 argv = sync_pipe_add_arg(argv, &argc, "-a");
427 g_snprintf(sautostop_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->autostop_duration);
428 argv = sync_pipe_add_arg(argv, &argc, sautostop_duration);
431 for (j = 0; j < capture_opts->ifaces->len; j++) {
432 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
434 argv = sync_pipe_add_arg(argv, &argc, "-i");
435 argv = sync_pipe_add_arg(argv, &argc, interface_opts.name);
437 if (interface_opts.cfilter != NULL && strlen(interface_opts.cfilter) != 0) {
438 argv = sync_pipe_add_arg(argv, &argc, "-f");
439 argv = sync_pipe_add_arg(argv, &argc, interface_opts.cfilter);
441 if (interface_opts.snaplen != WTAP_MAX_PACKET_SIZE) {
442 argv = sync_pipe_add_arg(argv, &argc, "-s");
443 g_snprintf(ssnap, ARGV_NUMBER_LEN, "%d", interface_opts.snaplen);
444 argv = sync_pipe_add_arg(argv, &argc, ssnap);
447 if (interface_opts.linktype != -1) {
448 argv = sync_pipe_add_arg(argv, &argc, "-y");
449 g_snprintf(sdlt, ARGV_NUMBER_LEN, "%s", linktype_val_to_name(interface_opts.linktype));
450 argv = sync_pipe_add_arg(argv, &argc, sdlt);
453 if (!interface_opts.promisc_mode) {
454 argv = sync_pipe_add_arg(argv, &argc, "-p");
457 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
458 if (interface_opts.buffer_size != 1) {
459 argv = sync_pipe_add_arg(argv, &argc, "-B");
460 g_snprintf(buffer_size, ARGV_NUMBER_LEN, "%d", interface_opts.buffer_size);
461 argv = sync_pipe_add_arg(argv, &argc, buffer_size);
465 if (interface_opts.monitor_mode) {
466 argv = sync_pipe_add_arg(argv, &argc, "-I");
469 #ifdef HAVE_PCAP_REMOTE
470 if (interface_opts.datatx_udp)
471 argv = sync_pipe_add_arg(argv, &argc, "-u");
473 if (!interface_opts.nocap_rpcap)
474 argv = sync_pipe_add_arg(argv, &argc, "-r");
476 if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
477 argv = sync_pipe_add_arg(argv, &argc, "-A");
478 g_snprintf(sauth, sizeof(sauth), "%s:%s",
479 interface_opts.auth_username,
480 interface_opts.auth_password);
481 argv = sync_pipe_add_arg(argv, &argc, sauth);
485 #ifdef HAVE_PCAP_SETSAMPLING
486 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
487 argv = sync_pipe_add_arg(argv, &argc, "-m");
488 g_snprintf(ssampling, ARGV_NUMBER_LEN, "%s:%d",
489 interface_opts.sampling_method == CAPTURE_SAMP_BY_COUNT ? "count" :
490 interface_opts.sampling_method == CAPTURE_SAMP_BY_TIMER ? "timer" :
492 interface_opts.sampling_param);
493 argv = sync_pipe_add_arg(argv, &argc, ssampling);
498 /* dumpcap should be running in capture child mode (hidden feature) */
500 argv = sync_pipe_add_arg(argv, &argc, "-Z");
502 g_snprintf(control_id, ARGV_NUMBER_LEN, "%d", GetCurrentProcessId());
503 argv = sync_pipe_add_arg(argv, &argc, control_id);
505 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
509 if (capture_opts->save_file) {
510 argv = sync_pipe_add_arg(argv, &argc, "-w");
511 argv = sync_pipe_add_arg(argv, &argc, capture_opts->save_file);
513 for (i = 0; i < argc; i++) {
514 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", i, argv[i]);
518 /* init SECURITY_ATTRIBUTES */
519 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
520 sa.bInheritHandle = TRUE;
521 sa.lpSecurityDescriptor = NULL;
523 /* Create a pipe for the child process */
524 /* (increase this value if you have trouble while fast capture file switches) */
525 if (! CreatePipe(&sync_pipe_read, &sync_pipe_write, &sa, 5120)) {
526 /* Couldn't create the pipe between parent and child. */
527 report_failure("Couldn't create sync pipe: %s",
528 win32strerror(GetLastError()));
529 g_free( (gpointer) argv[0]);
530 g_free( (gpointer) argv);
534 /* Create the signal pipe */
535 signal_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, control_id);
536 signal_pipe = CreateNamedPipe(utf_8to16(signal_pipe_name),
537 PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 65535, 65535, 0, NULL);
538 g_free(signal_pipe_name);
540 if (signal_pipe == INVALID_HANDLE_VALUE) {
541 /* Couldn't create the signal pipe between parent and child. */
542 report_failure("Couldn't create signal pipe: %s",
543 win32strerror(GetLastError()));
544 g_free( (gpointer) argv[0]);
545 g_free( (gpointer) argv);
549 /* init STARTUPINFO */
550 memset(&si, 0, sizeof(si));
553 si.dwFlags = STARTF_USESHOWWINDOW;
554 si.wShowWindow = SW_SHOW;
556 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
557 si.wShowWindow = SW_HIDE; /* this hides the console window */
558 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
559 si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
560 si.hStdError = sync_pipe_write;
561 /*si.hStdError = (HANDLE) _get_osfhandle(2);*/
564 /* convert args array into a single string */
565 /* XXX - could change sync_pipe_add_arg() instead */
566 /* there is a drawback here: the length is internally limited to 1024 bytes */
567 for(i=0; argv[i] != 0; i++) {
568 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
569 quoted_arg = protect_arg(argv[i]);
570 g_string_append(args, quoted_arg);
575 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
576 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
577 report_failure("Couldn't run %s in child process: %s",
578 args->str, win32strerror(GetLastError()));
579 CloseHandle(sync_pipe_read);
580 CloseHandle(sync_pipe_write);
581 g_free( (gpointer) argv[0]);
582 g_free( (gpointer) argv);
585 capture_opts->fork_child = (int) pi.hProcess;
586 g_string_free(args, TRUE);
588 /* associate the operating system filehandle to a C run-time file handle */
589 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
590 sync_pipe_read_fd = _open_osfhandle( (long) sync_pipe_read, _O_BINARY);
592 /* associate the operating system filehandle to a C run-time file handle */
593 capture_opts->signal_pipe_write_fd = _open_osfhandle( (long) signal_pipe, _O_BINARY);
596 if (pipe(sync_pipe) < 0) {
597 /* Couldn't create the pipe between parent and child. */
598 report_failure("Couldn't create sync pipe: %s", g_strerror(errno));
599 g_free( (gpointer) argv[0]);
604 if ((capture_opts->fork_child = fork()) == 0) {
606 * Child process - run dumpcap with the right arguments to make
607 * it just capture with the specified capture parameters
609 dup2(sync_pipe[PIPE_WRITE], 2);
610 ws_close(sync_pipe[PIPE_READ]);
611 execv(argv[0], (gpointer)argv);
612 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
613 argv[0], g_strerror(errno));
614 sync_pipe_errmsg_to_parent(2, errmsg, "");
616 /* Exit with "_exit()", so that we don't close the connection
617 to the X server (and cause stuff buffered up by our parent but
618 not yet sent to be sent, as that stuff should only be sent by
619 our parent). We've sent an error message to the parent, so
620 we exit with an exit status of 1 (any exit status other than
621 0 or 1 will cause an additional message to report that exit
622 status, over and above the error message we sent to the parent). */
626 sync_pipe_read_fd = sync_pipe[PIPE_READ];
629 g_free( (gpointer) argv[0]); /* exename */
631 /* Parent process - read messages from the child process over the
633 g_free( (gpointer) argv); /* free up arg array */
635 /* Close the write side of the pipe, so that only the child has it
636 open, and thus it completely closes, and thus returns to us
637 an EOF indication, if the child closes it (either deliberately
638 or by exiting abnormally). */
640 CloseHandle(sync_pipe_write);
642 ws_close(sync_pipe[PIPE_WRITE]);
645 if (capture_opts->fork_child == -1) {
646 /* We couldn't even create the child process. */
647 report_failure("Couldn't create child process: %s", g_strerror(errno));
648 ws_close(sync_pipe_read_fd);
650 ws_close(capture_opts->signal_pipe_write_fd);
655 capture_opts->fork_child_status = 0;
657 /* we might wait for a moment till child is ready, so update screen now */
658 main_window_update();
660 /* We were able to set up to read the capture file;
661 arrange that our callback be called whenever it's possible
662 to read from the sync pipe, so that it's called when
663 the child process wants to tell us something. */
665 /* we have a running capture, now wait for the real capture filename */
666 pipe_input_set_handler(sync_pipe_read_fd, (gpointer) capture_opts,
667 &capture_opts->fork_child, sync_pipe_input_cb);
673 * Open two pipes to dumpcap with the supplied arguments, one for its
674 * standard output and one for its standard error.
676 * On success, *msg is unchanged and 0 is returned; data_read_fd,
677 * messsage_read_fd, and fork_child point to the standard output pipe's
678 * file descriptor, the standard error pipe's file descriptor, and
679 * the child's PID/handle, respectively.
681 * On failure, *msg points to an error message for the failure, and -1 is
682 * returned, in which case *msg must be freed with g_free().
684 /* XXX - This duplicates a lot of code in sync_pipe_start() */
685 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
686 #define PIPE_BUF_SIZE 5120
688 sync_pipe_open_command(const char** argv, int *data_read_fd,
689 int *message_read_fd, int *fork_child, gchar **msg)
691 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
693 HANDLE sync_pipe[2]; /* pipe used to send messages from child to parent */
694 HANDLE data_pipe[2]; /* pipe used to send data from child to parent */
695 GString *args = g_string_sized_new(200);
697 SECURITY_ATTRIBUTES sa;
699 PROCESS_INFORMATION pi;
703 int sync_pipe[2]; /* pipe used to send messages from child to parent */
704 int data_pipe[2]; /* pipe used to send data from child to parent */
709 *message_read_fd = -1;
710 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_open_command");
713 /* We can't return anything */
715 g_string_free(args, TRUE);
721 /* init SECURITY_ATTRIBUTES */
722 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
723 sa.bInheritHandle = TRUE;
724 sa.lpSecurityDescriptor = NULL;
726 /* Create a pipe for the child process to send us messages */
727 /* (increase this value if you have trouble while fast capture file switches) */
728 if (! CreatePipe(&sync_pipe[PIPE_READ], &sync_pipe[PIPE_WRITE], &sa, 5120)) {
729 /* Couldn't create the message pipe between parent and child. */
730 *msg = g_strdup_printf("Couldn't create sync pipe: %s",
731 win32strerror(GetLastError()));
732 g_free( (gpointer) argv[0]);
733 g_free( (gpointer) argv);
737 /* Create a pipe for the child process to send us data */
738 /* (increase this value if you have trouble while fast capture file switches) */
739 if (! CreatePipe(&data_pipe[PIPE_READ], &data_pipe[PIPE_WRITE], &sa, 5120)) {
740 /* Couldn't create the message pipe between parent and child. */
741 *msg = g_strdup_printf("Couldn't create data pipe: %s",
742 win32strerror(GetLastError()));
743 CloseHandle(sync_pipe[PIPE_READ]);
744 CloseHandle(sync_pipe[PIPE_WRITE]);
745 g_free( (gpointer) argv[0]);
746 g_free( (gpointer) argv);
750 /* init STARTUPINFO */
751 memset(&si, 0, sizeof(si));
754 si.dwFlags = STARTF_USESHOWWINDOW;
755 si.wShowWindow = SW_SHOW;
757 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
758 si.wShowWindow = SW_HIDE; /* this hides the console window */
760 si.hStdOutput = data_pipe[PIPE_WRITE];
761 si.hStdError = sync_pipe[PIPE_WRITE];
764 /* convert args array into a single string */
765 /* XXX - could change sync_pipe_add_arg() instead */
766 /* there is a drawback here: the length is internally limited to 1024 bytes */
767 for(i=0; argv[i] != 0; i++) {
768 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
769 quoted_arg = protect_arg(argv[i]);
770 g_string_append(args, quoted_arg);
775 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
776 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
777 *msg = g_strdup_printf("Couldn't run %s in child process: %s",
778 args->str, win32strerror(GetLastError()));
779 CloseHandle(data_pipe[PIPE_READ]);
780 CloseHandle(data_pipe[PIPE_WRITE]);
781 CloseHandle(sync_pipe[PIPE_READ]);
782 CloseHandle(sync_pipe[PIPE_WRITE]);
783 g_free( (gpointer) argv[0]);
784 g_free( (gpointer) argv);
787 *fork_child = (int) pi.hProcess;
788 g_string_free(args, TRUE);
790 /* associate the operating system filehandles to C run-time file handles */
791 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
792 *data_read_fd = _open_osfhandle( (long) data_pipe[PIPE_READ], _O_BINARY);
793 *message_read_fd = _open_osfhandle( (long) sync_pipe[PIPE_READ], _O_BINARY);
795 /* Create a pipe for the child process to send us messages */
796 if (pipe(sync_pipe) < 0) {
797 /* Couldn't create the message pipe between parent and child. */
798 *msg = g_strdup_printf("Couldn't create sync pipe: %s", g_strerror(errno));
799 g_free( (gpointer) argv[0]);
804 /* Create a pipe for the child process to send us data */
805 if (pipe(data_pipe) < 0) {
806 /* Couldn't create the data pipe between parent and child. */
807 *msg = g_strdup_printf("Couldn't create data pipe: %s", g_strerror(errno));
808 ws_close(sync_pipe[PIPE_READ]);
809 ws_close(sync_pipe[PIPE_WRITE]);
810 g_free( (gpointer) argv[0]);
815 if ((*fork_child = fork()) == 0) {
817 * Child process - run dumpcap with the right arguments to make
818 * it just capture with the specified capture parameters
820 dup2(data_pipe[PIPE_WRITE], 1);
821 ws_close(data_pipe[PIPE_READ]);
822 ws_close(data_pipe[PIPE_WRITE]);
823 dup2(sync_pipe[PIPE_WRITE], 2);
824 ws_close(sync_pipe[PIPE_READ]);
825 ws_close(sync_pipe[PIPE_WRITE]);
826 execv(argv[0], (gpointer)argv);
827 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
828 argv[0], g_strerror(errno));
829 sync_pipe_errmsg_to_parent(2, errmsg, "");
831 /* Exit with "_exit()", so that we don't close the connection
832 to the X server (and cause stuff buffered up by our parent but
833 not yet sent to be sent, as that stuff should only be sent by
834 our parent). We've sent an error message to the parent, so
835 we exit with an exit status of 1 (any exit status other than
836 0 or 1 will cause an additional message to report that exit
837 status, over and above the error message we sent to the parent). */
841 *data_read_fd = data_pipe[PIPE_READ];
842 *message_read_fd = sync_pipe[PIPE_READ];
845 g_free( (gpointer) argv[0]); /* exename */
847 /* Parent process - read messages from the child process over the
849 g_free( (gpointer) argv); /* free up arg array */
851 /* Close the write sides of the pipes, so that only the child has them
852 open, and thus they completely close, and thus return to us
853 an EOF indication, if the child closes them (either deliberately
854 or by exiting abnormally). */
856 CloseHandle(data_pipe[PIPE_WRITE]);
857 CloseHandle(sync_pipe[PIPE_WRITE]);
859 ws_close(data_pipe[PIPE_WRITE]);
860 ws_close(sync_pipe[PIPE_WRITE]);
863 if (*fork_child == -1) {
864 /* We couldn't even create the child process. */
865 *msg = g_strdup_printf("Couldn't create child process: %s", g_strerror(errno));
866 ws_close(*data_read_fd);
867 ws_close(*message_read_fd);
871 /* we might wait for a moment till child is ready, so update screen now */
872 main_window_update();
877 * Wait for dumpcap to finish. On success, *msg is unchanged, and 0 is
878 * returned. On failure, *msg points to an error message for the
879 * failure, and -1 is returned. In the latter case, *msg must be
880 * freed with g_free().
883 sync_pipe_close_command(int *data_read_fd, int *message_read_fd,
884 int *fork_child, gchar **msg)
886 ws_close(*data_read_fd);
887 if (message_read_fd != NULL)
888 ws_close(*message_read_fd);
891 /* XXX - Should we signal the child somehow? */
892 sync_pipe_kill(*fork_child);
895 return sync_pipe_wait_for_child(*fork_child, msg);
899 * Run dumpcap with the supplied arguments.
901 * On success, *data points to a buffer containing the dumpcap output,
902 * *primary_msg and *secondary_message are NULL, and 0 is returned; *data
903 * must be freed with g_free().
905 * On failure, *data is NULL, *primary_msg points to an error message,
906 * *secondary_msg either points to an additional error message or is
907 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
908 * must be freed with g_free().
910 /* XXX - This duplicates a lot of code in sync_pipe_start() */
911 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
912 #define PIPE_BUF_SIZE 5120
914 sync_pipe_run_command(const char** argv, gchar **data, gchar **primary_msg,
915 gchar **secondary_msg)
918 int data_pipe_read_fd, sync_pipe_read_fd, fork_child, ret;
920 gchar buffer[PIPE_BUF_SIZE+1];
924 char *primary_msg_text;
925 int secondary_msg_len;
926 char *secondary_msg_text;
928 GString *data_buf = NULL;
931 ret = sync_pipe_open_command(argv, &data_pipe_read_fd, &sync_pipe_read_fd,
935 *secondary_msg = NULL;
941 * We were able to set up to read dumpcap's output. Do so.
943 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
945 nread = pipe_read_block(sync_pipe_read_fd, &indicator, SP_MAX_MSG_LEN,
946 buffer, primary_msg);
948 /* We got a read error from the sync pipe, or we got no data at
949 all from the sync pipe, so we're not going to be getting any
950 data or error message from the child process. Pick up its
951 exit status, and complain.
953 We don't have to worry about killing the child, if the sync pipe
954 returned an error. Usually this error is caused as the child killed
955 itself while going down. Even in the rare cases that this isn't the
956 case, the child will get an error when writing to the broken pipe
957 the next time, cleaning itself up then. */
958 ret = sync_pipe_wait_for_child(fork_child, &wait_msg);
960 /* We got an EOF from the sync pipe. That means that it exited
961 before giving us any data to read. If ret is -1, we report
962 that as a bad exit (e.g., exiting due to a signal); otherwise,
963 we report it as a premature exit. */
965 *primary_msg = wait_msg;
967 *primary_msg = g_strdup("Child dumpcap closed sync pipe prematurely");
969 /* We got an error from the sync pipe. If ret is -1, report
970 both the sync pipe I/O error and the wait error. */
972 combined_msg = g_strdup_printf("%s\n\n%s", *primary_msg, wait_msg);
973 g_free(*primary_msg);
975 *primary_msg = combined_msg;
978 *secondary_msg = NULL;
983 /* we got a valid message block from the child, process it */
988 * Error from dumpcap; there will be a primary message and a
992 /* convert primary message */
993 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
994 primary_msg_text = buffer+4;
995 /* convert secondary message */
996 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
998 secondary_msg_text = primary_msg_text + primary_msg_len + 4;
999 /* the capture child will close the sync_pipe, nothing to do */
1002 * Pick up the child status.
1004 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1008 * Child process failed unexpectedly, or wait failed; msg is the
1012 *secondary_msg = NULL;
1015 * Child process failed, but returned the expected exit status.
1016 * Return the messages it gave us, and indicate failure.
1018 *primary_msg = g_strdup(primary_msg_text);
1019 *secondary_msg = g_strdup(secondary_msg_text);
1026 /* read the output from the command */
1027 data_buf = g_string_new("");
1028 while ((count = ws_read(data_pipe_read_fd, buffer, PIPE_BUF_SIZE)) > 0) {
1029 buffer[count] = '\0';
1030 g_string_append(data_buf, buffer);
1034 * Pick up the child status.
1036 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1040 * Child process failed unexpectedly, or wait failed; msg is the
1044 *secondary_msg = NULL;
1045 g_string_free(data_buf, TRUE);
1049 * Child process succeeded.
1051 *primary_msg = NULL;
1052 *secondary_msg = NULL;
1053 *data = data_buf->str;
1054 g_string_free(data_buf, FALSE);
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;
1073 * Child process returned an unknown status.
1075 *primary_msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1077 *secondary_msg = NULL;
1087 * Get the list of interfaces using dumpcap.
1089 * On success, *data points to a buffer containing the dumpcap output,
1090 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1091 * must be freed with g_free().
1093 * On failure, *data is NULL, *primary_msg points to an error message,
1094 * *secondary_msg either points to an additional error message or is
1095 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1096 * must be freed with g_free().
1099 sync_interface_list_open(gchar **data, gchar **primary_msg,
1100 gchar **secondary_msg)
1105 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_list_open");
1107 argv = init_pipe_args(&argc);
1110 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1111 *secondary_msg = NULL;
1116 /* Ask for the interface list */
1117 argv = sync_pipe_add_arg(argv, &argc, "-D");
1120 /* Run dumpcap in capture child mode */
1121 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1122 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1124 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1128 * Get the capabilities of an interface using dumpcap.
1130 * On success, *data points to a buffer containing the dumpcap output,
1131 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1132 * must be freed with g_free().
1134 * On failure, *data is NULL, *primary_msg points to an error message,
1135 * *secondary_msg either points to an additional error message or is
1136 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1137 * must be freed with g_free().
1140 sync_if_capabilities_open(const gchar *ifname, gboolean monitor_mode,
1141 gchar **data, gchar **primary_msg,
1142 gchar **secondary_msg)
1147 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_linktype_list_open");
1149 argv = init_pipe_args(&argc);
1152 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1153 *secondary_msg = NULL;
1158 /* Ask for the interface capabilities */
1159 argv = sync_pipe_add_arg(argv, &argc, "-i");
1160 argv = sync_pipe_add_arg(argv, &argc, ifname);
1161 argv = sync_pipe_add_arg(argv, &argc, "-L");
1163 argv = sync_pipe_add_arg(argv, &argc, "-I");
1166 /* Run dumpcap in capture child mode */
1167 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1168 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1170 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1174 * Start getting interface statistics using dumpcap. On success, read_fd
1175 * contains the file descriptor for the pipe's stdout, *msg is unchanged,
1176 * and zero is returned. On failure, *msg will point to an error message
1177 * that must be g_free()d, and -1 will be returned.
1180 sync_interface_stats_open(int *data_read_fd, int *fork_child, gchar **msg)
1184 int message_read_fd, ret;
1186 gchar buffer[PIPE_BUF_SIZE+1];
1189 int primary_msg_len;
1190 char *primary_msg_text;
1191 int secondary_msg_len;
1192 /*char *secondary_msg_text;*/
1195 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_stats_open");
1197 argv = init_pipe_args(&argc);
1200 *msg = g_strdup("We don't know where to find dumpcap.");
1204 /* Ask for the interface statistics */
1205 argv = sync_pipe_add_arg(argv, &argc, "-S");
1208 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1209 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1211 ret = sync_pipe_open_command(argv, data_read_fd, &message_read_fd,
1217 * We were able to set up to read dumpcap's output. Do so.
1219 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1221 nread = pipe_read_block(message_read_fd, &indicator, SP_MAX_MSG_LEN,
1224 /* We got a read error from the sync pipe, or we got no data at
1225 all from the sync pipe, so we're not going to be getting any
1226 data or error message from the child process. Pick up its
1227 exit status, and complain.
1229 We don't have to worry about killing the child, if the sync pipe
1230 returned an error. Usually this error is caused as the child killed
1231 itself while going down. Even in the rare cases that this isn't the
1232 case, the child will get an error when writing to the broken pipe
1233 the next time, cleaning itself up then. */
1234 ret = sync_pipe_wait_for_child(*fork_child, &wait_msg);
1236 /* We got an EOF from the sync pipe. That means that it exited
1237 before giving us any data to read. If ret is -1, we report
1238 that as a bad exit (e.g., exiting due to a signal); otherwise,
1239 we report it as a premature exit. */
1243 *msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1245 /* We got an error from the sync pipe. If ret is -1, report
1246 both the sync pipe I/O error and the wait error. */
1248 combined_msg = g_strdup_printf("%s\n\n%s", *msg, wait_msg);
1251 *msg = combined_msg;
1258 /* we got a valid message block from the child, process it */
1263 * Error from dumpcap; there will be a primary message and a
1264 * secondary message.
1267 /* convert primary message */
1268 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1269 primary_msg_text = buffer+4;
1270 /* convert secondary message */
1271 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1272 &secondary_msg_len);
1273 /*secondary_msg_text = primary_msg_text + primary_msg_len + 4;*/
1274 /* the capture child will close the sync_pipe, nothing to do */
1277 * Pick up the child status.
1279 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1283 * Child process failed unexpectedly, or wait failed; msg is the
1288 * Child process failed, but returned the expected exit status.
1289 * Return the messages it gave us, and indicate failure.
1291 *msg = g_strdup(primary_msg_text);
1297 /* Close the message pipe. */
1298 ws_close(message_read_fd);
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 returned an unknown status.
1316 *msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1325 /* Close down the stats process */
1327 sync_interface_stats_close(int *read_fd, int *fork_child, gchar **msg)
1329 return sync_pipe_close_command(read_fd, NULL, fork_child, msg);
1332 /* read a number of bytes from a pipe */
1333 /* (blocks until enough bytes read or an error occurs) */
1335 pipe_read_bytes(int pipe_fd, char *bytes, int required, char **msg)
1342 newly = read(pipe_fd, &bytes[offset], required);
1345 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1346 "read from pipe %d: EOF (capture closed?)", pipe_fd);
1353 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1354 "read from pipe %d: error(%u): %s", pipe_fd, error,
1356 *msg = g_strdup_printf("Error reading from sync pipe: %s",
1369 static gboolean pipe_data_available(int pipe_fd) {
1370 #ifdef _WIN32 /* PeekNamedPipe */
1371 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
1374 if (hPipe == INVALID_HANDLE_VALUE)
1377 if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
1380 if (bytes_avail > 0)
1385 struct timeval timeout;
1388 FD_SET(pipe_fd, &rfds);
1390 timeout.tv_usec = 0;
1392 if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
1399 /* Read a line from a pipe, similar to fgets */
1401 sync_pipe_gets_nonblock(int pipe_fd, char *bytes, int max) {
1405 while(offset < max - 1) {
1407 if (! pipe_data_available(pipe_fd))
1409 newly = read(pipe_fd, &bytes[offset], 1);
1411 /* EOF - not necessarily an error */
1413 } else if (newly < 0) {
1415 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1416 "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1418 } else if (bytes[offset] == '\n') {
1424 bytes[offset] = '\0';
1430 /* convert header values (indicator and 3-byte length) */
1432 pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len) {
1434 g_assert(header_len == 4);
1436 /* convert header values */
1437 *indicator = header[0];
1438 *block_len = header[1]<<16 | header[2]<<8 | header[3];
1441 /* read a message from the sending pipe in the standard format
1442 (1-byte message indicator, 3-byte message length (excluding length
1443 and indicator field), and the rest is the message) */
1445 pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
1452 /* read header (indicator and 3-byte length) */
1453 newly = pipe_read_bytes(pipe_fd, header, 4, err_msg);
1457 * Immediate EOF; if the capture child exits normally, this
1458 * is an "I'm done" indication, so don't report it as an
1461 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1462 "read %d got an EOF", pipe_fd);
1465 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1466 "read %d failed to read header: %u", pipe_fd, newly);
1469 * Short read, but not an immediate EOF.
1471 *err_msg = g_strdup_printf("Premature EOF reading from sync pipe: got only %d bytes",
1477 /* convert header values */
1478 pipe_convert_header(header, 4, indicator, &required);
1480 /* only indicator with no value? */
1482 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1483 "read %d indicator: %c empty value", pipe_fd, *indicator);
1487 /* does the data fit into the given buffer? */
1488 if(required > len) {
1489 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1490 "read %d length error, required %d > len %d, indicator: %u",
1491 pipe_fd, required, len, *indicator);
1493 /* we have a problem here, try to read some more bytes from the pipe to debug where the problem really is */
1494 memcpy(msg, header, sizeof(header));
1495 newly = read(pipe_fd, &msg[sizeof(header)], len-sizeof(header));
1496 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1502 /* read the actual block data */
1503 newly = pipe_read_bytes(pipe_fd, msg, required, err_msg);
1504 if(newly != required) {
1506 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1512 /* XXX If message is "2part", the msg probably won't be sent to debug log correctly */
1513 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1514 "read %d ok indicator: %c len: %u msg: %s", pipe_fd, *indicator,
1521 /* There's stuff to read from the sync pipe, meaning the child has sent
1522 us a message, or the sync pipe has closed, meaning the child has
1523 closed it (perhaps because it exited). */
1525 sync_pipe_input_cb(gint source, gpointer user_data)
1527 capture_options *capture_opts = (capture_options *)user_data;
1529 char buffer[SP_MAX_MSG_LEN+1];
1535 char *secondary_msg;
1536 char *wait_msg, *combined_msg;
1538 nread = pipe_read_block(source, &indicator, SP_MAX_MSG_LEN, buffer,
1541 /* We got a read error, or a bad message, or an EOF, from the sync pipe.
1543 If we got a read error or a bad message, nread is -1 and
1544 primary_msg is set to point to an error message. We don't
1545 have to worry about killing the child; usually this error
1546 is caused as the child killed itself while going down.
1547 Even in the rare cases that this isn't the case, the child
1548 will get an error when writing to the broken pipe the next time,
1549 cleaning itself up then.
1551 If we got an EOF, nread is 0 and primary_msg isn't set. This
1552 is an indication that the capture is finished. */
1553 ret = sync_pipe_wait_for_child(capture_opts->fork_child, &wait_msg);
1555 /* We got an EOF from the sync pipe. That means that the capture
1556 child exited, and not in the middle of a message; we treat
1557 that as an indication that it's done, and only report an
1558 error if ret is -1, in which case wait_msg is the error
1561 primary_msg = wait_msg;
1563 /* We got an error from the sync pipe. If ret is -1, report
1564 both the sync pipe I/O error and the wait error. */
1566 combined_msg = g_strdup_printf("%s\n\n%s", primary_msg, wait_msg);
1567 g_free(primary_msg);
1569 primary_msg = combined_msg;
1573 /* No more child process. */
1574 capture_opts->fork_child = -1;
1575 capture_opts->fork_child_status = ret;
1578 ws_close(capture_opts->signal_pipe_write_fd);
1580 capture_input_closed(capture_opts, primary_msg);
1581 g_free(primary_msg);
1585 /* we got a valid message block from the child, process it */
1588 if(!capture_input_new_file(capture_opts, buffer)) {
1589 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: file failed, closing capture");
1591 /* We weren't able to open the new capture file; user has been
1592 alerted. Close the sync pipe. */
1595 /* the child has send us a filename which we couldn't open.
1596 this probably means, the child is creating files faster than we can handle it.
1597 this should only be the case for very fast file switches
1598 we can't do much more than telling the child to stop
1599 (this is the "emergency brake" if user e.g. wants to switch files every second) */
1600 sync_pipe_stop(capture_opts);
1603 case SP_PACKET_COUNT:
1604 nread = atoi(buffer);
1605 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: new packets %u", nread);
1606 capture_input_new_packets(capture_opts, nread);
1609 /* convert primary message */
1610 pipe_convert_header(buffer, 4, &indicator, &primary_len);
1611 primary_msg = buffer+4;
1612 /* convert secondary message */
1613 pipe_convert_header(primary_msg + primary_len, 4, &indicator, &secondary_len);
1614 secondary_msg = primary_msg + primary_len + 4;
1615 /* message output */
1616 capture_input_error_message(capture_opts, primary_msg, secondary_msg);
1617 /* the capture child will close the sync_pipe, nothing to do for now */
1618 /* (an error message doesn't mean we have to stop capturing) */
1620 case SP_BAD_FILTER: {
1624 ch = strtok(buffer, ":");
1625 index = (int)strtol(ch, NULL, 10);
1626 ch = strtok(NULL, ":");
1627 capture_input_cfilter_error_message(capture_opts, index, ch);
1628 /* the capture child will close the sync_pipe, nothing to do for now */
1632 capture_input_drops(capture_opts, (guint32)strtoul(buffer, NULL, 10));
1635 g_assert_not_reached();
1643 /* the child process is going down, wait until it's completely terminated */
1645 sync_pipe_wait_for_child(int fork_child, gchar **msgp)
1647 int fork_child_status;
1650 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: wait till child closed");
1651 g_assert(fork_child != -1);
1653 *msgp = NULL; /* assume no error */
1656 if (_cwait(&fork_child_status, fork_child, _WAIT_CHILD) == -1) {
1657 *msgp = g_strdup_printf("Error from cwait(): %s", g_strerror(errno));
1661 * The child exited; return its exit status. Do not treat this as
1664 ret = fork_child_status;
1665 if ((fork_child_status & 0xC0000000) == ERROR_SEVERITY_ERROR) {
1666 /* Probably an exception code */
1667 *msgp = g_strdup_printf("Child dumpcap process died: %s",
1668 win32strexception(fork_child_status));
1673 if (waitpid(fork_child, &fork_child_status, 0) != -1) {
1674 if (WIFEXITED(fork_child_status)) {
1676 * The child exited; return its exit status. Do not treat this as
1679 ret = WEXITSTATUS(fork_child_status);
1680 } else if (WIFSTOPPED(fork_child_status)) {
1681 /* It stopped, rather than exiting. "Should not happen." */
1682 *msgp = g_strdup_printf("Child dumpcap process stopped: %s",
1683 sync_pipe_signame(WSTOPSIG(fork_child_status)));
1685 } else if (WIFSIGNALED(fork_child_status)) {
1686 /* It died with a signal. */
1687 *msgp = g_strdup_printf("Child dumpcap process died: %s%s",
1688 sync_pipe_signame(WTERMSIG(fork_child_status)),
1689 WCOREDUMP(fork_child_status) ? " - core dumped" : "");
1692 /* What? It had to either have exited, or stopped, or died with
1693 a signal; what happened here? */
1694 *msgp = g_strdup_printf("Bad status from waitpid(): %#o",
1699 *msgp = g_strdup_printf("Error from waitpid(): %s", g_strerror(errno));
1704 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: capture child closed");
1710 /* convert signal to corresponding name */
1712 sync_pipe_signame(int sig)
1715 static char sigmsg_buf[6+1+3+1];
1724 sigmsg = "Interrupted";
1732 sigmsg = "Illegal instruction";
1736 sigmsg = "Trace trap";
1744 sigmsg = "Arithmetic exception";
1752 sigmsg = "Bus error";
1756 sigmsg = "Segmentation violation";
1759 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1760 Linux is POSIX compliant. These are not POSIX-defined signals ---
1761 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1763 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1764 were omitted from POSIX.1 because their behavior is
1765 implementation dependent and could not be adequately catego-
1766 rized. Conforming implementations may deliver these sig-
1767 nals, but must document the circumstances under which they
1768 are delivered and note any restrictions concerning their
1771 So we only check for SIGSYS on those systems that happen to
1772 implement them (a system can be POSIX-compliant and implement
1773 them, it's just that POSIX doesn't *require* a POSIX-compliant
1774 system to implement them).
1779 sigmsg = "Bad system call";
1784 sigmsg = "Broken pipe";
1788 sigmsg = "Alarm clock";
1792 sigmsg = "Terminated";
1796 /* Returning a static buffer is ok in the context we use it here */
1797 g_snprintf(sigmsg_buf, sizeof sigmsg_buf, "Signal %d", sig);
1798 sigmsg = sigmsg_buf;
1807 /* tell the child through the signal pipe that we want to quit the capture */
1809 signal_pipe_capquit_to_child(capture_options *capture_opts)
1811 const char quit_msg[] = "QUIT";
1815 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "signal_pipe_capquit_to_child");
1817 /* it doesn't matter *what* we send here, the first byte will stop the capture */
1818 /* simply sending a "QUIT" string */
1819 /*pipe_write_block(capture_opts->signal_pipe_write_fd, SP_QUIT, quit_msg);*/
1820 ret = write(capture_opts->signal_pipe_write_fd, quit_msg, sizeof quit_msg);
1822 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1823 "signal_pipe_capquit_to_child: %d header: error %s", capture_opts->signal_pipe_write_fd, g_strerror(errno));
1829 /* user wants to stop the capture run */
1831 sync_pipe_stop(capture_options *capture_opts)
1836 gboolean terminate = TRUE;
1839 if (capture_opts->fork_child != -1) {
1841 /* send the SIGINT signal to close the capture child gracefully. */
1842 int sts = kill(capture_opts->fork_child, SIGINT);
1844 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1845 "Sending SIGINT to child failed: %s\n", g_strerror(errno));
1848 #define STOP_SLEEP_TIME 500 /* ms */
1849 #define STOP_CHECK_TIME 50
1850 /* First, use the special signal pipe to try to close the capture child
1853 signal_pipe_capquit_to_child(capture_opts);
1855 /* Next, wait for the process to exit on its own */
1856 for (count = 0; count < STOP_SLEEP_TIME / STOP_CHECK_TIME; count++) {
1857 if (GetExitCodeProcess((HANDLE) capture_opts->fork_child, &childstatus) &&
1858 childstatus != STILL_ACTIVE) {
1862 Sleep(STOP_CHECK_TIME);
1865 /* Force the issue. */
1867 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1868 "sync_pipe_stop: forcing child to exit");
1869 sync_pipe_kill(capture_opts->fork_child);
1876 /* Wireshark has to exit, force the capture child to close */
1878 sync_pipe_kill(int fork_child)
1880 if (fork_child != -1) {
1882 int sts = kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
1884 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1885 "Sending SIGTERM to child failed: %s\n", g_strerror(errno));
1888 /* Remark: This is not the preferred method of closing a process!
1889 * the clean way would be getting the process id of the child process,
1890 * then getting window handle hWnd of that process (using EnumChildWindows),
1891 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
1893 * Unfortunately, I don't know how to get the process id from the
1894 * handle. OpenProcess will get an handle (not a window handle)
1895 * from the process ID; it will not get a window handle from the
1896 * process ID. (How could it? A process can have more than one
1897 * window. For that matter, a process might have *no* windows,
1898 * as a process running dumpcap, the normal child process program,
1901 * Hint: GenerateConsoleCtrlEvent() will only work if both processes are
1902 * running in the same console; that's not necessarily the case for
1903 * us, as we might not be running in a console.
1904 * And this also will require to have the process id.
1906 TerminateProcess((HANDLE) (fork_child), 0);
1911 #endif /* HAVE_LIBPCAP */