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