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