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