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" },
277 { STATUS_UNWIND_CONSOLIDATE, "Frame consolidation executed" },
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];
338 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
339 char buffer_size[ARGV_NUMBER_LEN];
342 HANDLE sync_pipe_read; /* pipe used to send messages from child to parent */
343 HANDLE sync_pipe_write; /* pipe used to send messages from child to parent */
344 HANDLE signal_pipe; /* named pipe used to send messages from parent to child (currently only stop) */
345 GString *args = g_string_sized_new(200);
347 SECURITY_ATTRIBUTES sa;
349 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 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_start");
364 capture_opts_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, capture_opts);
366 capture_opts->fork_child = -1;
368 argv = init_pipe_args(&argc);
370 /* We don't know where to find dumpcap. */
371 report_failure("We don't know where to find dumpcap.");
375 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[0]: %s", argv[0]);
377 argv = sync_pipe_add_arg(argv, &argc, "-i");
378 argv = sync_pipe_add_arg(argv, &argc, capture_opts->iface);
380 if (capture_opts->has_snaplen) {
381 argv = sync_pipe_add_arg(argv, &argc, "-s");
382 g_snprintf(ssnap, ARGV_NUMBER_LEN, "%d",capture_opts->snaplen);
383 argv = sync_pipe_add_arg(argv, &argc, ssnap);
386 if (capture_opts->linktype != -1) {
387 argv = sync_pipe_add_arg(argv, &argc, "-y");
388 g_snprintf(sdlt, ARGV_NUMBER_LEN, "%s",linktype_val_to_name(capture_opts->linktype));
389 argv = sync_pipe_add_arg(argv, &argc, sdlt);
392 if(capture_opts->multi_files_on) {
393 if (capture_opts->has_autostop_filesize) {
394 argv = sync_pipe_add_arg(argv, &argc, "-b");
395 g_snprintf(sfilesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
396 argv = sync_pipe_add_arg(argv, &argc, sfilesize);
399 if (capture_opts->has_file_duration) {
400 argv = sync_pipe_add_arg(argv, &argc, "-b");
401 g_snprintf(sfile_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->file_duration);
402 argv = sync_pipe_add_arg(argv, &argc, sfile_duration);
405 if (capture_opts->has_ring_num_files) {
406 argv = sync_pipe_add_arg(argv, &argc, "-b");
407 g_snprintf(sring_num_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->ring_num_files);
408 argv = sync_pipe_add_arg(argv, &argc, sring_num_files);
411 if (capture_opts->has_autostop_files) {
412 argv = sync_pipe_add_arg(argv, &argc, "-a");
413 g_snprintf(sautostop_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->autostop_files);
414 argv = sync_pipe_add_arg(argv, &argc, sautostop_files);
417 if (capture_opts->has_autostop_filesize) {
418 argv = sync_pipe_add_arg(argv, &argc, "-a");
419 g_snprintf(sautostop_filesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
420 argv = sync_pipe_add_arg(argv, &argc, sautostop_filesize);
424 if (capture_opts->has_autostop_packets) {
425 argv = sync_pipe_add_arg(argv, &argc, "-c");
426 g_snprintf(scount, ARGV_NUMBER_LEN, "%d",capture_opts->autostop_packets);
427 argv = sync_pipe_add_arg(argv, &argc, scount);
430 if (capture_opts->has_autostop_duration) {
431 argv = sync_pipe_add_arg(argv, &argc, "-a");
432 g_snprintf(sautostop_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->autostop_duration);
433 argv = sync_pipe_add_arg(argv, &argc, sautostop_duration);
436 if (!capture_opts->promisc_mode)
437 argv = sync_pipe_add_arg(argv, &argc, "-p");
438 #ifdef HAVE_PCAP_CREATE
439 if (capture_opts->monitor_mode)
440 argv = sync_pipe_add_arg(argv, &argc, "-I");
442 if (capture_opts->use_pcapng)
443 argv = sync_pipe_add_arg(argv, &argc, "-n");
444 #ifdef HAVE_PCAP_REMOTE
445 if (capture_opts->datatx_udp)
446 argv = sync_pipe_add_arg(argv, &argc, "-u");
448 if (!capture_opts->nocap_rpcap)
449 argv = sync_pipe_add_arg(argv, &argc, "-r");
451 if (capture_opts->auth_type == CAPTURE_AUTH_PWD)
453 argv = sync_pipe_add_arg(argv, &argc, "-A");
454 g_snprintf(sauth, sizeof(sauth), "%s:%s", capture_opts->auth_username,
455 capture_opts->auth_password);
456 argv = sync_pipe_add_arg(argv, &argc, sauth);
459 #ifdef HAVE_PCAP_SETSAMPLING
460 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
462 argv = sync_pipe_add_arg(argv, &argc, "-m");
463 g_snprintf(ssampling, ARGV_NUMBER_LEN, "%s:%d",
464 capture_opts->sampling_method == CAPTURE_SAMP_BY_COUNT ? "count" :
465 capture_opts->sampling_method == CAPTURE_SAMP_BY_TIMER ? "timer" :
467 capture_opts->sampling_param);
468 argv = sync_pipe_add_arg(argv, &argc, ssampling);
472 /* dumpcap should be running in capture child mode (hidden feature) */
474 argv = sync_pipe_add_arg(argv, &argc, "-Z");
476 g_snprintf(control_id, ARGV_NUMBER_LEN, "%d", GetCurrentProcessId());
477 argv = sync_pipe_add_arg(argv, &argc, control_id);
479 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
483 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
484 argv = sync_pipe_add_arg(argv, &argc, "-B");
485 #ifdef HAVE_PCAP_REMOTE
486 if (capture_opts->src_type == CAPTURE_IFREMOTE)
487 /* No buffer size when using remote interfaces */
488 g_snprintf(buffer_size, ARGV_NUMBER_LEN, "%d", 1);
491 g_snprintf(buffer_size, ARGV_NUMBER_LEN, "%d",capture_opts->buffer_size);
492 argv = sync_pipe_add_arg(argv, &argc, buffer_size);
495 if (capture_opts->cfilter != NULL && strlen(capture_opts->cfilter) != 0) {
496 argv = sync_pipe_add_arg(argv, &argc, "-f");
497 argv = sync_pipe_add_arg(argv, &argc, capture_opts->cfilter);
500 if(capture_opts->save_file) {
501 argv = sync_pipe_add_arg(argv, &argc, "-w");
502 argv = sync_pipe_add_arg(argv, &argc, capture_opts->save_file);
506 /* init SECURITY_ATTRIBUTES */
507 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
508 sa.bInheritHandle = TRUE;
509 sa.lpSecurityDescriptor = NULL;
511 /* Create a pipe for the child process */
512 /* (increase this value if you have trouble while fast capture file switches) */
513 if (! CreatePipe(&sync_pipe_read, &sync_pipe_write, &sa, 5120)) {
514 /* Couldn't create the pipe between parent and child. */
515 report_failure("Couldn't create sync pipe: %s",
516 win32strerror(GetLastError()));
517 g_free( (gpointer) argv[0]);
518 g_free( (gpointer) argv);
522 /* Create the signal pipe */
523 signal_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, control_id);
524 signal_pipe = CreateNamedPipe(utf_8to16(signal_pipe_name),
525 PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 65535, 65535, 0, NULL);
526 g_free(signal_pipe_name);
528 if (signal_pipe == INVALID_HANDLE_VALUE) {
529 /* Couldn't create the signal pipe between parent and child. */
530 report_failure("Couldn't create signal pipe: %s",
531 win32strerror(GetLastError()));
532 g_free( (gpointer) argv[0]);
533 g_free( (gpointer) argv);
537 /* init STARTUPINFO */
538 memset(&si, 0, sizeof(si));
541 si.dwFlags = STARTF_USESHOWWINDOW;
542 si.wShowWindow = SW_SHOW;
544 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
545 si.wShowWindow = SW_HIDE; /* this hides the console window */
546 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
547 si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
548 si.hStdError = sync_pipe_write;
549 /*si.hStdError = (HANDLE) _get_osfhandle(2);*/
552 /* convert args array into a single string */
553 /* XXX - could change sync_pipe_add_arg() instead */
554 /* there is a drawback here: the length is internally limited to 1024 bytes */
555 for(i=0; argv[i] != 0; i++) {
556 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
557 quoted_arg = protect_arg(argv[i]);
558 g_string_append(args, quoted_arg);
563 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
564 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
565 report_failure("Couldn't run %s in child process: %s",
566 args->str, win32strerror(GetLastError()));
567 CloseHandle(sync_pipe_read);
568 CloseHandle(sync_pipe_write);
569 g_free( (gpointer) argv[0]);
570 g_free( (gpointer) argv);
573 capture_opts->fork_child = (int) pi.hProcess;
574 g_string_free(args, TRUE);
576 /* associate the operating system filehandle to a C run-time file handle */
577 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
578 sync_pipe_read_fd = _open_osfhandle( (long) sync_pipe_read, _O_BINARY);
580 /* associate the operating system filehandle to a C run-time file handle */
581 capture_opts->signal_pipe_write_fd = _open_osfhandle( (long) signal_pipe, _O_BINARY);
584 if (pipe(sync_pipe) < 0) {
585 /* Couldn't create the pipe between parent and child. */
586 report_failure("Couldn't create sync pipe: %s", strerror(errno));
587 g_free( (gpointer) argv[0]);
592 if ((capture_opts->fork_child = fork()) == 0) {
594 * Child process - run dumpcap with the right arguments to make
595 * it just capture with the specified capture parameters
597 dup2(sync_pipe[PIPE_WRITE], 2);
598 ws_close(sync_pipe[PIPE_READ]);
599 execv(argv[0], (gpointer)argv);
600 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
601 argv[0], strerror(errno));
602 sync_pipe_errmsg_to_parent(2, errmsg, "");
604 /* Exit with "_exit()", so that we don't close the connection
605 to the X server (and cause stuff buffered up by our parent but
606 not yet sent to be sent, as that stuff should only be sent by
607 our parent). We've sent an error message to the parent, so
608 we exit with an exit status of 1 (any exit status other than
609 0 or 1 will cause an additional message to report that exit
610 status, over and above the error message we sent to the parent). */
614 sync_pipe_read_fd = sync_pipe[PIPE_READ];
617 g_free( (gpointer) argv[0]); /* exename */
619 /* Parent process - read messages from the child process over the
621 g_free( (gpointer) argv); /* free up arg array */
623 /* Close the write side of the pipe, so that only the child has it
624 open, and thus it completely closes, and thus returns to us
625 an EOF indication, if the child closes it (either deliberately
626 or by exiting abnormally). */
628 CloseHandle(sync_pipe_write);
630 ws_close(sync_pipe[PIPE_WRITE]);
633 if (capture_opts->fork_child == -1) {
634 /* We couldn't even create the child process. */
635 report_failure("Couldn't create child process: %s", strerror(errno));
636 ws_close(sync_pipe_read_fd);
638 ws_close(capture_opts->signal_pipe_write_fd);
643 capture_opts->fork_child_status = 0;
645 /* we might wait for a moment till child is ready, so update screen now */
646 main_window_update();
648 /* We were able to set up to read the capture file;
649 arrange that our callback be called whenever it's possible
650 to read from the sync pipe, so that it's called when
651 the child process wants to tell us something. */
653 /* we have a running capture, now wait for the real capture filename */
654 pipe_input_set_handler(sync_pipe_read_fd, (gpointer) capture_opts,
655 &capture_opts->fork_child, sync_pipe_input_cb);
661 * Open two pipes to dumpcap with the supplied arguments, one for its
662 * standard output and one for its standard error.
664 * On success, *msg is unchanged and 0 is returned; data_read_fd,
665 * messsage_read_fd, and fork_child point to the standard output pipe's
666 * file descriptor, the standard error pipe's file descriptor, and
667 * the child's PID/handle, respectively.
669 * On failure, *msg points to an error message for the failure, and -1 is
670 * returned, in which case *msg must be freed with g_free().
672 /* XXX - This duplicates a lot of code in sync_pipe_start() */
673 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
674 #define PIPE_BUF_SIZE 5120
676 sync_pipe_open_command(const char** argv, int *data_read_fd,
677 int *message_read_fd, int *fork_child, gchar **msg)
679 enum PIPES { PIPE_READ, PIPE_WRITE }; /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
681 HANDLE sync_pipe[2]; /* pipe used to send messages from child to parent */
682 HANDLE data_pipe[2]; /* pipe used to send data from child to parent */
683 GString *args = g_string_sized_new(200);
685 SECURITY_ATTRIBUTES sa;
687 PROCESS_INFORMATION pi;
691 int sync_pipe[2]; /* pipe used to send messages from child to parent */
692 int data_pipe[2]; /* pipe used to send data from child to parent */
697 *message_read_fd = -1;
698 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_open_command");
701 /* We can't return anything */
703 g_string_free(args, TRUE);
709 /* init SECURITY_ATTRIBUTES */
710 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
711 sa.bInheritHandle = TRUE;
712 sa.lpSecurityDescriptor = NULL;
714 /* Create a pipe for the child process to send us messages */
715 /* (increase this value if you have trouble while fast capture file switches) */
716 if (! CreatePipe(&sync_pipe[PIPE_READ], &sync_pipe[PIPE_WRITE], &sa, 5120)) {
717 /* Couldn't create the message pipe between parent and child. */
718 *msg = g_strdup_printf("Couldn't create sync pipe: %s",
719 win32strerror(GetLastError()));
720 g_free( (gpointer) argv[0]);
721 g_free( (gpointer) argv);
725 /* Create a pipe for the child process to send us data */
726 /* (increase this value if you have trouble while fast capture file switches) */
727 if (! CreatePipe(&data_pipe[PIPE_READ], &data_pipe[PIPE_WRITE], &sa, 5120)) {
728 /* Couldn't create the message pipe between parent and child. */
729 *msg = g_strdup_printf("Couldn't create data pipe: %s",
730 win32strerror(GetLastError()));
731 CloseHandle(sync_pipe[PIPE_READ]);
732 CloseHandle(sync_pipe[PIPE_WRITE]);
733 g_free( (gpointer) argv[0]);
734 g_free( (gpointer) argv);
738 /* init STARTUPINFO */
739 memset(&si, 0, sizeof(si));
742 si.dwFlags = STARTF_USESHOWWINDOW;
743 si.wShowWindow = SW_SHOW;
745 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
746 si.wShowWindow = SW_HIDE; /* this hides the console window */
748 si.hStdOutput = data_pipe[PIPE_WRITE];
749 si.hStdError = sync_pipe[PIPE_WRITE];
752 /* convert args array into a single string */
753 /* XXX - could change sync_pipe_add_arg() instead */
754 /* there is a drawback here: the length is internally limited to 1024 bytes */
755 for(i=0; argv[i] != 0; i++) {
756 if(i != 0) g_string_append_c(args, ' '); /* don't prepend a space before the path!!! */
757 quoted_arg = protect_arg(argv[i]);
758 g_string_append(args, quoted_arg);
763 if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
764 CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
765 *msg = g_strdup_printf("Couldn't run %s in child process: %s",
766 args->str, win32strerror(GetLastError()));
767 CloseHandle(data_pipe[PIPE_READ]);
768 CloseHandle(data_pipe[PIPE_WRITE]);
769 CloseHandle(sync_pipe[PIPE_READ]);
770 CloseHandle(sync_pipe[PIPE_WRITE]);
771 g_free( (gpointer) argv[0]);
772 g_free( (gpointer) argv);
775 *fork_child = (int) pi.hProcess;
776 g_string_free(args, TRUE);
778 /* associate the operating system filehandles to C run-time file handles */
779 /* (good file handle infos at: http://www.flounder.com/handles.htm) */
780 *data_read_fd = _open_osfhandle( (long) data_pipe[PIPE_READ], _O_BINARY);
781 *message_read_fd = _open_osfhandle( (long) sync_pipe[PIPE_READ], _O_BINARY);
783 /* Create a pipe for the child process to send us messages */
784 if (pipe(sync_pipe) < 0) {
785 /* Couldn't create the message pipe between parent and child. */
786 *msg = g_strdup_printf("Couldn't create sync pipe: %s", strerror(errno));
787 g_free( (gpointer) argv[0]);
792 /* Create a pipe for the child process to send us data */
793 if (pipe(data_pipe) < 0) {
794 /* Couldn't create the data pipe between parent and child. */
795 *msg = g_strdup_printf("Couldn't create data pipe: %s", strerror(errno));
796 ws_close(sync_pipe[PIPE_READ]);
797 ws_close(sync_pipe[PIPE_WRITE]);
798 g_free( (gpointer) argv[0]);
803 if ((*fork_child = fork()) == 0) {
805 * Child process - run dumpcap with the right arguments to make
806 * it just capture with the specified capture parameters
808 dup2(data_pipe[PIPE_WRITE], 1);
809 ws_close(data_pipe[PIPE_READ]);
810 ws_close(data_pipe[PIPE_WRITE]);
811 dup2(sync_pipe[PIPE_WRITE], 2);
812 ws_close(sync_pipe[PIPE_READ]);
813 ws_close(sync_pipe[PIPE_WRITE]);
814 execv(argv[0], (gpointer)argv);
815 g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
816 argv[0], strerror(errno));
817 sync_pipe_errmsg_to_parent(2, errmsg, "");
819 /* Exit with "_exit()", so that we don't close the connection
820 to the X server (and cause stuff buffered up by our parent but
821 not yet sent to be sent, as that stuff should only be sent by
822 our parent). We've sent an error message to the parent, so
823 we exit with an exit status of 1 (any exit status other than
824 0 or 1 will cause an additional message to report that exit
825 status, over and above the error message we sent to the parent). */
829 *data_read_fd = data_pipe[PIPE_READ];
830 *message_read_fd = sync_pipe[PIPE_READ];
833 g_free( (gpointer) argv[0]); /* exename */
835 /* Parent process - read messages from the child process over the
837 g_free( (gpointer) argv); /* free up arg array */
839 /* Close the write sides of the pipes, so that only the child has them
840 open, and thus they completely close, and thus return to us
841 an EOF indication, if the child closes them (either deliberately
842 or by exiting abnormally). */
844 CloseHandle(data_pipe[PIPE_WRITE]);
845 CloseHandle(sync_pipe[PIPE_WRITE]);
847 ws_close(data_pipe[PIPE_WRITE]);
848 ws_close(sync_pipe[PIPE_WRITE]);
851 if (*fork_child == -1) {
852 /* We couldn't even create the child process. */
853 *msg = g_strdup_printf("Couldn't create child process: %s", strerror(errno));
854 ws_close(*data_read_fd);
855 ws_close(*message_read_fd);
859 /* we might wait for a moment till child is ready, so update screen now */
860 main_window_update();
865 * Wait for dumpcap to finish. On success, *msg is unchanged, and 0 is
866 * returned. On failure, *msg points to an error message for the
867 * failure, and -1 is returned. In the latter case, *msg must be
868 * freed with g_free().
871 sync_pipe_close_command(int *data_read_fd, int *message_read_fd,
872 int *fork_child, gchar **msg)
874 ws_close(*data_read_fd);
875 if (message_read_fd != NULL)
876 ws_close(*message_read_fd);
879 /* XXX - Should we signal the child somehow? */
880 sync_pipe_kill(*fork_child);
883 return sync_pipe_wait_for_child(*fork_child, msg);
887 * Run dumpcap with the supplied arguments.
889 * On success, *data points to a buffer containing the dumpcap output,
890 * *primary_msg and *secondary_message are NULL, and 0 is returned; *data
891 * must be freed with g_free().
893 * On failure, *data is NULL, *primary_msg points to an error message,
894 * *secondary_msg either points to an additional error message or is
895 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
896 * must be freed with g_free().
898 /* XXX - This duplicates a lot of code in sync_pipe_start() */
899 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
900 #define PIPE_BUF_SIZE 5120
902 sync_pipe_run_command(const char** argv, gchar **data, gchar **primary_msg,
903 gchar **secondary_msg)
906 int data_pipe_read_fd, sync_pipe_read_fd, fork_child, ret;
908 gchar buffer[PIPE_BUF_SIZE+1];
912 char *primary_msg_text;
913 int secondary_msg_len;
914 char *secondary_msg_text;
916 GString *data_buf = NULL;
919 ret = sync_pipe_open_command(argv, &data_pipe_read_fd, &sync_pipe_read_fd,
923 *secondary_msg = NULL;
929 * We were able to set up to read dumpcap's output. Do so.
931 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
933 nread = pipe_read_block(sync_pipe_read_fd, &indicator, SP_MAX_MSG_LEN,
934 buffer, primary_msg);
936 /* We got a read error from the sync pipe, or we got no data at
937 all from the sync pipe, so we're not going to be getting any
938 data or error message from the child process. Pick up its
939 exit status, and complain.
941 We don't have to worry about killing the child, if the sync pipe
942 returned an error. Usually this error is caused as the child killed
943 itself while going down. Even in the rare cases that this isn't the
944 case, the child will get an error when writing to the broken pipe
945 the next time, cleaning itself up then. */
946 ret = sync_pipe_wait_for_child(fork_child, &wait_msg);
948 /* We got an EOF from the sync pipe. That means that it exited
949 before giving us any data to read. If ret is -1, we report
950 that as a bad exit (e.g., exiting due to a signal); otherwise,
951 we report it as a premature exit. */
953 *primary_msg = wait_msg;
955 *primary_msg = g_strdup("Child dumpcap closed sync pipe prematurely");
957 /* We got an error from the sync pipe. If ret is -1, report
958 both the sync pipe I/O error and the wait error. */
960 combined_msg = g_strdup_printf("%s\n\n%s", *primary_msg, wait_msg);
961 g_free(*primary_msg);
963 *primary_msg = combined_msg;
966 *secondary_msg = NULL;
971 /* we got a valid message block from the child, process it */
976 * Error from dumpcap; there will be a primary message and a
980 /* convert primary message */
981 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
982 primary_msg_text = buffer+4;
983 /* convert secondary message */
984 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
986 secondary_msg_text = primary_msg_text + primary_msg_len + 4;
987 /* the capture child will close the sync_pipe, nothing to do */
990 * Pick up the child status.
992 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
996 * Child process failed unexpectedly, or wait failed; msg is the
1000 *secondary_msg = NULL;
1003 * Child process failed, but returned the expected exit status.
1004 * Return the messages it gave us, and indicate failure.
1006 *primary_msg = g_strdup(primary_msg_text);
1007 *secondary_msg = g_strdup(secondary_msg_text);
1014 /* read the output from the command */
1015 data_buf = g_string_new("");
1016 while ((count = ws_read(data_pipe_read_fd, buffer, PIPE_BUF_SIZE)) > 0) {
1017 buffer[count] = '\0';
1018 g_string_append(data_buf, buffer);
1022 * Pick up the child status.
1024 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1028 * Child process failed unexpectedly, or wait failed; msg is the
1032 *secondary_msg = NULL;
1033 g_string_free(data_buf, TRUE);
1037 * Child process succeeded.
1039 *primary_msg = NULL;
1040 *secondary_msg = NULL;
1041 *data = data_buf->str;
1042 g_string_free(data_buf, FALSE);
1048 * Pick up the child status.
1050 ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1054 * Child process failed unexpectedly, or wait failed; msg is the
1058 *secondary_msg = NULL;
1061 * Child process returned an unknown status.
1063 *primary_msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1065 *secondary_msg = NULL;
1075 * Get the list of interfaces using dumpcap.
1077 * On success, *data points to a buffer containing the dumpcap output,
1078 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1079 * must be freed with g_free().
1081 * On failure, *data is NULL, *primary_msg points to an error message,
1082 * *secondary_msg either points to an additional error message or is
1083 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1084 * must be freed with g_free().
1087 sync_interface_list_open(gchar **data, gchar **primary_msg,
1088 gchar **secondary_msg)
1093 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_list_open");
1095 argv = init_pipe_args(&argc);
1098 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1099 *secondary_msg = NULL;
1104 /* Ask for the interface list */
1105 argv = sync_pipe_add_arg(argv, &argc, "-D");
1108 /* Run dumpcap in capture child mode */
1109 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1110 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1112 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1116 * Get the capabilities of an interface using dumpcap.
1118 * On success, *data points to a buffer containing the dumpcap output,
1119 * *primary_msg and *secondary_msg are NULL, and 0 is returned. *data
1120 * must be freed with g_free().
1122 * On failure, *data is NULL, *primary_msg points to an error message,
1123 * *secondary_msg either points to an additional error message or is
1124 * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1125 * must be freed with g_free().
1128 sync_if_capabilities_open(const gchar *ifname, gboolean monitor_mode,
1129 gchar **data, gchar **primary_msg,
1130 gchar **secondary_msg)
1135 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_linktype_list_open");
1137 argv = init_pipe_args(&argc);
1140 *primary_msg = g_strdup("We don't know where to find dumpcap.");
1141 *secondary_msg = NULL;
1146 /* Ask for the interface capabilities */
1147 argv = sync_pipe_add_arg(argv, &argc, "-i");
1148 argv = sync_pipe_add_arg(argv, &argc, ifname);
1149 argv = sync_pipe_add_arg(argv, &argc, "-L");
1151 argv = sync_pipe_add_arg(argv, &argc, "-I");
1154 /* Run dumpcap in capture child mode */
1155 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1156 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1158 return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1162 * Start getting interface statistics using dumpcap. On success, read_fd
1163 * contains the file descriptor for the pipe's stdout, *msg is unchanged,
1164 * and zero is returned. On failure, *msg will point to an error message
1165 * that must be g_free()d, and -1 will be returned.
1168 sync_interface_stats_open(int *data_read_fd, int *fork_child, gchar **msg)
1172 int message_read_fd, ret;
1174 gchar buffer[PIPE_BUF_SIZE+1];
1177 int primary_msg_len;
1178 char *primary_msg_text;
1179 int secondary_msg_len;
1180 char *secondary_msg_text;
1183 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_stats_open");
1185 argv = init_pipe_args(&argc);
1188 *msg = g_strdup("We don't know where to find dumpcap.");
1192 /* Ask for the interface statistics */
1193 argv = sync_pipe_add_arg(argv, &argc, "-S");
1196 argv = sync_pipe_add_arg(argv, &argc, "-Z");
1197 argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1199 ret = sync_pipe_open_command(argv, data_read_fd, &message_read_fd,
1205 * We were able to set up to read dumpcap's output. Do so.
1207 * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1209 nread = pipe_read_block(message_read_fd, &indicator, SP_MAX_MSG_LEN,
1212 /* We got a read error from the sync pipe, or we got no data at
1213 all from the sync pipe, so we're not going to be getting any
1214 data or error message from the child process. Pick up its
1215 exit status, and complain.
1217 We don't have to worry about killing the child, if the sync pipe
1218 returned an error. Usually this error is caused as the child killed
1219 itself while going down. Even in the rare cases that this isn't the
1220 case, the child will get an error when writing to the broken pipe
1221 the next time, cleaning itself up then. */
1222 ret = sync_pipe_wait_for_child(*fork_child, &wait_msg);
1224 /* We got an EOF from the sync pipe. That means that it exited
1225 before giving us any data to read. If ret is -1, we report
1226 that as a bad exit (e.g., exiting due to a signal); otherwise,
1227 we report it as a premature exit. */
1231 *msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1233 /* We got an error from the sync pipe. If ret is -1, report
1234 both the sync pipe I/O error and the wait error. */
1236 combined_msg = g_strdup_printf("%s\n\n%s", *msg, wait_msg);
1239 *msg = combined_msg;
1246 /* we got a valid message block from the child, process it */
1251 * Error from dumpcap; there will be a primary message and a
1252 * secondary message.
1255 /* convert primary message */
1256 pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1257 primary_msg_text = buffer+4;
1258 /* convert secondary message */
1259 pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1260 &secondary_msg_len);
1261 secondary_msg_text = primary_msg_text + primary_msg_len + 4;
1262 /* the capture child will close the sync_pipe, nothing to do */
1265 * Pick up the child status.
1267 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1271 * Child process failed unexpectedly, or wait failed; msg is the
1276 * Child process failed, but returned the expected exit status.
1277 * Return the messages it gave us, and indicate failure.
1279 *msg = g_strdup(primary_msg_text);
1285 /* Close the message pipe. */
1286 ws_close(message_read_fd);
1291 * Pick up the child status.
1293 ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1297 * Child process failed unexpectedly, or wait failed; msg is the
1302 * Child process returned an unknown status.
1304 *msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1313 /* Close down the stats process */
1315 sync_interface_stats_close(int *read_fd, int *fork_child, gchar **msg)
1317 return sync_pipe_close_command(read_fd, NULL, fork_child, msg);
1320 /* read a number of bytes from a pipe */
1321 /* (blocks until enough bytes read or an error occurs) */
1323 pipe_read_bytes(int pipe_fd, char *bytes, int required, char **msg)
1330 newly = read(pipe_fd, &bytes[offset], required);
1333 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1334 "read from pipe %d: EOF (capture closed?)", pipe_fd);
1341 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1342 "read from pipe %d: error(%u): %s", pipe_fd, error,
1344 *msg = g_strdup_printf("Error reading from sync pipe: %s",
1357 static gboolean pipe_data_available(int pipe_fd) {
1358 #ifdef _WIN32 /* PeekNamedPipe */
1359 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
1362 if (hPipe == INVALID_HANDLE_VALUE)
1365 if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
1368 if (bytes_avail > 0)
1373 struct timeval timeout;
1376 FD_SET(pipe_fd, &rfds);
1378 timeout.tv_usec = 0;
1380 if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
1387 /* Read a line from a pipe, similar to fgets */
1389 sync_pipe_gets_nonblock(int pipe_fd, char *bytes, int max) {
1393 while(offset < max - 1) {
1395 if (! pipe_data_available(pipe_fd))
1397 newly = read(pipe_fd, &bytes[offset], 1);
1399 /* EOF - not necessarily an error */
1401 } else if (newly < 0) {
1403 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1404 "read from pipe %d: error(%u): %s", pipe_fd, errno, strerror(errno));
1406 } else if (bytes[offset] == '\n') {
1412 bytes[offset] = '\0';
1418 /* convert header values (indicator and 3-byte length) */
1420 pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len) {
1422 g_assert(header_len == 4);
1424 /* convert header values */
1425 *indicator = header[0];
1426 *block_len = header[1]<<16 | header[2]<<8 | header[3];
1429 /* read a message from the sending pipe in the standard format
1430 (1-byte message indicator, 3-byte message length (excluding length
1431 and indicator field), and the rest is the message) */
1433 pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
1440 /* read header (indicator and 3-byte length) */
1441 newly = pipe_read_bytes(pipe_fd, header, 4, err_msg);
1445 * Immediate EOF; if the capture child exits normally, this
1446 * is an "I'm done" indication, so don't report it as an
1449 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1450 "read %d got an EOF", pipe_fd);
1453 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1454 "read %d failed to read header: %u", pipe_fd, newly);
1457 * Short read, but not an immediate EOF.
1459 *err_msg = g_strdup_printf("Premature EOF reading from sync pipe: got only %d bytes",
1465 /* convert header values */
1466 pipe_convert_header(header, 4, indicator, &required);
1468 /* only indicator with no value? */
1470 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1471 "read %d indicator: %c empty value", pipe_fd, *indicator);
1475 /* does the data fit into the given buffer? */
1476 if(required > len) {
1477 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1478 "read %d length error, required %d > len %d, indicator: %u",
1479 pipe_fd, required, len, *indicator);
1481 /* we have a problem here, try to read some more bytes from the pipe to debug where the problem really is */
1482 memcpy(msg, header, sizeof(header));
1483 newly = read(pipe_fd, &msg[sizeof(header)], len-sizeof(header));
1484 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1490 /* read the actual block data */
1491 newly = pipe_read_bytes(pipe_fd, msg, required, err_msg);
1492 if(newly != required) {
1494 *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1500 /* XXX If message is "2part", the msg probably won't be sent to debug log correctly */
1501 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1502 "read %d ok indicator: %c len: %u msg: %s", pipe_fd, *indicator,
1509 /* There's stuff to read from the sync pipe, meaning the child has sent
1510 us a message, or the sync pipe has closed, meaning the child has
1511 closed it (perhaps because it exited). */
1513 sync_pipe_input_cb(gint source, gpointer user_data)
1515 capture_options *capture_opts = (capture_options *)user_data;
1517 char buffer[SP_MAX_MSG_LEN+1];
1523 char *secondary_msg;
1524 char *wait_msg, *combined_msg;
1526 nread = pipe_read_block(source, &indicator, SP_MAX_MSG_LEN, buffer,
1529 /* We got a read error, or a bad message, or an EOF, from the sync pipe.
1531 If we got a read error or a bad message, nread is -1 and
1532 primary_msg is set to point to an error message. We don't
1533 have to worry about killing the child; usually this error
1534 is caused as the child killed itself while going down.
1535 Even in the rare cases that this isn't the case, the child
1536 will get an error when writing to the broken pipe the next time,
1537 cleaning itself up then.
1539 If we got an EOF, nread is 0 and primary_msg isn't set. This
1540 is an indication that the capture is finished. */
1541 ret = sync_pipe_wait_for_child(capture_opts->fork_child, &wait_msg);
1543 /* We got an EOF from the sync pipe. That means that the capture
1544 child exited, and not in the middle of a message; we treat
1545 that as an indication that it's done, and only report an
1546 error if ret is -1, in which case wait_msg is the error
1549 primary_msg = wait_msg;
1551 /* We got an error from the sync pipe. If ret is -1, report
1552 both the sync pipe I/O error and the wait error. */
1554 combined_msg = g_strdup_printf("%s\n\n%s", primary_msg, wait_msg);
1555 g_free(primary_msg);
1557 primary_msg = combined_msg;
1561 /* No more child process. */
1562 capture_opts->fork_child = -1;
1563 capture_opts->fork_child_status = ret;
1566 ws_close(capture_opts->signal_pipe_write_fd);
1568 capture_input_closed(capture_opts, primary_msg);
1569 g_free(primary_msg);
1573 /* we got a valid message block from the child, process it */
1576 if(!capture_input_new_file(capture_opts, buffer)) {
1577 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: file failed, closing capture");
1579 /* We weren't able to open the new capture file; user has been
1580 alerted. Close the sync pipe. */
1583 /* the child has send us a filename which we couldn't open.
1584 this probably means, the child is creating files faster than we can handle it.
1585 this should only be the case for very fast file switches
1586 we can't do much more than telling the child to stop
1587 (this is the "emergency brake" if user e.g. wants to switch files every second) */
1588 sync_pipe_stop(capture_opts);
1591 case SP_PACKET_COUNT:
1592 nread = atoi(buffer);
1593 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: new packets %u", nread);
1594 capture_input_new_packets(capture_opts, nread);
1597 /* convert primary message */
1598 pipe_convert_header(buffer, 4, &indicator, &primary_len);
1599 primary_msg = buffer+4;
1600 /* convert secondary message */
1601 pipe_convert_header(primary_msg + primary_len, 4, &indicator, &secondary_len);
1602 secondary_msg = primary_msg + primary_len + 4;
1603 /* message output */
1604 capture_input_error_message(capture_opts, primary_msg, secondary_msg);
1605 /* the capture child will close the sync_pipe, nothing to do for now */
1606 /* (an error message doesn't mean we have to stop capturing) */
1609 capture_input_cfilter_error_message(capture_opts, buffer);
1610 /* the capture child will close the sync_pipe, nothing to do for now */
1613 capture_input_drops(capture_opts, (guint32)strtoul(buffer, NULL, 10));
1616 g_assert_not_reached();
1624 /* the child process is going down, wait until it's completely terminated */
1626 sync_pipe_wait_for_child(int fork_child, gchar **msgp)
1628 int fork_child_status;
1631 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: wait till child closed");
1632 g_assert(fork_child != -1);
1634 *msgp = NULL; /* assume no error */
1637 if (_cwait(&fork_child_status, fork_child, _WAIT_CHILD) == -1) {
1638 *msgp = g_strdup_printf("Error from cwait(): %s", strerror(errno));
1642 * The child exited; return its exit status. Do not treat this as
1645 ret = fork_child_status;
1646 if ((fork_child_status & 0xC0000000) == ERROR_SEVERITY_ERROR) {
1647 /* Probably an exception code */
1648 *msgp = g_strdup_printf("Child dumpcap process died: %s",
1649 win32strexception(fork_child_status));
1654 if (waitpid(fork_child, &fork_child_status, 0) != -1) {
1655 if (WIFEXITED(fork_child_status)) {
1657 * The child exited; return its exit status. Do not treat this as
1660 ret = WEXITSTATUS(fork_child_status);
1661 } else if (WIFSTOPPED(fork_child_status)) {
1662 /* It stopped, rather than exiting. "Should not happen." */
1663 *msgp = g_strdup_printf("Child dumpcap process stopped: %s",
1664 sync_pipe_signame(WSTOPSIG(fork_child_status)));
1666 } else if (WIFSIGNALED(fork_child_status)) {
1667 /* It died with a signal. */
1668 *msgp = g_strdup_printf("Child dumpcap process died: %s%s",
1669 sync_pipe_signame(WTERMSIG(fork_child_status)),
1670 WCOREDUMP(fork_child_status) ? " - core dumped" : "");
1673 /* What? It had to either have exited, or stopped, or died with
1674 a signal; what happened here? */
1675 *msgp = g_strdup_printf("Bad status from waitpid(): %#o",
1680 *msgp = g_strdup_printf("Error from waitpid(): %s", strerror(errno));
1685 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: capture child closed");
1691 /* convert signal to corresponding name */
1693 sync_pipe_signame(int sig)
1696 static char sigmsg_buf[6+1+3+1];
1705 sigmsg = "Interrupted";
1713 sigmsg = "Illegal instruction";
1717 sigmsg = "Trace trap";
1725 sigmsg = "Arithmetic exception";
1733 sigmsg = "Bus error";
1737 sigmsg = "Segmentation violation";
1740 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1741 Linux is POSIX compliant. These are not POSIX-defined signals ---
1742 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1744 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1745 were omitted from POSIX.1 because their behavior is
1746 implementation dependent and could not be adequately catego-
1747 rized. Conforming implementations may deliver these sig-
1748 nals, but must document the circumstances under which they
1749 are delivered and note any restrictions concerning their
1752 So we only check for SIGSYS on those systems that happen to
1753 implement them (a system can be POSIX-compliant and implement
1754 them, it's just that POSIX doesn't *require* a POSIX-compliant
1755 system to implement them).
1760 sigmsg = "Bad system call";
1765 sigmsg = "Broken pipe";
1769 sigmsg = "Alarm clock";
1773 sigmsg = "Terminated";
1777 /* Returning a static buffer is ok in the context we use it here */
1778 g_snprintf(sigmsg_buf, sizeof sigmsg_buf, "Signal %d", sig);
1779 sigmsg = sigmsg_buf;
1788 /* tell the child through the signal pipe that we want to quit the capture */
1790 signal_pipe_capquit_to_child(capture_options *capture_opts)
1792 const char quit_msg[] = "QUIT";
1796 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "signal_pipe_capquit_to_child");
1798 /* it doesn't matter *what* we send here, the first byte will stop the capture */
1799 /* simply sending a "QUIT" string */
1800 /*pipe_write_block(capture_opts->signal_pipe_write_fd, SP_QUIT, quit_msg);*/
1801 ret = write(capture_opts->signal_pipe_write_fd, quit_msg, sizeof quit_msg);
1803 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1804 "signal_pipe_capquit_to_child: %d header: error %s", capture_opts->signal_pipe_write_fd, strerror(errno));
1810 /* user wants to stop the capture run */
1812 sync_pipe_stop(capture_options *capture_opts)
1817 gboolean terminate = TRUE;
1820 if (capture_opts->fork_child != -1) {
1822 /* send the SIGINT signal to close the capture child gracefully. */
1823 int sts = kill(capture_opts->fork_child, SIGINT);
1825 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1826 "Sending SIGINT to child failed: %s\n", strerror(errno));
1829 #define STOP_SLEEP_TIME 500 /* ms */
1830 #define STOP_CHECK_TIME 50
1831 /* First, use the special signal pipe to try to close the capture child
1834 signal_pipe_capquit_to_child(capture_opts);
1836 /* Next, wait for the process to exit on its own */
1837 for (count = 0; count < STOP_SLEEP_TIME / STOP_CHECK_TIME; count++) {
1838 if (GetExitCodeProcess((HANDLE) capture_opts->fork_child, &childstatus) &&
1839 childstatus != STILL_ACTIVE) {
1843 Sleep(STOP_CHECK_TIME);
1846 /* Force the issue. */
1848 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1849 "sync_pipe_stop: forcing child to exit");
1850 sync_pipe_kill(capture_opts->fork_child);
1857 /* Wireshark has to exit, force the capture child to close */
1859 sync_pipe_kill(int fork_child)
1861 if (fork_child != -1) {
1863 int sts = kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
1865 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1866 "Sending SIGTERM to child failed: %s\n", strerror(errno));
1869 /* Remark: This is not the preferred method of closing a process!
1870 * the clean way would be getting the process id of the child process,
1871 * then getting window handle hWnd of that process (using EnumChildWindows),
1872 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
1874 * Unfortunately, I don't know how to get the process id from the
1875 * handle. OpenProcess will get an handle (not a window handle)
1876 * from the process ID; it will not get a window handle from the
1877 * process ID. (How could it? A process can have more than one
1878 * window. For that matter, a process might have *no* windows,
1879 * as a process running dumpcap, the normal child process program,
1882 * Hint: GenerateConsoleCtrlEvent() will only work if both processes are
1883 * running in the same console; that's not necessarily the case for
1884 * us, as we might not be running in a console.
1885 * And this also will require to have the process id.
1887 TerminateProcess((HANDLE) (fork_child), 0);
1892 #endif /* HAVE_LIBPCAP */