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