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