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