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