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