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