Ed Beroset <beroset@mindspring.com> via bug 5531
[metze/wireshark/wip.git] / capture_sync.c
1 /* capture_sync.c
2  * Synchronisation between Wireshark capture parent and child instances
3  *
4  * $Id$
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
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.
14  *
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.
19  *
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.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #ifdef HAVE_LIBPCAP
30
31 #include <glib.h>
32 #include <stdio.h>
33 #include <ctype.h>
34 #include <string.h>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39
40 #ifdef HAVE_FCNTL_H
41 #include <fcntl.h>
42 #endif
43
44 #include <signal.h>
45
46 #ifdef _WIN32
47 #include <wsutil/unicode-utils.h>
48 #endif
49
50 #ifdef HAVE_SYS_WAIT_H
51 # include <sys/wait.h>
52 #endif
53
54 #include "capture-pcap-util.h"
55
56 #ifndef _WIN32
57 /*
58  * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
59  * macros) on UNIX systems that don't have them.
60  */
61 #ifndef WIFEXITED
62 # define WIFEXITED(status)      (((status) & 0177) == 0)
63 #endif
64 #ifndef WIFSTOPPED
65 # define WIFSTOPPED(status)     (((status) & 0177) == 0177)
66 #endif
67 #ifndef WIFSIGNALED
68 # define WIFSIGNALED(status)    (!WIFSTOPPED(status) && !WIFEXITED(status))
69 #endif
70 #ifndef WEXITSTATUS
71 # define WEXITSTATUS(status)    ((status) >> 8)
72 #endif
73 #ifndef WTERMSIG
74 # define WTERMSIG(status)       ((status) & 0177)
75 #endif
76 #ifndef WCOREDUMP
77 # define WCOREDUMP(status)      ((status) & 0200)
78 #endif
79 #ifndef WSTOPSIG
80 # define WSTOPSIG(status)       ((status) >> 8)
81 #endif
82 #endif /* _WIN32 */
83
84 #include <epan/packet.h>
85 #include <epan/prefs.h>
86
87 #include "globals.h"
88 #include "file.h"
89 #include <epan/filesystem.h>
90 #include <epan/report_err.h>
91
92 #include "capture.h"
93 #include "capture_sync.h"
94
95 #include "sync_pipe.h"
96
97 #ifdef _WIN32
98 #include "capture-wpcap.h"
99 #endif
100 #include "ui_util.h"
101 #include <wsutil/file_util.h>
102 #include "log.h"
103
104 #ifdef _WIN32
105 #include <process.h>    /* For spawning child process */
106 #endif
107
108
109
110 #ifndef _WIN32
111 static const char *sync_pipe_signame(int);
112 #endif
113
114
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,
119                            char **err_msg);
120
121
122
123 /* Append an arg (realloc) to an argc/argv array */
124 /* (add a string pointer to a NULL-terminated array of string pointers) */
125 static const char **
126 sync_pipe_add_arg(const char **args, int *argc, const char *arg)
127 {
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 *));
133
134     /* Stuff the pointer into the penultimate element of the array, which
135        is the one at the index specified by "*argc". */
136     args[*argc] = g_strdup(arg);
137     /* Now bump the count. */
138     (*argc)++;
139
140     /* We overwrite the NULL pointer; put it back right after the
141        element we added. */
142     args[*argc] = NULL;
143
144     return args;
145 }
146
147
148
149 #ifdef _WIN32
150 /* Quote the argument element if necessary, so that it will get
151  * reconstructed correctly in the C runtime startup code.  Note that
152  * the unquoting algorithm in the C runtime is really weird, and
153  * rather different than what Unix shells do. See stdargv.c in the C
154  * runtime sources (in the Platform SDK, in src/crt).
155  *
156  * Stolen from GLib's protect_argv(), an internal routine that quotes
157  * string in an argument list so that they arguments will be handled
158  * correctly in the command-line string passed to CreateProcess()
159  * if that string is constructed by gluing those strings together.
160  */
161 static gchar *
162 protect_arg (const gchar *argv)
163 {
164     gchar *new_arg;
165     const gchar *p = argv;
166     gchar *q;
167     gint len = 0;
168     gboolean need_dblquotes = FALSE;
169
170     while (*p) {
171         if (*p == ' ' || *p == '\t')
172             need_dblquotes = TRUE;
173         else if (*p == '"')
174             len++;
175         else if (*p == '\\') {
176             const gchar *pp = p;
177
178             while (*pp && *pp == '\\')
179                 pp++;
180             if (*pp == '"')
181                 len++;
182         }
183         len++;
184         p++;
185     }
186
187     q = new_arg = g_malloc (len + need_dblquotes*2 + 1);
188     p = argv;
189
190     if (need_dblquotes)
191         *q++ = '"';
192
193     while (*p) {
194         if (*p == '"')
195             *q++ = '\\';
196         else if (*p == '\\') {
197             const gchar *pp = p;
198
199             while (*pp && *pp == '\\')
200                 pp++;
201             if (*pp == '"')
202                 *q++ = '\\';
203         }
204         *q++ = *p;
205         p++;
206     }
207
208     if (need_dblquotes)
209         *q++ = '"';
210     *q++ = '\0';
211
212     return new_arg;
213 }
214
215 /*
216  * Generate a string for a Win32 error.
217  */
218 #define ERRBUF_SIZE    1024
219 static const char *
220 win32strerror(DWORD error)
221 {
222     static char errbuf[ERRBUF_SIZE+1];
223     size_t errlen;
224     char *p;
225
226     FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
227                    ERRBUF_SIZE, NULL);
228
229     /*
230      * "FormatMessage()" "helpfully" sticks CR/LF at the end of the
231      * message.  Get rid of it.
232      */
233     errlen = strlen(errbuf);
234     if (errlen >= 2) {
235         errbuf[errlen - 1] = '\0';
236         errbuf[errlen - 2] = '\0';
237     }
238     p = strchr(errbuf, '\0');
239     g_snprintf(p, (gulong)(sizeof errbuf - (p-errbuf)), " (%lu)", error);
240     return errbuf;
241 }
242
243 /*
244  * Generate a string for a Win32 exception code.
245  */
246 static const char *
247 win32strexception(DWORD exception)
248 {
249     static char errbuf[ERRBUF_SIZE+1];
250     static const struct exception_msg {
251         int code;
252         char *msg;
253     } exceptions[] = {
254         { EXCEPTION_ACCESS_VIOLATION, "Access violation" },
255         { EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded" },
256         { EXCEPTION_BREAKPOINT, "Breakpoint" },
257         { EXCEPTION_DATATYPE_MISALIGNMENT, "Data type misalignment" },
258         { EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal floating-point operand" },
259         { EXCEPTION_FLT_DIVIDE_BY_ZERO, "Floating-point divide by zero" },
260         { EXCEPTION_FLT_INEXACT_RESULT, "Floating-point inexact result" },
261         { EXCEPTION_FLT_INVALID_OPERATION, "Invalid floating-point operation" },
262         { EXCEPTION_FLT_OVERFLOW, "Floating-point overflow" },
263         { EXCEPTION_FLT_STACK_CHECK, "Floating-point stack check" },
264         { EXCEPTION_FLT_UNDERFLOW, "Floating-point underflow" },
265         { EXCEPTION_GUARD_PAGE, "Guard page violation" },
266         { EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction" },
267         { EXCEPTION_IN_PAGE_ERROR, "Page-in error" },
268         { EXCEPTION_INT_DIVIDE_BY_ZERO, "Integer divide by zero" },
269         { EXCEPTION_INT_OVERFLOW, "Integer overflow" },
270         { EXCEPTION_INVALID_DISPOSITION, "Invalid disposition" },
271         { EXCEPTION_INVALID_HANDLE, "Invalid handle" },
272         { EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception" },
273         { EXCEPTION_PRIV_INSTRUCTION, "Privileged instruction" },
274         { EXCEPTION_SINGLE_STEP, "Single-step complete" },
275         { EXCEPTION_STACK_OVERFLOW, "Stack overflow" },
276         { 0, NULL }
277     };
278 #define N_EXCEPTIONS    (sizeof exceptions / sizeof exceptions[0])
279     int i;
280
281     for (i = 0; i < N_EXCEPTIONS; i++) {
282         if (exceptions[i].code == exception)
283             return exceptions[i].msg;
284     }
285     g_snprintf(errbuf, (gulong)sizeof errbuf, "Exception 0x%08x", exception);
286     return errbuf;
287 }
288 #endif
289
290 /* Initialize an argument list and add dumpcap to it. */
291 static const char **
292 init_pipe_args(int *argc) {
293     const char **argv;
294     const char *progfile_dir;
295     char *exename;
296
297     progfile_dir = get_progfile_dir();
298     if (progfile_dir == NULL) {
299       return NULL;
300     }
301
302     /* Allocate the string pointer array with enough space for the
303        terminating NULL pointer. */
304     *argc = 0;
305     argv = g_malloc(sizeof (char *));
306     *argv = NULL;
307
308     /* take Wireshark's absolute program path and replace "Wireshark" with "dumpcap" */
309     exename = g_strdup_printf("%s" G_DIR_SEPARATOR_S "dumpcap", progfile_dir);
310
311     /* Make that the first argument in the argument list (argv[0]). */
312     argv = sync_pipe_add_arg(argv, argc, exename);
313
314     return argv;
315 }
316
317 #define ARGV_NUMBER_LEN 24
318 /* a new capture run: start a new dumpcap task and hand over parameters through command line */
319 gboolean
320 sync_pipe_start(capture_options *capture_opts) {
321     char ssnap[ARGV_NUMBER_LEN];
322     char sdlt[ARGV_NUMBER_LEN];
323     char scount[ARGV_NUMBER_LEN];
324     char sfilesize[ARGV_NUMBER_LEN];
325     char sfile_duration[ARGV_NUMBER_LEN];
326     char sring_num_files[ARGV_NUMBER_LEN];
327     char sautostop_files[ARGV_NUMBER_LEN];
328     char sautostop_filesize[ARGV_NUMBER_LEN];
329     char sautostop_duration[ARGV_NUMBER_LEN];
330 #ifdef HAVE_PCAP_REMOTE
331     char sauth[256];
332 #endif
333 #ifdef HAVE_PCAP_SETSAMPLING
334     char ssampling[ARGV_NUMBER_LEN];
335 #endif
336
337 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
338     char buffer_size[ARGV_NUMBER_LEN];
339 #endif
340
341 #ifdef _WIN32
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);
346     gchar *quoted_arg;
347     SECURITY_ATTRIBUTES sa;
348     STARTUPINFO si;
349     PROCESS_INFORMATION pi;
350     char control_id[ARGV_NUMBER_LEN];
351     gchar *signal_pipe_name;
352 #else
353     char errmsg[1024+1];
354     int sync_pipe[2];                       /* pipe used to send messages from child to parent */
355     enum PIPES { PIPE_READ, PIPE_WRITE };   /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
356 #endif
357     int sync_pipe_read_fd;
358     int argc;
359     const char **argv;
360     int i;
361     guint j;
362     interface_options interface_opts;
363
364     if (capture_opts->ifaces->len > 1)
365         capture_opts->use_pcapng = TRUE;
366     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_start");
367     capture_opts_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, capture_opts);
368
369     capture_opts->fork_child = -1;
370
371     argv = init_pipe_args(&argc);
372     if (!argv) {
373         /* We don't know where to find dumpcap. */
374         report_failure("We don't know where to find dumpcap.");
375         return FALSE;
376     }
377
378     if (capture_opts->ifaces->len > 1)
379         argv = sync_pipe_add_arg(argv, &argc, "-t");
380
381     if (capture_opts->use_pcapng)
382         argv = sync_pipe_add_arg(argv, &argc, "-n");
383     else
384         argv = sync_pipe_add_arg(argv, &argc, "-P");
385
386     if (capture_opts->multi_files_on) {
387         if (capture_opts->has_autostop_filesize) {
388             argv = sync_pipe_add_arg(argv, &argc, "-b");
389             g_snprintf(sfilesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
390             argv = sync_pipe_add_arg(argv, &argc, sfilesize);
391         }
392
393         if (capture_opts->has_file_duration) {
394             argv = sync_pipe_add_arg(argv, &argc, "-b");
395             g_snprintf(sfile_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->file_duration);
396             argv = sync_pipe_add_arg(argv, &argc, sfile_duration);
397         }
398
399         if (capture_opts->has_ring_num_files) {
400             argv = sync_pipe_add_arg(argv, &argc, "-b");
401             g_snprintf(sring_num_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->ring_num_files);
402             argv = sync_pipe_add_arg(argv, &argc, sring_num_files);
403         }
404
405         if (capture_opts->has_autostop_files) {
406             argv = sync_pipe_add_arg(argv, &argc, "-a");
407             g_snprintf(sautostop_files, ARGV_NUMBER_LEN, "files:%d",capture_opts->autostop_files);
408             argv = sync_pipe_add_arg(argv, &argc, sautostop_files);
409         }
410     } else {
411         if (capture_opts->has_autostop_filesize) {
412             argv = sync_pipe_add_arg(argv, &argc, "-a");
413             g_snprintf(sautostop_filesize, ARGV_NUMBER_LEN, "filesize:%d",capture_opts->autostop_filesize);
414             argv = sync_pipe_add_arg(argv, &argc, sautostop_filesize);
415         }
416     }
417
418     if (capture_opts->has_autostop_packets) {
419         argv = sync_pipe_add_arg(argv, &argc, "-c");
420         g_snprintf(scount, ARGV_NUMBER_LEN, "%d",capture_opts->autostop_packets);
421         argv = sync_pipe_add_arg(argv, &argc, scount);
422     }
423
424     if (capture_opts->has_autostop_duration) {
425         argv = sync_pipe_add_arg(argv, &argc, "-a");
426         g_snprintf(sautostop_duration, ARGV_NUMBER_LEN, "duration:%d",capture_opts->autostop_duration);
427         argv = sync_pipe_add_arg(argv, &argc, sautostop_duration);
428     }
429
430     for (j = 0; j < capture_opts->ifaces->len; j++) {
431         interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
432
433         argv = sync_pipe_add_arg(argv, &argc, "-i");
434         argv = sync_pipe_add_arg(argv, &argc, interface_opts.name);
435
436         if (interface_opts.cfilter != NULL && strlen(interface_opts.cfilter) != 0) {
437             argv = sync_pipe_add_arg(argv, &argc, "-f");
438             argv = sync_pipe_add_arg(argv, &argc, interface_opts.cfilter);
439         }
440         if (interface_opts.snaplen != WTAP_MAX_PACKET_SIZE) {
441             argv = sync_pipe_add_arg(argv, &argc, "-s");
442             g_snprintf(ssnap, ARGV_NUMBER_LEN, "%d", interface_opts.snaplen);
443             argv = sync_pipe_add_arg(argv, &argc, ssnap);
444         }
445
446         if (interface_opts.linktype != -1) {
447             argv = sync_pipe_add_arg(argv, &argc, "-y");
448             g_snprintf(sdlt, ARGV_NUMBER_LEN, "%s", linktype_val_to_name(interface_opts.linktype));
449             argv = sync_pipe_add_arg(argv, &argc, sdlt);
450         }
451
452         if (!interface_opts.promisc_mode) {
453             argv = sync_pipe_add_arg(argv, &argc, "-p");
454         }
455
456 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
457         if (interface_opts.buffer_size != 1) {
458             argv = sync_pipe_add_arg(argv, &argc, "-B");
459             g_snprintf(buffer_size, ARGV_NUMBER_LEN, "%d", interface_opts.buffer_size);
460             argv = sync_pipe_add_arg(argv, &argc, buffer_size);
461         }
462 #endif
463
464         if (interface_opts.monitor_mode) {
465             argv = sync_pipe_add_arg(argv, &argc, "-I");
466         }
467
468 #ifdef HAVE_PCAP_REMOTE
469         if (interface_opts.datatx_udp)
470             argv = sync_pipe_add_arg(argv, &argc, "-u");
471
472         if (!interface_opts.nocap_rpcap)
473             argv = sync_pipe_add_arg(argv, &argc, "-r");
474
475         if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
476             argv = sync_pipe_add_arg(argv, &argc, "-A");
477             g_snprintf(sauth, sizeof(sauth), "%s:%s",
478                        interface_opts.auth_username,
479                        interface_opts.auth_password);
480             argv = sync_pipe_add_arg(argv, &argc, sauth);
481         }
482 #endif
483
484 #ifdef HAVE_PCAP_SETSAMPLING
485         if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
486             argv = sync_pipe_add_arg(argv, &argc, "-m");
487             g_snprintf(ssampling, ARGV_NUMBER_LEN, "%s:%d",
488                        interface_opts.sampling_method == CAPTURE_SAMP_BY_COUNT ? "count" :
489                        interface_opts.sampling_method == CAPTURE_SAMP_BY_TIMER ? "timer" :
490                        "undef",
491                        interface_opts.sampling_param);
492             argv = sync_pipe_add_arg(argv, &argc, ssampling);
493         }
494 #endif
495     }
496
497     /* dumpcap should be running in capture child mode (hidden feature) */
498 #ifndef DEBUG_CHILD
499     argv = sync_pipe_add_arg(argv, &argc, "-Z");
500 #ifdef _WIN32
501     g_snprintf(control_id, ARGV_NUMBER_LEN, "%d", GetCurrentProcessId());
502     argv = sync_pipe_add_arg(argv, &argc, control_id);
503 #else
504     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
505 #endif
506 #endif
507
508     if (capture_opts->save_file) {
509         argv = sync_pipe_add_arg(argv, &argc, "-w");
510         argv = sync_pipe_add_arg(argv, &argc, capture_opts->save_file);
511     }
512     for (i = 0; i < argc; i++) {
513         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", i, argv[i]);
514     }
515
516 #ifdef _WIN32
517     /* init SECURITY_ATTRIBUTES */
518     sa.nLength = sizeof(SECURITY_ATTRIBUTES);
519     sa.bInheritHandle = TRUE;
520     sa.lpSecurityDescriptor = NULL;
521
522     /* Create a pipe for the child process */
523     /* (increase this value if you have trouble while fast capture file switches) */
524     if (! CreatePipe(&sync_pipe_read, &sync_pipe_write, &sa, 5120)) {
525         /* Couldn't create the pipe between parent and child. */
526         report_failure("Couldn't create sync pipe: %s",
527                        win32strerror(GetLastError()));
528         for (i = 0; i < argc; i++) {
529             g_free( (gpointer) argv[i]);
530         }
531         g_free( (gpointer) argv);
532         return FALSE;
533     }
534
535     /* Create the signal pipe */
536     signal_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, control_id);
537     signal_pipe = CreateNamedPipe(utf_8to16(signal_pipe_name),
538                                   PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 1, 65535, 65535, 0, NULL);
539     g_free(signal_pipe_name);
540
541     if (signal_pipe == INVALID_HANDLE_VALUE) {
542         /* Couldn't create the signal pipe between parent and child. */
543         report_failure("Couldn't create signal pipe: %s",
544                        win32strerror(GetLastError()));
545         for (i = 0; i < argc; i++) {
546             g_free( (gpointer) argv[i]);
547         }
548         g_free( (gpointer) argv);
549         return FALSE;
550     }
551
552     /* init STARTUPINFO */
553     memset(&si, 0, sizeof(si));
554     si.cb           = sizeof(si);
555 #ifdef DEBUG_CHILD
556     si.dwFlags = STARTF_USESHOWWINDOW;
557     si.wShowWindow  = SW_SHOW;
558 #else
559     si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
560     si.wShowWindow  = SW_HIDE;  /* this hides the console window */
561     si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
562     si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
563     si.hStdError = sync_pipe_write;
564     /*si.hStdError = (HANDLE) _get_osfhandle(2);*/
565 #endif
566
567     /* convert args array into a single string */
568     /* XXX - could change sync_pipe_add_arg() instead */
569     /* there is a drawback here: the length is internally limited to 1024 bytes */
570     for(i=0; argv[i] != 0; i++) {
571         if(i != 0) g_string_append_c(args, ' ');    /* don't prepend a space before the path!!! */
572         quoted_arg = protect_arg(argv[i]);
573         g_string_append(args, quoted_arg);
574         g_free(quoted_arg);
575     }
576
577     /* call dumpcap */
578     if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
579                       CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
580         report_failure("Couldn't run %s in child process: %s",
581                        args->str, win32strerror(GetLastError()));
582         CloseHandle(sync_pipe_read);
583         CloseHandle(sync_pipe_write);
584         for (i = 0; i < argc; i++) {
585             g_free( (gpointer) argv[i]);
586         }
587         g_free( (gpointer) argv);
588         return FALSE;
589     }
590     capture_opts->fork_child = (int) pi.hProcess;
591     g_string_free(args, TRUE);
592
593     /* associate the operating system filehandle to a C run-time file handle */
594     /* (good file handle infos at: http://www.flounder.com/handles.htm) */
595     sync_pipe_read_fd = _open_osfhandle( (long) sync_pipe_read, _O_BINARY);
596
597     /* associate the operating system filehandle to a C run-time file handle */
598     capture_opts->signal_pipe_write_fd = _open_osfhandle( (long) signal_pipe, _O_BINARY);
599
600 #else /* _WIN32 */
601     if (pipe(sync_pipe) < 0) {
602         /* Couldn't create the pipe between parent and child. */
603         report_failure("Couldn't create sync pipe: %s", g_strerror(errno));
604         for (i = 0; i < argc; i++) {
605             g_free( (gpointer) argv[i]);
606         }
607         g_free(argv);
608         return FALSE;
609     }
610
611     if ((capture_opts->fork_child = fork()) == 0) {
612         /*
613          * Child process - run dumpcap with the right arguments to make
614          * it just capture with the specified capture parameters
615          */
616         dup2(sync_pipe[PIPE_WRITE], 2);
617         ws_close(sync_pipe[PIPE_READ]);
618         execv(argv[0], (gpointer)argv);
619         g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
620                    argv[0], g_strerror(errno));
621         sync_pipe_errmsg_to_parent(2, errmsg, "");
622
623         /* Exit with "_exit()", so that we don't close the connection
624            to the X server (and cause stuff buffered up by our parent but
625            not yet sent to be sent, as that stuff should only be sent by
626            our parent).  We've sent an error message to the parent, so
627            we exit with an exit status of 1 (any exit status other than
628            0 or 1 will cause an additional message to report that exit
629            status, over and above the error message we sent to the parent). */
630         _exit(1);
631     }
632
633     sync_pipe_read_fd = sync_pipe[PIPE_READ];
634 #endif
635
636     for (i = 0; i < argc; i++) {
637         g_free( (gpointer) argv[i]);
638     }
639
640     /* Parent process - read messages from the child process over the
641        sync pipe. */
642     g_free( (gpointer) argv);   /* free up arg array */
643
644     /* Close the write side of the pipe, so that only the child has it
645        open, and thus it completely closes, and thus returns to us
646        an EOF indication, if the child closes it (either deliberately
647        or by exiting abnormally). */
648 #ifdef _WIN32
649     CloseHandle(sync_pipe_write);
650 #else
651     ws_close(sync_pipe[PIPE_WRITE]);
652 #endif
653
654     if (capture_opts->fork_child == -1) {
655         /* We couldn't even create the child process. */
656         report_failure("Couldn't create child process: %s", g_strerror(errno));
657         ws_close(sync_pipe_read_fd);
658 #ifdef _WIN32
659         ws_close(capture_opts->signal_pipe_write_fd);
660 #endif
661         return FALSE;
662     }
663
664     capture_opts->fork_child_status = 0;
665
666     /* we might wait for a moment till child is ready, so update screen now */
667     main_window_update();
668
669     /* We were able to set up to read the capture file;
670        arrange that our callback be called whenever it's possible
671        to read from the sync pipe, so that it's called when
672        the child process wants to tell us something. */
673
674     /* we have a running capture, now wait for the real capture filename */
675     pipe_input_set_handler(sync_pipe_read_fd, (gpointer) capture_opts,
676                            &capture_opts->fork_child, sync_pipe_input_cb);
677
678     return TRUE;
679 }
680
681 /*
682  * Open two pipes to dumpcap with the supplied arguments, one for its
683  * standard output and one for its standard error.
684  *
685  * On success, *msg is unchanged and 0 is returned; data_read_fd,
686  * messsage_read_fd, and fork_child point to the standard output pipe's
687  * file descriptor, the standard error pipe's file descriptor, and
688  * the child's PID/handle, respectively.
689  *
690  * On failure, *msg points to an error message for the failure, and -1 is
691  * returned, in which case *msg must be freed with g_free().
692  */
693 /* XXX - This duplicates a lot of code in sync_pipe_start() */
694 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
695 #define PIPE_BUF_SIZE 5120
696 static int
697 sync_pipe_open_command(const char** argv, int *data_read_fd,
698                        int *message_read_fd, int *fork_child, gchar **msg)
699 {
700     enum PIPES { PIPE_READ, PIPE_WRITE };   /* Constants 0 and 1 for PIPE_READ and PIPE_WRITE */
701 #ifdef _WIN32
702     HANDLE sync_pipe[2];                    /* pipe used to send messages from child to parent */
703     HANDLE data_pipe[2];                    /* pipe used to send data from child to parent */
704     GString *args = g_string_sized_new(200);
705     gchar *quoted_arg;
706     SECURITY_ATTRIBUTES sa;
707     STARTUPINFO si;
708     PROCESS_INFORMATION pi;
709 #else
710     char errmsg[1024+1];
711     int sync_pipe[2];                       /* pipe used to send messages from child to parent */
712     int data_pipe[2];                       /* pipe used to send data from child to parent */
713 #endif
714     int i;
715     *fork_child = -1;
716     *data_read_fd = -1;
717     *message_read_fd = -1;
718     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_open_command");
719
720     if (!msg) {
721         /* We can't return anything */
722 #ifdef _WIN32
723         g_string_free(args, TRUE);
724 #endif
725         return -1;
726     }
727
728 #ifdef _WIN32
729     /* init SECURITY_ATTRIBUTES */
730     sa.nLength = sizeof(SECURITY_ATTRIBUTES);
731     sa.bInheritHandle = TRUE;
732     sa.lpSecurityDescriptor = NULL;
733
734     /* Create a pipe for the child process to send us messages */
735     /* (increase this value if you have trouble while fast capture file switches) */
736     if (! CreatePipe(&sync_pipe[PIPE_READ], &sync_pipe[PIPE_WRITE], &sa, 5120)) {
737         /* Couldn't create the message pipe between parent and child. */
738         *msg = g_strdup_printf("Couldn't create sync pipe: %s",
739                                win32strerror(GetLastError()));
740         for (i = 0; argv[i] != NULL; i++) {
741             g_free( (gpointer) argv[i]);
742         }
743         g_free( (gpointer) argv);
744         return -1;
745     }
746
747     /* Create a pipe for the child process to send us data */
748     /* (increase this value if you have trouble while fast capture file switches) */
749     if (! CreatePipe(&data_pipe[PIPE_READ], &data_pipe[PIPE_WRITE], &sa, 5120)) {
750         /* Couldn't create the message pipe between parent and child. */
751         *msg = g_strdup_printf("Couldn't create data pipe: %s",
752                                win32strerror(GetLastError()));
753         CloseHandle(sync_pipe[PIPE_READ]);
754         CloseHandle(sync_pipe[PIPE_WRITE]);
755         for (i = 0; argv[i] != NULL; i++) {
756             g_free( (gpointer) argv[i]);
757         }
758         g_free( (gpointer) argv);
759         return -1;
760     }
761
762     /* init STARTUPINFO */
763     memset(&si, 0, sizeof(si));
764     si.cb           = sizeof(si);
765 #ifdef DEBUG_CHILD
766     si.dwFlags = STARTF_USESHOWWINDOW;
767     si.wShowWindow  = SW_SHOW;
768 #else
769     si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
770     si.wShowWindow  = SW_HIDE;  /* this hides the console window */
771     si.hStdInput = NULL;
772     si.hStdOutput = data_pipe[PIPE_WRITE];
773     si.hStdError = sync_pipe[PIPE_WRITE];
774 #endif
775
776     /* convert args array into a single string */
777     /* XXX - could change sync_pipe_add_arg() instead */
778     /* there is a drawback here: the length is internally limited to 1024 bytes */
779     for(i=0; argv[i] != 0; i++) {
780         if(i != 0) g_string_append_c(args, ' ');    /* don't prepend a space before the path!!! */
781         quoted_arg = protect_arg(argv[i]);
782         g_string_append(args, quoted_arg);
783         g_free(quoted_arg);
784     }
785
786     /* call dumpcap */
787     if(!CreateProcess(NULL, utf_8to16(args->str), NULL, NULL, TRUE,
788                       CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
789         *msg = g_strdup_printf("Couldn't run %s in child process: %s",
790                                args->str, win32strerror(GetLastError()));
791         CloseHandle(data_pipe[PIPE_READ]);
792         CloseHandle(data_pipe[PIPE_WRITE]);
793         CloseHandle(sync_pipe[PIPE_READ]);
794         CloseHandle(sync_pipe[PIPE_WRITE]);
795         for (i = 0; argv[i] != NULL; i++) {
796             g_free( (gpointer) argv[i]);
797         }
798         g_free( (gpointer) argv);
799         return -1;
800     }
801     *fork_child = (int) pi.hProcess;
802     g_string_free(args, TRUE);
803
804     /* associate the operating system filehandles to C run-time file handles */
805     /* (good file handle infos at: http://www.flounder.com/handles.htm) */
806     *data_read_fd = _open_osfhandle( (long) data_pipe[PIPE_READ], _O_BINARY);
807     *message_read_fd = _open_osfhandle( (long) sync_pipe[PIPE_READ], _O_BINARY);
808 #else /* _WIN32 */
809     /* Create a pipe for the child process to send us messages */
810     if (pipe(sync_pipe) < 0) {
811         /* Couldn't create the message pipe between parent and child. */
812         *msg = g_strdup_printf("Couldn't create sync pipe: %s", g_strerror(errno));
813         for (i = 0; argv[i] != NULL; i++) {
814             g_free( (gpointer) argv[i]);
815         }
816         g_free(argv);
817         return -1;
818     }
819
820     /* Create a pipe for the child process to send us data */
821     if (pipe(data_pipe) < 0) {
822         /* Couldn't create the data pipe between parent and child. */
823         *msg = g_strdup_printf("Couldn't create data pipe: %s", g_strerror(errno));
824         ws_close(sync_pipe[PIPE_READ]);
825         ws_close(sync_pipe[PIPE_WRITE]);
826         for (i = 0; argv[i] != NULL; i++) {
827             g_free( (gpointer) argv[i]);
828         }
829         g_free(argv);
830         return -1;
831     }
832
833     if ((*fork_child = fork()) == 0) {
834         /*
835          * Child process - run dumpcap with the right arguments to make
836          * it just capture with the specified capture parameters
837          */
838         dup2(data_pipe[PIPE_WRITE], 1);
839         ws_close(data_pipe[PIPE_READ]);
840         ws_close(data_pipe[PIPE_WRITE]);
841         dup2(sync_pipe[PIPE_WRITE], 2);
842         ws_close(sync_pipe[PIPE_READ]);
843         ws_close(sync_pipe[PIPE_WRITE]);
844         execv(argv[0], (gpointer)argv);
845         g_snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
846                    argv[0], g_strerror(errno));
847         sync_pipe_errmsg_to_parent(2, errmsg, "");
848
849         /* Exit with "_exit()", so that we don't close the connection
850            to the X server (and cause stuff buffered up by our parent but
851            not yet sent to be sent, as that stuff should only be sent by
852            our parent).  We've sent an error message to the parent, so
853            we exit with an exit status of 1 (any exit status other than
854            0 or 1 will cause an additional message to report that exit
855            status, over and above the error message we sent to the parent). */
856         _exit(1);
857     }
858
859     *data_read_fd = data_pipe[PIPE_READ];
860     *message_read_fd = sync_pipe[PIPE_READ];
861 #endif
862
863     for (i = 0; argv[i] != NULL; i++) {
864         g_free( (gpointer) argv[i]);
865     }
866
867     /* Parent process - read messages from the child process over the
868        sync pipe. */
869     g_free( (gpointer) argv);   /* free up arg array */
870
871     /* Close the write sides of the pipes, so that only the child has them
872        open, and thus they completely close, and thus return to us
873        an EOF indication, if the child closes them (either deliberately
874        or by exiting abnormally). */
875 #ifdef _WIN32
876     CloseHandle(data_pipe[PIPE_WRITE]);
877     CloseHandle(sync_pipe[PIPE_WRITE]);
878 #else
879     ws_close(data_pipe[PIPE_WRITE]);
880     ws_close(sync_pipe[PIPE_WRITE]);
881 #endif
882
883     if (*fork_child == -1) {
884         /* We couldn't even create the child process. */
885         *msg = g_strdup_printf("Couldn't create child process: %s", g_strerror(errno));
886         ws_close(*data_read_fd);
887         ws_close(*message_read_fd);
888         return -1;
889     }
890
891     /* we might wait for a moment till child is ready, so update screen now */
892     main_window_update();
893     return 0;
894 }
895
896 /*
897  * Close the pipes we're using to read from dumpcap, and wait for it
898  * to exit.  On success, *msgp is unchanged, and the exit status of
899  * dumpcap is returned.  On failure (which includes "dumpcap exited
900  * due to being killed by a signal or an exception"), *msgp points
901  * to an error message for the failure, and -1 is returned.  In the
902  * latter case, *msgp must be freed with g_free().
903  */
904 static int
905 sync_pipe_close_command(int *data_read_fd, int *message_read_fd,
906                         int *fork_child, gchar **msgp)
907 {
908     ws_close(*data_read_fd);
909     if (message_read_fd != NULL)
910         ws_close(*message_read_fd);
911
912 #ifdef _WIN32
913     /* XXX - Should we signal the child somehow? */
914     sync_pipe_kill(*fork_child);
915 #endif
916
917     return sync_pipe_wait_for_child(*fork_child, msgp);
918 }
919
920 /*
921  * Run dumpcap with the supplied arguments.
922  *
923  * On success, *data points to a buffer containing the dumpcap output,
924  * *primary_msg and *secondary_message are NULL, and 0 is returned; *data
925  * must be freed with g_free().
926  *
927  * On failure, *data is NULL, *primary_msg points to an error message,
928  * *secondary_msg either points to an additional error message or is
929  * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
930  * must be freed with g_free().
931  */
932 /* XXX - This duplicates a lot of code in sync_pipe_start() */
933 /* XXX - assumes PIPE_BUF_SIZE > SP_MAX_MSG_LEN */
934 #define PIPE_BUF_SIZE 5120
935 static int
936 sync_pipe_run_command(const char** argv, gchar **data, gchar **primary_msg,
937                       gchar **secondary_msg)
938 {
939     gchar *msg;
940     int data_pipe_read_fd, sync_pipe_read_fd, fork_child, ret;
941     char *wait_msg;
942     gchar buffer[PIPE_BUF_SIZE+1];
943     int  nread;
944     char indicator;
945     int  primary_msg_len;
946     char *primary_msg_text;
947     int  secondary_msg_len;
948     char *secondary_msg_text;
949     char *combined_msg;
950     GString *data_buf = NULL;
951     int count;
952
953     ret = sync_pipe_open_command(argv, &data_pipe_read_fd, &sync_pipe_read_fd,
954                                  &fork_child, &msg);
955     if (ret == -1) {
956         *primary_msg = msg;
957         *secondary_msg = NULL;
958         *data = NULL;
959         return -1;
960     }
961
962     /*
963      * We were able to set up to read dumpcap's output.  Do so.
964      *
965      * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
966      */
967     nread = pipe_read_block(sync_pipe_read_fd, &indicator, SP_MAX_MSG_LEN,
968                             buffer, primary_msg);
969     if(nread <= 0) {
970         /* We got a read error from the sync pipe, or we got no data at
971            all from the sync pipe, so we're not going to be getting any
972            data or error message from the child process.  Pick up its
973            exit status, and complain.
974
975            We don't have to worry about killing the child, if the sync pipe
976            returned an error. Usually this error is caused as the child killed
977            itself while going down. Even in the rare cases that this isn't the
978            case, the child will get an error when writing to the broken pipe
979            the next time, cleaning itself up then. */
980         ret = sync_pipe_wait_for_child(fork_child, &wait_msg);
981         if(nread == 0) {
982             /* We got an EOF from the sync pipe.  That means that it exited
983                before giving us any data to read.  If ret is -1, we report
984                that as a bad exit (e.g., exiting due to a signal); otherwise,
985                we report it as a premature exit. */
986             if (ret == -1)
987                 *primary_msg = wait_msg;
988             else
989                 *primary_msg = g_strdup("Child dumpcap closed sync pipe prematurely");
990         } else {
991             /* We got an error from the sync pipe.  If ret is -1, report
992                both the sync pipe I/O error and the wait error. */
993             if (ret == -1) {
994                 combined_msg = g_strdup_printf("%s\n\n%s", *primary_msg, wait_msg);
995                 g_free(*primary_msg);
996                 g_free(wait_msg);
997                 *primary_msg = combined_msg;
998             }
999         }
1000         *secondary_msg = NULL;
1001
1002         return -1;
1003     }
1004
1005     /* we got a valid message block from the child, process it */
1006     switch(indicator) {
1007
1008     case SP_ERROR_MSG:
1009         /*
1010          * Error from dumpcap; there will be a primary message and a
1011          * secondary message.
1012          */
1013
1014         /* convert primary message */
1015         pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1016         primary_msg_text = buffer+4;
1017         /* convert secondary message */
1018         pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1019                             &secondary_msg_len);
1020         secondary_msg_text = primary_msg_text + primary_msg_len + 4;
1021         /* the capture child will close the sync_pipe, nothing to do */
1022
1023         /*
1024          * Pick up the child status.
1025          */
1026         ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1027                                       &fork_child, &msg);
1028         if (ret == -1) {
1029             /*
1030              * Child process failed unexpectedly, or wait failed; msg is the
1031              * error message.
1032              */
1033             *primary_msg = msg;
1034             *secondary_msg = NULL;
1035         } else {
1036             /*
1037              * Child process failed, but returned the expected exit status.
1038              * Return the messages it gave us, and indicate failure.
1039              */
1040             *primary_msg = g_strdup(primary_msg_text);
1041             *secondary_msg = g_strdup(secondary_msg_text);
1042             ret = -1;
1043         }
1044         *data = NULL;
1045         break;
1046
1047     case SP_SUCCESS:
1048         /* read the output from the command */
1049         data_buf = g_string_new("");
1050         while ((count = ws_read(data_pipe_read_fd, buffer, PIPE_BUF_SIZE)) > 0) {
1051             buffer[count] = '\0';
1052             g_string_append(data_buf, buffer);
1053         }
1054
1055         /*
1056          * Pick up the child status.
1057          */
1058         ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1059                                       &fork_child, &msg);
1060         if (ret == -1) {
1061             /*
1062              * Child process failed unexpectedly, or wait failed; msg is the
1063              * error message.
1064              */
1065             *primary_msg = msg;
1066             *secondary_msg = NULL;
1067             g_string_free(data_buf, TRUE);
1068             *data = NULL;
1069         } else {
1070             /*
1071              * Child process succeeded.
1072              */
1073             *primary_msg = NULL;
1074             *secondary_msg = NULL;
1075             *data = data_buf->str;
1076             g_string_free(data_buf, FALSE);
1077         }
1078         break;
1079
1080     default:
1081         /*
1082          * Pick up the child status.
1083          */
1084         ret = sync_pipe_close_command(&data_pipe_read_fd, &sync_pipe_read_fd,
1085                                       &fork_child, &msg);
1086         if (ret == -1) {
1087             /*
1088              * Child process failed unexpectedly, or wait failed; msg is the
1089              * error message.
1090              */
1091             *primary_msg = msg;
1092             *secondary_msg = NULL;
1093         } else {
1094             /*
1095              * Child process returned an unknown status.
1096              */
1097             *primary_msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1098                                            indicator);
1099             *secondary_msg = NULL;
1100             ret = -1;
1101         }
1102         *data = NULL;
1103         break;
1104     }
1105     return ret;
1106 }
1107
1108 /*
1109  * Get the list of interfaces using dumpcap.
1110  *
1111  * On success, *data points to a buffer containing the dumpcap output,
1112  * *primary_msg and *secondary_msg are NULL, and 0 is returned.  *data
1113  * must be freed with g_free().
1114  *
1115  * On failure, *data is NULL, *primary_msg points to an error message,
1116  * *secondary_msg either points to an additional error message or is
1117  * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1118  * must be freed with g_free().
1119  */
1120 int
1121 sync_interface_list_open(gchar **data, gchar **primary_msg,
1122                          gchar **secondary_msg)
1123 {
1124     int argc;
1125     const char **argv;
1126
1127     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_list_open");
1128
1129     argv = init_pipe_args(&argc);
1130
1131     if (!argv) {
1132         *primary_msg = g_strdup("We don't know where to find dumpcap.");
1133         *secondary_msg = NULL;
1134         *data = NULL;
1135         return -1;
1136     }
1137
1138     /* Ask for the interface list */
1139     argv = sync_pipe_add_arg(argv, &argc, "-D");
1140
1141 #ifndef DEBUG_CHILD
1142     /* Run dumpcap in capture child mode */
1143     argv = sync_pipe_add_arg(argv, &argc, "-Z");
1144     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1145 #endif
1146     return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1147 }
1148
1149 /*
1150  * Get the capabilities of an interface using dumpcap.
1151  *
1152  * On success, *data points to a buffer containing the dumpcap output,
1153  * *primary_msg and *secondary_msg are NULL, and 0 is returned.  *data
1154  * must be freed with g_free().
1155  *
1156  * On failure, *data is NULL, *primary_msg points to an error message,
1157  * *secondary_msg either points to an additional error message or is
1158  * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1159  * must be freed with g_free().
1160  */
1161 int
1162 sync_if_capabilities_open(const gchar *ifname, gboolean monitor_mode,
1163                           gchar **data, gchar **primary_msg,
1164                           gchar **secondary_msg)
1165 {
1166     int argc;
1167     const char **argv;
1168
1169     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_linktype_list_open");
1170
1171     argv = init_pipe_args(&argc);
1172
1173     if (!argv) {
1174         *primary_msg = g_strdup("We don't know where to find dumpcap.");
1175         *secondary_msg = NULL;
1176         *data = NULL;
1177         return -1;
1178     }
1179
1180     /* Ask for the interface capabilities */
1181     argv = sync_pipe_add_arg(argv, &argc, "-i");
1182     argv = sync_pipe_add_arg(argv, &argc, ifname);
1183     argv = sync_pipe_add_arg(argv, &argc, "-L");
1184     if (monitor_mode)
1185         argv = sync_pipe_add_arg(argv, &argc, "-I");
1186
1187 #ifndef DEBUG_CHILD
1188     /* Run dumpcap in capture child mode */
1189     argv = sync_pipe_add_arg(argv, &argc, "-Z");
1190     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1191 #endif
1192     return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1193 }
1194
1195 /*
1196  * Start getting interface statistics using dumpcap.  On success, read_fd
1197  * contains the file descriptor for the pipe's stdout, *msg is unchanged,
1198  * and zero is returned.  On failure, *msg will point to an error message
1199  * that must be g_free()d, and -1 will be returned.
1200  */
1201 int
1202 sync_interface_stats_open(int *data_read_fd, int *fork_child, gchar **msg)
1203 {
1204     int argc;
1205     const char **argv;
1206     int message_read_fd, ret;
1207     char *wait_msg;
1208     gchar buffer[PIPE_BUF_SIZE+1];
1209     int  nread;
1210     char indicator;
1211     int  primary_msg_len;
1212     char *primary_msg_text;
1213     int  secondary_msg_len;
1214     /*char *secondary_msg_text;*/
1215     char *combined_msg;
1216
1217     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_stats_open");
1218
1219     argv = init_pipe_args(&argc);
1220
1221     if (!argv) {
1222         *msg = g_strdup("We don't know where to find dumpcap.");
1223         return -1;
1224     }
1225
1226     /* Ask for the interface statistics */
1227     argv = sync_pipe_add_arg(argv, &argc, "-S");
1228
1229 #ifndef DEBUG_CHILD
1230     argv = sync_pipe_add_arg(argv, &argc, "-Z");
1231     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1232 #endif
1233     ret = sync_pipe_open_command(argv, data_read_fd, &message_read_fd,
1234                                  fork_child, msg);
1235     if (ret == -1)
1236         return -1;
1237
1238     /*
1239      * We were able to set up to read dumpcap's output.  Do so.
1240      *
1241      * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1242      */
1243     nread = pipe_read_block(message_read_fd, &indicator, SP_MAX_MSG_LEN,
1244                             buffer, msg);
1245     if(nread <= 0) {
1246         /* We got a read error from the sync pipe, or we got no data at
1247            all from the sync pipe, so we're not going to be getting any
1248            data or error message from the child process.  Pick up its
1249            exit status, and complain.
1250
1251            We don't have to worry about killing the child, if the sync pipe
1252            returned an error. Usually this error is caused as the child killed
1253            itself while going down. Even in the rare cases that this isn't the
1254            case, the child will get an error when writing to the broken pipe
1255            the next time, cleaning itself up then. */
1256         ret = sync_pipe_wait_for_child(*fork_child, &wait_msg);
1257         if(nread == 0) {
1258             /* We got an EOF from the sync pipe.  That means that it exited
1259                before giving us any data to read.  If ret is -1, we report
1260                that as a bad exit (e.g., exiting due to a signal); otherwise,
1261                we report it as a premature exit. */
1262             if (ret == -1)
1263                 *msg = wait_msg;
1264             else
1265                 *msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1266         } else {
1267             /* We got an error from the sync pipe.  If ret is -1, report
1268                both the sync pipe I/O error and the wait error. */
1269             if (ret == -1) {
1270                 combined_msg = g_strdup_printf("%s\n\n%s", *msg, wait_msg);
1271                 g_free(*msg);
1272                 g_free(wait_msg);
1273                 *msg = combined_msg;
1274             }
1275         }
1276
1277         return -1;
1278     }
1279
1280     /* we got a valid message block from the child, process it */
1281     switch(indicator) {
1282
1283     case SP_ERROR_MSG:
1284         /*
1285          * Error from dumpcap; there will be a primary message and a
1286          * secondary message.
1287          */
1288
1289         /* convert primary message */
1290         pipe_convert_header(buffer, 4, &indicator, &primary_msg_len);
1291         primary_msg_text = buffer+4;
1292         /* convert secondary message */
1293         pipe_convert_header(primary_msg_text + primary_msg_len, 4, &indicator,
1294                             &secondary_msg_len);
1295         /*secondary_msg_text = primary_msg_text + primary_msg_len + 4;*/
1296         /* the capture child will close the sync_pipe, nothing to do */
1297
1298         /*
1299          * Pick up the child status.
1300          */
1301         ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1302                                       fork_child, msg);
1303         if (ret == -1) {
1304             /*
1305              * Child process failed unexpectedly, or wait failed; msg is the
1306              * error message.
1307              */
1308         } else {
1309             /*
1310              * Child process failed, but returned the expected exit status.
1311              * Return the messages it gave us, and indicate failure.
1312              */
1313             *msg = g_strdup(primary_msg_text);
1314             ret = -1;
1315         }
1316         break;
1317
1318     case SP_SUCCESS:
1319         /* Close the message pipe. */
1320         ws_close(message_read_fd);
1321         break;
1322
1323     default:
1324         /*
1325          * Pick up the child status.
1326          */
1327         ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1328                                       fork_child, msg);
1329         if (ret == -1) {
1330             /*
1331              * Child process failed unexpectedly, or wait failed; msg is the
1332              * error message.
1333              */
1334         } else {
1335             /*
1336              * Child process returned an unknown status.
1337              */
1338             *msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1339                                    indicator);
1340             ret = -1;
1341         }
1342         break;
1343     }
1344     return ret;
1345 }
1346
1347 /* Close down the stats process */
1348 int
1349 sync_interface_stats_close(int *read_fd, int *fork_child, gchar **msg)
1350 {
1351     return sync_pipe_close_command(read_fd, NULL, fork_child, msg);
1352 }
1353
1354 /* read a number of bytes from a pipe */
1355 /* (blocks until enough bytes read or an error occurs) */
1356 static int
1357 pipe_read_bytes(int pipe_fd, char *bytes, int required, char **msg)
1358 {
1359     int newly;
1360     int offset = 0;
1361     int error;
1362
1363     while(required) {
1364         newly = read(pipe_fd, &bytes[offset], required);
1365         if (newly == 0) {
1366             /* EOF */
1367             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1368                   "read from pipe %d: EOF (capture closed?)", pipe_fd);
1369             *msg = 0;
1370             return offset;
1371         }
1372         if (newly < 0) {
1373             /* error */
1374             error = errno;
1375             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1376                   "read from pipe %d: error(%u): %s", pipe_fd, error,
1377                   g_strerror(error));
1378             *msg = g_strdup_printf("Error reading from sync pipe: %s",
1379                                    g_strerror(error));
1380             return newly;
1381         }
1382
1383         required -= newly;
1384         offset += newly;
1385     }
1386
1387     *msg = NULL;
1388     return offset;
1389 }
1390
1391 static gboolean pipe_data_available(int pipe_fd) {
1392 #ifdef _WIN32 /* PeekNamedPipe */
1393     HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
1394     DWORD bytes_avail;
1395
1396     if (hPipe == INVALID_HANDLE_VALUE)
1397         return FALSE;
1398
1399     if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
1400         return FALSE;
1401
1402     if (bytes_avail > 0)
1403         return TRUE;
1404     return FALSE;
1405 #else /* select */
1406     fd_set rfds;
1407     struct timeval timeout;
1408
1409     FD_ZERO(&rfds);
1410     FD_SET(pipe_fd, &rfds);
1411     timeout.tv_sec = 0;
1412     timeout.tv_usec = 0;
1413
1414     if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
1415         return TRUE;
1416
1417     return FALSE;
1418 #endif
1419 }
1420
1421 /* Read a line from a pipe, similar to fgets */
1422 int
1423 sync_pipe_gets_nonblock(int pipe_fd, char *bytes, int max) {
1424     int newly;
1425     int offset = -1;
1426
1427     while(offset < max - 1) {
1428         offset++;
1429         if (! pipe_data_available(pipe_fd))
1430             break;
1431         newly = read(pipe_fd, &bytes[offset], 1);
1432         if (newly == 0) {
1433             /* EOF - not necessarily an error */
1434             break;
1435         } else if (newly < 0) {
1436             /* error */
1437             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1438                   "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1439             return newly;
1440         } else if (bytes[offset] == '\n') {
1441             break;
1442         }
1443     }
1444
1445     if (offset >= 0)
1446         bytes[offset] = '\0';
1447
1448     return offset;
1449 }
1450
1451
1452 /* convert header values (indicator and 3-byte length) */
1453 static void
1454 pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len) {
1455
1456     g_assert(header_len == 4);
1457
1458     /* convert header values */
1459     *indicator = header[0];
1460     *block_len = header[1]<<16 | header[2]<<8 | header[3];
1461 }
1462
1463 /* read a message from the sending pipe in the standard format
1464    (1-byte message indicator, 3-byte message length (excluding length
1465    and indicator field), and the rest is the message) */
1466 static int
1467 pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
1468                 char **err_msg)
1469 {
1470     int required;
1471     int newly;
1472     guchar header[4];
1473
1474     /* read header (indicator and 3-byte length) */
1475     newly = pipe_read_bytes(pipe_fd, header, 4, err_msg);
1476     if(newly != 4) {
1477         if (newly == 0) {
1478             /*
1479              * Immediate EOF; if the capture child exits normally, this
1480              * is an "I'm done" indication, so don't report it as an
1481              * error.
1482              */
1483             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1484                   "read %d got an EOF", pipe_fd);
1485             return 0;
1486         }
1487         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1488               "read %d failed to read header: %u", pipe_fd, newly);
1489         if (newly != -1) {
1490             /*
1491              * Short read, but not an immediate EOF.
1492              */
1493             *err_msg = g_strdup_printf("Premature EOF reading from sync pipe: got only %d bytes",
1494                                        newly);
1495         }
1496         return -1;
1497     }
1498
1499     /* convert header values */
1500     pipe_convert_header(header, 4, indicator, &required);
1501
1502     /* only indicator with no value? */
1503     if(required == 0) {
1504         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1505               "read %d indicator: %c empty value", pipe_fd, *indicator);
1506         return 4;
1507     }
1508
1509     /* does the data fit into the given buffer? */
1510     if(required > len) {
1511         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1512               "read %d length error, required %d > len %d, indicator: %u",
1513               pipe_fd, required, len, *indicator);
1514
1515         /* we have a problem here, try to read some more bytes from the pipe to debug where the problem really is */
1516         memcpy(msg, header, sizeof(header));
1517         newly = read(pipe_fd, &msg[sizeof(header)], len-sizeof(header));
1518         *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1519                                    msg);
1520         return -1;
1521     }
1522     len = required;
1523
1524     /* read the actual block data */
1525     newly = pipe_read_bytes(pipe_fd, msg, required, err_msg);
1526     if(newly != required) {
1527         if (newly != -1) {
1528             *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1529                                        msg);
1530         }
1531         return -1;
1532     }
1533
1534     /* XXX If message is "2part", the msg probably won't be sent to debug log correctly */
1535     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1536           "read %d ok indicator: %c len: %u msg: %s", pipe_fd, *indicator,
1537           len, msg);
1538     *err_msg = NULL;
1539     return newly + 4;
1540 }
1541
1542
1543 /* There's stuff to read from the sync pipe, meaning the child has sent
1544    us a message, or the sync pipe has closed, meaning the child has
1545    closed it (perhaps because it exited). */
1546 static gboolean
1547 sync_pipe_input_cb(gint source, gpointer user_data)
1548 {
1549     capture_options *capture_opts = (capture_options *)user_data;
1550     int  ret;
1551     char buffer[SP_MAX_MSG_LEN+1];
1552     int  nread;
1553     char indicator;
1554     int  primary_len;
1555     char *primary_msg;
1556     int  secondary_len;
1557     char *secondary_msg;
1558     char *wait_msg, *combined_msg;
1559
1560     nread = pipe_read_block(source, &indicator, SP_MAX_MSG_LEN, buffer,
1561                             &primary_msg);
1562     if(nread <= 0) {
1563         /* We got a read error, or a bad message, or an EOF, from the sync pipe.
1564
1565            If we got a read error or a bad message, nread is -1 and
1566            primary_msg is set to point to an error message.  We don't
1567            have to worry about killing the child; usually this error
1568            is caused as the child killed  itself while going down.
1569            Even in the rare cases that this isn't the case, the child
1570            will get an error when writing to the broken pipe the next time,
1571            cleaning itself up then.
1572
1573            If we got an EOF, nread is 0 and primary_msg isn't set.  This
1574            is an indication that the capture is finished. */
1575         ret = sync_pipe_wait_for_child(capture_opts->fork_child, &wait_msg);
1576         if(nread == 0) {
1577             /* We got an EOF from the sync pipe.  That means that the capture
1578                child exited, and not in the middle of a message; we treat
1579                that as an indication that it's done, and only report an
1580                error if ret is -1, in which case wait_msg is the error
1581                message. */
1582             if (ret == -1)
1583                 primary_msg = wait_msg;
1584         } else {
1585             /* We got an error from the sync pipe.  If ret is -1, report
1586                both the sync pipe I/O error and the wait error. */
1587             if (ret == -1) {
1588                 combined_msg = g_strdup_printf("%s\n\n%s", primary_msg, wait_msg);
1589                 g_free(primary_msg);
1590                 g_free(wait_msg);
1591                 primary_msg = combined_msg;
1592             }
1593         }
1594
1595         /* No more child process. */
1596         capture_opts->fork_child = -1;
1597         capture_opts->fork_child_status = ret;
1598
1599 #ifdef _WIN32
1600         ws_close(capture_opts->signal_pipe_write_fd);
1601 #endif
1602         capture_input_closed(capture_opts, primary_msg);
1603         g_free(primary_msg);
1604         return FALSE;
1605     }
1606
1607     /* we got a valid message block from the child, process it */
1608     switch(indicator) {
1609     case SP_FILE:
1610         if(!capture_input_new_file(capture_opts, buffer)) {
1611             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: file failed, closing capture");
1612
1613             /* We weren't able to open the new capture file; user has been
1614                alerted. Close the sync pipe. */
1615             ws_close(source);
1616
1617             /* The child has sent us a filename which we couldn't open.
1618
1619                This could mean that the child is creating files faster
1620                than we can handle it.  (XXX - why would that result in
1621                a failure to open the file?)
1622
1623                That should only be the case for very fast file switches;
1624                We can't do much more than telling the child to stop.
1625                (This is the "emergency brake" if the user e.g. wants to
1626                switch files every second).
1627
1628                This can also happen if the user specified "-", meaning
1629                "standard output", as the capture file. */
1630             sync_pipe_stop(capture_opts);
1631             capture_input_closed(capture_opts, NULL);
1632             return FALSE;
1633         }
1634         break;
1635     case SP_PACKET_COUNT:
1636         nread = atoi(buffer);
1637         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: new packets %u", nread);
1638         capture_input_new_packets(capture_opts, nread);
1639         break;
1640     case SP_ERROR_MSG:
1641         /* convert primary message */
1642         pipe_convert_header(buffer, 4, &indicator, &primary_len);
1643         primary_msg = buffer+4;
1644         /* convert secondary message */
1645         pipe_convert_header(primary_msg + primary_len, 4, &indicator, &secondary_len);
1646         secondary_msg = primary_msg + primary_len + 4;
1647         /* message output */
1648         capture_input_error_message(capture_opts, primary_msg, secondary_msg);
1649         /* the capture child will close the sync_pipe, nothing to do for now */
1650         /* (an error message doesn't mean we have to stop capturing) */
1651         break;
1652     case SP_BAD_FILTER: {
1653         char *ch;
1654         int index;
1655
1656         ch = strtok(buffer, ":");
1657         index = (int)strtol(ch, NULL, 10);
1658         ch = strtok(NULL, ":");
1659         capture_input_cfilter_error_message(capture_opts, index, ch);
1660          /* the capture child will close the sync_pipe, nothing to do for now */
1661          break;
1662         }
1663     case SP_DROPS:
1664         capture_input_drops(capture_opts, (guint32)strtoul(buffer, NULL, 10));
1665         break;
1666     default:
1667         g_assert_not_reached();
1668     }
1669
1670     return TRUE;
1671 }
1672
1673
1674
1675 /*
1676  * dumpcap is exiting; wait for it to exit.  On success, *msgp is
1677  * unchanged, and the exit status of dumpcap is returned.  On
1678  * failure (which includes "dumpcap exited due to being killed by
1679  * a signal or an exception"), *msgp points to an error message
1680  * for the failure, and -1 is returned.  In the latter case, *msgp
1681  * must be freed with g_free().
1682  */
1683 static int
1684 sync_pipe_wait_for_child(int fork_child, gchar **msgp)
1685 {
1686     int fork_child_status;
1687     int ret;
1688
1689     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: wait till child closed");
1690     g_assert(fork_child != -1);
1691
1692     *msgp = NULL; /* assume no error */
1693 #ifdef _WIN32
1694     if (_cwait(&fork_child_status, fork_child, _WAIT_CHILD) == -1) {
1695         *msgp = g_strdup_printf("Error from cwait(): %s", g_strerror(errno));
1696         ret = -1;
1697     } else {
1698         /*
1699          * The child exited; return its exit status.  Do not treat this as
1700          * an error.
1701          */
1702         ret = fork_child_status;
1703         if ((fork_child_status & 0xC0000000) == ERROR_SEVERITY_ERROR) {
1704             /* Probably an exception code */
1705             *msgp = g_strdup_printf("Child dumpcap process died: %s",
1706                                     win32strexception(fork_child_status));
1707             ret = -1;
1708         }
1709     }
1710 #else
1711     if (waitpid(fork_child, &fork_child_status, 0) != -1) {
1712         if (WIFEXITED(fork_child_status)) {
1713             /*
1714              * The child exited; return its exit status.  Do not treat this as
1715              * an error.
1716              */
1717             ret = WEXITSTATUS(fork_child_status);
1718         } else if (WIFSTOPPED(fork_child_status)) {
1719             /* It stopped, rather than exiting.  "Should not happen." */
1720             *msgp = g_strdup_printf("Child dumpcap process stopped: %s",
1721                                     sync_pipe_signame(WSTOPSIG(fork_child_status)));
1722             ret = -1;
1723         } else if (WIFSIGNALED(fork_child_status)) {
1724             /* It died with a signal. */
1725             *msgp = g_strdup_printf("Child dumpcap process died: %s%s",
1726                                     sync_pipe_signame(WTERMSIG(fork_child_status)),
1727                                     WCOREDUMP(fork_child_status) ? " - core dumped" : "");
1728             ret = -1;
1729         } else {
1730             /* What?  It had to either have exited, or stopped, or died with
1731                a signal; what happened here? */
1732             *msgp = g_strdup_printf("Bad status from waitpid(): %#o",
1733                                     fork_child_status);
1734             ret = -1;
1735         }
1736     } else {
1737         *msgp = g_strdup_printf("Error from waitpid(): %s", g_strerror(errno));
1738         ret = -1;
1739     }
1740 #endif
1741
1742     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: capture child closed");
1743     return ret;
1744 }
1745
1746
1747 #ifndef _WIN32
1748 /* convert signal to corresponding name */
1749 static const char *
1750 sync_pipe_signame(int sig)
1751 {
1752     const char *sigmsg;
1753     static char sigmsg_buf[6+1+3+1];
1754
1755     switch (sig) {
1756
1757     case SIGHUP:
1758         sigmsg = "Hangup";
1759         break;
1760
1761     case SIGINT:
1762         sigmsg = "Interrupted";
1763         break;
1764
1765     case SIGQUIT:
1766         sigmsg = "Quit";
1767         break;
1768
1769     case SIGILL:
1770         sigmsg = "Illegal instruction";
1771         break;
1772
1773     case SIGTRAP:
1774         sigmsg = "Trace trap";
1775         break;
1776
1777     case SIGABRT:
1778         sigmsg = "Abort";
1779         break;
1780
1781     case SIGFPE:
1782         sigmsg = "Arithmetic exception";
1783         break;
1784
1785     case SIGKILL:
1786         sigmsg = "Killed";
1787         break;
1788
1789     case SIGBUS:
1790         sigmsg = "Bus error";
1791         break;
1792
1793     case SIGSEGV:
1794         sigmsg = "Segmentation violation";
1795         break;
1796
1797         /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1798            Linux is POSIX compliant.  These are not POSIX-defined signals ---
1799            ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1800
1801            ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1802            were omitted from POSIX.1 because their behavior is
1803            implementation dependent and could not be adequately catego-
1804            rized.  Conforming implementations may deliver these sig-
1805            nals, but must document the circumstances under which they
1806            are delivered and note any restrictions concerning their
1807            delivery.''
1808
1809            So we only check for SIGSYS on those systems that happen to
1810            implement them (a system can be POSIX-compliant and implement
1811            them, it's just that POSIX doesn't *require* a POSIX-compliant
1812            system to implement them).
1813         */
1814
1815 #ifdef SIGSYS
1816     case SIGSYS:
1817         sigmsg = "Bad system call";
1818         break;
1819 #endif
1820
1821     case SIGPIPE:
1822         sigmsg = "Broken pipe";
1823         break;
1824
1825     case SIGALRM:
1826         sigmsg = "Alarm clock";
1827         break;
1828
1829     case SIGTERM:
1830         sigmsg = "Terminated";
1831         break;
1832
1833     default:
1834         /* Returning a static buffer is ok in the context we use it here */
1835         g_snprintf(sigmsg_buf, sizeof sigmsg_buf, "Signal %d", sig);
1836         sigmsg = sigmsg_buf;
1837         break;
1838     }
1839     return sigmsg;
1840 }
1841 #endif
1842
1843
1844 #ifdef _WIN32
1845 /* tell the child through the signal pipe that we want to quit the capture */
1846 static void
1847 signal_pipe_capquit_to_child(capture_options *capture_opts)
1848 {
1849     const char quit_msg[] = "QUIT";
1850     int ret;
1851
1852
1853     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "signal_pipe_capquit_to_child");
1854
1855     /* it doesn't matter *what* we send here, the first byte will stop the capture */
1856     /* simply sending a "QUIT" string */
1857     /*pipe_write_block(capture_opts->signal_pipe_write_fd, SP_QUIT, quit_msg);*/
1858     ret = write(capture_opts->signal_pipe_write_fd, quit_msg, sizeof quit_msg);
1859     if(ret == -1) {
1860         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1861               "signal_pipe_capquit_to_child: %d header: error %s", capture_opts->signal_pipe_write_fd, g_strerror(errno));
1862     }
1863 }
1864 #endif
1865
1866
1867 /* user wants to stop the capture run */
1868 void
1869 sync_pipe_stop(capture_options *capture_opts)
1870 {
1871 #ifdef _WIN32
1872     int count;
1873     DWORD childstatus;
1874     gboolean terminate = TRUE;
1875 #endif
1876
1877     if (capture_opts->fork_child != -1) {
1878 #ifndef _WIN32
1879         /* send the SIGINT signal to close the capture child gracefully. */
1880         int sts = kill(capture_opts->fork_child, SIGINT);
1881         if (sts != 0) {
1882             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1883                   "Sending SIGINT to child failed: %s\n", g_strerror(errno));
1884         }
1885 #else
1886 #define STOP_SLEEP_TIME 500 /* ms */
1887 #define STOP_CHECK_TIME 50
1888         /* First, use the special signal pipe to try to close the capture child
1889          * gracefully.
1890          */
1891         signal_pipe_capquit_to_child(capture_opts);
1892
1893         /* Next, wait for the process to exit on its own */
1894         for (count = 0; count < STOP_SLEEP_TIME / STOP_CHECK_TIME; count++) {
1895             if (GetExitCodeProcess((HANDLE) capture_opts->fork_child, &childstatus) &&
1896                 childstatus != STILL_ACTIVE) {
1897                 terminate = FALSE;
1898                 break;
1899             }
1900             Sleep(STOP_CHECK_TIME);
1901         }
1902
1903         /* Force the issue. */
1904         if (terminate) {
1905             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1906                   "sync_pipe_stop: forcing child to exit");
1907             sync_pipe_kill(capture_opts->fork_child);
1908         }
1909 #endif
1910     }
1911 }
1912
1913
1914 /* Wireshark has to exit, force the capture child to close */
1915 void
1916 sync_pipe_kill(int fork_child)
1917 {
1918     if (fork_child != -1) {
1919 #ifndef _WIN32
1920         int sts = kill(fork_child, SIGTERM);    /* SIGTERM so it can clean up if necessary */
1921         if (sts != 0) {
1922             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1923                   "Sending SIGTERM to child failed: %s\n", g_strerror(errno));
1924         }
1925 #else
1926         /* Remark: This is not the preferred method of closing a process!
1927          * the clean way would be getting the process id of the child process,
1928          * then getting window handle hWnd of that process (using EnumChildWindows),
1929          * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
1930          *
1931          * Unfortunately, I don't know how to get the process id from the
1932          * handle.  OpenProcess will get an handle (not a window handle)
1933          * from the process ID; it will not get a window handle from the
1934          * process ID.  (How could it?  A process can have more than one
1935          * window.  For that matter, a process might have *no* windows,
1936          * as a process running dumpcap, the normal child process program,
1937          * probably does.)
1938          *
1939          * Hint: GenerateConsoleCtrlEvent() will only work if both processes are
1940          * running in the same console; that's not necessarily the case for
1941          * us, as we might not be running in a console.
1942          * And this also will require to have the process id.
1943          */
1944         TerminateProcess((HANDLE) (fork_child), 0);
1945 #endif
1946     }
1947 }
1948
1949 #endif /* HAVE_LIBPCAP */