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