Point to the Wayback Machine for a now-dead link.
[gd/wireshark/.git] / extcap.c
1 /* extcap.c
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  * SPDX-License-Identifier: GPL-2.0-or-later
11  */
12
13 #include <config.h>
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18
19 #ifdef _WIN32
20 #include <windows.h>
21 #include <process.h>
22 #include <time.h>
23 #else
24 /* Include for unlink */
25 #include <unistd.h>
26 #endif
27
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_WAIT_H
30 #include <sys/wait.h>
31 #endif
32
33 #include <glib.h>
34 #include <log.h>
35
36 #include <epan/prefs.h>
37
38 #include "ui/iface_toolbar.h"
39
40 #include <wsutil/file_util.h>
41 #include <wsutil/filesystem.h>
42 #include <wsutil/ws_pipe.h>
43 #include <wsutil/ws_printf.h>
44 #include <wsutil/tempfile.h>
45
46 #include "capture_opts.h"
47
48 #include "extcap.h"
49 #include "extcap_parser.h"
50
51 #include "version_info.h"
52
53 static void extcap_child_watch_cb(GPid pid, gint status, gpointer user_data);
54
55 /* internal container, for all the extcap executables that have been found.
56  * Will be resetted if extcap_clear_interfaces() is being explicitly called
57  * and is being used for printing information about all extcap interfaces found,
58  * as well as storing all sub-interfaces
59  */
60 static GHashTable * _loaded_interfaces = NULL;
61
62 /* Internal container, which maps each ifname to the tool providing it, for faster
63  * lookup. The key and string value are owned by this table.
64  */
65 static GHashTable * _tool_for_ifname = NULL;
66
67 /* internal container, for all the extcap executables that have been found
68  * and that provides a toolbar with controls to be added to a Interface Toolbar
69  */
70 static GHashTable *_toolbars = NULL;
71
72 /* internal container, to map preference names to pointers that hold preference
73  * values. These ensure that preferences can survive extcap if garbage
74  * collection, and does not lead to dangling pointers in the prefs subsystem.
75  */
76 static GHashTable *extcap_prefs_dynamic_vals = NULL;
77
78 typedef struct _extcap_callback_info_t
79 {
80     const gchar * extcap;
81     const gchar * ifname;
82     gchar * output;
83     void * data;
84     gchar ** err_str;
85 } extcap_callback_info_t;
86
87 /* Callback definition for extcap_foreach */
88 typedef gboolean(*extcap_cb_t)(extcap_callback_info_t info_structure);
89
90 /** GThreadPool does not support pushing new work from a thread while waiting
91  * for the thread pool to finish. This data structure tracks ongoing work.
92  * See https://gitlab.gnome.org/GNOME/glib/issues/1598 */
93 typedef struct thread_pool {
94     GThreadPool    *pool;
95     gint            count;  /**< Number of tasks that have not finished. */
96     GCond           cond;
97     GMutex          data_mutex;
98 } thread_pool_t;
99
100 /**
101  * Callback definition for extcap_run_all, invoked with a thread pool (to
102  * schedule new tasks), an opaque data parameter, and the output from last task
103  * (or NULL if it failed). The output must be freed by the callback function.
104  * The implementation MUST be thread-safe.
105  */
106 typedef void (*extcap_run_cb_t)(thread_pool_t *pool, void *data, char *output);
107
108 typedef struct extcap_run_task {
109     const char     *extcap_path;
110     char          **argv;       /**< NULL-terminated arguments list, freed when the task is completed. */
111     extcap_run_cb_t output_cb;
112     void           *data;       /** Parameter to be passed to output_cb. */
113 } extcap_run_task_t;
114
115 typedef struct extcap_iface_info {
116     char *ifname;                       /**< Interface name. */
117     char *output;                       /**< Output of --extcap-config. */
118 } extcap_iface_info_t;
119
120 typedef struct extcap_run_extcaps_info {
121     char    *extcap_path;               /**< Extcap program path, MUST be the first member.  */
122     char    *output;                    /**< Output of --extcap-interfaces. */
123     guint   num_interfaces;             /**< Number of discovered interfaces. */
124     extcap_iface_info_t *iface_infos;   /**< Per-interface information. */
125 } extcap_run_extcaps_info_t;
126
127
128 static void extcap_load_interface_list(void);
129
130 static gboolean
131 thread_pool_push(thread_pool_t *pool, gpointer data, GError **error)
132 {
133     g_mutex_lock(&pool->data_mutex);
134     ++pool->count;
135     g_mutex_unlock(&pool->data_mutex);
136     return g_thread_pool_push(pool->pool, data, error);
137 }
138
139 static void
140 thread_pool_wait(thread_pool_t *pool)
141 {
142     g_mutex_lock(&pool->data_mutex);
143     while (pool->count != 0) {
144         g_cond_wait(&pool->cond, &pool->data_mutex);
145     }
146     g_mutex_unlock(&pool->data_mutex);
147 }
148
149 static GHashTable *
150 extcap_loaded_interfaces(void)
151 {
152     if (prefs.capture_no_extcap)
153         return NULL;
154
155     if ( !_loaded_interfaces || g_hash_table_size(_loaded_interfaces) == 0 )
156         extcap_load_interface_list();
157
158     return _loaded_interfaces;
159 }
160
161 void
162 extcap_clear_interfaces(void)
163 {
164     if ( _loaded_interfaces )
165         g_hash_table_destroy(_loaded_interfaces);
166     _loaded_interfaces = NULL;
167
168     if ( _tool_for_ifname )
169         g_hash_table_destroy(_tool_for_ifname);
170     _tool_for_ifname = NULL;
171 }
172
173 static gint
174 compare_tools(gconstpointer a, gconstpointer b)
175 {
176     return g_strcmp0((*(extcap_info *const *)a)->basename, (*(extcap_info *const *)b)->basename);
177 }
178
179 void
180 extcap_get_descriptions(plugin_description_callback callback, void *callback_data)
181 {
182     GHashTable * tools = extcap_loaded_interfaces();
183     GPtrArray *tools_array = g_ptr_array_new();
184
185     if (tools && g_hash_table_size(tools) > 0) {
186         GList * keys = g_hash_table_get_keys(tools);
187         GList * walker = g_list_first(keys);
188         while (walker && walker->data) {
189             extcap_info * tool = (extcap_info *)g_hash_table_lookup(tools, walker->data);
190             if (tool) {
191                 g_ptr_array_add(tools_array, tool);
192             }
193             walker = g_list_next(walker);
194         }
195         g_list_free(keys);
196     }
197
198     g_ptr_array_sort(tools_array, compare_tools);
199
200     for (guint i = 0; i < tools_array->len; i++) {
201         extcap_info *tool = (extcap_info *)tools_array->pdata[i];
202         callback(tool->basename, tool->version, "extcap", tool->full_path, callback_data);
203     }
204
205     g_ptr_array_free(tools_array, TRUE);
206 }
207
208 static void
209 print_extcap_description(const char *basename, const char *version,
210                         const char *description, const char *filename,
211                         void *user_data _U_)
212 {
213     ws_debug_printf("%-16s\t%s\t%s\t%s\n", basename, version, description, filename);
214 }
215
216 void
217 extcap_dump_all(void)
218 {
219     extcap_get_descriptions(print_extcap_description, NULL);
220 }
221
222 /**
223  * Obtains a list of extcap program paths. Use g_slist_free_full(paths, g_free)
224  * to destroy the list.
225  */
226 static GSList *
227 extcap_get_extcap_paths(void)
228 {
229     GDir *dir;
230     const char *dirname = get_extcap_dir();
231     const gchar *file;
232     GSList *paths = NULL;
233
234     if ((dir = g_dir_open(dirname, 0, NULL)) != NULL) {
235         while ((file = g_dir_read_name(dir)) != NULL) {
236             /* full path to extcap binary */
237             gchar *extcap_path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", dirname, file);
238             /* treat anything executable as an extcap binary */
239             if (g_file_test(extcap_path, G_FILE_TEST_IS_REGULAR) &&
240                 g_file_test(extcap_path, G_FILE_TEST_IS_EXECUTABLE)) {
241                 paths = g_slist_append(paths, extcap_path);
242             } else {
243                 g_free(extcap_path);
244             }
245
246         }
247         g_dir_close(dir);
248     }
249
250     return paths;
251 }
252
253 static extcap_interface *
254 extcap_find_interface_for_ifname(const gchar *ifname)
255 {
256     extcap_interface * result = NULL;
257
258     if ( !ifname || ! _tool_for_ifname || ! _loaded_interfaces )
259         return result;
260
261     gchar * extcap_util = (gchar *)g_hash_table_lookup(_tool_for_ifname, ifname);
262     if ( ! extcap_util )
263         return result;
264
265     extcap_info * element = (extcap_info *)g_hash_table_lookup(_loaded_interfaces, extcap_util);
266     if ( ! element )
267         return result;
268
269     GList * walker = element->interfaces;
270     while ( walker && walker->data && ! result )
271     {
272         extcap_interface * interface = (extcap_interface *)walker->data;
273         if ( g_strcmp0(interface->call, ifname) == 0 )
274         {
275             result = interface;
276             break;
277         }
278
279         walker = g_list_next ( walker );
280     }
281
282     return result;
283 }
284
285 static void
286 extcap_free_toolbar(gpointer data)
287 {
288     if (!data)
289     {
290         return;
291     }
292
293     iface_toolbar *toolbar = (iface_toolbar *)data;
294
295     g_free(toolbar->menu_title);
296     g_free(toolbar->help);
297     g_list_free_full(toolbar->ifnames, g_free);
298     g_list_free_full(toolbar->controls, (GDestroyNotify)extcap_free_toolbar_control);
299     g_free(toolbar);
300 }
301
302 static gchar *
303 extcap_if_executable(const gchar *ifname)
304 {
305     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
306     return interface != NULL ? interface->extcap_path : NULL;
307 }
308
309 static void
310 extcap_iface_toolbar_add(const gchar *extcap, iface_toolbar *toolbar_entry)
311 {
312     char *toolname;
313
314     if (!extcap || !toolbar_entry)
315     {
316         return;
317     }
318
319     toolname = g_path_get_basename(extcap);
320
321     if (!g_hash_table_lookup(_toolbars, toolname))
322     {
323         g_hash_table_insert(_toolbars, g_strdup(toolname), toolbar_entry);
324     }
325
326     g_free(toolname);
327 }
328
329 static gchar **
330 extcap_convert_arguments_to_array(GList * arguments)
331 {
332     gchar ** result = NULL;
333     if ( arguments )
334     {
335         GList * walker = g_list_first(arguments);
336         int cnt = 0;
337
338         result = (gchar **) g_malloc0(sizeof(gchar *) * (g_list_length(arguments)));
339
340         while(walker)
341         {
342             result[cnt] = g_strdup((const gchar *)walker->data);
343             walker = g_list_next(walker);
344             cnt++;
345         }
346     }
347     return result;
348 }
349
350 static void extcap_free_array(gchar ** args, int argc)
351 {
352     int cnt = 0;
353
354     for ( cnt = 0; cnt < argc; cnt++ )
355         g_free(args[cnt]);
356     g_free(args);
357 }
358
359 static void
360 extcap_free_extcaps_info_array(extcap_run_extcaps_info_t *infos, guint count)
361 {
362     for (guint i = 0; i < count; i++) {
363         g_free(infos[i].extcap_path);
364         g_free(infos[i].output);
365         for (guint j = 0; j < infos[i].num_interfaces; j++) {
366             extcap_iface_info_t *iface_info = &infos[i].iface_infos[j];
367             g_free(iface_info->ifname);
368             g_free(iface_info->output);
369         }
370         g_free(infos[i].iface_infos);
371     }
372     g_free(infos);
373 }
374
375 static void
376 extcap_run_one(const extcap_interface *interface, GList *arguments, extcap_cb_t cb, void *user_data, char **err_str)
377 {
378     const char *dirname = get_extcap_dir();
379     gchar **args = extcap_convert_arguments_to_array(arguments);
380     int cnt = g_list_length(arguments);
381     gchar *command_output;
382     if (ws_pipe_spawn_sync(dirname, interface->extcap_path, cnt, args, &command_output)) {
383         extcap_callback_info_t cb_info = {
384             .ifname = interface->call,
385             .extcap = interface->extcap_path,
386             .output = command_output,
387             .data = user_data,
388             .err_str = err_str,
389         };
390         cb(cb_info);
391         g_free(command_output);
392     }
393     extcap_free_array(args, cnt);
394 }
395
396 /** Thread callback to run an extcap program and pass its output. */
397 static void
398 extcap_thread_callback(gpointer data, gpointer user_data)
399 {
400     extcap_run_task_t *task = (extcap_run_task_t *)data;
401     thread_pool_t *pool = (thread_pool_t *)user_data;
402     const char *dirname = get_extcap_dir();
403
404     char *command_output;
405     if (ws_pipe_spawn_sync(dirname, task->extcap_path, g_strv_length(task->argv), task->argv, &command_output)) {
406         task->output_cb(pool, task->data, command_output);
407     } else {
408         task->output_cb(pool, task->data, NULL);
409     }
410     g_strfreev(task->argv);
411     g_free(task);
412
413     // Notify when all tasks are completed and no new subtasks were created.
414     g_mutex_lock(&pool->data_mutex);
415     if (--pool->count == 0) {
416         g_cond_signal(&pool->cond);
417     }
418     g_mutex_unlock(&pool->data_mutex);
419 }
420
421 /*
422  * Run all extcap programs with the given arguments list, invoke the callback to
423  * do some processing and return the results.
424  *
425  * @param [IN] argv NULL-terminated arguments list.
426  * @param [IN] output_cb Thread callback function that receives the output.
427  * @param [IN] data_size Size of the per-program information that will be returned.
428  * @param [OUT] count Size of the returned array.
429  * @return Array of information or NULL if there are none. The first member of
430  * each element (char *extcap_path) must be freed.
431  */
432 static gpointer
433 extcap_run_all(const char *argv[], extcap_run_cb_t output_cb, gsize data_size, guint *count)
434 {
435     /* Need enough space for at least 'extcap_path'. */
436     g_assert(data_size >= sizeof(char *));
437
438     GSList *paths = extcap_get_extcap_paths();
439     int i = 0;
440 #if GLIB_CHECK_VERSION(2,36,0)
441     int max_threads = (int)g_get_num_processors();
442 #else
443     // If the number of processors is unavailable, just use some sane maximum.
444     // extcap should not be CPU bound, so -1 could also be used for unlimited.
445     int max_threads = 8;
446 #endif
447
448     if (!paths) {
449         *count = 0;
450         return NULL;
451     }
452
453     guint64 start_time = g_get_monotonic_time();
454     guint paths_count = g_slist_length(paths);
455     /* GSList is not thread-safe, so pre-allocate an array instead. */
456     gpointer infos = g_malloc0_n(paths_count, data_size);
457
458     thread_pool_t pool;
459     pool.pool = g_thread_pool_new(extcap_thread_callback, &pool, max_threads, FALSE, NULL);
460     pool.count = 0;
461     g_cond_init(&pool.cond);
462     g_mutex_init(&pool.data_mutex);
463
464     for (GSList *path = paths; path; path = g_slist_next(path), i++) {
465         extcap_run_task_t *task = g_new0(extcap_run_task_t, 1);
466
467         task->extcap_path = (char *)path->data;
468         task->argv = g_strdupv((char **)argv);
469         task->output_cb = output_cb;
470         task->data = ((char *)infos) + (i * data_size);
471         *((char **)task->data) = (char *)path->data;
472
473         thread_pool_push(&pool, task, NULL);
474     }
475     g_slist_free(paths);    /* Note: the contents are transferred to 'infos'. */
476
477     /* Wait for all (sub)tasks to complete. */
478     thread_pool_wait(&pool);
479
480     g_mutex_clear(&pool.data_mutex);
481     g_cond_clear(&pool.cond);
482     g_thread_pool_free(pool.pool, FALSE, TRUE);
483
484     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "extcap: completed discovery of %d tools in %.3fms",
485             paths_count, (g_get_monotonic_time() - start_time) / 1000.0);
486     *count = paths_count;
487     return infos;
488 }
489
490 static void extcap_free_dlt(gpointer d, gpointer user_data _U_)
491 {
492     if (d == NULL)
493     {
494         return;
495     }
496
497     g_free(((extcap_dlt *)d)->name);
498     g_free(((extcap_dlt *)d)->display);
499     g_free(d);
500 }
501
502 static void extcap_free_dlts(GList *dlts)
503 {
504     g_list_foreach(dlts, extcap_free_dlt, NULL);
505     g_list_free(dlts);
506 }
507
508 static gboolean cb_dlt(extcap_callback_info_t cb_info)
509 {
510     GList *dlts = NULL, *temp = NULL;
511
512     if_capabilities_t *caps;
513     GList *linktype_list = NULL;
514     data_link_info_t *data_link_info;
515     extcap_dlt *dlt_item;
516
517     dlts = extcap_parse_dlts(cb_info.output);
518     temp = dlts;
519
520     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap pipe %s ", cb_info.extcap);
521
522     /*
523      * Allocate the interface capabilities structure.
524      */
525     caps = (if_capabilities_t *) g_malloc(sizeof * caps);
526     caps->can_set_rfmon = FALSE;
527     caps->timestamp_types = NULL;
528
529     while (dlts)
530     {
531         dlt_item = (extcap_dlt *)dlts->data;
532         if (dlt_item)
533         {
534             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
535                   "  DLT %d name=\"%s\" display=\"%s\" ", dlt_item->number,
536                   dlt_item->name, dlt_item->display);
537
538             data_link_info = g_new(data_link_info_t, 1);
539             data_link_info->dlt = dlt_item->number;
540             data_link_info->name = g_strdup(dlt_item->name);
541             data_link_info->description = g_strdup(dlt_item->display);
542             linktype_list = g_list_append(linktype_list, data_link_info);
543         }
544
545         dlts = g_list_next(dlts);
546     }
547
548     /* Check to see if we built a list */
549     if (linktype_list != NULL && cb_info.data != NULL)
550     {
551         caps->data_link_types = linktype_list;
552         *(if_capabilities_t **) cb_info.data = caps;
553     }
554     else
555     {
556         if (cb_info.err_str)
557         {
558             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  returned no DLTs");
559             *(cb_info.err_str) = g_strdup("Extcap returned no DLTs");
560         }
561         g_free(caps);
562     }
563
564     extcap_free_dlts(temp);
565
566     return FALSE;
567 }
568
569 if_capabilities_t *
570 extcap_get_if_dlts(const gchar *ifname, char **err_str)
571 {
572     GList * arguments = NULL;
573     if_capabilities_t *caps = NULL;
574
575     if (err_str != NULL)
576     {
577         *err_str = NULL;
578     }
579
580     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
581     if (interface)
582     {
583         arguments = g_list_append(arguments, g_strdup(EXTCAP_ARGUMENT_LIST_DLTS));
584         arguments = g_list_append(arguments, g_strdup(EXTCAP_ARGUMENT_INTERFACE));
585         arguments = g_list_append(arguments, g_strdup(ifname));
586
587         extcap_run_one(interface, arguments, cb_dlt, &caps, err_str);
588
589         g_list_free_full(arguments, g_free);
590     }
591
592     return caps;
593 }
594
595 static void extcap_free_interface(gpointer i)
596 {
597
598     extcap_interface *interface = (extcap_interface *)i;
599
600     if (i == NULL)
601     {
602         return;
603     }
604
605     g_free(interface->call);
606     g_free(interface->display);
607     g_free(interface->version);
608     g_free(interface->help);
609     g_free(interface->extcap_path);
610     g_free(interface);
611 }
612
613 static void extcap_free_interfaces(GList *interfaces)
614 {
615     if (interfaces == NULL)
616     {
617         return;
618     }
619
620     g_list_free_full(interfaces, extcap_free_interface);
621 }
622
623 static gint
624 if_info_compare(gconstpointer a, gconstpointer b)
625 {
626     gint comp = 0;
627     const if_info_t *if_a = (const if_info_t *)a;
628     const if_info_t *if_b = (const if_info_t *)b;
629
630     if ((comp = g_strcmp0(if_a->name, if_b->name)) == 0)
631     {
632         return g_strcmp0(if_a->friendly_name, if_b->friendly_name);
633     }
634
635     return comp;
636 }
637
638 gchar *
639 extcap_get_help_for_ifname(const char *ifname)
640 {
641     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
642     return interface != NULL ? interface->help : NULL;
643 }
644
645 GList *
646 append_extcap_interface_list(GList *list, char **err_str _U_)
647 {
648     GList *interface_list = NULL;
649     extcap_interface *data = NULL;
650     GList *ifutilkeys_head = NULL, *ifutilkeys = NULL;
651
652     if (prefs.capture_no_extcap)
653         return list;
654
655     /* Update the extcap interfaces and get a list of their if_infos */
656     if ( !_loaded_interfaces || g_hash_table_size(_loaded_interfaces) == 0 )
657         extcap_load_interface_list();
658
659     ifutilkeys_head = g_hash_table_get_keys(_loaded_interfaces);
660     ifutilkeys = ifutilkeys_head;
661     while ( ifutilkeys && ifutilkeys->data )
662     {
663         extcap_info * extinfo =
664                 (extcap_info *) g_hash_table_lookup(_loaded_interfaces, (gchar *)ifutilkeys->data);
665         GList * walker = extinfo->interfaces;
666         while ( walker && walker->data )
667         {
668             interface_list = g_list_append(interface_list, walker->data);
669             walker = g_list_next(walker);
670         }
671
672         ifutilkeys = g_list_next(ifutilkeys);
673     }
674     g_list_free(ifutilkeys_head);
675
676     /* Sort that list */
677     interface_list = g_list_sort(interface_list, if_info_compare);
678
679     /* Append the interfaces in that list to the list we're handed. */
680     while (interface_list != NULL)
681     {
682         GList *entry = g_list_first(interface_list);
683         data = (extcap_interface *)entry->data;
684         interface_list = g_list_delete_link(interface_list, entry);
685
686         if_info_t * if_info = g_new0(if_info_t, 1);
687         if_info->name = g_strdup(data->call);
688         if_info->friendly_name = g_strdup(data->display);
689
690         if_info->type = IF_EXTCAP;
691
692         if_info->extcap = g_strdup(data->extcap_path);
693
694         list = g_list_append(list, if_info);
695     }
696
697     return list;
698 }
699
700 void extcap_register_preferences(void)
701 {
702     if (prefs.capture_no_extcap)
703         return;
704
705     module_t *dev_module = prefs_find_module("extcap");
706
707     if (!dev_module)
708     {
709         return;
710     }
711
712     // Will load information about extcaps and their supported config.
713     extcap_load_interface_list();
714 }
715
716 /**
717  * Releases the dynamic preference value pointers. Must not be called before
718  * prefs_cleanup since these pointers could still be in use.
719  */
720 void extcap_cleanup(void)
721 {
722     if (extcap_prefs_dynamic_vals)
723         g_hash_table_destroy(extcap_prefs_dynamic_vals);
724
725     if (_loaded_interfaces)
726         g_hash_table_destroy(_loaded_interfaces);
727
728     if (_tool_for_ifname)
729         g_hash_table_destroy(_tool_for_ifname);
730 }
731
732 /**
733  * Obtains a pointer which can store a value for the given preference name.
734  * The preference name that can be passed to the prefs API is stored into
735  * 'prefs_name'.
736  *
737  * Extcap interfaces (and their preferences) are dynamic, they can be created
738  * and destroyed at will. Thus their data structures are insufficient to pass to
739  * the preferences APIs which require pointers which are valid until the
740  * preferences are removed (at exit).
741  */
742 static gchar **extcap_prefs_dynamic_valptr(const char *name, char **pref_name)
743 {
744     gchar **valp;
745     if (!extcap_prefs_dynamic_vals)
746     {
747         /* Initialize table only as needed, most preferences are not dynamic */
748         extcap_prefs_dynamic_vals = g_hash_table_new_full(g_str_hash, g_str_equal,
749                                     g_free, g_free);
750     }
751     if (!g_hash_table_lookup_extended(extcap_prefs_dynamic_vals, name,
752                                       (gpointer *)pref_name, (gpointer *)&valp))
753     {
754         /* New dynamic pref, allocate, initialize and store. */
755         valp = g_new0(gchar *, 1);
756         *pref_name = g_strdup(name);
757         g_hash_table_insert(extcap_prefs_dynamic_vals, *pref_name, valp);
758     }
759     return valp;
760 }
761
762 void extcap_free_if_configuration(GList *list, gboolean free_args)
763 {
764     GList *elem, *sl;
765
766     for (elem = g_list_first(list); elem; elem = elem->next)
767     {
768         if (elem->data != NULL)
769         {
770             sl = g_list_first((GList *)elem->data);
771             if (free_args)
772             {
773                 extcap_free_arg_list(sl);
774             }
775             else
776             {
777                 g_list_free(sl);
778             }
779         }
780     }
781     g_list_free(list);
782 }
783
784 struct preference *
785 extcap_pref_for_argument(const gchar *ifname, struct _extcap_arg *arg)
786 {
787     struct preference *pref = NULL;
788
789     GRegex *regex_name = g_regex_new("[-]+", G_REGEX_RAW, (GRegexMatchFlags) 0, NULL);
790     GRegex *regex_ifname = g_regex_new("(?![a-zA-Z0-9_]).", G_REGEX_RAW, (GRegexMatchFlags) 0, NULL);
791     if (regex_name && regex_ifname)
792     {
793         if (prefs_find_module("extcap"))
794         {
795             gchar *pref_name = g_regex_replace(regex_name, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL);
796             gchar *ifname_underscore = g_regex_replace(regex_ifname, ifname, strlen(ifname), 0, "_", (GRegexMatchFlags) 0, NULL);
797             gchar *ifname_lowercase = g_ascii_strdown(ifname_underscore, -1);
798             gchar *pref_ifname = g_strconcat(ifname_lowercase, ".", pref_name, NULL);
799
800             pref = prefs_find_preference(prefs_find_module("extcap"), pref_ifname);
801
802             g_free(pref_name);
803             g_free(ifname_underscore);
804             g_free(ifname_lowercase);
805             g_free(pref_ifname);
806         }
807     }
808     if (regex_name)
809     {
810         g_regex_unref(regex_name);
811     }
812     if (regex_ifname)
813     {
814         g_regex_unref(regex_ifname);
815     }
816
817     return pref;
818 }
819
820 static gboolean cb_preference(extcap_callback_info_t cb_info)
821 {
822     GList *arguments = NULL;
823     GList **il = (GList **) cb_info.data;
824     module_t *dev_module = NULL;
825
826     arguments = extcap_parse_args(cb_info.output);
827
828     dev_module = prefs_find_module("extcap");
829
830     if (dev_module)
831     {
832         GList *walker = arguments;
833
834         GRegex *regex_name = g_regex_new("[-]+", G_REGEX_RAW, (GRegexMatchFlags) 0, NULL);
835         GRegex *regex_ifname = g_regex_new("(?![a-zA-Z0-9_]).", G_REGEX_RAW, (GRegexMatchFlags) 0, NULL);
836         if (regex_name && regex_ifname)
837         {
838             while (walker != NULL)
839             {
840                 extcap_arg *arg = (extcap_arg *)walker->data;
841                 arg->device_name = g_strdup(cb_info.ifname);
842
843                 if (arg->save)
844                 {
845                     struct preference *pref = NULL;
846
847                     gchar *pref_name = g_regex_replace(regex_name, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL);
848                     gchar *ifname_underscore = g_regex_replace(regex_ifname, cb_info.ifname, strlen(cb_info.ifname), 0, "_", (GRegexMatchFlags) 0, NULL);
849                     gchar *ifname_lowercase = g_ascii_strdown(ifname_underscore, -1);
850                     gchar *pref_ifname = g_strconcat(ifname_lowercase, ".", pref_name, NULL);
851
852                     if ((pref = prefs_find_preference(dev_module, pref_ifname)) == NULL)
853                     {
854                         char *pref_name_for_prefs;
855                         char *pref_title = wmem_strdup(wmem_epan_scope(), arg->display);
856
857                         arg->pref_valptr = extcap_prefs_dynamic_valptr(pref_ifname, &pref_name_for_prefs);
858                         /* Set an initial value if any (the string will be copied at registration) */
859                         if (arg->default_complex)
860                         {
861                             *arg->pref_valptr = arg->default_complex->_val;
862                         }
863
864                         prefs_register_string_preference(dev_module, pref_name_for_prefs,
865                                                          pref_title, pref_title, (const char **)arg->pref_valptr);
866                     }
867                     else
868                     {
869                         /* Been here before, restore stored value */
870                         if (arg->pref_valptr == NULL)
871                         {
872                             arg->pref_valptr = (gchar**)g_hash_table_lookup(extcap_prefs_dynamic_vals, pref_ifname);
873                         }
874                     }
875
876                     g_free(pref_name);
877                     g_free(ifname_underscore);
878                     g_free(ifname_lowercase);
879                     g_free(pref_ifname);
880                 }
881
882                 walker = g_list_next(walker);
883             }
884         }
885         if (regex_name)
886         {
887             g_regex_unref(regex_name);
888         }
889         if (regex_ifname)
890         {
891             g_regex_unref(regex_ifname);
892         }
893     }
894
895     *il = g_list_append(*il, arguments);
896
897     /* By returning false, extcap_foreach will break on first found */
898     return TRUE;
899 }
900
901 GList *
902 extcap_get_if_configuration(const char *ifname)
903 {
904     GList * arguments = NULL;
905     GList *ret = NULL;
906
907     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
908     if (interface)
909     {
910         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
911               get_extcap_dir());
912
913         arguments = g_list_append(arguments, g_strdup(EXTCAP_ARGUMENT_CONFIG));
914         arguments = g_list_append(arguments, g_strdup(EXTCAP_ARGUMENT_INTERFACE));
915         arguments = g_list_append(arguments, g_strdup(ifname));
916
917         extcap_run_one(interface, arguments, cb_preference, &ret, NULL);
918
919         g_list_free_full(arguments, g_free);
920     }
921
922     return ret;
923 }
924
925 static gboolean cb_reload_preference(extcap_callback_info_t cb_info)
926 {
927     GList *arguments = NULL, * walker = NULL;
928     GList **il = (GList **) cb_info.data;
929
930     arguments = extcap_parse_values(cb_info.output);
931
932     walker = g_list_first(arguments);
933     while (walker != NULL)
934     {
935         extcap_value * val = (extcap_value *)walker->data;
936         *il = g_list_append(*il, val);
937         walker = g_list_next(walker);
938     }
939     g_list_free(arguments);
940
941     /* By returning false, extcap_foreach will break on first found */
942     return FALSE;
943 }
944
945 GList *
946 extcap_get_if_configuration_values(const char * ifname, const char * argname, GHashTable *arguments)
947 {
948     GList * args = NULL;
949     GList *ret = NULL;
950
951     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
952     if (interface)
953     {
954         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
955               get_extcap_dir());
956
957         args = g_list_append(args, g_strdup(EXTCAP_ARGUMENT_CONFIG));
958         args = g_list_append(args, g_strdup(EXTCAP_ARGUMENT_INTERFACE));
959         args = g_list_append(args, g_strdup(ifname));
960         args = g_list_append(args, g_strdup(EXTCAP_ARGUMENT_RELOAD_OPTION));
961         args = g_list_append(args, g_strdup(argname));
962
963         if ( arguments )
964         {
965             GList * keys = g_hash_table_get_keys(arguments);
966             GList * walker = g_list_first(keys);
967             while ( walker )
968             {
969                 const gchar * key_data = (const gchar *)walker->data;
970                 args = g_list_append(args, g_strdup(key_data));
971                 args = g_list_append(args, g_strdup((const gchar *)g_hash_table_lookup(arguments, key_data)));
972                 walker = g_list_next(walker);
973             }
974             g_list_free(keys);
975         }
976
977         extcap_run_one(interface, args, cb_reload_preference, &ret, NULL);
978
979         g_list_free_full(args, g_free);
980     }
981
982     return ret;
983 }
984
985 /**
986  * If is_required is FALSE: returns TRUE if the extcap interface has
987  * configurable options.
988  * If is_required is TRUE: returns TRUE when the extcap interface has
989  * configurable options that required modification. (For example, when an
990  * argument is required but empty.)
991  */
992 gboolean
993 extcap_has_configuration(const char *ifname, gboolean is_required)
994 {
995     GList *arguments = 0;
996     GList *walker = 0, * item = 0;
997
998     gboolean found = FALSE;
999
1000     arguments = extcap_get_if_configuration(ifname);
1001     walker = g_list_first(arguments);
1002
1003     while (walker != NULL && !found)
1004     {
1005         item = g_list_first((GList *)(walker->data));
1006         while (item != NULL && !found)
1007         {
1008             if ((extcap_arg *)(item->data) != NULL)
1009             {
1010                 extcap_arg *arg = (extcap_arg *)(item->data);
1011                 /* Should required options be present, or any kind of options */
1012                 if (!is_required)
1013                 {
1014                     found = TRUE;
1015                 }
1016                 else if (arg->is_required)
1017                 {
1018                     const gchar *stored = NULL;
1019                     const gchar *defval = NULL;
1020
1021                     if (arg->pref_valptr != NULL)
1022                     {
1023                         stored = *arg->pref_valptr;
1024                     }
1025
1026                     if (arg->default_complex != NULL && arg->default_complex->_val != NULL)
1027                     {
1028                         defval = arg->default_complex->_val;
1029                     }
1030
1031                     if (arg->is_required)
1032                     {
1033                         /* If stored and defval is identical and the argument is required,
1034                          * configuration is needed */
1035                         if (defval && stored && g_strcmp0(stored, defval) == 0)
1036                         {
1037                             found = TRUE;
1038                         }
1039                         else if (!defval && (!stored || !*stored))
1040                         {
1041                             found = TRUE;
1042                         }
1043                     }
1044
1045                     if (arg->arg_type == EXTCAP_ARG_FILESELECT)
1046                     {
1047                         if (arg->fileexists && !(file_exists(defval) || file_exists(stored)))
1048                         {
1049                             found = TRUE;
1050                         }
1051                     }
1052                 }
1053             }
1054
1055             item = item->next;
1056         }
1057         walker = walker->next;
1058     }
1059     extcap_free_if_configuration(arguments, TRUE);
1060
1061     return found;
1062 }
1063
1064 static gboolean cb_verify_filter(extcap_callback_info_t cb_info)
1065 {
1066     extcap_filter_status *status = (extcap_filter_status *)cb_info.data;
1067     size_t output_size, i;
1068
1069     output_size = strlen(cb_info.output);
1070     if (output_size == 0) {
1071         *status = EXTCAP_FILTER_VALID;
1072     } else {
1073         *status = EXTCAP_FILTER_INVALID;
1074         for (i = 0; i < output_size; i++) {
1075             if (cb_info.output[i] == '\n' || cb_info.output[i] == '\r') {
1076                 cb_info.output[i] = '\0';
1077                 break;
1078             }
1079         }
1080         *cb_info.err_str = g_strdup(cb_info.output);
1081     }
1082
1083     return TRUE;
1084 }
1085
1086 extcap_filter_status
1087 extcap_verify_capture_filter(const char *ifname, const char *filter, gchar **err_str)
1088 {
1089     GList * arguments = NULL;
1090     extcap_filter_status status = EXTCAP_FILTER_UNKNOWN;
1091
1092     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
1093     if (interface)
1094     {
1095         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
1096               get_extcap_dir());
1097
1098         arguments = g_list_append(arguments, g_strdup(EXTCAP_ARGUMENT_CAPTURE_FILTER));
1099         arguments = g_list_append(arguments, g_strdup(filter));
1100         arguments = g_list_append(arguments, g_strdup(EXTCAP_ARGUMENT_INTERFACE));
1101         arguments = g_list_append(arguments, g_strdup(ifname));
1102
1103         extcap_run_one(interface, arguments, cb_verify_filter, &status, err_str);
1104         g_list_free_full(arguments, g_free);
1105     }
1106
1107     return status;
1108 }
1109
1110 gboolean
1111 extcap_has_toolbar(const char *ifname)
1112 {
1113     if (!iface_toolbar_use())
1114     {
1115         return FALSE;
1116     }
1117
1118     GList *toolbar_list = g_hash_table_get_values (_toolbars);
1119     for (GList *walker = toolbar_list; walker; walker = walker->next)
1120     {
1121         iface_toolbar *toolbar = (iface_toolbar *) walker->data;
1122         if (g_list_find_custom(toolbar->ifnames, ifname, (GCompareFunc) g_strcmp0))
1123         {
1124             g_list_free(toolbar_list);
1125             return TRUE;
1126         }
1127     }
1128
1129     g_list_free(toolbar_list);
1130     return FALSE;
1131 }
1132
1133 void extcap_if_cleanup(capture_options *capture_opts, gchar **errormsg)
1134 {
1135     interface_options *interface_opts;
1136     ws_pipe_t *pipedata;
1137     guint icnt = 0;
1138     gboolean overwrite_exitcode;
1139     gchar *buffer;
1140 #define STDERR_BUFFER_SIZE 1024
1141
1142     for (icnt = 0; icnt < capture_opts->ifaces->len; icnt++)
1143     {
1144         interface_opts = &g_array_index(capture_opts->ifaces, interface_options,
1145                                        icnt);
1146
1147         /* skip native interfaces */
1148         if (interface_opts->if_type != IF_EXTCAP)
1149         {
1150             continue;
1151         }
1152
1153         overwrite_exitcode = FALSE;
1154
1155         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1156               "Extcap [%s] - Cleaning up fifo: %s; PID: %d", interface_opts->name,
1157               interface_opts->extcap_fifo, interface_opts->extcap_pid);
1158 #ifdef _WIN32
1159         if (interface_opts->extcap_pipe_h != INVALID_HANDLE_VALUE)
1160         {
1161             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1162                   "Extcap [%s] - Closing pipe", interface_opts->name);
1163             FlushFileBuffers(interface_opts->extcap_pipe_h);
1164             DisconnectNamedPipe(interface_opts->extcap_pipe_h);
1165             CloseHandle(interface_opts->extcap_pipe_h);
1166             interface_opts->extcap_pipe_h = INVALID_HANDLE_VALUE;
1167         }
1168         if (interface_opts->extcap_control_in_h != INVALID_HANDLE_VALUE)
1169         {
1170             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1171                   "Extcap [%s] - Closing control_in pipe", interface_opts->name);
1172             FlushFileBuffers(interface_opts->extcap_control_in_h);
1173             DisconnectNamedPipe(interface_opts->extcap_control_in_h);
1174             CloseHandle(interface_opts->extcap_control_in_h);
1175             interface_opts->extcap_control_in_h = INVALID_HANDLE_VALUE;
1176         }
1177         if (interface_opts->extcap_control_out_h != INVALID_HANDLE_VALUE)
1178         {
1179             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1180                   "Extcap [%s] - Closing control_out pipe", interface_opts->name);
1181             FlushFileBuffers(interface_opts->extcap_control_out_h);
1182             DisconnectNamedPipe(interface_opts->extcap_control_out_h);
1183             CloseHandle(interface_opts->extcap_control_out_h);
1184             interface_opts->extcap_control_out_h = INVALID_HANDLE_VALUE;
1185         }
1186 #else
1187         if (interface_opts->extcap_fifo != NULL && file_exists(interface_opts->extcap_fifo))
1188         {
1189             /* the fifo will not be freed here, but with the other capture_opts in capture_sync */
1190             ws_unlink(interface_opts->extcap_fifo);
1191             interface_opts->extcap_fifo = NULL;
1192         }
1193         if (interface_opts->extcap_control_in && file_exists(interface_opts->extcap_control_in))
1194         {
1195             ws_unlink(interface_opts->extcap_control_in);
1196             interface_opts->extcap_control_in = NULL;
1197         }
1198         if (interface_opts->extcap_control_out && file_exists(interface_opts->extcap_control_out))
1199         {
1200             ws_unlink(interface_opts->extcap_control_out);
1201             interface_opts->extcap_control_out = NULL;
1202         }
1203 #endif
1204         /* Maybe the client closed and removed fifo, but ws should check if
1205          * pid should be closed */
1206         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1207               "Extcap [%s] - Closing spawned PID: %d", interface_opts->name,
1208               interface_opts->extcap_pid);
1209
1210         pipedata = (ws_pipe_t *) interface_opts->extcap_pipedata;
1211         if (pipedata)
1212         {
1213             if (pipedata->stderr_fd > 0)
1214             {
1215                 buffer = (gchar *)g_malloc0(STDERR_BUFFER_SIZE + 1);
1216                 ws_read_string_from_pipe(ws_get_pipe_handle(pipedata->stderr_fd), buffer, STDERR_BUFFER_SIZE + 1);
1217                 if (strlen(buffer) > 0)
1218                 {
1219                     pipedata->stderr_msg = g_strdup(buffer);
1220                     pipedata->exitcode = 1;
1221                 }
1222                 g_free(buffer);
1223             }
1224
1225 #ifndef _WIN32
1226             /* Final child watch may not have been called */
1227             if (interface_opts->extcap_child_watch > 0)
1228             {
1229                 extcap_child_watch_cb(pipedata->pid, 0, capture_opts);
1230                 /* it will have changed in extcap_child_watch_cb */
1231                 interface_opts = &g_array_index(capture_opts->ifaces, interface_options,
1232                                                icnt);
1233             }
1234 #endif
1235
1236             if (pipedata->stderr_msg != NULL)
1237             {
1238                 overwrite_exitcode = TRUE;
1239             }
1240
1241             if (overwrite_exitcode || pipedata->exitcode != 0)
1242             {
1243                 if (pipedata->stderr_msg != NULL)
1244                 {
1245                     if (*errormsg == NULL)
1246                     {
1247                         *errormsg = g_strdup_printf("Error by extcap pipe: %s", pipedata->stderr_msg);
1248                     }
1249                     else
1250                     {
1251                         gchar *temp = g_strconcat(*errormsg, "\nError by extcap pipe: " , pipedata->stderr_msg, NULL);
1252                         g_free(*errormsg);
1253                         *errormsg = temp;
1254                     }
1255                     g_free(pipedata->stderr_msg);
1256                 }
1257
1258                 pipedata->stderr_msg = NULL;
1259                 pipedata->exitcode = 0;
1260             }
1261         }
1262
1263         if (interface_opts->extcap_child_watch > 0)
1264         {
1265             g_source_remove(interface_opts->extcap_child_watch);
1266             interface_opts->extcap_child_watch = 0;
1267         }
1268
1269         if (pipedata) {
1270             if (pipedata->stdout_fd > 0)
1271             {
1272                 ws_close(pipedata->stdout_fd);
1273             }
1274
1275             if (pipedata->stderr_fd > 0)
1276             {
1277                 ws_close(pipedata->stderr_fd);
1278             }
1279
1280             if (interface_opts->extcap_pid != WS_INVALID_PID)
1281             {
1282                 ws_pipe_close(pipedata);
1283                 interface_opts->extcap_pid = WS_INVALID_PID;
1284
1285                 g_free(pipedata);
1286                 interface_opts->extcap_pipedata = NULL;
1287             }
1288         }
1289     }
1290 }
1291
1292 static gboolean
1293 extcap_add_arg_and_remove_cb(gpointer key, gpointer value, gpointer data)
1294 {
1295     GPtrArray *args = (GPtrArray *)data;
1296
1297     if (key != NULL)
1298     {
1299         g_ptr_array_add(args, g_strdup((const gchar *)key));
1300
1301         if (value != NULL)
1302         {
1303             g_ptr_array_add(args, g_strdup((const gchar *)value));
1304         }
1305
1306         return TRUE;
1307     }
1308
1309     return FALSE;
1310 }
1311
1312 void extcap_child_watch_cb(GPid pid, gint status, gpointer user_data)
1313 {
1314     guint i;
1315     interface_options *interface_opts;
1316     ws_pipe_t *pipedata = NULL;
1317     capture_options *capture_opts = (capture_options *)(user_data);
1318
1319     if (capture_opts == NULL || capture_opts->ifaces == NULL || capture_opts->ifaces->len == 0)
1320     {
1321         return;
1322     }
1323
1324     /* Close handle to child process. */
1325     g_spawn_close_pid(pid);
1326
1327     /* Update extcap_pid in interface options structure. */
1328     for (i = 0; i < capture_opts->ifaces->len; i++)
1329     {
1330         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
1331         if (interface_opts->extcap_pid == pid)
1332         {
1333             pipedata = (ws_pipe_t *)interface_opts->extcap_pipedata;
1334             if (pipedata != NULL)
1335             {
1336                 interface_opts->extcap_pid = WS_INVALID_PID;
1337                 pipedata->exitcode = 0;
1338 #ifndef _WIN32
1339                 if (WIFEXITED(status))
1340                 {
1341                     if (WEXITSTATUS(status) != 0)
1342                     {
1343                         pipedata->exitcode = WEXITSTATUS(status);
1344                     }
1345                 }
1346                 else
1347                 {
1348                     pipedata->exitcode = G_SPAWN_ERROR_FAILED;
1349                 }
1350 #else
1351                 if (status != 0)
1352                 {
1353                     pipedata->exitcode = status;
1354                 }
1355 #endif
1356                 if (status == 0 && pipedata->stderr_msg != NULL)
1357                 {
1358                     pipedata->exitcode = 1;
1359                 }
1360             }
1361             g_source_remove(interface_opts->extcap_child_watch);
1362             interface_opts->extcap_child_watch = 0;
1363             break;
1364         }
1365     }
1366 }
1367
1368 static
1369 GPtrArray *extcap_prepare_arguments(interface_options *interface_opts)
1370 {
1371     GPtrArray *result = NULL;
1372
1373     if (interface_opts->if_type == IF_EXTCAP)
1374     {
1375         result = g_ptr_array_new();
1376
1377 #define add_arg(X) g_ptr_array_add(result, g_strdup(X))
1378
1379         add_arg(interface_opts->extcap);
1380         add_arg(EXTCAP_ARGUMENT_RUN_CAPTURE);
1381         add_arg(EXTCAP_ARGUMENT_INTERFACE);
1382         add_arg(interface_opts->name);
1383         if (interface_opts->cfilter && strlen(interface_opts->cfilter) > 0)
1384         {
1385             add_arg(EXTCAP_ARGUMENT_CAPTURE_FILTER);
1386             add_arg(interface_opts->cfilter);
1387         }
1388         add_arg(EXTCAP_ARGUMENT_RUN_PIPE);
1389         add_arg(interface_opts->extcap_fifo);
1390         if (interface_opts->extcap_control_in)
1391         {
1392             add_arg(EXTCAP_ARGUMENT_CONTROL_OUT);
1393             add_arg(interface_opts->extcap_control_in);
1394         }
1395         if (interface_opts->extcap_control_out)
1396         {
1397             add_arg(EXTCAP_ARGUMENT_CONTROL_IN);
1398             add_arg(interface_opts->extcap_control_out);
1399         }
1400         if (interface_opts->extcap_args == NULL || g_hash_table_size(interface_opts->extcap_args) == 0)
1401         {
1402             /* User did not perform interface configuration.
1403              *
1404              * Check if there are any boolean flags that are set by default
1405              * and hence their argument should be added.
1406              */
1407             GList *arglist;
1408             GList *elem;
1409
1410             arglist = extcap_get_if_configuration(interface_opts->name);
1411             for (elem = g_list_first(arglist); elem; elem = elem->next)
1412             {
1413                 GList *arg_list;
1414                 extcap_arg *arg_iter;
1415
1416                 if (elem->data == NULL)
1417                 {
1418                     continue;
1419                 }
1420
1421                 arg_list = g_list_first((GList *)elem->data);
1422                 while (arg_list != NULL)
1423                 {
1424                     const gchar *stored = NULL;
1425                     /* In case of boolflags only first element in arg_list is relevant. */
1426                     arg_iter = (extcap_arg *)(arg_list->data);
1427                     if (arg_iter->pref_valptr != NULL)
1428                     {
1429                         stored = *arg_iter->pref_valptr;
1430                     }
1431
1432                     if (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG)
1433                     {
1434                         if (extcap_complex_get_bool(arg_iter->default_complex))
1435                         {
1436                             add_arg(arg_iter->call);
1437                         }
1438                         else if (g_strcmp0(stored, "true") == 0)
1439                         {
1440                             add_arg(arg_iter->call);
1441                         }
1442                     }
1443                     else
1444                     {
1445                         if (stored && strlen(stored) > 0) {
1446                             add_arg(arg_iter->call);
1447                             add_arg(stored);
1448                         }
1449                     }
1450
1451                     arg_list = arg_list->next;
1452                 }
1453             }
1454
1455             extcap_free_if_configuration(arglist, TRUE);
1456         }
1457         else
1458         {
1459             g_hash_table_foreach_remove(interface_opts->extcap_args, extcap_add_arg_and_remove_cb, result);
1460         }
1461         add_arg(NULL);
1462 #undef add_arg
1463
1464     }
1465
1466     return result;
1467 }
1468
1469 static void ptr_array_free(gpointer data, gpointer user_data _U_)
1470 {
1471     g_free(data);
1472 }
1473
1474 #ifdef _WIN32
1475 static gboolean extcap_create_pipe(const gchar *ifname, gchar **fifo, HANDLE *handle_out, const gchar *pipe_prefix)
1476 {
1477     gchar timestr[ 14 + 1 ];
1478     time_t current_time;
1479     gchar *pipename = NULL;
1480     SECURITY_ATTRIBUTES security;
1481
1482     /* create pipename */
1483     current_time = time(NULL);
1484     /*
1485      * XXX - we trust Windows not to return a time before the Epoch here,
1486      * so we won't get a null pointer back from localtime().
1487      */
1488     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
1489     pipename = g_strconcat("\\\\.\\pipe\\", pipe_prefix, "_", ifname, "_", timestr, NULL);
1490
1491     /* Security struct to enable Inheritable HANDLE */
1492     memset(&security, 0, sizeof(SECURITY_ATTRIBUTES));
1493     security.nLength = sizeof(SECURITY_ATTRIBUTES);
1494     security.bInheritHandle = TRUE;
1495     security.lpSecurityDescriptor = NULL;
1496
1497     /* create a namedPipe */
1498     *handle_out = CreateNamedPipe(
1499                  utf_8to16(pipename),
1500                  PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1501                  PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1502                  1, 65536, 65536,
1503                  300,
1504                  &security);
1505
1506     if (*handle_out == INVALID_HANDLE_VALUE)
1507     {
1508         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nError creating pipe => (%d)", GetLastError());
1509         g_free (pipename);
1510         return FALSE;
1511     }
1512     else
1513     {
1514         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nWireshark Created pipe =>(%s)", pipename);
1515         *fifo = g_strdup(pipename);
1516     }
1517
1518     return TRUE;
1519 }
1520 #else
1521 static gboolean extcap_create_pipe(const gchar *ifname, gchar **fifo, const gchar *pipe_prefix)
1522 {
1523     gchar *temp_name = NULL;
1524     int fd = 0;
1525
1526     gchar *pfx = g_strconcat(pipe_prefix, "_", ifname, NULL);
1527     if ((fd = create_tempfile(&temp_name, pfx, NULL)) < 0)
1528     {
1529         g_free(pfx);
1530         return FALSE;
1531     }
1532     g_free(pfx);
1533
1534     ws_close(fd);
1535
1536     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1537           "Extcap - Creating fifo: %s", temp_name);
1538
1539     if (file_exists(temp_name))
1540     {
1541         ws_unlink(temp_name);
1542     }
1543
1544     if (mkfifo(temp_name, 0600) == 0)
1545     {
1546         *fifo = g_strdup(temp_name);
1547     }
1548
1549     return TRUE;
1550 }
1551 #endif
1552
1553 /* call mkfifo for each extcap,
1554  * returns FALSE if there's an error creating a FIFO */
1555 gboolean
1556 extcap_init_interfaces(capture_options *capture_opts)
1557 {
1558     guint i;
1559     interface_options *interface_opts;
1560     ws_pipe_t *pipedata;
1561
1562     for (i = 0; i < capture_opts->ifaces->len; i++)
1563     {
1564         GPtrArray *args = NULL;
1565         GPid pid = WS_INVALID_PID;
1566
1567         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
1568
1569         /* skip native interfaces */
1570         if (interface_opts->if_type != IF_EXTCAP)
1571         {
1572             continue;
1573         }
1574
1575         /* create control pipes if having toolbar */
1576         if (extcap_has_toolbar(interface_opts->name))
1577         {
1578             extcap_create_pipe(interface_opts->name, &interface_opts->extcap_control_in,
1579 #ifdef _WIN32
1580                                &interface_opts->extcap_control_in_h,
1581 #endif
1582                                EXTCAP_CONTROL_IN_PREFIX);
1583             extcap_create_pipe(interface_opts->name, &interface_opts->extcap_control_out,
1584 #ifdef _WIN32
1585                                &interface_opts->extcap_control_out_h,
1586 #endif
1587                                EXTCAP_CONTROL_OUT_PREFIX);
1588         }
1589
1590         /* create pipe for fifo */
1591         if (!extcap_create_pipe(interface_opts->name, &interface_opts->extcap_fifo,
1592 #ifdef _WIN32
1593                                 &interface_opts->extcap_pipe_h,
1594 #endif
1595                                 EXTCAP_PIPE_PREFIX))
1596         {
1597             return FALSE;
1598         }
1599
1600
1601         /* Create extcap call */
1602         args = extcap_prepare_arguments(interface_opts);
1603
1604         pipedata = g_new0(ws_pipe_t, 1);
1605
1606         pid = ws_pipe_spawn_async(pipedata, args);
1607
1608         g_ptr_array_foreach(args, ptr_array_free, NULL);
1609         g_ptr_array_free(args, TRUE);
1610
1611         if (pid == WS_INVALID_PID)
1612         {
1613             g_free(pipedata);
1614             continue;
1615         }
1616
1617         ws_close(pipedata->stdin_fd);
1618         interface_opts->extcap_pid = pid;
1619
1620         interface_opts->extcap_child_watch =
1621             g_child_watch_add(pid, extcap_child_watch_cb, (gpointer)capture_opts);
1622
1623 #ifdef _WIN32
1624         /* On Windows, wait for extcap to connect to named pipe.
1625          * Some extcaps will present UAC screen to user.
1626          * 30 second timeout should be reasonable timeout for extcap to
1627          * connect to named pipe (including user interaction).
1628          * Wait on multiple object in case of extcap termination
1629          * without opening pipe.
1630          */
1631         if (pid != WS_INVALID_PID)
1632         {
1633             HANDLE pipe_handles[3];
1634             int num_pipe_handles = 1;
1635             pipe_handles[0] = interface_opts->extcap_pipe_h;
1636
1637             if (extcap_has_toolbar(interface_opts->name))
1638             {
1639                 pipe_handles[1] = interface_opts->extcap_control_in_h;
1640                 pipe_handles[2] = interface_opts->extcap_control_out_h;
1641                 num_pipe_handles += 2;
1642              }
1643
1644             ws_pipe_wait_for_pipe(pipe_handles, num_pipe_handles, pid);
1645         }
1646 #endif
1647
1648         interface_opts->extcap_pipedata = (gpointer) pipedata;
1649     }
1650
1651     return TRUE;
1652 }
1653
1654 /************* EXTCAP LOAD INTERFACE LIST ***************
1655  *
1656  * The following code handles loading and reloading the interface list. It is explicitly
1657  * kept separate from the rest
1658  */
1659
1660
1661 static void
1662 extcap_free_interface_info(gpointer data)
1663 {
1664     extcap_info *info = (extcap_info *)data;
1665
1666     g_free(info->basename);
1667     g_free(info->full_path);
1668     g_free(info->version);
1669     g_free(info->help);
1670
1671     extcap_free_interfaces(info->interfaces);
1672
1673     g_free(info);
1674 }
1675
1676 static extcap_info *
1677 extcap_ensure_interface(const gchar * toolname, gboolean create_if_nonexist)
1678 {
1679     extcap_info * element = 0;
1680
1681     if ( prefs.capture_no_extcap )
1682         return NULL;
1683
1684     if ( ! toolname )
1685         return element;
1686
1687     if ( ! _loaded_interfaces )
1688         _loaded_interfaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_interface);
1689
1690     element = (extcap_info *) g_hash_table_lookup(_loaded_interfaces, toolname );
1691     if ( ! element && create_if_nonexist )
1692     {
1693         g_hash_table_insert(_loaded_interfaces, g_strdup(toolname), g_new0(extcap_info, 1));
1694         element = (extcap_info *) g_hash_table_lookup(_loaded_interfaces, toolname );
1695     }
1696
1697     return element;
1698 }
1699
1700 extcap_info *
1701 extcap_get_tool_by_ifname(const gchar *ifname)
1702 {
1703     if ( ifname && _tool_for_ifname )
1704     {
1705         gchar * toolname = (gchar *)g_hash_table_lookup(_tool_for_ifname, ifname);
1706         if ( toolname )
1707             return extcap_ensure_interface(toolname, FALSE);
1708     }
1709
1710     return NULL;
1711 }
1712
1713 extcap_info *
1714 extcap_get_tool_info(const gchar * toolname)
1715 {
1716     return extcap_ensure_interface(toolname, FALSE);
1717 }
1718
1719 static void remove_extcap_entry(gpointer entry, gpointer data _U_)
1720 {
1721     extcap_interface *int_iter = (extcap_interface*)entry;
1722
1723     if (int_iter->if_type == EXTCAP_SENTENCE_EXTCAP)
1724         extcap_free_interface(entry);
1725 }
1726
1727 static void
1728 process_new_extcap(const char *extcap, char *output)
1729 {
1730     GList * interfaces = NULL, * control_items = NULL, * walker = NULL;
1731     extcap_interface * int_iter = NULL;
1732     extcap_info * element = NULL;
1733     iface_toolbar * toolbar_entry = NULL;
1734     gchar * toolname = g_path_get_basename(extcap);
1735
1736     GList * interface_keys = g_hash_table_get_keys(_loaded_interfaces);
1737
1738     /* Load interfaces from utility */
1739     interfaces = extcap_parse_interfaces(output, &control_items);
1740
1741     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Loading interface list for %s ", extcap);
1742
1743     /* Seems, that there where no interfaces to be loaded */
1744     if ( ! interfaces || g_list_length(interfaces) == 0 )
1745     {
1746         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Cannot load interfaces for %s", extcap );
1747         g_list_free(interface_keys);
1748         g_free(toolname);
1749         return;
1750     }
1751
1752     /* Load or create the storage element for the tool */
1753     element = extcap_ensure_interface(toolname, TRUE);
1754     if ( element == NULL )
1755     {
1756         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_ERROR, "Cannot store interface %s, maybe duplicate?", extcap );
1757         g_list_foreach(interfaces, remove_extcap_entry, NULL);
1758         g_list_free(interfaces);
1759         g_list_free(interface_keys);
1760         g_free(toolname);
1761         return;
1762     }
1763
1764     if (control_items)
1765     {
1766         toolbar_entry = g_new0(iface_toolbar, 1);
1767         toolbar_entry->controls = control_items;
1768     }
1769
1770     walker = interfaces;
1771     gchar* help = NULL;
1772     while (walker != NULL)
1773     {
1774         int_iter = (extcap_interface *)walker->data;
1775
1776         if (int_iter->call != NULL)
1777             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Interface found %s\n", int_iter->call);
1778
1779         /* Help is not necessarily stored with the interface, but rather with the version string.
1780          * As the version string allways comes in front of the interfaces, this ensures, that it get's
1781          * properly stored with the interface */
1782         if (int_iter->if_type == EXTCAP_SENTENCE_EXTCAP)
1783         {
1784             if (int_iter->call != NULL)
1785                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Extcap [%s] ", int_iter->call);
1786
1787             /* Only initialize values if none are set. Need to check only one element here */
1788             if ( ! element->version )
1789             {
1790                 element->version = g_strdup(int_iter->version);
1791                 element->basename = g_strdup(toolname);
1792                 element->full_path = g_strdup(extcap);
1793                 element->help = g_strdup(int_iter->help);
1794             }
1795
1796             help = int_iter->help;
1797             if (toolbar_entry)
1798             {
1799                 toolbar_entry->menu_title = g_strdup(int_iter->display);
1800                 toolbar_entry->help = g_strdup(int_iter->help);
1801             }
1802
1803             walker = g_list_next(walker);
1804             continue;
1805         }
1806
1807         /* Only interface definitions will be parsed here. help is already set by the extcap element,
1808          * which makes it necessary to have version in the list before the interfaces. This is normally
1809          * the case by design, but could be changed by separating the information in extcap-base. */
1810         if ( int_iter->if_type == EXTCAP_SENTENCE_INTERFACE )
1811         {
1812             if ( g_list_find(interface_keys, int_iter->call) )
1813             {
1814                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_WARNING, "Extcap interface \"%s\" is already provided by \"%s\" ",
1815                       int_iter->call, extcap_if_executable(int_iter->call));
1816                 walker = g_list_next(walker);
1817                 continue;
1818             }
1819
1820             if ((int_iter->call != NULL) && (int_iter->display))
1821                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Interface [%s] \"%s\" ", int_iter->call, int_iter->display);
1822
1823             int_iter->extcap_path = g_strdup(extcap);
1824
1825             /* Only set the help, if it exists and no parsed help information is present */
1826             if ( ! int_iter->help && help )
1827                 int_iter->help = g_strdup(help);
1828
1829             element->interfaces = g_list_append(element->interfaces, int_iter);
1830             g_hash_table_insert(_tool_for_ifname, g_strdup(int_iter->call), g_strdup(toolname));
1831
1832             if (toolbar_entry)
1833             {
1834                 if (!toolbar_entry->menu_title)
1835                 {
1836                     toolbar_entry->menu_title = g_strdup(int_iter->display);
1837                 }
1838                 toolbar_entry->ifnames = g_list_append(toolbar_entry->ifnames, g_strdup(int_iter->call));
1839             }
1840         }
1841
1842         walker = g_list_next(walker);
1843     }
1844
1845     if (toolbar_entry && toolbar_entry->menu_title)
1846     {
1847         iface_toolbar_add(toolbar_entry);
1848         extcap_iface_toolbar_add(extcap, toolbar_entry);
1849     }
1850
1851     g_list_foreach(interfaces, remove_extcap_entry, NULL);
1852     g_list_free(interfaces);
1853     g_list_free(interface_keys);
1854     g_free(toolname);
1855 }
1856
1857
1858 /** Thread callback to save the output of a --extcap-config call. */
1859 static void
1860 extcap_process_config_cb(thread_pool_t *pool _U_, void *data, char *output)
1861 {
1862     extcap_iface_info_t *iface_info = (extcap_iface_info_t *)data;
1863     iface_info->output = output;
1864 }
1865
1866 /**
1867  * Thread callback to process discovered interfaces, scheduling more tasks to
1868  * retrieve the configuration for each interface. Called once for every extcap
1869  * program.
1870  */
1871 static void
1872 extcap_process_interfaces_cb(thread_pool_t *pool, void *data, char *output)
1873 {
1874     extcap_run_extcaps_info_t *info = (extcap_run_extcaps_info_t *)data;
1875     guint i = 0;
1876     guint num_interfaces = 0;
1877
1878     if (!output) {
1879         // No interfaces available, nothing to do.
1880         return;
1881     }
1882
1883     // Save output for process_new_extcap.
1884     info->output = output;
1885
1886     // Are there any interfaces to query information from?
1887     GList *interfaces = extcap_parse_interfaces(output, NULL);
1888     for (GList *iface = interfaces; iface; iface = g_list_next(iface)) {
1889         extcap_interface *intf = (extcap_interface *)iface->data;
1890         if (intf->if_type == EXTCAP_SENTENCE_INTERFACE) {
1891             ++num_interfaces;
1892         }
1893     }
1894     if (num_interfaces == 0) {
1895         // nothing to do.
1896         g_list_free_full(interfaces, extcap_free_interface);
1897         return;
1898     }
1899
1900     /* GSList is not thread-safe, so pre-allocate an array instead. */
1901     info->iface_infos = g_new0(extcap_iface_info_t, num_interfaces);
1902     info->num_interfaces = num_interfaces;
1903
1904     // Schedule new commands to retrieve the configuration.
1905     for (GList *iface = interfaces; iface; iface = g_list_next(iface)) {
1906         extcap_interface *intf = (extcap_interface *)iface->data;
1907         if (intf->if_type != EXTCAP_SENTENCE_INTERFACE) {
1908             continue;
1909         }
1910
1911         const char *argv[] = {
1912             EXTCAP_ARGUMENT_CONFIG,
1913             EXTCAP_ARGUMENT_INTERFACE,
1914             intf->call,
1915             NULL
1916         };
1917         extcap_run_task_t *task = g_new0(extcap_run_task_t, 1);
1918         extcap_iface_info_t *iface_info = &info->iface_infos[i++];
1919
1920         task->extcap_path = info->extcap_path;
1921         task->argv = g_strdupv((char **)argv);
1922         task->output_cb = extcap_process_config_cb;
1923         task->data = iface_info;
1924         iface_info->ifname = g_strdup(intf->call);
1925
1926         thread_pool_push(pool, task, NULL);
1927     }
1928     g_list_free_full(interfaces, extcap_free_interface);
1929 }
1930
1931 /**
1932  * Thread callback to check whether the new-style --list-interfaces call with an
1933  * explicit function succeeded. If not, schedule a call without the new version
1934  * argument.
1935  */
1936 static void
1937 extcap_list_interfaces_cb(thread_pool_t *pool, void *data, char *output)
1938 {
1939     extcap_run_extcaps_info_t *info = (extcap_run_extcaps_info_t *)data;
1940
1941     if (!output) {
1942         /* No output available, schedule a fallback query. */
1943         const char *argv[] = {
1944             EXTCAP_ARGUMENT_LIST_INTERFACES,
1945             NULL
1946         };
1947         extcap_run_task_t *task = g_new0(extcap_run_task_t, 1);
1948
1949         task->extcap_path = info->extcap_path;
1950         task->argv = g_strdupv((char **)argv);
1951         task->output_cb = extcap_process_interfaces_cb;
1952         task->data = info;
1953
1954         thread_pool_push(pool, task, NULL);
1955     } else {
1956         extcap_process_interfaces_cb(pool, info, output);
1957     }
1958 }
1959
1960
1961 /* Handles loading of the interfaces. */
1962 static void
1963 extcap_load_interface_list(void)
1964 {
1965     if (prefs.capture_no_extcap)
1966         return;
1967
1968     if (_toolbars)
1969     {
1970         // Remove existing interface toolbars here instead of in extcap_clear_interfaces()
1971         // to avoid flicker in shown toolbars when refreshing interfaces.
1972         GList *toolbar_list = g_hash_table_get_values (_toolbars);
1973         for (GList *walker = toolbar_list; walker; walker = walker->next)
1974         {
1975             iface_toolbar *toolbar = (iface_toolbar *) walker->data;
1976             iface_toolbar_remove(toolbar->menu_title);
1977         }
1978         g_list_free(toolbar_list);
1979         g_hash_table_remove_all(_toolbars);
1980     } else {
1981         _toolbars = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_toolbar);
1982     }
1983
1984     if (_loaded_interfaces == NULL)
1985     {
1986         int major = 0;
1987         int minor = 0;
1988         guint count = 0;
1989         extcap_run_extcaps_info_t *infos;
1990         GList *unused_arguments = NULL;
1991
1992         _loaded_interfaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_interface_info);
1993         /* Cleanup lookup table */
1994         if ( _tool_for_ifname )
1995         {
1996             g_hash_table_remove_all(_tool_for_ifname);
1997             _tool_for_ifname = 0;
1998         } else {
1999             _tool_for_ifname = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
2000         }
2001
2002         get_ws_version_number(&major, &minor, NULL);
2003         char *arg_version = g_strdup_printf("%s=%d.%d", EXTCAP_ARGUMENT_VERSION, major, minor);
2004         const char *argv[] = {
2005             EXTCAP_ARGUMENT_LIST_INTERFACES,
2006             arg_version,
2007             NULL
2008         };
2009         infos = (extcap_run_extcaps_info_t *)extcap_run_all(argv,
2010                 extcap_list_interfaces_cb, sizeof(extcap_run_extcaps_info_t),
2011                 &count);
2012         for (guint i = 0; i < count; i++) {
2013             if (!infos[i].output) {
2014                 continue;
2015             }
2016
2017             // Save new extcap and each discovered interface.
2018             process_new_extcap(infos[i].extcap_path, infos[i].output);
2019             for (guint j = 0; j < infos[i].num_interfaces; j++) {
2020                 extcap_iface_info_t *iface_info = &infos[i].iface_infos[j];
2021
2022                 if (!iface_info->output) {
2023                     continue;
2024                 }
2025
2026                 extcap_callback_info_t cb_info = {
2027                     .ifname = iface_info->ifname,
2028                     .output = iface_info->output,
2029                     .data = &unused_arguments,
2030                 };
2031                 cb_preference(cb_info);
2032             }
2033         }
2034         /* XXX rework cb_preference such that this unused list can be removed. */
2035         extcap_free_if_configuration(unused_arguments, TRUE);
2036         extcap_free_extcaps_info_array(infos, count);
2037         g_free(arg_version);
2038     }
2039 }
2040
2041 /*
2042  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
2043  *
2044  * Local variables:
2045  * c-basic-offset: 4
2046  * tab-width: 8
2047  * indent-tabs-mode: nil
2048  * End:
2049  *
2050  * vi: set shiftwidth=4 tabstop=8 expandtab:
2051  * :indentSize=4:tabSize=8:noTabs=true:
2052  */