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