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