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