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