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