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