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