From Mike Garratt:
[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_actual(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 /* centralised logging and timing for sync_pipe_run_command_actual(), 
1132 * redirects to sync_pipe_run_command_actual()
1133 */
1134 static int
1135 sync_pipe_run_command(char** argv, gchar **data, gchar **primary_msg,
1136                       gchar **secondary_msg)
1137 {
1138     int ret, i;
1139     GTimeVal start_time;
1140     GTimeVal end_time;
1141     float elapsed;
1142     int logging_enabled;
1143     
1144     /* check if logging is actually enabled, otherwise don't expend the CPU generating logging */
1145     logging_enabled=( (G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO) & G_LOG_LEVEL_MASK & prefs.console_log_level);
1146     if(logging_enabled){
1147         g_get_current_time(&start_time);
1148         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_INFO, "sync_pipe_run_command() starts");
1149         for(i=0; argv[i] != 0; i++) {
1150             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  argv[%d]: %s", i, argv[i]);
1151         }
1152     }
1153     /* do the actual sync pipe run command */
1154     ret=sync_pipe_run_command_actual(argv, data, primary_msg, secondary_msg);
1155
1156     if(logging_enabled){
1157         g_get_current_time(&end_time);
1158         elapsed = (float) ((end_time.tv_sec - start_time.tv_sec) +
1159                            ((end_time.tv_usec - start_time.tv_usec) / 1e6));
1160
1161         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_INFO, "sync_pipe_run_command() ends, taking %.3fs, result=%d", elapsed, ret);
1162
1163     }
1164     return ret;
1165 }
1166
1167
1168 int
1169 sync_interface_set_80211_chan(const gchar *iface, const char *freq, const gchar *type,
1170                               gchar **data, gchar **primary_msg,
1171                               gchar **secondary_msg)
1172 {
1173     int argc, ret;
1174     char **argv;
1175     gchar *opt;
1176
1177     argv = init_pipe_args(&argc);
1178
1179     if (!argv) {
1180         *primary_msg = g_strdup("We don't know where to find dumpcap.");
1181         *secondary_msg = NULL;
1182         *data = NULL;
1183         return -1;
1184     }
1185
1186     argv = sync_pipe_add_arg(argv, &argc, "-i");
1187     argv = sync_pipe_add_arg(argv, &argc, iface);
1188
1189     if (type)
1190         opt = g_strdup_printf("%s,%s", freq, type);
1191     else
1192         opt = g_strdup_printf("%s", freq);
1193
1194     if (!opt) {
1195         *primary_msg = g_strdup("Out of mem.");
1196         *secondary_msg = NULL;
1197         *data = NULL;
1198         return -1;
1199     }
1200
1201     argv = sync_pipe_add_arg(argv, &argc, "-k");
1202     argv = sync_pipe_add_arg(argv, &argc, opt);
1203
1204 #ifndef DEBUG_CHILD
1205     /* Run dumpcap in capture child mode */
1206     argv = sync_pipe_add_arg(argv, &argc, "-Z");
1207     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1208 #endif
1209
1210     ret = sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1211     g_free(opt);
1212     return ret;
1213 }
1214
1215 /*
1216  * Get the list of interfaces using dumpcap.
1217  *
1218  * On success, *data points to a buffer containing the dumpcap output,
1219  * *primary_msg and *secondary_msg are NULL, and 0 is returned.  *data
1220  * must be freed with g_free().
1221  *
1222  * On failure, *data is NULL, *primary_msg points to an error message,
1223  * *secondary_msg either points to an additional error message or is
1224  * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1225  * must be freed with g_free().
1226  */
1227 int
1228 sync_interface_list_open(gchar **data, gchar **primary_msg,
1229                          gchar **secondary_msg)
1230 {
1231     int argc;
1232     char **argv;
1233
1234     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_list_open");
1235
1236     argv = init_pipe_args(&argc);
1237
1238     if (!argv) {
1239         *primary_msg = g_strdup("We don't know where to find dumpcap.");
1240         *secondary_msg = NULL;
1241         *data = NULL;
1242         return -1;
1243     }
1244
1245     /* Ask for the interface list */
1246     argv = sync_pipe_add_arg(argv, &argc, "-D");
1247
1248 #ifndef DEBUG_CHILD
1249     /* Run dumpcap in capture child mode */
1250     argv = sync_pipe_add_arg(argv, &argc, "-Z");
1251     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1252 #endif
1253     return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1254 }
1255
1256 /*
1257  * Get the capabilities of an interface using dumpcap.
1258  *
1259  * On success, *data points to a buffer containing the dumpcap output,
1260  * *primary_msg and *secondary_msg are NULL, and 0 is returned.  *data
1261  * must be freed with g_free().
1262  *
1263  * On failure, *data is NULL, *primary_msg points to an error message,
1264  * *secondary_msg either points to an additional error message or is
1265  * NULL, and -1 is returned; *primary_msg, and *secondary_msg if not NULL,
1266  * must be freed with g_free().
1267  */
1268 int
1269 sync_if_capabilities_open(const gchar *ifname, gboolean monitor_mode,
1270                           gchar **data, gchar **primary_msg,
1271                           gchar **secondary_msg)
1272 {
1273     int argc;
1274     char **argv;
1275
1276     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_if_capabilities_open");
1277
1278     argv = init_pipe_args(&argc);
1279
1280     if (!argv) {
1281         *primary_msg = g_strdup("We don't know where to find dumpcap.");
1282         *secondary_msg = NULL;
1283         *data = NULL;
1284         return -1;
1285     }
1286
1287     /* Ask for the interface capabilities */
1288     argv = sync_pipe_add_arg(argv, &argc, "-i");
1289     argv = sync_pipe_add_arg(argv, &argc, ifname);
1290     argv = sync_pipe_add_arg(argv, &argc, "-L");
1291     if (monitor_mode)
1292         argv = sync_pipe_add_arg(argv, &argc, "-I");
1293
1294 #ifndef DEBUG_CHILD
1295     /* Run dumpcap in capture child mode */
1296     argv = sync_pipe_add_arg(argv, &argc, "-Z");
1297     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1298 #endif
1299     return sync_pipe_run_command(argv, data, primary_msg, secondary_msg);
1300 }
1301
1302 /*
1303  * Start getting interface statistics using dumpcap.  On success, read_fd
1304  * contains the file descriptor for the pipe's stdout, *msg is unchanged,
1305  * and zero is returned.  On failure, *msg will point to an error message
1306  * that must be g_free()d, and -1 will be returned.
1307  */
1308 int
1309 sync_interface_stats_open(int *data_read_fd, int *fork_child, gchar **msg)
1310 {
1311     int argc;
1312     char **argv;
1313     int message_read_fd, ret;
1314     char *wait_msg;
1315     gchar buffer[PIPE_BUF_SIZE+1];
1316     ssize_t nread;
1317     char indicator;
1318     int  primary_msg_len;
1319     char *primary_msg_text;
1320     int  secondary_msg_len;
1321     /*char *secondary_msg_text;*/
1322     char *combined_msg;
1323
1324     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_interface_stats_open");
1325
1326     argv = init_pipe_args(&argc);
1327
1328     if (!argv) {
1329         *msg = g_strdup("We don't know where to find dumpcap.");
1330         return -1;
1331     }
1332
1333     /* Ask for the interface statistics */
1334     argv = sync_pipe_add_arg(argv, &argc, "-S");
1335
1336 #ifndef DEBUG_CHILD
1337     argv = sync_pipe_add_arg(argv, &argc, "-Z");
1338     argv = sync_pipe_add_arg(argv, &argc, SIGNAL_PIPE_CTRL_ID_NONE);
1339 #endif
1340     ret = sync_pipe_open_command(argv, data_read_fd, &message_read_fd,
1341                                  fork_child, msg);
1342     if (ret == -1)
1343         return -1;
1344
1345     /*
1346      * We were able to set up to read dumpcap's output.  Do so.
1347      *
1348      * First, wait for an SP_ERROR_MSG message or SP_SUCCESS message.
1349      */
1350     nread = pipe_read_block(message_read_fd, &indicator, SP_MAX_MSG_LEN,
1351                             buffer, msg);
1352     if(nread <= 0) {
1353         /* We got a read error from the sync pipe, or we got no data at
1354            all from the sync pipe, so we're not going to be getting any
1355            data or error message from the child process.  Pick up its
1356            exit status, and complain.
1357
1358            We don't have to worry about killing the child, if the sync pipe
1359            returned an error. Usually this error is caused as the child killed
1360            itself while going down. Even in the rare cases that this isn't the
1361            case, the child will get an error when writing to the broken pipe
1362            the next time, cleaning itself up then. */
1363         ret = sync_pipe_wait_for_child(*fork_child, &wait_msg);
1364         if(nread == 0) {
1365             /* We got an EOF from the sync pipe.  That means that it exited
1366                before giving us any data to read.  If ret is -1, we report
1367                that as a bad exit (e.g., exiting due to a signal); otherwise,
1368                we report it as a premature exit. */
1369             if (ret == -1)
1370                 *msg = wait_msg;
1371             else
1372                 *msg = g_strdup("Child dumpcap closed sync pipe prematurely");
1373         } else {
1374             /* We got an error from the sync pipe.  If ret is -1, report
1375                both the sync pipe I/O error and the wait error. */
1376             if (ret == -1) {
1377                 combined_msg = g_strdup_printf("%s\n\n%s", *msg, wait_msg);
1378                 g_free(*msg);
1379                 g_free(wait_msg);
1380                 *msg = combined_msg;
1381             }
1382         }
1383
1384         return -1;
1385     }
1386
1387     /* we got a valid message block from the child, process it */
1388     switch(indicator) {
1389
1390     case SP_ERROR_MSG:
1391         /*
1392          * Error from dumpcap; there will be a primary message and a
1393          * secondary message.
1394          */
1395
1396         /* convert primary message */
1397         pipe_convert_header((guchar*)buffer, 4, &indicator, &primary_msg_len);
1398         primary_msg_text = buffer+4;
1399         /* convert secondary message */
1400         pipe_convert_header((guchar*)primary_msg_text + primary_msg_len, 4, &indicator,
1401                             &secondary_msg_len);
1402         /*secondary_msg_text = primary_msg_text + primary_msg_len + 4;*/
1403         /* the capture child will close the sync_pipe, nothing to do */
1404
1405         /*
1406          * Pick up the child status.
1407          */
1408         ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1409                                       fork_child, msg);
1410         if (ret == -1) {
1411             /*
1412              * Child process failed unexpectedly, or wait failed; msg is the
1413              * error message.
1414              */
1415         } else {
1416             /*
1417              * Child process failed, but returned the expected exit status.
1418              * Return the messages it gave us, and indicate failure.
1419              */
1420             *msg = g_strdup(primary_msg_text);
1421             ret = -1;
1422         }
1423         break;
1424
1425     case SP_SUCCESS:
1426         /* Close the message pipe. */
1427         ws_close(message_read_fd);
1428         break;
1429
1430     default:
1431         /*
1432          * Pick up the child status.
1433          */
1434         ret = sync_pipe_close_command(data_read_fd, &message_read_fd,
1435                                       fork_child, msg);
1436         if (ret == -1) {
1437             /*
1438              * Child process failed unexpectedly, or wait failed; msg is the
1439              * error message.
1440              */
1441         } else {
1442             /*
1443              * Child process returned an unknown status.
1444              */
1445             *msg = g_strdup_printf("dumpcap process gave an unexpected message type: 0x%02x",
1446                                    indicator);
1447             ret = -1;
1448         }
1449         break;
1450     }
1451     return ret;
1452 }
1453
1454 /* Close down the stats process */
1455 int
1456 sync_interface_stats_close(int *read_fd, int *fork_child, gchar **msg)
1457 {
1458 #ifndef _WIN32
1459     /*
1460      * Don't bother waiting for the child. sync_pipe_close_command
1461      * does this for us on Windows.
1462      */
1463     sync_pipe_kill(*fork_child);
1464 #endif
1465     return sync_pipe_close_command(read_fd, NULL, fork_child, msg);
1466 }
1467
1468 /* read a number of bytes from a pipe */
1469 /* (blocks until enough bytes read or an error occurs) */
1470 static ssize_t
1471 pipe_read_bytes(int pipe_fd, char *bytes, int required, char **msg)
1472 {
1473     ssize_t newly;
1474     ssize_t offset = 0;
1475     int error;
1476
1477     while(required) {
1478         newly = read(pipe_fd, &bytes[offset], required);
1479         if (newly == 0) {
1480             /* EOF */
1481             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1482                   "read from pipe %d: EOF (capture closed?)", pipe_fd);
1483             *msg = 0;
1484             return offset;
1485         }
1486         if (newly < 0) {
1487             /* error */
1488             error = errno;
1489             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1490                   "read from pipe %d: error(%u): %s", pipe_fd, error,
1491                   g_strerror(error));
1492             *msg = g_strdup_printf("Error reading from sync pipe: %s",
1493                                    g_strerror(error));
1494             return newly;
1495         }
1496
1497         required -= (int)newly;
1498         offset += newly;
1499     }
1500
1501     *msg = NULL;
1502     return offset;
1503 }
1504
1505 static gboolean pipe_data_available(int pipe_fd) {
1506 #ifdef _WIN32 /* PeekNamedPipe */
1507     HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
1508     DWORD bytes_avail;
1509
1510     if (hPipe == INVALID_HANDLE_VALUE)
1511         return FALSE;
1512
1513     if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
1514         return FALSE;
1515
1516     if (bytes_avail > 0)
1517         return TRUE;
1518     return FALSE;
1519 #else /* select */
1520     fd_set rfds;
1521     struct timeval timeout;
1522
1523     FD_ZERO(&rfds);
1524     FD_SET(pipe_fd, &rfds);
1525     timeout.tv_sec = 0;
1526     timeout.tv_usec = 0;
1527
1528     if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
1529         return TRUE;
1530
1531     return FALSE;
1532 #endif
1533 }
1534
1535 /* Read a line from a pipe, similar to fgets */
1536 int
1537 sync_pipe_gets_nonblock(int pipe_fd, char *bytes, int max) {
1538     ssize_t newly;
1539     int offset = -1;
1540
1541     while(offset < max - 1) {
1542         offset++;
1543         if (! pipe_data_available(pipe_fd))
1544             break;
1545         newly = read(pipe_fd, &bytes[offset], 1);
1546         if (newly == 0) {
1547             /* EOF - not necessarily an error */
1548             break;
1549         } else if (newly == -1) {
1550             /* error */
1551             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1552                   "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1553             return -1;
1554         } else if (bytes[offset] == '\n') {
1555             break;
1556         }
1557     }
1558
1559     if (offset >= 0)
1560         bytes[offset] = '\0';
1561
1562     return offset;
1563 }
1564
1565
1566 /* convert header values (indicator and 3-byte length) */
1567 static void
1568 pipe_convert_header(const guchar *header, int header_len, char *indicator, int *block_len) {
1569
1570     g_assert(header_len == 4);
1571
1572     /* convert header values */
1573     *indicator = header[0];
1574     *block_len = (header[1]&0xFF)<<16 | (header[2]&0xFF)<<8 | (header[3]&0xFF);
1575 }
1576
1577 /* read a message from the sending pipe in the standard format
1578    (1-byte message indicator, 3-byte message length (excluding length
1579    and indicator field), and the rest is the message) */
1580 static ssize_t
1581 pipe_read_block(int pipe_fd, char *indicator, int len, char *msg,
1582                 char **err_msg)
1583 {
1584     int required;
1585     ssize_t newly;
1586     gchar header[4];
1587
1588     /* read header (indicator and 3-byte length) */
1589     newly = pipe_read_bytes(pipe_fd, header, 4, err_msg);
1590     if(newly != 4) {
1591         if (newly == 0) {
1592             /*
1593              * Immediate EOF; if the capture child exits normally, this
1594              * is an "I'm done" indication, so don't report it as an
1595              * error.
1596              */
1597             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1598                   "read %d got an EOF", pipe_fd);
1599             return 0;
1600         }
1601         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1602               "read %d failed to read header: %lu", pipe_fd, (long)newly);
1603         if (newly != -1) {
1604             /*
1605              * Short read, but not an immediate EOF.
1606              */
1607             *err_msg = g_strdup_printf("Premature EOF reading from sync pipe: got only %ld bytes",
1608                                        (long)newly);
1609         }
1610         return -1;
1611     }
1612
1613     /* convert header values */
1614     pipe_convert_header((guchar*)header, 4, indicator, &required);
1615
1616     /* only indicator with no value? */
1617     if(required == 0) {
1618         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1619               "read %d indicator: %c empty value", pipe_fd, *indicator);
1620         return 4;
1621     }
1622
1623     /* does the data fit into the given buffer? */
1624     if(required > len) {
1625         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1626               "read %d length error, required %d > len %d, header: 0x%02x 0x%02x 0x%02x 0x%02x",
1627               pipe_fd, required, len,
1628               header[0], header[1], header[2], header[3]);
1629
1630         /* we have a problem here, try to read some more bytes from the pipe to debug where the problem really is */
1631         memcpy(msg, header, sizeof(header));
1632         newly = read(pipe_fd, &msg[sizeof(header)], len-sizeof(header));
1633         if (newly < 0) { /* error */
1634             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1635                   "read from pipe %d: error(%u): %s", pipe_fd, errno, g_strerror(errno));
1636         }
1637         *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1638                                    msg);
1639         return -1;
1640     }
1641     len = required;
1642
1643     /* read the actual block data */
1644     newly = pipe_read_bytes(pipe_fd, msg, required, err_msg);
1645     if(newly != required) {
1646         if (newly != -1) {
1647             *err_msg = g_strdup_printf("Unknown message from dumpcap, try to show it as a string: %s",
1648                                        msg);
1649         }
1650         return -1;
1651     }
1652
1653     /* XXX If message is "2part", the msg probably won't be sent to debug log correctly */
1654     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1655           "read %d ok indicator: %c len: %u msg: %s", pipe_fd, *indicator,
1656           len, msg);
1657     *err_msg = NULL;
1658     return newly + 4;
1659 }
1660
1661
1662 /* There's stuff to read from the sync pipe, meaning the child has sent
1663    us a message, or the sync pipe has closed, meaning the child has
1664    closed it (perhaps because it exited). */
1665 static gboolean
1666 sync_pipe_input_cb(gint source, gpointer user_data)
1667 {
1668     capture_session *cap_session = (capture_session *)user_data;
1669     int  ret;
1670     char buffer[SP_MAX_MSG_LEN+1];
1671     ssize_t nread;
1672     char indicator;
1673     int  primary_len;
1674     char *primary_msg;
1675     int  secondary_len;
1676     char *secondary_msg;
1677     char *wait_msg, *combined_msg;
1678     int npackets;
1679
1680     nread = pipe_read_block(source, &indicator, SP_MAX_MSG_LEN, buffer,
1681                             &primary_msg);
1682     if(nread <= 0) {
1683         /* We got a read error, or a bad message, or an EOF, from the sync pipe.
1684
1685            If we got a read error or a bad message, nread is -1 and
1686            primary_msg is set to point to an error message.  We don't
1687            have to worry about killing the child; usually this error
1688            is caused as the child killed  itself while going down.
1689            Even in the rare cases that this isn't the case, the child
1690            will get an error when writing to the broken pipe the next time,
1691            cleaning itself up then.
1692
1693            If we got an EOF, nread is 0 and primary_msg isn't set.  This
1694            is an indication that the capture is finished. */
1695         ret = sync_pipe_wait_for_child(cap_session->fork_child, &wait_msg);
1696         if(nread == 0) {
1697             /* We got an EOF from the sync pipe.  That means that the capture
1698                child exited, and not in the middle of a message; we treat
1699                that as an indication that it's done, and only report an
1700                error if ret is -1, in which case wait_msg is the error
1701                message. */
1702             if (ret == -1)
1703                 primary_msg = wait_msg;
1704         } else {
1705             /* We got an error from the sync pipe.  If ret is -1, report
1706                both the sync pipe I/O error and the wait error. */
1707             if (ret == -1) {
1708                 combined_msg = g_strdup_printf("%s\n\n%s", primary_msg, wait_msg);
1709                 g_free(primary_msg);
1710                 g_free(wait_msg);
1711                 primary_msg = combined_msg;
1712             }
1713         }
1714
1715         /* No more child process. */
1716         cap_session->fork_child = -1;
1717         cap_session->fork_child_status = ret;
1718
1719 #ifdef _WIN32
1720         ws_close(cap_session->signal_pipe_write_fd);
1721 #endif
1722         capture_input_closed(cap_session, primary_msg);
1723         g_free(primary_msg);
1724         return FALSE;
1725     }
1726
1727     /* we got a valid message block from the child, process it */
1728     switch(indicator) {
1729     case SP_FILE:
1730         if(!capture_input_new_file(cap_session, buffer)) {
1731             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: file failed, closing capture");
1732
1733             /* We weren't able to open the new capture file; user has been
1734                alerted. Close the sync pipe. */
1735             ws_close(source);
1736
1737             /* The child has sent us a filename which we couldn't open.
1738
1739                This could mean that the child is creating files faster
1740                than we can handle it.  (XXX - why would that result in
1741                a failure to open the file?)
1742
1743                That should only be the case for very fast file switches;
1744                We can't do much more than telling the child to stop.
1745                (This is the "emergency brake" if the user e.g. wants to
1746                switch files every second).
1747
1748                This can also happen if the user specified "-", meaning
1749                "standard output", as the capture file. */
1750             sync_pipe_stop(cap_session);
1751             capture_input_closed(cap_session, NULL);
1752             return FALSE;
1753         }
1754         break;
1755     case SP_PACKET_COUNT:
1756         npackets = atoi(buffer);
1757         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_input_cb: new packets %u", npackets);
1758         capture_input_new_packets(cap_session, npackets);
1759         break;
1760     case SP_ERROR_MSG:
1761         /* convert primary message */
1762         pipe_convert_header((guchar*)buffer, 4, &indicator, &primary_len);
1763         primary_msg = buffer+4;
1764         /* convert secondary message */
1765         pipe_convert_header((guchar*)primary_msg + primary_len, 4, &indicator, &secondary_len);
1766         secondary_msg = primary_msg + primary_len + 4;
1767         /* message output */
1768         capture_input_error_message(cap_session, primary_msg, secondary_msg);
1769         /* the capture child will close the sync_pipe, nothing to do for now */
1770         /* (an error message doesn't mean we have to stop capturing) */
1771         break;
1772     case SP_BAD_FILTER: {
1773         char *ch;
1774         int indx;
1775
1776         ch = strtok(buffer, ":");
1777         indx = (int)strtol(ch, NULL, 10);
1778         ch = strtok(NULL, ":");
1779         capture_input_cfilter_error_message(cap_session, indx, ch);
1780          /* the capture child will close the sync_pipe, nothing to do for now */
1781          break;
1782         }
1783     case SP_DROPS:
1784         capture_input_drops(cap_session, (guint32)strtoul(buffer, NULL, 10));
1785         break;
1786     default:
1787         g_assert_not_reached();
1788     }
1789
1790     return TRUE;
1791 }
1792
1793
1794
1795 /*
1796  * dumpcap is exiting; wait for it to exit.  On success, *msgp is
1797  * unchanged, and the exit status of dumpcap is returned.  On
1798  * failure (which includes "dumpcap exited due to being killed by
1799  * a signal or an exception"), *msgp points to an error message
1800  * for the failure, and -1 is returned.  In the latter case, *msgp
1801  * must be freed with g_free().
1802  */
1803 static int
1804 sync_pipe_wait_for_child(int fork_child, gchar **msgp)
1805 {
1806     int fork_child_status;
1807     int ret;
1808     GTimeVal start_time;
1809     GTimeVal end_time;
1810     float elapsed;
1811
1812     /*
1813      * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
1814      * replace this
1815      */
1816     g_get_current_time(&start_time);
1817
1818     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: wait till child closed");
1819     g_assert(fork_child != -1);
1820
1821     *msgp = NULL; /* assume no error */
1822 #ifdef _WIN32
1823     if (_cwait(&fork_child_status, fork_child, _WAIT_CHILD) == -1) {
1824         *msgp = g_strdup_printf("Error from cwait(): %s", g_strerror(errno));
1825         ret = -1;
1826     } else {
1827         /*
1828          * The child exited; return its exit status.  Do not treat this as
1829          * an error.
1830          */
1831         ret = fork_child_status;
1832         if ((fork_child_status & 0xC0000000) == ERROR_SEVERITY_ERROR) {
1833             /* Probably an exception code */
1834             *msgp = g_strdup_printf("Child dumpcap process died: %s",
1835                                     win32strexception(fork_child_status));
1836             ret = -1;
1837         }
1838     }
1839 #else
1840     if (waitpid(fork_child, &fork_child_status, 0) != -1) {
1841         if (WIFEXITED(fork_child_status)) {
1842             /*
1843              * The child exited; return its exit status.  Do not treat this as
1844              * an error.
1845              */
1846             ret = WEXITSTATUS(fork_child_status);
1847         } else if (WIFSTOPPED(fork_child_status)) {
1848             /* It stopped, rather than exiting.  "Should not happen." */
1849             *msgp = g_strdup_printf("Child dumpcap process stopped: %s",
1850                                     sync_pipe_signame(WSTOPSIG(fork_child_status)));
1851             ret = -1;
1852         } else if (WIFSIGNALED(fork_child_status)) {
1853             /* It died with a signal. */
1854             *msgp = g_strdup_printf("Child dumpcap process died: %s%s",
1855                                     sync_pipe_signame(WTERMSIG(fork_child_status)),
1856                                     WCOREDUMP(fork_child_status) ? " - core dumped" : "");
1857             ret = -1;
1858         } else {
1859             /* What?  It had to either have exited, or stopped, or died with
1860                a signal; what happened here? */
1861             *msgp = g_strdup_printf("Bad status from waitpid(): %#o",
1862                                     fork_child_status);
1863             ret = -1;
1864         }
1865     } else {
1866         *msgp = g_strdup_printf("Error from waitpid(): %s", g_strerror(errno));
1867         ret = -1;
1868     }
1869 #endif
1870
1871     g_get_current_time(&end_time);
1872     elapsed = (float) ((end_time.tv_sec - start_time.tv_sec) +
1873                        ((end_time.tv_usec - start_time.tv_usec) / 1e6));
1874     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "sync_pipe_wait_for_child: capture child closed after %.3fs", elapsed);
1875     return ret;
1876 }
1877
1878
1879 #ifndef _WIN32
1880 /* convert signal to corresponding name */
1881 static const char *
1882 sync_pipe_signame(int sig)
1883 {
1884     const char *sigmsg;
1885     static char sigmsg_buf[6+1+3+1];
1886
1887     switch (sig) {
1888
1889     case SIGHUP:
1890         sigmsg = "Hangup";
1891         break;
1892
1893     case SIGINT:
1894         sigmsg = "Interrupted";
1895         break;
1896
1897     case SIGQUIT:
1898         sigmsg = "Quit";
1899         break;
1900
1901     case SIGILL:
1902         sigmsg = "Illegal instruction";
1903         break;
1904
1905     case SIGTRAP:
1906         sigmsg = "Trace trap";
1907         break;
1908
1909     case SIGABRT:
1910         sigmsg = "Abort";
1911         break;
1912
1913     case SIGFPE:
1914         sigmsg = "Arithmetic exception";
1915         break;
1916
1917     case SIGKILL:
1918         sigmsg = "Killed";
1919         break;
1920
1921     case SIGBUS:
1922         sigmsg = "Bus error";
1923         break;
1924
1925     case SIGSEGV:
1926         sigmsg = "Segmentation violation";
1927         break;
1928
1929         /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1930            Linux is POSIX compliant.  These are not POSIX-defined signals ---
1931            ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1932
1933            ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1934            were omitted from POSIX.1 because their behavior is
1935            implementation dependent and could not be adequately catego-
1936            rized.  Conforming implementations may deliver these sig-
1937            nals, but must document the circumstances under which they
1938            are delivered and note any restrictions concerning their
1939            delivery.''
1940
1941            So we only check for SIGSYS on those systems that happen to
1942            implement them (a system can be POSIX-compliant and implement
1943            them, it's just that POSIX doesn't *require* a POSIX-compliant
1944            system to implement them).
1945         */
1946
1947 #ifdef SIGSYS
1948     case SIGSYS:
1949         sigmsg = "Bad system call";
1950         break;
1951 #endif
1952
1953     case SIGPIPE:
1954         sigmsg = "Broken pipe";
1955         break;
1956
1957     case SIGALRM:
1958         sigmsg = "Alarm clock";
1959         break;
1960
1961     case SIGTERM:
1962         sigmsg = "Terminated";
1963         break;
1964
1965     default:
1966         /* Returning a static buffer is ok in the context we use it here */
1967         g_snprintf(sigmsg_buf, sizeof sigmsg_buf, "Signal %d", sig);
1968         sigmsg = sigmsg_buf;
1969         break;
1970     }
1971     return sigmsg;
1972 }
1973 #endif
1974
1975
1976 #ifdef _WIN32
1977 /* tell the child through the signal pipe that we want to quit the capture */
1978 static void
1979 signal_pipe_capquit_to_child(capture_session *cap_session)
1980 {
1981     const char quit_msg[] = "QUIT";
1982     int ret;
1983
1984     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "signal_pipe_capquit_to_child");
1985
1986     /* it doesn't matter *what* we send here, the first byte will stop the capture */
1987     /* simply sending a "QUIT" string */
1988     /*pipe_write_block(cap_session->signal_pipe_write_fd, SP_QUIT, quit_msg);*/
1989     ret = write(cap_session->signal_pipe_write_fd, quit_msg, sizeof quit_msg);
1990     if(ret == -1) {
1991         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
1992               "signal_pipe_capquit_to_child: %d header: error %s", cap_session->signal_pipe_write_fd, g_strerror(errno));
1993     }
1994 }
1995 #endif
1996
1997
1998 /* user wants to stop the capture run */
1999 void
2000 sync_pipe_stop(capture_session *cap_session)
2001 {
2002 #ifdef _WIN32
2003     int count;
2004     DWORD childstatus;
2005     gboolean terminate = TRUE;
2006 #endif
2007
2008     if (cap_session->fork_child != -1) {
2009 #ifndef _WIN32
2010         /* send the SIGINT signal to close the capture child gracefully. */
2011         int sts = kill(cap_session->fork_child, SIGINT);
2012         if (sts != 0) {
2013             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
2014                   "Sending SIGINT to child failed: %s\n", g_strerror(errno));
2015         }
2016 #else
2017 #define STOP_SLEEP_TIME 500 /* ms */
2018 #define STOP_CHECK_TIME 50
2019         /* First, use the special signal pipe to try to close the capture child
2020          * gracefully.
2021          */
2022         signal_pipe_capquit_to_child(cap_session);
2023
2024         /* Next, wait for the process to exit on its own */
2025         for (count = 0; count < STOP_SLEEP_TIME / STOP_CHECK_TIME; count++) {
2026             if (GetExitCodeProcess((HANDLE) cap_session->fork_child, &childstatus) &&
2027                 childstatus != STILL_ACTIVE) {
2028                 terminate = FALSE;
2029                 break;
2030             }
2031             Sleep(STOP_CHECK_TIME);
2032         }
2033
2034         /* Force the issue. */
2035         if (terminate) {
2036             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
2037                   "sync_pipe_stop: forcing child to exit");
2038             sync_pipe_kill(cap_session->fork_child);
2039         }
2040 #endif
2041     }
2042 }
2043
2044
2045 /* Wireshark has to exit, force the capture child to close */
2046 void
2047 sync_pipe_kill(int fork_child)
2048 {
2049     if (fork_child != -1) {
2050 #ifndef _WIN32
2051         int sts = kill(fork_child, SIGTERM);    /* SIGTERM so it can clean up if necessary */
2052         if (sts != 0) {
2053             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_WARNING,
2054                   "Sending SIGTERM to child failed: %s\n", g_strerror(errno));
2055         }
2056 #else
2057         /* Remark: This is not the preferred method of closing a process!
2058          * the clean way would be getting the process id of the child process,
2059          * then getting window handle hWnd of that process (using EnumChildWindows),
2060          * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
2061          *
2062          * Unfortunately, I don't know how to get the process id from the
2063          * handle.  OpenProcess will get an handle (not a window handle)
2064          * from the process ID; it will not get a window handle from the
2065          * process ID.  (How could it?  A process can have more than one
2066          * window.  For that matter, a process might have *no* windows,
2067          * as a process running dumpcap, the normal child process program,
2068          * probably does.)
2069          *
2070          * Hint: GenerateConsoleCtrlEvent() will only work if both processes are
2071          * running in the same console; that's not necessarily the case for
2072          * us, as we might not be running in a console.
2073          * And this also will require to have the process id.
2074          */
2075         TerminateProcess((HANDLE) (fork_child), 0);
2076 #endif
2077     }
2078 }
2079
2080 #endif /* HAVE_LIBPCAP */