extcap: Fix call to child watch
[metze/wireshark/wip.git] / extcap.c
1 /* extcap.h
2  *
3  * Routines for extcap external capture
4  * Copyright 2013, Mike Ryan <mikeryan@lacklustre.net>
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include <config.h>
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #ifdef _WIN32
32 #include <windows.h>
33 #include <process.h>
34 #include <time.h>
35 #else
36 /* Include for unlink */
37 #include <unistd.h>
38 #endif
39
40 #include <glib.h>
41 #include <log.h>
42
43 #include <epan/prefs.h>
44 #include <epan/prefs-int.h>
45
46 #include <wsutil/file_util.h>
47 #include <wsutil/filesystem.h>
48 #include <wsutil/tempfile.h>
49
50 #include "capture_opts.h"
51
52 #ifdef HAVE_EXTCAP
53
54 #include "extcap.h"
55 #include "extcap_parser.h"
56
57 #ifdef _WIN32
58 static HANDLE pipe_h = NULL;
59 #endif
60
61 /* internal container, for all the extcap interfaces that have been found.
62  * will be resetted by every call to extcap_interface_list() and is being
63  * used in extcap_get_if_* as well as extcap_init_interfaces to ensure,
64  * that only extcap interfaces are being given to underlying extcap programs
65  */
66 static GHashTable *ifaces = NULL;
67
68 /* internal container, for all the extcap executables that have been found.
69  * will be resetted by every call to extcap_interface_list() and is being
70  * used for printing information about all extcap interfaces found
71  */
72 static GHashTable *tools = NULL;
73
74 /* Callback definition for extcap_foreach */
75 typedef gboolean (*extcap_cb_t)(const gchar *extcap, const gchar *ifname, gchar *output, void *data,
76         gchar **err_str);
77
78 /* #define ARG_DEBUG */
79 #if ARG_DEBUG
80 static void extcap_debug_arguments ( extcap_arg *arg_iter );
81 #endif
82
83 static gboolean
84 extcap_if_exists(const gchar *ifname)
85 {
86     if ( !ifname || !ifaces )
87         return FALSE;
88
89     if ( g_hash_table_lookup(ifaces, ifname) )
90         return TRUE;
91
92     return FALSE;
93 }
94
95 static gboolean
96 extcap_if_exists_for_extcap(const gchar *ifname, const gchar *extcap)
97 {
98     gchar *entry = (gchar *)g_hash_table_lookup(ifaces, ifname);
99
100     if ( entry && strcmp(entry, extcap) == 0 )
101         return TRUE;
102
103     return FALSE;
104 }
105
106 static gchar *
107 extcap_if_executable(const gchar *ifname)
108 {
109     return (gchar *)g_hash_table_lookup(ifaces, ifname);
110 }
111
112 static void
113 extcap_if_add(const gchar *ifname, const gchar *extcap)
114 {
115     if ( !g_hash_table_lookup(ifaces, ifname) )
116         g_hash_table_insert(ifaces, g_strdup(ifname), g_strdup(extcap));
117 }
118
119 static void
120 extcap_tool_add(const gchar *extcap, const extcap_interface *interface)
121 {
122     char *toolname;
123
124     if ( !extcap || !interface )
125         return;
126
127     toolname = g_path_get_basename(extcap);
128
129     if ( !g_hash_table_lookup(tools, toolname) ) {
130         extcap_info * store = (extcap_info *)g_new0(extcap_info, 1);
131         store->version = g_strdup(interface->version);
132         store->full_path = g_strdup(extcap);
133         store->basename = g_strdup(toolname);
134
135         g_hash_table_insert(tools, g_strdup(toolname), store);
136     }
137
138     g_free(toolname);
139 }
140
141 /* Note: args does not need to be NULL-terminated. */
142 static void extcap_foreach(gint argc, gchar **args, extcap_cb_t cb,
143         void *cb_data, char **err_str, const char * ifname _U_) {
144     const char *dirname = get_extcap_dir();
145     GDir *dir;
146     const gchar *file;
147     gboolean keep_going;
148     gint i;
149     gchar **argv;
150 #ifdef _WIN32
151     gchar **dll_search_envp;
152     gchar *progfile_dir;
153 #endif
154
155     keep_going = TRUE;
156
157     argv = (gchar **) g_malloc0(sizeof(gchar *) * (argc + 2));
158
159 #ifdef _WIN32
160     /*
161      * Make sure executables can find dependent DLLs and that they're *our*
162      * DLLs: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586.aspx
163      * Alternatively we could create a simple wrapper exe similar to Create
164      * Hidden Process (http://www.commandline.co.uk/chp/).
165      */
166     dll_search_envp = g_get_environ();
167     progfile_dir = g_strdup_printf("%s;%s", get_progfile_dir(), g_environ_getenv(dll_search_envp, "Path"));
168     dll_search_envp = g_environ_setenv(dll_search_envp, "Path", progfile_dir, TRUE);
169     g_free(progfile_dir);
170 #endif
171
172     if ((dir = g_dir_open(dirname, 0, NULL)) != NULL) {
173         GString *extcap_path = NULL;
174
175         extcap_path = g_string_new("");
176         while (keep_going && (file = g_dir_read_name(dir)) != NULL ) {
177             gchar *command_output = NULL;
178             gboolean status = FALSE;
179             gint exit_status = 0;
180             gchar **envp = NULL;
181
182             /* full path to extcap binary */
183 #ifdef _WIN32
184             g_string_printf(extcap_path, "%s\\%s", dirname, file);
185             envp = dll_search_envp;
186 #else
187             g_string_printf(extcap_path, "%s/%s", dirname, file);
188 #endif
189             if ( extcap_if_exists(ifname) && !extcap_if_exists_for_extcap(ifname, extcap_path->str ) )
190                 continue;
191
192 #ifdef _WIN32
193             argv[0] = g_strescape(extcap_path->str, NULL);
194 #else
195             argv[0] = g_strdup(extcap_path->str);
196 #endif
197             for (i = 0; i < argc; ++i)
198                 argv[i+1] = args[i];
199             argv[argc+1] = NULL;
200
201             status = g_spawn_sync(dirname, argv, envp,
202                 (GSpawnFlags) 0, NULL, NULL,
203                     &command_output, NULL, &exit_status, NULL);
204
205             if (status && exit_status == 0)
206             keep_going = cb(extcap_path->str, ifname, command_output, cb_data, err_str);
207
208             g_free(argv[0]);
209             g_free(command_output);
210         }
211
212         g_dir_close(dir);
213         g_string_free(extcap_path, TRUE);
214     }
215
216 #ifdef _WIN32
217     g_strfreev(dll_search_envp);
218 #endif
219     g_free(argv);
220 }
221
222 static gboolean dlt_cb(const gchar *extcap _U_, const gchar *ifname _U_, gchar *output, void *data,
223         char **err_str) {
224     extcap_token_sentence *tokens;
225     extcap_dlt *dlts, *dlt_iter, *next;
226     if_capabilities_t *caps;
227     GList *linktype_list = NULL;
228     data_link_info_t *data_link_info;
229
230     tokens = extcap_tokenize_sentences(output);
231     extcap_parse_dlts(tokens, &dlts);
232
233     extcap_free_tokenized_sentence_list(tokens);
234
235     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap pipe %s ", extcap);
236
237     /*
238      * Allocate the interface capabilities structure.
239      */
240     caps = (if_capabilities_t *) g_malloc(sizeof *caps);
241     caps->can_set_rfmon = FALSE;
242
243     dlt_iter = dlts;
244     while (dlt_iter != NULL ) {
245         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
246                 "  DLT %d name=\"%s\" display=\"%s\" ", dlt_iter->number,
247                 dlt_iter->name, dlt_iter->display);
248
249         data_link_info = g_new(data_link_info_t, 1);
250         data_link_info->dlt = dlt_iter->number;
251         data_link_info->name = g_strdup(dlt_iter->name);
252         data_link_info->description = g_strdup(dlt_iter->display);
253         linktype_list = g_list_append(linktype_list, data_link_info);
254         dlt_iter = dlt_iter->next_dlt;
255     }
256
257     /* Check to see if we built a list */
258     if (linktype_list != NULL && data != NULL) {
259         caps->data_link_types = linktype_list;
260         *(if_capabilities_t **) data = caps;
261     } else {
262         if (err_str) {
263             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  returned no DLTs");
264             *err_str = g_strdup("Extcap returned no DLTs");
265         }
266         g_free(caps);
267     }
268
269     dlt_iter = dlts;
270     while (dlt_iter != NULL ) {
271         next = dlt_iter->next_dlt;
272         extcap_free_dlt(dlt_iter);
273         dlt_iter = next;
274     }
275
276     return FALSE;
277 }
278
279 if_capabilities_t *
280 extcap_get_if_dlts(const gchar *ifname, char **err_str) {
281     gchar *argv[3];
282     gint i;
283     if_capabilities_t *caps = NULL;
284
285     if (ifname != NULL && err_str != NULL)
286         *err_str = NULL;
287
288     if ( extcap_if_exists(ifname) )
289     {
290         argv[0] = g_strdup(EXTCAP_ARGUMENT_LIST_DLTS);
291         argv[1] = g_strdup(EXTCAP_ARGUMENT_INTERFACE);
292         argv[2] = g_strdup(ifname);
293
294         if (err_str)
295             *err_str = NULL;
296         extcap_foreach(3, argv, dlt_cb, &caps, err_str, ifname);
297
298         for (i = 0; i < 3; ++i)
299             g_free(argv[i]);
300     }
301
302     return caps;
303 }
304
305 static gboolean interfaces_cb(const gchar *extcap, const gchar *ifname _U_, gchar *output, void *data,
306         char **err_str _U_) {
307     GList **il = (GList **) data;
308     extcap_token_sentence *tokens;
309     extcap_interface *interfaces, *int_iter; /*, *next; */
310     if_info_t *if_info;
311
312     tokens = extcap_tokenize_sentences(output);
313     extcap_parse_interfaces(tokens, &interfaces);
314
315     extcap_free_tokenized_sentence_list(tokens);
316
317     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap pipe %s ", extcap);
318
319     int_iter = interfaces;
320     while (int_iter != NULL ) {
321         if ( int_iter->if_type == EXTCAP_SENTENCE_INTERFACE && extcap_if_exists(int_iter->call) )
322         {
323             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_WARNING, "Extcap interface \"%s\" is already provided by \"%s\" ",
324                     int_iter->call, (gchar *)extcap_if_executable(int_iter->call) );
325             int_iter = int_iter->next_interface;
326             continue;
327         }
328
329         if ( int_iter->if_type == EXTCAP_SENTENCE_INTERFACE )
330             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Interface [%s] \"%s\" ",
331                     int_iter->call, int_iter->display);
332         else if ( int_iter->if_type == EXTCAP_SENTENCE_EXTCAP )
333             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Extcap [%s] ", int_iter->call);
334
335         if ( int_iter->if_type == EXTCAP_SENTENCE_INTERFACE ) {
336             if_info = g_new0(if_info_t, 1);
337             if_info->name = g_strdup(int_iter->call);
338             if_info->friendly_name = g_strdup(int_iter->display);
339
340             if_info->type = IF_EXTCAP;
341
342             if_info->extcap = g_strdup(extcap);
343             *il = g_list_append(*il, if_info);
344
345             extcap_if_add(int_iter->call, extcap);
346         }
347
348         /* Call for interfaces and tools alike. Multiple calls (because a tool has multiple
349          * interfaces) are handled internally */
350         extcap_tool_add(extcap, int_iter);
351
352         int_iter = int_iter->next_interface;
353     }
354     extcap_free_interface(interfaces);
355
356     return TRUE;
357 }
358
359 static gint
360 if_info_compare(gconstpointer a, gconstpointer b)
361 {
362     gint comp = 0;
363     if_info_t * if_a = (if_info_t *)a;
364     if_info_t * if_b = (if_info_t *)b;
365
366     if ( (comp = g_strcmp0(if_a->name, if_b->name)) == 0 )
367         return g_strcmp0(if_a->friendly_name, if_b->friendly_name);
368
369     return comp;
370 }
371
372 GHashTable *
373 extcap_tools_list(void) {
374     if ( tools == NULL || g_hash_table_size(tools) == 0 )
375         extcap_interface_list(NULL);
376
377     return tools;
378 }
379
380 static void
381 extcap_free_info (gpointer data) {
382     extcap_info * info = (extcap_info *)data;
383
384     g_free (info->basename);
385     g_free (info->full_path);
386     g_free (info->version);
387     g_free (info);
388 }
389
390 GList *
391 extcap_interface_list(char **err_str) {
392     gchar *argv;
393     /* gint i; */
394     GList *ret = NULL;
395
396     if (err_str != NULL)
397     *err_str = NULL;
398
399     /* ifaces is used as cache, do not destroy its contents when
400      * returning or no extcap interfaces can be queried for options */
401     if (ifaces == NULL)
402         ifaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
403     else
404         g_hash_table_remove_all(ifaces);
405
406     if (tools == NULL)
407         tools = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_info);
408     else
409         g_hash_table_remove_all(tools);
410
411     argv = g_strdup(EXTCAP_ARGUMENT_LIST_INTERFACES);
412
413     if (err_str)
414     *err_str = NULL;
415     extcap_foreach(1, &argv, interfaces_cb, &ret, err_str, NULL);
416
417     g_free(argv);
418
419     return g_list_sort ( ret, if_info_compare );
420 }
421
422 static void extcap_free_arg_elem(gpointer data, gpointer user_data _U_) {
423     extcap_free_arg((extcap_arg *) data);
424     g_free(data);
425 }
426
427 void extcap_register_preferences(void)
428 {
429     GList * interfaces = NULL;
430
431     module_t * dev_module = prefs_find_module("extcap");
432
433     if ( !dev_module )
434         return;
435
436     if ( ! ifaces || g_hash_table_size(ifaces) == 0 )
437         extcap_interface_list(NULL);
438
439     interfaces = g_hash_table_get_keys(ifaces);
440
441     while ( interfaces ) {
442         extcap_get_if_configuration((gchar *)interfaces->data);
443
444         interfaces = g_list_next(interfaces);
445     }
446 }
447
448 static void extcap_free_if_configuration(GList *list)
449 {
450     GList *elem, *sl;
451
452     for (elem = g_list_first(list); elem; elem = elem->next)
453     {
454         if (elem->data != NULL) {
455             /* g_list_free_full() only exists since 2.28. */
456             sl = g_list_first((GList *)elem->data);
457             g_list_foreach(sl, (GFunc)extcap_free_arg_elem, NULL);
458             g_list_free(sl);
459         }
460     }
461     g_list_free(list);
462 }
463
464 gchar * extcap_settings_key(const gchar * ifname, const gchar * setting)
465 {
466     gchar * setting_nohyphen;
467     gchar * ifname_underscore;
468     gchar * ifname_lower;
469     gchar * key;
470     GRegex * regex = g_regex_new ("(?![a-zA-Z1-9_]).", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL );
471
472     if (!regex)
473         return NULL;
474
475     setting_nohyphen =
476         g_regex_replace_literal(regex, setting, strlen(setting), 0,
477             "", (GRegexMatchFlags) 0, NULL );
478     ifname_underscore =
479         g_regex_replace_literal(regex, ifname, strlen(ifname), 0,
480             "_", (GRegexMatchFlags) 0, NULL );
481     ifname_lower = g_utf8_strdown(ifname_underscore, -1);
482     key = g_strconcat(ifname_lower, ".", setting_nohyphen, NULL);
483
484     g_free(setting_nohyphen);
485     g_free(ifname_underscore);
486     g_free(ifname_lower);
487     g_regex_unref(regex);
488
489     return key;
490 }
491
492 static gboolean search_cb(const gchar *extcap _U_, const gchar *ifname _U_, gchar *output, void *data,
493         char **err_str _U_) {
494     extcap_token_sentence *tokens = NULL;
495     GList *arguments = NULL;
496     GList **il = (GList **) data;
497     module_t * dev_module = NULL;
498
499     tokens = extcap_tokenize_sentences(output);
500     arguments = extcap_parse_args(tokens);
501
502     extcap_free_tokenized_sentence_list(tokens);
503
504 #if ARG_DEBUG
505     extcap_debug_arguments ( arguments );
506 #endif
507
508     dev_module = prefs_find_module("extcap");
509
510     if ( dev_module ) {
511         GList * walker = arguments;
512
513         while ( walker != NULL ) {
514             extcap_arg * arg = (extcap_arg *)walker->data;
515
516             if ( arg->save ) {
517                 struct preference * pref = NULL;
518                 gchar * pref_ifname = extcap_settings_key(ifname, arg->call);
519
520                 if ( ( pref = prefs_find_preference(dev_module, pref_ifname) ) == NULL ) {
521                     /* Set an initial value */
522                     if ( ! arg->storeval && arg->default_complex )
523                         arg->storeval = g_strdup(arg->default_complex->_val);
524
525                     prefs_register_string_preference(dev_module, g_strdup(pref_ifname),
526                             arg->display, arg->display, (const gchar **)&(arg->storeval));
527                 } else {
528                     /* Been here before, restore stored value */
529                     if (! arg->storeval && pref->varp.string)
530                         arg->storeval = g_strdup(*(pref->varp.string));
531                     }
532                 g_free(pref_ifname);
533             }
534
535             walker = g_list_next(walker);
536         }
537     }
538
539     *il = g_list_append(*il, arguments);
540
541     /* By returning false, extcap_foreach will break on first found */
542     return TRUE;
543 }
544
545 GList *
546 extcap_get_if_configuration(const char * ifname) {
547     gchar *argv[3];
548     GList *ret = NULL;
549     gchar **err_str = NULL;
550     int i;
551
552     if ( extcap_if_exists(ifname) )
553     {
554         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
555                 get_extcap_dir());
556
557         argv[0] = g_strdup(EXTCAP_ARGUMENT_CONFIG);
558         argv[1] = g_strdup(EXTCAP_ARGUMENT_INTERFACE);
559         argv[2] = g_strdup(ifname);
560
561         extcap_foreach(3, argv, search_cb, &ret, err_str, ifname);
562
563         for (i = 0; i < 3; i++)
564             g_free(argv[i]);
565     }
566
567     return ret;
568 }
569
570 gboolean
571 extcap_has_configuration(const char * ifname, gboolean is_required) {
572     GList * arguments = 0;
573     GList * walker = 0, * item = 0;
574
575     gboolean found = FALSE;
576
577     arguments = extcap_get_if_configuration((const char *)( ifname ) );
578     walker = g_list_first(arguments);
579
580     while ( walker != NULL && ! found ) {
581         item = g_list_first((GList *)(walker->data));
582         while ( item != NULL && ! found ) {
583             if ( (extcap_arg *)(item->data) != NULL ) {
584                 extcap_arg * arg = (extcap_arg *)(item->data);
585                 /* Should required options be present, or any kind of options */
586                 if ( ! is_required )
587                     found = TRUE;
588                 else if ( arg->is_required ) {
589                     gchar * stored = NULL;
590                     gchar * defval = NULL;
591
592                     if ( arg->storeval != NULL )
593                         stored = arg->storeval;
594
595                     if ( arg->default_complex != NULL && arg->default_complex->_val != NULL )
596                         defval = arg->default_complex->_val;
597
598                     if ( arg->is_required ) {
599                         /* If stored and defval is identical and the argument is required,
600                          * configuration is needed */
601                         if ( defval && stored && g_strcmp0(stored, defval) == 0 )
602                             found = TRUE;
603                         else if ( ! defval && (!stored || strlen(g_strchomp(stored)) <= (size_t)0) )
604                             found = TRUE;
605                     }
606
607                     if ( arg->arg_type == EXTCAP_ARG_FILESELECT ) {
608                         if ( arg->fileexists && ! ( file_exists(defval) || file_exists(stored) ) )
609                             found = TRUE;
610                     }
611                 }
612             }
613
614             item = item->next;
615         }
616         walker = walker->next;
617     }
618     extcap_free_if_configuration(arguments);
619
620     return found;
621 }
622
623 void extcap_cleanup(capture_options * capture_opts) {
624     interface_options interface_opts;
625     guint icnt = 0;
626
627     for (icnt = 0; icnt < capture_opts->ifaces->len; icnt++) {
628         interface_opts = g_array_index(capture_opts->ifaces, interface_options,
629                 icnt);
630
631         /* skip native interfaces */
632         if (interface_opts.if_type != IF_EXTCAP)
633         continue;
634
635         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
636                 "Extcap [%s] - Cleaning up fifo: %s; PID: %d", interface_opts.name,
637                 interface_opts.extcap_fifo, interface_opts.extcap_pid);
638 #ifdef _WIN32
639         if (pipe_h)
640         {
641             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
642                 "Extcap [%s] - Closing pipe", interface_opts.name);
643             FlushFileBuffers(pipe_h);
644             DisconnectNamedPipe(pipe_h);
645             CloseHandle(pipe_h);
646         }
647 #else
648         if (interface_opts.extcap_fifo != NULL && file_exists(interface_opts.extcap_fifo))
649         {
650             /* the fifo will not be freed here, but with the other capture_opts in capture_sync */
651             ws_unlink(interface_opts.extcap_fifo);
652             interface_opts.extcap_fifo = NULL;
653         }
654 #endif
655         /* Maybe the client closed and removed fifo, but ws should check if
656          * pid should be closed */
657         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
658                 "Extcap [%s] - Closing spawned PID: %d", interface_opts.name,
659                 interface_opts.extcap_pid);
660
661         if (interface_opts.extcap_pid != INVALID_EXTCAP_PID)
662         {
663 #ifdef _WIN32
664             TerminateProcess(interface_opts.extcap_pid, 0);
665 #endif
666             g_spawn_close_pid(interface_opts.extcap_pid);
667             interface_opts.extcap_pid = INVALID_EXTCAP_PID;
668         }
669
670         /* Make sure modified interface_opts is saved in capture_opts. */
671         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, icnt);
672         g_array_insert_val(capture_opts->ifaces, icnt, interface_opts);
673     }
674 }
675
676 static gboolean
677 extcap_add_arg_and_remove_cb(gpointer key, gpointer value, gpointer data) {
678     GPtrArray *args = (GPtrArray *)data;
679
680     if ( key != NULL )
681     {
682         g_ptr_array_add(args, g_strdup((const gchar*)key));
683
684         if ( value != NULL )
685             g_ptr_array_add(args, g_strdup((const gchar*)value));
686
687         return TRUE;
688     }
689
690     return FALSE;
691 }
692
693 static void extcap_child_watch_cb(GPid pid, gint status _U_, gpointer user_data)
694 {
695     guint i;
696     interface_options interface_opts;
697     capture_options *capture_opts = (capture_options *)user_data;
698
699     /* Close handle to child process. */
700     g_spawn_close_pid(pid);
701
702     /* Update extcap_pid in interface options structure. */
703     for (i = 0; i < capture_opts->ifaces->len; i++)
704     {
705         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
706         if (interface_opts.extcap_pid == pid)
707         {
708             interface_opts.extcap_pid = INVALID_EXTCAP_PID;
709             g_source_remove(interface_opts.extcap_child_watch);
710             interface_opts.extcap_child_watch = 0;
711
712             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
713             g_array_insert_val(capture_opts->ifaces, i, interface_opts);
714             break;
715         }
716     }
717 }
718
719 /* call mkfifo for each extcap,
720  * returns FALSE if there's an error creating a FIFO */
721 gboolean
722 extcap_init_interfaces(capture_options *capture_opts)
723 {
724     guint i;
725     interface_options interface_opts;
726
727     for (i = 0; i < capture_opts->ifaces->len; i++)
728     {
729         GPtrArray *args = NULL;
730         GPid pid = INVALID_EXTCAP_PID;
731         gchar **tmp;
732         int tmp_i;
733
734         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
735
736         /* skip native interfaces */
737         if (interface_opts.if_type != IF_EXTCAP )
738             continue;
739
740         /* create pipe for fifo */
741         if ( ! extcap_create_pipe ( &interface_opts.extcap_fifo ) )
742             return FALSE;
743
744         /* Create extcap call */
745         args = g_ptr_array_new();
746 #define add_arg(X) g_ptr_array_add(args, g_strdup(X))
747
748         add_arg(interface_opts.extcap);
749         add_arg(EXTCAP_ARGUMENT_RUN_CAPTURE);
750         add_arg(EXTCAP_ARGUMENT_INTERFACE);
751         add_arg(interface_opts.name);
752         if (interface_opts.cfilter && strlen(interface_opts.cfilter) > 0) {
753             add_arg(EXTCAP_ARGUMENT_CAPTURE_FILTER);
754             add_arg(interface_opts.cfilter);
755         }
756         add_arg(EXTCAP_ARGUMENT_RUN_PIPE);
757         add_arg(interface_opts.extcap_fifo);
758         if (interface_opts.extcap_args == NULL || g_hash_table_size(interface_opts.extcap_args) == 0)
759         {
760             /* User did not perform interface configuration.
761              *
762              * Check if there are any boolean flags that are set by default
763              * and hence their argument should be added.
764              */
765             GList *arglist;
766             GList *elem;
767
768             arglist = extcap_get_if_configuration(interface_opts.name);
769             for (elem = g_list_first(arglist); elem; elem = elem->next)
770             {
771                 GList * arg_list;
772                 extcap_arg *arg_iter;
773
774                 if (elem->data == NULL)
775                 {
776                     continue;
777                 }
778
779                 arg_list = g_list_first((GList *)elem->data);
780                 while (arg_list != NULL) {
781                     gchar * stored = NULL, * defval = NULL;
782                     /* In case of boolflags only first element in arg_list is relevant. */
783                     arg_iter = (extcap_arg*) (arg_list->data);
784                     if ( arg_iter->storeval != NULL )
785                         stored = arg_iter->storeval;
786
787                     if ( arg_iter->default_complex != NULL && arg_iter->default_complex->_val != NULL )
788                         defval = arg_iter->default_complex->_val;
789
790                     /* Different data in storage then set for default */
791                     if ( g_strcmp0(stored, defval) != 0 ) {
792                         if ( arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG ) {
793                             if ( g_strcmp0(stored, "true") == 0 )
794                                 add_arg(arg_iter->call);
795                         } else {
796                             gchar * call = g_strconcat(arg_iter->call, " ", stored, NULL);
797                             add_arg(call);
798                             g_free(call);
799                         }
800                     } else if  (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG) {
801                         if (extcap_complex_get_bool(arg_iter->default_complex))
802                             add_arg(arg_iter->call);
803                     }
804
805                     arg_list = arg_list->next;
806                 }
807             }
808
809             extcap_free_if_configuration(arglist);
810         }
811         else
812         {
813             g_hash_table_foreach_remove(interface_opts.extcap_args, extcap_add_arg_and_remove_cb, args);
814         }
815         add_arg(NULL);
816 #undef add_arg
817
818         /* Dump commandline parameters sent to extcap. */
819         for (tmp = (gchar **)args->pdata, tmp_i = 0; *tmp && **tmp; ++tmp_i, ++tmp)
820         {
821             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", tmp_i, *tmp);
822         }
823
824         /* Wireshark for windows crashes here sometimes *
825          * Access violation reading location 0x...      */
826         g_spawn_async(NULL, (gchar **)args->pdata, NULL,
827                     (GSpawnFlags) G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL,
828                     &pid,NULL);
829
830         g_ptr_array_foreach(args, (GFunc)g_free, NULL);
831         g_ptr_array_free(args, TRUE);
832         interface_opts.extcap_pid = pid;
833         interface_opts.extcap_child_watch =
834             g_child_watch_add(pid, extcap_child_watch_cb, (gpointer)capture_opts);
835         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
836         g_array_insert_val(capture_opts->ifaces, i, interface_opts);
837
838 #ifdef _WIN32
839         /* On Windows, wait for extcap to connect to named pipe.
840          * Some extcaps will present UAC screen to user.
841          * 30 second timeout should be reasonable timeout for extcap to
842          * connect to named pipe (including user interaction).
843          * Wait on multiple object in case of extcap termination
844          * without opening pipe.
845          *
846          * Minimum supported version of Windows: XP / Server 2003.
847          */
848         if (pid != INVALID_EXTCAP_PID)
849         {
850             DWORD dw;
851             HANDLE handles[2];
852             OVERLAPPED ov;
853             ov.Pointer = 0;
854             ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
855
856             ConnectNamedPipe(pipe_h, &ov);
857             handles[0] = ov.hEvent;
858             handles[1] = pid;
859
860             if (GetLastError() == ERROR_PIPE_CONNECTED)
861             {
862                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "extcap connected to pipe");
863             }
864             else
865             {
866                 dw = WaitForMultipleObjects(2, handles, FALSE, 30000);
867                 if (dw == WAIT_OBJECT_0)
868                 {
869                     /* ConnectNamedPipe finished. */
870                     DWORD code;
871
872                     code = GetLastError();
873                     if (code == ERROR_IO_PENDING)
874                     {
875                         DWORD dummy;
876                         if (!GetOverlappedResult(ov.hEvent, &ov, &dummy, TRUE))
877                         {
878                             code = GetLastError();
879                         }
880                         else
881                         {
882                             code = ERROR_SUCCESS;
883                         }
884                     }
885
886                     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "ConnectNamedPipe code: %d", code);
887                 }
888                 else if (dw == (WAIT_OBJECT_0 + 1))
889                 {
890                     /* extcap process terminated. */
891                     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "extcap terminated without connecting to pipe!");
892                 }
893                 else if (dw == WAIT_TIMEOUT)
894                 {
895                     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "extcap didn't connect to pipe within 30 seconds!");
896                 }
897                 else
898                 {
899                     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "WaitForMultipleObjects returned 0x%08X. Error %d", dw, GetLastError());
900                 }
901             }
902
903             CloseHandle(ov.hEvent);
904         }
905 #endif
906     }
907
908     return TRUE;
909 }
910
911 #ifdef _WIN32
912 /* called by capture_sync to get the CreatNamedPipe handle*/
913 HANDLE
914 extcap_get_win32_handle()
915 {
916     return pipe_h;
917 }
918 #endif
919
920 gboolean extcap_create_pipe(char ** fifo)
921 {
922 #ifdef _WIN32
923     gchar timestr[ 14+1 ];
924     time_t current_time;
925
926     gchar *pipename = NULL;
927
928     SECURITY_ATTRIBUTES security;
929     /* create pipename */
930     current_time = time(NULL);
931     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
932     pipename = g_strconcat ( "\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, "_", timestr, NULL );
933
934     /* Security struct to enable Inheritable HANDLE */
935     memset(&security, 0, sizeof(SECURITY_ATTRIBUTES));
936     security.nLength = sizeof(SECURITY_ATTRIBUTES);
937     security.bInheritHandle = TRUE;
938     security.lpSecurityDescriptor = NULL;
939
940     /* create a namedPipe*/
941     pipe_h = CreateNamedPipe(
942                 utf_8to16(pipename),
943                 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
944                 PIPE_TYPE_MESSAGE| PIPE_READMODE_MESSAGE | PIPE_WAIT,
945                 5, 65536, 65536,
946                 300,
947                 &security);
948
949     if (pipe_h == INVALID_HANDLE_VALUE)
950     {
951         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,"\nError creating pipe => (%d)", GetLastError());
952         return FALSE;
953     }
954     else
955     {
956         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,"\nWireshark Created pipe =>(%s)",pipename);
957         *fifo = g_strdup(pipename);
958     }
959 #else
960     gchar *temp_name = NULL;
961     int fd = 0;
962
963     if ((fd = create_tempfile(&temp_name, EXTCAP_PIPE_PREFIX)) < 0 )
964         return FALSE;
965
966     ws_close(fd);
967
968     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
969             "Extcap - Creating fifo: %s", temp_name);
970
971     if ( file_exists(temp_name) )
972         ws_unlink(temp_name);
973
974     if (mkfifo(temp_name, 0600) == 0)
975         *fifo = g_strdup(temp_name);
976 #endif
977
978     return TRUE;
979 }
980
981 #if ARG_DEBUG
982 void extcap_debug_arguments ( extcap_arg *arg_iter )
983 {
984     extcap_value *v = NULL;
985     GList *walker = NULL;
986
987     printf("debug - parser dump\n");
988     while (arg_iter != NULL) {
989         printf("ARG %d call=%s display=\"%s\" type=", arg_iter->arg_num, arg_iter->call, arg_iter->display);
990
991         switch (arg_iter->arg_type) {
992             case EXTCAP_ARG_INTEGER:
993             printf("int\n");
994             break;
995             case EXTCAP_ARG_UNSIGNED:
996             printf("unsigned\n");
997             break;
998             case EXTCAP_ARG_LONG:
999             printf("long\n");
1000             break;
1001             case EXTCAP_ARG_DOUBLE:
1002             printf("double\n");
1003             break;
1004             case EXTCAP_ARG_BOOLEAN:
1005             printf("boolean\n");
1006             break;
1007             case EXTCAP_ARG_MENU:
1008             printf("menu\n");
1009             break;
1010             case EXTCAP_ARG_RADIO:
1011             printf("radio\n");
1012             break;
1013             case EXTCAP_ARG_SELECTOR:
1014             printf("selctor\n");
1015             break;
1016             case EXTCAP_ARG_STRING:
1017             printf ( "string\n" );
1018             break;
1019             case EXTCAP_ARG_PASSWORD:
1020             printf ( "PASSWORD\n" );
1021             break;
1022             case EXTCAP_ARG_MULTICHECK:
1023             printf ( "unknown\n" );
1024             break;
1025             case EXTCAP_ARG_UNKNOWN:
1026             printf ( "unknown\n" );
1027             break;
1028         }
1029
1030         if (arg_iter->range_start != NULL && arg_iter->range_end != NULL) {
1031             printf("\tRange: ");
1032             extcap_printf_complex(arg_iter->range_start);
1033             printf(" - ");
1034             extcap_printf_complex(arg_iter->range_end);
1035             printf("\n");
1036         }
1037
1038         for ( walker = g_list_first ( arg_iter->value_list ); walker; walker = walker->next )
1039         {
1040             v = (extcap_value *)walker->data;
1041             if (v->is_default)
1042             printf("*");
1043             printf("\tcall=\"%p\" display=\"%p\"\n", v->call, v->display);
1044             printf("\tcall=\"%s\" display=\"%s\"\n", v->call, v->display);
1045         }
1046
1047         arg_iter = arg_iter->next_arg;
1048     }
1049 }
1050 #endif
1051 #endif
1052
1053 /*
1054  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1055  *
1056  * Local variables:
1057  * c-basic-offset: 4
1058  * tab-width: 8
1059  * indent-tabs-mode: nil
1060  * End:
1061  *
1062  * vi: set shiftwidth=4 tabstop=8 expandtab:
1063  * :indentSize=4:tabSize=8:noTabs=true:
1064  */