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