Put special pipe-handling code into libwsutil.
[metze/wireshark/wip.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+
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 #ifdef HAVE_SYS_TYPES_H
29 #include <sys/types.h>
30 #endif
31 #ifdef HAVE_SYS_WAIT_H
32 #include <sys/wait.h>
33 #endif
34
35 #include <glib.h>
36 #include <log.h>
37
38 #include <epan/prefs.h>
39
40 #include "ui/iface_toolbar.h"
41
42 #include <wsutil/glib-compat.h>
43 #include <wsutil/file_util.h>
44 #include <wsutil/filesystem.h>
45 #include <wsutil/ws_pipe.h>
46 #include <wsutil/tempfile.h>
47
48 #include "capture_opts.h"
49
50 #include "extcap.h"
51 #include "extcap_parser.h"
52 #include "extcap_spawn.h"
53
54 #ifdef _WIN32
55 static HANDLE pipe_h = INVALID_HANDLE_VALUE;
56 #endif
57
58 static void extcap_child_watch_cb(GPid pid, gint status, gpointer user_data);
59
60 /* internal container, for all the extcap executables that have been found.
61  * Will be resetted if extcap_clear_interfaces() is being explicitly called
62  * and is being used for printing information about all extcap interfaces found,
63  * as well as storing all sub-interfaces
64  */
65 static GHashTable * _loaded_interfaces = NULL;
66
67 /* Internal container, which maps each ifname to the tool providing it, for faster
68  * lookup. The key and string value are owned by this table.
69  */
70 static GHashTable * _tool_for_ifname = NULL;
71
72 /* internal container, for all the extcap executables that have been found
73  * and that provides a toolbar with controls to be added to a Interface Toolbar
74  */
75 static GHashTable *_toolbars = NULL;
76
77 /* internal container, to map preference names to pointers that hold preference
78  * values. These ensure that preferences can survive extcap if garbage
79  * collection, and does not lead to dangling pointers in the prefs subsystem.
80  */
81 static GHashTable *extcap_prefs_dynamic_vals = NULL;
82
83 typedef struct _extcap_callback_info_t
84 {
85     const gchar * extcap;
86     const gchar * ifname;
87     gchar * output;
88     void * data;
89     gchar ** err_str;
90 } extcap_callback_info_t;
91
92 /* Callback definition for extcap_foreach */
93 typedef gboolean(*extcap_cb_t)(extcap_callback_info_t info_structure);
94
95 static void extcap_load_interface_list(void);
96
97 GHashTable *
98 extcap_loaded_interfaces(void)
99 {
100     if ( !_loaded_interfaces || g_hash_table_size(_loaded_interfaces) == 0 )
101         extcap_load_interface_list();
102
103     return _loaded_interfaces;
104 }
105
106 void
107 extcap_clear_interfaces(void)
108 {
109     if ( _loaded_interfaces )
110         g_hash_table_destroy(_loaded_interfaces);
111     _loaded_interfaces = NULL;
112
113     if ( _tool_for_ifname )
114         g_hash_table_destroy(_tool_for_ifname);
115     _tool_for_ifname = NULL;
116 }
117
118 guint extcap_count(void)
119 {
120     const char *dirname = get_extcap_dir();
121     GDir *dir;
122     guint count;
123
124     count = 0;
125
126     if ((dir = g_dir_open(dirname, 0, NULL)) != NULL)
127     {
128         GString *extcap_path = NULL;
129         const gchar *file;
130
131         extcap_path = g_string_new("");
132         while ((file = g_dir_read_name(dir)) != NULL)
133         {
134             /* full path to extcap binary */
135             g_string_printf(extcap_path, "%s" G_DIR_SEPARATOR_S "%s", dirname, file);
136             /* treat anything executable as an extcap binary */
137             if (g_file_test(extcap_path->str, G_FILE_TEST_IS_REGULAR) &&
138                 g_file_test(extcap_path->str, G_FILE_TEST_IS_EXECUTABLE))
139             {
140                 count++;
141             }
142         }
143
144         g_dir_close(dir);
145         g_string_free(extcap_path, TRUE);
146     }
147     return count;
148 }
149
150 static gboolean
151 extcap_if_exists(const gchar *ifname)
152 {
153     if (!ifname || !_tool_for_ifname)
154     {
155         return FALSE;
156     }
157
158     if (g_hash_table_lookup(_tool_for_ifname, ifname))
159     {
160         return TRUE;
161     }
162
163     return FALSE;
164 }
165
166 static extcap_interface *
167 extcap_find_interface_for_ifname(const gchar *ifname)
168 {
169     extcap_interface * result = NULL;
170
171     if ( !ifname || ! _tool_for_ifname || ! _loaded_interfaces )
172         return result;
173
174     gchar * extcap_util = (gchar *)g_hash_table_lookup(_tool_for_ifname, ifname);
175     if ( ! extcap_util )
176         return result;
177
178     extcap_info * element = (extcap_info *)g_hash_table_lookup(_loaded_interfaces, extcap_util);
179     if ( ! element )
180         return result;
181
182     GList * walker = element->interfaces;
183     while ( walker && walker->data && ! result )
184     {
185         extcap_interface * interface = (extcap_interface *)walker->data;
186         if ( g_strcmp0(interface->call, ifname) == 0 )
187         {
188             result = interface;
189             break;
190         }
191
192         walker = g_list_next ( walker );
193     }
194
195     return result;
196 }
197
198 static void
199 extcap_free_toolbar_value(iface_toolbar_value *value)
200 {
201     if (!value)
202     {
203         return;
204     }
205
206     g_free(value->value);
207     g_free(value->display);
208     g_free(value);
209 }
210
211 static void
212 extcap_free_toolbar_control(iface_toolbar_control *control)
213 {
214     if (!control)
215     {
216         return;
217     }
218
219     g_free(control->display);
220     g_free(control->validation);
221     g_free(control->tooltip);
222     if (control->ctrl_type == INTERFACE_TYPE_STRING) {
223         g_free(control->default_value.string);
224     }
225     g_list_foreach(control->values, (GFunc)extcap_free_toolbar_value, NULL);
226     g_list_free(control->values);
227     g_free(control);
228 }
229
230 static void
231 extcap_free_toolbar(gpointer data)
232 {
233     if (!data)
234     {
235         return;
236     }
237
238     iface_toolbar *toolbar = (iface_toolbar *)data;
239
240     g_free(toolbar->menu_title);
241     g_free(toolbar->help);
242     g_list_free_full(toolbar->ifnames, g_free);
243     g_list_foreach(toolbar->controls, (GFunc)extcap_free_toolbar_control, NULL);
244     g_list_free(toolbar->controls);
245     g_free(toolbar);
246 }
247
248 static gboolean
249 extcap_if_exists_for_extcap(const gchar *ifname, const gchar *extcap)
250 {
251     extcap_interface *entry = extcap_find_interface_for_ifname(ifname);
252
253     if (entry && strcmp(entry->extcap_path, extcap) == 0)
254     {
255         return TRUE;
256     }
257
258     return FALSE;
259 }
260
261 static gchar *
262 extcap_if_executable(const gchar *ifname)
263 {
264     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
265     return interface != NULL ? interface->extcap_path : NULL;
266 }
267
268 static void
269 extcap_iface_toolbar_add(const gchar *extcap, iface_toolbar *toolbar_entry)
270 {
271     char *toolname;
272
273     if (!extcap || !toolbar_entry)
274     {
275         return;
276     }
277
278     toolname = g_path_get_basename(extcap);
279
280     if (!g_hash_table_lookup(_toolbars, toolname))
281     {
282         g_hash_table_insert(_toolbars, g_strdup(toolname), toolbar_entry);
283     }
284
285     g_free(toolname);
286 }
287
288 /* Note: args does not need to be NULL-terminated. */
289 static gboolean extcap_foreach(gint argc, gchar **args,
290                                       extcap_cb_t cb, extcap_callback_info_t cb_info)
291 {
292     GDir *dir;
293     gboolean keep_going;
294     const char *dirname = get_extcap_dir();
295
296     keep_going = TRUE;
297
298     if ((dir = g_dir_open(dirname, 0, NULL)) != NULL)
299     {
300         GString *extcap_path = NULL;
301         const gchar *file;
302
303         extcap_path = g_string_new("");
304         while (keep_going && (file = g_dir_read_name(dir)) != NULL)
305         {
306             gchar *command_output = NULL;
307
308             /* full path to extcap binary */
309             g_string_printf(extcap_path, "%s" G_DIR_SEPARATOR_S "%s", dirname, file);
310             /* treat anything executable as an extcap binary */
311             if (g_file_test(extcap_path->str, G_FILE_TEST_IS_REGULAR) &&
312                 g_file_test(extcap_path->str, G_FILE_TEST_IS_EXECUTABLE))
313             {
314                 if (extcap_if_exists(cb_info.ifname) && !extcap_if_exists_for_extcap(cb_info.ifname, extcap_path->str))
315                 {
316                     continue;
317                 }
318
319                 if (extcap_spawn_sync((gchar *) dirname, extcap_path->str, argc, args, &command_output))
320                 {
321                     cb_info.output = command_output;
322                     cb_info.extcap = extcap_path->str;
323
324                     keep_going = cb(cb_info);
325                 }
326
327                 g_free(command_output);
328             }
329         }
330
331         g_dir_close(dir);
332         g_string_free(extcap_path, TRUE);
333     }
334
335     return keep_going;
336 }
337
338 static void extcap_free_dlt(gpointer d, gpointer user_data _U_)
339 {
340     if (d == NULL)
341     {
342         return;
343     }
344
345     g_free(((extcap_dlt *)d)->name);
346     g_free(((extcap_dlt *)d)->display);
347     g_free(d);
348 }
349
350 static void extcap_free_dlts(GList *dlts)
351 {
352     g_list_foreach(dlts, extcap_free_dlt, NULL);
353     g_list_free(dlts);
354 }
355
356 static gboolean cb_dlt(extcap_callback_info_t cb_info)
357 {
358     GList *dlts = NULL, *temp = NULL;
359
360     if_capabilities_t *caps;
361     GList *linktype_list = NULL;
362     data_link_info_t *data_link_info;
363     extcap_dlt *dlt_item;
364
365     dlts = extcap_parse_dlts(cb_info.output);
366     temp = dlts;
367
368     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap pipe %s ", cb_info.extcap);
369
370     /*
371      * Allocate the interface capabilities structure.
372      */
373     caps = (if_capabilities_t *) g_malloc(sizeof * caps);
374     caps->can_set_rfmon = FALSE;
375     caps->timestamp_types = NULL;
376
377     while (dlts)
378     {
379         dlt_item = (extcap_dlt *)dlts->data;
380         if (dlt_item)
381         {
382             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
383                   "  DLT %d name=\"%s\" display=\"%s\" ", dlt_item->number,
384                   dlt_item->name, dlt_item->display);
385
386             data_link_info = g_new(data_link_info_t, 1);
387             data_link_info->dlt = dlt_item->number;
388             data_link_info->name = g_strdup(dlt_item->name);
389             data_link_info->description = g_strdup(dlt_item->display);
390             linktype_list = g_list_append(linktype_list, data_link_info);
391         }
392
393         dlts = g_list_next(dlts);
394     }
395
396     /* Check to see if we built a list */
397     if (linktype_list != NULL && cb_info.data != NULL)
398     {
399         caps->data_link_types = linktype_list;
400         *(if_capabilities_t **) cb_info.data = caps;
401     }
402     else
403     {
404         if (cb_info.err_str)
405         {
406             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  returned no DLTs");
407             *(cb_info.err_str) = g_strdup("Extcap returned no DLTs");
408         }
409         g_free(caps);
410     }
411
412     extcap_free_dlts(temp);
413
414     return FALSE;
415 }
416
417 if_capabilities_t *
418 extcap_get_if_dlts(const gchar *ifname, char **err_str)
419 {
420     gchar *argv[3];
421     gint i;
422     if_capabilities_t *caps = NULL;
423
424     if (err_str != NULL)
425     {
426         *err_str = NULL;
427     }
428
429     if (extcap_if_exists(ifname))
430     {
431         argv[0] = g_strdup(EXTCAP_ARGUMENT_LIST_DLTS);
432         argv[1] = g_strdup(EXTCAP_ARGUMENT_INTERFACE);
433         argv[2] = g_strdup(ifname);
434
435         extcap_callback_info_t cb_info;
436         cb_info.data = &caps;
437         cb_info.err_str = err_str;
438         cb_info.ifname = ifname;
439
440         extcap_foreach(3, argv, cb_dlt, cb_info);
441
442         for (i = 0; i < 3; ++i)
443         {
444             g_free(argv[i]);
445         }
446     }
447
448     return caps;
449 }
450
451 static void extcap_free_interface(gpointer i)
452 {
453
454     extcap_interface *interface = (extcap_interface *)i;
455
456     if (i == NULL)
457     {
458         return;
459     }
460
461     g_free(interface->call);
462     g_free(interface->display);
463     g_free(interface->version);
464     g_free(interface->help);
465     g_free(interface->extcap_path);
466     g_free(interface);
467 }
468
469 static void extcap_free_interfaces(GList *interfaces)
470 {
471     if (interfaces == NULL)
472     {
473         return;
474     }
475
476     g_list_foreach(interfaces, (GFunc)extcap_free_interface, NULL);
477     g_list_free(interfaces);
478 }
479
480 static gint
481 if_info_compare(gconstpointer a, gconstpointer b)
482 {
483     gint comp = 0;
484     const if_info_t *if_a = (const if_info_t *)a;
485     const if_info_t *if_b = (const if_info_t *)b;
486
487     if ((comp = g_strcmp0(if_a->name, if_b->name)) == 0)
488     {
489         return g_strcmp0(if_a->friendly_name, if_b->friendly_name);
490     }
491
492     return comp;
493 }
494
495 gchar *
496 extcap_get_help_for_ifname(const char *ifname)
497 {
498     extcap_interface *interface = extcap_find_interface_for_ifname(ifname);
499     return interface != NULL ? interface->help : NULL;
500 }
501
502 GList *
503 append_extcap_interface_list(GList *list, char **err_str _U_)
504 {
505     GList *interface_list = NULL;
506     extcap_interface *data = NULL;
507     GList *ifutilkeys_head = NULL, *ifutilkeys = NULL;
508
509     /* Update the extcap interfaces and get a list of their if_infos */
510     if ( !_loaded_interfaces || g_hash_table_size(_loaded_interfaces) == 0 )
511         extcap_load_interface_list();
512
513     ifutilkeys_head = g_hash_table_get_keys(_loaded_interfaces);
514     ifutilkeys = ifutilkeys_head;
515     while ( ifutilkeys && ifutilkeys->data )
516     {
517         extcap_info * extinfo =
518                 (extcap_info *) g_hash_table_lookup(_loaded_interfaces, (gchar *)ifutilkeys->data);
519         GList * walker = extinfo->interfaces;
520         while ( walker && walker->data )
521         {
522             interface_list = g_list_append(interface_list, walker->data);
523             walker = g_list_next(walker);
524         }
525
526         ifutilkeys = g_list_next(ifutilkeys);
527     }
528     g_list_free(ifutilkeys_head);
529
530     /* Sort that list */
531     interface_list = g_list_sort(interface_list, if_info_compare);
532
533     /* Append the interfaces in that list to the list we're handed. */
534     while (interface_list != NULL)
535     {
536         GList *entry = g_list_first(interface_list);
537         data = (extcap_interface *)entry->data;
538         interface_list = g_list_delete_link(interface_list, entry);
539
540         if_info_t * if_info = g_new0(if_info_t, 1);
541         if_info->name = g_strdup(data->call);
542         if_info->friendly_name = g_strdup(data->display);
543
544         if_info->type = IF_EXTCAP;
545
546         if_info->extcap = g_strdup(data->extcap_path);
547
548         list = g_list_append(list, if_info);
549     }
550
551     return list;
552 }
553
554 static void
555 extcap_register_preferences_callback(gpointer key, gpointer value _U_, gpointer user_data _U_)
556 {
557     GList *arguments;
558
559     arguments = extcap_get_if_configuration((gchar *)key);
560     /* Memory for prefs are external to an interface, they are part of
561      * extcap core, so the parsed arguments can be freed. */
562     extcap_free_if_configuration(arguments, TRUE);
563 }
564
565 void extcap_register_preferences(void)
566 {
567     module_t *dev_module = prefs_find_module("extcap");
568
569     if (!dev_module)
570     {
571         return;
572     }
573
574     if ( !_loaded_interfaces || g_hash_table_size(_loaded_interfaces) == 0 )
575         extcap_load_interface_list();
576
577
578     g_hash_table_foreach(_tool_for_ifname, extcap_register_preferences_callback, NULL);
579 }
580
581 /**
582  * Releases the dynamic preference value pointers. Must not be called before
583  * prefs_cleanup since these pointers could still be in use.
584  */
585 void extcap_cleanup(void)
586 {
587     if (extcap_prefs_dynamic_vals)
588         g_hash_table_destroy(extcap_prefs_dynamic_vals);
589
590     if (_loaded_interfaces)
591         g_hash_table_destroy(_loaded_interfaces);
592
593     if (_tool_for_ifname)
594         g_hash_table_destroy(_tool_for_ifname);
595 }
596
597 /**
598  * Obtains a pointer which can store a value for the given preference name.
599  * The preference name that can be passed to the prefs API is stored into
600  * 'prefs_name'.
601  *
602  * Extcap interfaces (and their preferences) are dynamic, they can be created
603  * and destroyed at will. Thus their data structures are insufficient to pass to
604  * the preferences APIs which require pointers which are valid until the
605  * preferences are removed (at exit).
606  */
607 static gchar **extcap_prefs_dynamic_valptr(const char *name, char **pref_name)
608 {
609     gchar **valp;
610     if (!extcap_prefs_dynamic_vals)
611     {
612         /* Initialize table only as needed, most preferences are not dynamic */
613         extcap_prefs_dynamic_vals = g_hash_table_new_full(g_str_hash, g_str_equal,
614                                     g_free, g_free);
615     }
616     if (!g_hash_table_lookup_extended(extcap_prefs_dynamic_vals, name,
617                                       (gpointer *)pref_name, (gpointer *)&valp))
618     {
619         /* New dynamic pref, allocate, initialize and store. */
620         valp = g_new0(gchar *, 1);
621         *pref_name = g_strdup(name);
622         g_hash_table_insert(extcap_prefs_dynamic_vals, *pref_name, valp);
623     }
624     return valp;
625 }
626
627 void extcap_free_if_configuration(GList *list, gboolean free_args)
628 {
629     GList *elem, *sl;
630
631     for (elem = g_list_first(list); elem; elem = elem->next)
632     {
633         if (elem->data != NULL)
634         {
635             sl = g_list_first((GList *)elem->data);
636             if (free_args)
637             {
638                 extcap_free_arg_list(sl);
639             }
640             else
641             {
642                 g_list_free(sl);
643             }
644         }
645     }
646     g_list_free(list);
647 }
648
649 struct preference *
650 extcap_pref_for_argument(const gchar *ifname, struct _extcap_arg *arg)
651 {
652     struct preference *pref = NULL;
653
654     GRegex *regex_name = g_regex_new("[-]+", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
655     GRegex *regex_ifname = g_regex_new("(?![a-zA-Z1-9_]).", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
656     if (regex_name && regex_ifname)
657     {
658         if (prefs_find_module("extcap"))
659         {
660             gchar *pref_name = g_regex_replace(regex_name, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL);
661             gchar *ifname_underscore = g_regex_replace(regex_ifname, ifname, strlen(ifname), 0, "_", (GRegexMatchFlags) 0, NULL);
662             gchar *ifname_lowercase = g_ascii_strdown(ifname_underscore, -1);
663             gchar *pref_ifname = g_strconcat(ifname_lowercase, ".", pref_name, NULL);
664
665             pref = prefs_find_preference(prefs_find_module("extcap"), pref_ifname);
666
667             g_free(pref_name);
668             g_free(ifname_underscore);
669             g_free(ifname_lowercase);
670             g_free(pref_ifname);
671         }
672     }
673     if (regex_name)
674     {
675         g_regex_unref(regex_name);
676     }
677     if (regex_ifname)
678     {
679         g_regex_unref(regex_ifname);
680     }
681
682     return pref;
683 }
684
685 static gboolean cb_preference(extcap_callback_info_t cb_info)
686 {
687     GList *arguments = NULL;
688     GList **il = (GList **) cb_info.data;
689     module_t *dev_module = NULL;
690
691     arguments = extcap_parse_args(cb_info.output);
692
693     dev_module = prefs_find_module("extcap");
694
695     if (dev_module)
696     {
697         GList *walker = arguments;
698
699         GRegex *regex_name = g_regex_new("[-]+", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
700         GRegex *regex_ifname = g_regex_new("(?![a-zA-Z1-9_]).", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
701         if (regex_name && regex_ifname)
702         {
703             while (walker != NULL)
704             {
705                 extcap_arg *arg = (extcap_arg *)walker->data;
706                 arg->device_name = g_strdup(cb_info.ifname);
707
708                 if (arg->save)
709                 {
710                     struct preference *pref = NULL;
711
712                     gchar *pref_name = g_regex_replace(regex_name, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL);
713                     gchar *ifname_underscore = g_regex_replace(regex_ifname, cb_info.ifname, strlen(cb_info.ifname), 0, "_", (GRegexMatchFlags) 0, NULL);
714                     gchar *ifname_lowercase = g_ascii_strdown(ifname_underscore, -1);
715                     gchar *pref_ifname = g_strconcat(ifname_lowercase, ".", pref_name, NULL);
716
717                     if ((pref = prefs_find_preference(dev_module, pref_ifname)) == NULL)
718                     {
719                         char *pref_name_for_prefs;
720                         char *pref_title = wmem_strdup(wmem_epan_scope(), arg->display);
721
722                         arg->pref_valptr = extcap_prefs_dynamic_valptr(pref_ifname, &pref_name_for_prefs);
723                         /* Set an initial value if any (the string will be copied at registration) */
724                         if (arg->default_complex)
725                         {
726                             *arg->pref_valptr = arg->default_complex->_val;
727                         }
728
729                         prefs_register_string_preference(dev_module, pref_name_for_prefs,
730                                                          pref_title, pref_title, (const char **)arg->pref_valptr);
731                     }
732                     else
733                     {
734                         /* Been here before, restore stored value */
735                         if (arg->pref_valptr == NULL)
736                         {
737                             arg->pref_valptr = (gchar**)g_hash_table_lookup(extcap_prefs_dynamic_vals, pref_ifname);
738                         }
739                     }
740
741                     g_free(pref_name);
742                     g_free(ifname_underscore);
743                     g_free(ifname_lowercase);
744                     g_free(pref_ifname);
745                 }
746
747                 walker = g_list_next(walker);
748             }
749         }
750         if (regex_name)
751         {
752             g_regex_unref(regex_name);
753         }
754         if (regex_ifname)
755         {
756             g_regex_unref(regex_ifname);
757         }
758     }
759
760     *il = g_list_append(*il, arguments);
761
762     /* By returning false, extcap_foreach will break on first found */
763     return TRUE;
764 }
765
766 GList *
767 extcap_get_if_configuration(const char *ifname)
768 {
769     gchar *argv[3];
770     GList *ret = NULL;
771     gchar **err_str = NULL;
772     int i;
773
774     if (extcap_if_exists(ifname))
775     {
776         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
777               get_extcap_dir());
778
779         argv[0] = g_strdup(EXTCAP_ARGUMENT_CONFIG);
780         argv[1] = g_strdup(EXTCAP_ARGUMENT_INTERFACE);
781         argv[2] = g_strdup(ifname);
782
783         extcap_callback_info_t cb_info;
784         cb_info.data = &ret;
785         cb_info.err_str = err_str;
786         cb_info.ifname = ifname;
787
788         extcap_foreach(3, argv, cb_preference, cb_info);
789
790         for (i = 0; i < 3; i++)
791         {
792             g_free(argv[i]);
793         }
794     }
795
796     return ret;
797 }
798
799 /**
800  * If is_required is FALSE: returns TRUE if the extcap interface has
801  * configurable options.
802  * If is_required is TRUE: returns TRUE when the extcap interface has
803  * configurable options that required modification. (For example, when an
804  * argument is required but empty.)
805  */
806 gboolean
807 extcap_has_configuration(const char *ifname, gboolean is_required)
808 {
809     GList *arguments = 0;
810     GList *walker = 0, * item = 0;
811
812     gboolean found = FALSE;
813
814     arguments = extcap_get_if_configuration((const char *)(ifname));
815     walker = g_list_first(arguments);
816
817     while (walker != NULL && !found)
818     {
819         item = g_list_first((GList *)(walker->data));
820         while (item != NULL && !found)
821         {
822             if ((extcap_arg *)(item->data) != NULL)
823             {
824                 extcap_arg *arg = (extcap_arg *)(item->data);
825                 /* Should required options be present, or any kind of options */
826                 if (!is_required)
827                 {
828                     found = TRUE;
829                 }
830                 else if (arg->is_required)
831                 {
832                     const gchar *stored = NULL;
833                     const gchar *defval = NULL;
834
835                     if (arg->pref_valptr != NULL)
836                     {
837                         stored = *arg->pref_valptr;
838                     }
839
840                     if (arg->default_complex != NULL && arg->default_complex->_val != NULL)
841                     {
842                         defval = arg->default_complex->_val;
843                     }
844
845                     if (arg->is_required)
846                     {
847                         /* If stored and defval is identical and the argument is required,
848                          * configuration is needed */
849                         if (defval && stored && g_strcmp0(stored, defval) == 0)
850                         {
851                             found = TRUE;
852                         }
853                         else if (!defval && (!stored || !*stored))
854                         {
855                             found = TRUE;
856                         }
857                     }
858
859                     if (arg->arg_type == EXTCAP_ARG_FILESELECT)
860                     {
861                         if (arg->fileexists && !(file_exists(defval) || file_exists(stored)))
862                         {
863                             found = TRUE;
864                         }
865                     }
866                 }
867             }
868
869             item = item->next;
870         }
871         walker = walker->next;
872     }
873     extcap_free_if_configuration(arguments, TRUE);
874
875     return found;
876 }
877
878 static gboolean cb_verify_filter(extcap_callback_info_t cb_info)
879 {
880     extcap_filter_status *status = (extcap_filter_status *)cb_info.data;
881     size_t output_size, i;
882
883     output_size = strlen(cb_info.output);
884     if (output_size == 0) {
885         *status = EXTCAP_FILTER_VALID;
886     } else {
887         *status = EXTCAP_FILTER_INVALID;
888         for (i = 0; i < output_size; i++) {
889             if (cb_info.output[i] == '\n' || cb_info.output[i] == '\r') {
890                 cb_info.output[i] = '\0';
891                 break;
892             }
893         }
894         *cb_info.err_str = g_strdup(cb_info.output);
895     }
896
897     return TRUE;
898 }
899
900 extcap_filter_status
901 extcap_verify_capture_filter(const char *ifname, const char *filter, gchar **err_str)
902 {
903     gchar *argv[4];
904     extcap_filter_status status = EXTCAP_FILTER_UNKNOWN;
905
906     if (extcap_if_exists(ifname))
907     {
908         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
909               get_extcap_dir());
910
911         argv[0] = EXTCAP_ARGUMENT_CAPTURE_FILTER;
912         argv[1] = (gchar*)filter;
913         argv[2] = EXTCAP_ARGUMENT_INTERFACE;
914         argv[3] = (gchar*)ifname;
915
916         extcap_callback_info_t cb_info;
917         cb_info.data = &status;
918         cb_info.err_str = err_str;
919         cb_info.ifname = ifname;
920
921         extcap_foreach(4, argv, cb_verify_filter, cb_info);
922     }
923
924     return status;
925 }
926
927 gboolean
928 extcap_has_toolbar(const char *ifname)
929 {
930     if (!iface_toolbar_use())
931     {
932         return FALSE;
933     }
934
935     GList *toolbar_list = g_hash_table_get_values (_toolbars);
936     for (GList *walker = toolbar_list; walker; walker = walker->next)
937     {
938         iface_toolbar *toolbar = (iface_toolbar *) walker->data;
939         if (g_list_find_custom(toolbar->ifnames, ifname, (GCompareFunc) strcmp))
940         {
941             return TRUE;
942         }
943     }
944
945     return FALSE;
946 }
947
948 void extcap_if_cleanup(capture_options *capture_opts, gchar **errormsg)
949 {
950     interface_options *interface_opts;
951     extcap_userdata *userdata;
952     guint icnt = 0;
953     gboolean overwrite_exitcode;
954     gchar *buffer;
955 #define STDERR_BUFFER_SIZE 1024
956
957     for (icnt = 0; icnt < capture_opts->ifaces->len; icnt++)
958     {
959         interface_opts = &g_array_index(capture_opts->ifaces, interface_options,
960                                        icnt);
961
962         /* skip native interfaces */
963         if (interface_opts->if_type != IF_EXTCAP)
964         {
965             continue;
966         }
967
968         overwrite_exitcode = FALSE;
969
970         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
971               "Extcap [%s] - Cleaning up fifo: %s; PID: %d", interface_opts->name,
972               interface_opts->extcap_fifo, interface_opts->extcap_pid);
973 #ifdef _WIN32
974         if (interface_opts->extcap_pipe_h != INVALID_HANDLE_VALUE)
975         {
976             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
977                   "Extcap [%s] - Closing pipe", interface_opts->name);
978             FlushFileBuffers(interface_opts->extcap_pipe_h);
979             DisconnectNamedPipe(interface_opts->extcap_pipe_h);
980             CloseHandle(interface_opts->extcap_pipe_h);
981             interface_opts->extcap_pipe_h = INVALID_HANDLE_VALUE;
982         }
983         if (interface_opts->extcap_control_in_h != INVALID_HANDLE_VALUE)
984         {
985             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
986                   "Extcap [%s] - Closing control_in pipe", interface_opts->name);
987             FlushFileBuffers(interface_opts->extcap_control_in_h);
988             DisconnectNamedPipe(interface_opts->extcap_control_in_h);
989             CloseHandle(interface_opts->extcap_control_in_h);
990             interface_opts->extcap_control_in_h = INVALID_HANDLE_VALUE;
991         }
992         if (interface_opts->extcap_control_out_h != INVALID_HANDLE_VALUE)
993         {
994             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
995                   "Extcap [%s] - Closing control_out pipe", interface_opts->name);
996             FlushFileBuffers(interface_opts->extcap_control_out_h);
997             DisconnectNamedPipe(interface_opts->extcap_control_out_h);
998             CloseHandle(interface_opts->extcap_control_out_h);
999             interface_opts->extcap_control_out_h = INVALID_HANDLE_VALUE;
1000         }
1001 #else
1002         if (interface_opts->extcap_fifo != NULL && file_exists(interface_opts->extcap_fifo))
1003         {
1004             /* the fifo will not be freed here, but with the other capture_opts in capture_sync */
1005             ws_unlink(interface_opts->extcap_fifo);
1006             interface_opts->extcap_fifo = NULL;
1007         }
1008         if (interface_opts->extcap_control_in && file_exists(interface_opts->extcap_control_in))
1009         {
1010             ws_unlink(interface_opts->extcap_control_in);
1011             interface_opts->extcap_control_in = NULL;
1012         }
1013         if (interface_opts->extcap_control_out && file_exists(interface_opts->extcap_control_out))
1014         {
1015             ws_unlink(interface_opts->extcap_control_out);
1016             interface_opts->extcap_control_out = NULL;
1017         }
1018 #endif
1019         /* Maybe the client closed and removed fifo, but ws should check if
1020          * pid should be closed */
1021         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1022               "Extcap [%s] - Closing spawned PID: %d", interface_opts->name,
1023               interface_opts->extcap_pid);
1024
1025         userdata = (extcap_userdata *) interface_opts->extcap_userdata;
1026         if (userdata)
1027         {
1028             if (userdata->extcap_stderr_rd > 0 && ws_pipe_data_available(userdata->extcap_stderr_rd))
1029             {
1030                 buffer = (gchar *)g_malloc0(STDERR_BUFFER_SIZE + 1);
1031                 ws_read_string_from_pipe(ws_get_pipe_handle(userdata->extcap_stderr_rd), buffer, STDERR_BUFFER_SIZE + 1);
1032                 if (strlen(buffer) > 0)
1033                 {
1034                     userdata->extcap_stderr = g_strdup_printf("%s", buffer);
1035                     userdata->exitcode = 1;
1036                 }
1037                 g_free(buffer);
1038             }
1039
1040 #ifndef _WIN32
1041             /* Final child watch may not have been called */
1042             if (interface_opts->extcap_child_watch != 0)
1043             {
1044                 extcap_child_watch_cb(userdata->pid, 0, capture_opts);
1045                 /* it will have changed in extcap_child_watch_cb */
1046                 interface_opts = &g_array_index(capture_opts->ifaces, interface_options,
1047                                                icnt);
1048             }
1049 #endif
1050
1051             if (userdata->extcap_stderr != NULL)
1052             {
1053                 overwrite_exitcode = TRUE;
1054             }
1055
1056             if (overwrite_exitcode || userdata->exitcode != 0)
1057             {
1058                 if (userdata->extcap_stderr != 0)
1059                 {
1060                     if (*errormsg == NULL)
1061                     {
1062                         *errormsg = g_strdup_printf("Error by extcap pipe: %s", userdata->extcap_stderr);
1063                     }
1064                     else
1065                     {
1066                         gchar *temp = g_strconcat(*errormsg, "\nError by extcap pipe: " , userdata->extcap_stderr, NULL);
1067                         g_free(*errormsg);
1068                         *errormsg = temp;
1069                     }
1070                     g_free(userdata->extcap_stderr);
1071                 }
1072
1073                 userdata->extcap_stderr = NULL;
1074                 userdata->exitcode = 0;
1075             }
1076         }
1077
1078         if (interface_opts->extcap_child_watch > 0)
1079         {
1080             g_source_remove(interface_opts->extcap_child_watch);
1081             interface_opts->extcap_child_watch = 0;
1082         }
1083
1084         if (interface_opts->extcap_pid != INVALID_EXTCAP_PID)
1085         {
1086 #ifdef _WIN32
1087             TerminateProcess(interface_opts->extcap_pid, 0);
1088 #endif
1089             g_spawn_close_pid(interface_opts->extcap_pid);
1090             interface_opts->extcap_pid = INVALID_EXTCAP_PID;
1091
1092             g_free(interface_opts->extcap_userdata);
1093             interface_opts->extcap_userdata = NULL;
1094         }
1095     }
1096 }
1097
1098 static gboolean
1099 extcap_add_arg_and_remove_cb(gpointer key, gpointer value, gpointer data)
1100 {
1101     GPtrArray *args = (GPtrArray *)data;
1102
1103     if (key != NULL)
1104     {
1105         g_ptr_array_add(args, g_strdup((const gchar *)key));
1106
1107         if (value != NULL)
1108         {
1109             g_ptr_array_add(args, g_strdup((const gchar *)value));
1110         }
1111
1112         return TRUE;
1113     }
1114
1115     return FALSE;
1116 }
1117
1118 void extcap_child_watch_cb(GPid pid, gint status, gpointer user_data)
1119 {
1120     guint i;
1121     interface_options *interface_opts;
1122     extcap_userdata *userdata = NULL;
1123     capture_options *capture_opts = (capture_options *)(user_data);
1124
1125     if (capture_opts == NULL || capture_opts->ifaces == NULL || capture_opts->ifaces->len == 0)
1126     {
1127         return;
1128     }
1129
1130     /* Close handle to child process. */
1131     g_spawn_close_pid(pid);
1132
1133     /* Update extcap_pid in interface options structure. */
1134     for (i = 0; i < capture_opts->ifaces->len; i++)
1135     {
1136         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
1137         if (interface_opts->extcap_pid == pid)
1138         {
1139             userdata = (extcap_userdata *)interface_opts->extcap_userdata;
1140             if (userdata != NULL)
1141             {
1142                 interface_opts->extcap_pid = INVALID_EXTCAP_PID;
1143                 userdata->exitcode = 0;
1144 #ifndef _WIN32
1145                 if (WIFEXITED(status))
1146                 {
1147                     if (WEXITSTATUS(status) != 0)
1148                     {
1149                         userdata->exitcode = WEXITSTATUS(status);
1150                     }
1151                 }
1152                 else
1153                 {
1154                     userdata->exitcode = G_SPAWN_ERROR_FAILED;
1155                 }
1156 #else
1157                 if (status != 0)
1158                 {
1159                     userdata->exitcode = status;
1160                 }
1161 #endif
1162                 if (status == 0 && userdata->extcap_stderr != NULL)
1163                 {
1164                     userdata->exitcode = 1;
1165                 }
1166             }
1167             g_source_remove(interface_opts->extcap_child_watch);
1168             interface_opts->extcap_child_watch = 0;
1169             break;
1170         }
1171     }
1172 }
1173
1174 static
1175 GPtrArray *extcap_prepare_arguments(interface_options *interface_opts)
1176 {
1177     GPtrArray *result = NULL;
1178
1179     if (interface_opts->if_type == IF_EXTCAP)
1180     {
1181         result = g_ptr_array_new();
1182
1183 #define add_arg(X) g_ptr_array_add(result, g_strdup(X))
1184
1185         add_arg(interface_opts->extcap);
1186         add_arg(EXTCAP_ARGUMENT_RUN_CAPTURE);
1187         add_arg(EXTCAP_ARGUMENT_INTERFACE);
1188         add_arg(interface_opts->name);
1189         if (interface_opts->cfilter && strlen(interface_opts->cfilter) > 0)
1190         {
1191             add_arg(EXTCAP_ARGUMENT_CAPTURE_FILTER);
1192             add_arg(interface_opts->cfilter);
1193         }
1194         add_arg(EXTCAP_ARGUMENT_RUN_PIPE);
1195         add_arg(interface_opts->extcap_fifo);
1196         if (interface_opts->extcap_control_in)
1197         {
1198             add_arg(EXTCAP_ARGUMENT_CONTROL_OUT);
1199             add_arg(interface_opts->extcap_control_in);
1200         }
1201         if (interface_opts->extcap_control_out)
1202         {
1203             add_arg(EXTCAP_ARGUMENT_CONTROL_IN);
1204             add_arg(interface_opts->extcap_control_out);
1205         }
1206         if (interface_opts->extcap_args == NULL || g_hash_table_size(interface_opts->extcap_args) == 0)
1207         {
1208             /* User did not perform interface configuration.
1209              *
1210              * Check if there are any boolean flags that are set by default
1211              * and hence their argument should be added.
1212              */
1213             GList *arglist;
1214             GList *elem;
1215
1216             arglist = extcap_get_if_configuration(interface_opts->name);
1217             for (elem = g_list_first(arglist); elem; elem = elem->next)
1218             {
1219                 GList *arg_list;
1220                 extcap_arg *arg_iter;
1221
1222                 if (elem->data == NULL)
1223                 {
1224                     continue;
1225                 }
1226
1227                 arg_list = g_list_first((GList *)elem->data);
1228                 while (arg_list != NULL)
1229                 {
1230                     const gchar *stored = NULL;
1231                     /* In case of boolflags only first element in arg_list is relevant. */
1232                     arg_iter = (extcap_arg *)(arg_list->data);
1233                     if (arg_iter->pref_valptr != NULL)
1234                     {
1235                         stored = *arg_iter->pref_valptr;
1236                     }
1237
1238                     if (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG)
1239                     {
1240                         if (extcap_complex_get_bool(arg_iter->default_complex))
1241                         {
1242                             add_arg(arg_iter->call);
1243                         }
1244                         else if (g_strcmp0(stored, "true") == 0)
1245                         {
1246                             add_arg(arg_iter->call);
1247                         }
1248                     }
1249                     else
1250                     {
1251                         if (stored && strlen(stored) > 0) {
1252                             add_arg(arg_iter->call);
1253                             add_arg(stored);
1254                         }
1255                     }
1256
1257                     arg_list = arg_list->next;
1258                 }
1259             }
1260
1261             extcap_free_if_configuration(arglist, TRUE);
1262         }
1263         else
1264         {
1265             g_hash_table_foreach_remove(interface_opts->extcap_args, extcap_add_arg_and_remove_cb, result);
1266         }
1267         add_arg(NULL);
1268 #undef add_arg
1269
1270     }
1271
1272     return result;
1273 }
1274
1275 /* call mkfifo for each extcap,
1276  * returns FALSE if there's an error creating a FIFO */
1277 gboolean
1278 extcap_init_interfaces(capture_options *capture_opts)
1279 {
1280     guint i;
1281     interface_options *interface_opts;
1282     extcap_userdata *userdata;
1283
1284     for (i = 0; i < capture_opts->ifaces->len; i++)
1285     {
1286         GPtrArray *args = NULL;
1287         GPid pid = INVALID_EXTCAP_PID;
1288
1289         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
1290
1291         /* skip native interfaces */
1292         if (interface_opts->if_type != IF_EXTCAP)
1293         {
1294             continue;
1295         }
1296
1297         /* create control pipes if having toolbar */
1298         if (extcap_has_toolbar(interface_opts->name))
1299         {
1300             extcap_create_pipe(interface_opts->name, &interface_opts->extcap_control_in,
1301                                EXTCAP_CONTROL_IN_PREFIX, FALSE);
1302 #ifdef _WIN32
1303             interface_opts->extcap_control_in_h = pipe_h;
1304 #endif
1305             extcap_create_pipe(interface_opts->name, &interface_opts->extcap_control_out,
1306                                EXTCAP_CONTROL_OUT_PREFIX, FALSE);
1307 #ifdef _WIN32
1308             interface_opts->extcap_control_out_h = pipe_h;
1309 #endif
1310         }
1311
1312         /* create pipe for fifo */
1313         if (!extcap_create_pipe(interface_opts->name, &interface_opts->extcap_fifo,
1314                                 EXTCAP_PIPE_PREFIX, TRUE))
1315         {
1316             return FALSE;
1317         }
1318 #ifdef _WIN32
1319         interface_opts->extcap_pipe_h = pipe_h;
1320 #endif
1321
1322         /* Create extcap call */
1323         args = extcap_prepare_arguments(interface_opts);
1324
1325         userdata = g_new0(extcap_userdata, 1);
1326
1327         pid = extcap_spawn_async(userdata, args);
1328
1329         g_ptr_array_foreach(args, (GFunc)g_free, NULL);
1330         g_ptr_array_free(args, TRUE);
1331
1332         if (pid == INVALID_EXTCAP_PID)
1333         {
1334             g_free(userdata);
1335             continue;
1336         }
1337
1338         interface_opts->extcap_pid = pid;
1339
1340         interface_opts->extcap_child_watch =
1341             g_child_watch_add(pid, extcap_child_watch_cb, (gpointer)capture_opts);
1342
1343 #ifdef _WIN32
1344         /* On Windows, wait for extcap to connect to named pipe.
1345          * Some extcaps will present UAC screen to user.
1346          * 30 second timeout should be reasonable timeout for extcap to
1347          * connect to named pipe (including user interaction).
1348          * Wait on multiple object in case of extcap termination
1349          * without opening pipe.
1350          *
1351          * Minimum supported version of Windows: XP / Server 2003.
1352          */
1353         if (pid != INVALID_EXTCAP_PID)
1354         {
1355             HANDLE pipe_handles[3];
1356             int num_pipe_handles = 1;
1357             pipe_handles[0] = interface_opts->extcap_pipe_h;
1358
1359             if (extcap_has_toolbar(interface_opts->name))
1360             {
1361                 pipe_handles[1] = interface_opts->extcap_control_in_h;
1362                 pipe_handles[2] = interface_opts->extcap_control_out_h;
1363                 num_pipe_handles += 2;
1364              }
1365
1366             extcap_wait_for_pipe(pipe_handles, num_pipe_handles, pid);
1367         }
1368 #endif
1369
1370         interface_opts->extcap_userdata = (gpointer) userdata;
1371     }
1372
1373     return TRUE;
1374 }
1375
1376 gboolean extcap_create_pipe(const gchar *ifname, gchar **fifo, const gchar *pipe_prefix, gboolean byte_mode _U_)
1377 {
1378 #ifdef _WIN32
1379     gchar timestr[ 14 + 1 ];
1380     time_t current_time;
1381     gchar *pipename = NULL;
1382     SECURITY_ATTRIBUTES security;
1383
1384     /* create pipename */
1385     current_time = time(NULL);
1386     /*
1387      * XXX - we trust Windows not to return a time before the Epoch here,
1388      * so we won't get a null pointer back from localtime().
1389      */
1390     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
1391     pipename = g_strconcat("\\\\.\\pipe\\", pipe_prefix, "_", ifname, "_", timestr, NULL);
1392
1393     /* Security struct to enable Inheritable HANDLE */
1394     memset(&security, 0, sizeof(SECURITY_ATTRIBUTES));
1395     security.nLength = sizeof(SECURITY_ATTRIBUTES);
1396     security.bInheritHandle = TRUE;
1397     security.lpSecurityDescriptor = NULL;
1398
1399     /* create a namedPipe */
1400     pipe_h = CreateNamedPipe(
1401                  utf_8to16(pipename),
1402                  PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1403                  byte_mode ? PIPE_TYPE_BYTE : PIPE_TYPE_MESSAGE | byte_mode ? PIPE_READMODE_BYTE : PIPE_READMODE_MESSAGE | PIPE_WAIT,
1404                  1, 65536, 65536,
1405                  300,
1406                  &security);
1407
1408     if (pipe_h == INVALID_HANDLE_VALUE)
1409     {
1410         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nError creating pipe => (%d)", GetLastError());
1411         g_free (pipename);
1412         return FALSE;
1413     }
1414     else
1415     {
1416         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nWireshark Created pipe =>(%s)", pipename);
1417         *fifo = g_strdup(pipename);
1418     }
1419 #else
1420     gchar *temp_name = NULL;
1421     int fd = 0;
1422
1423     gchar *pfx = g_strconcat(pipe_prefix, "_", ifname, NULL);
1424     if ((fd = create_tempfile(&temp_name, pfx, NULL)) < 0)
1425     {
1426         g_free(pfx);
1427         return FALSE;
1428     }
1429     g_free(pfx);
1430
1431     ws_close(fd);
1432
1433     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1434           "Extcap - Creating fifo: %s", temp_name);
1435
1436     if (file_exists(temp_name))
1437     {
1438         ws_unlink(temp_name);
1439     }
1440
1441     if (mkfifo(temp_name, 0600) == 0)
1442     {
1443         *fifo = g_strdup(temp_name);
1444     }
1445 #endif
1446
1447     return TRUE;
1448 }
1449
1450 /************* EXTCAP LOAD INTERFACE LIST ***************
1451  *
1452  * The following code handles loading and reloading the interface list. It is explicitly
1453  * kept separate from the rest
1454  */
1455
1456
1457 static void
1458 extcap_free_interface_info(gpointer data)
1459 {
1460     extcap_info *info = (extcap_info *)data;
1461
1462     g_free(info->basename);
1463     g_free(info->full_path);
1464     g_free(info->version);
1465     g_free(info->help);
1466
1467     extcap_free_interfaces(info->interfaces);
1468
1469     g_free(info);
1470 }
1471
1472 static extcap_info *
1473 extcap_ensure_interface(const gchar * toolname, gboolean create_if_nonexist)
1474 {
1475     extcap_info * element = 0;
1476
1477     if ( ! toolname )
1478         return element;
1479
1480     if ( ! _loaded_interfaces )
1481         _loaded_interfaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_interface);
1482
1483     element = (extcap_info *) g_hash_table_lookup(_loaded_interfaces, toolname );
1484     if ( ! element && create_if_nonexist )
1485     {
1486         g_hash_table_insert(_loaded_interfaces, g_strdup(toolname), g_new0(extcap_info, 1));
1487         element = (extcap_info *) g_hash_table_lookup(_loaded_interfaces, toolname );
1488     }
1489
1490     return element;
1491 }
1492
1493 extcap_info *
1494 extcap_get_tool_by_ifname(const gchar *ifname)
1495 {
1496     if ( ifname && _tool_for_ifname )
1497     {
1498         gchar * toolname = (gchar *)g_hash_table_lookup(_tool_for_ifname, ifname);
1499         if ( toolname )
1500             return extcap_ensure_interface(toolname, FALSE);
1501     }
1502
1503     return NULL;
1504 }
1505
1506 extcap_info *
1507 extcap_get_tool_info(const gchar * toolname)
1508 {
1509     return extcap_ensure_interface(toolname, FALSE);
1510 }
1511
1512 static void remove_extcap_entry(gpointer entry, gpointer data _U_)
1513 {
1514     extcap_interface *int_iter = (extcap_interface*)entry;
1515
1516     if (int_iter->if_type == EXTCAP_SENTENCE_EXTCAP)
1517         extcap_free_interface(entry);
1518 }
1519
1520 static gboolean cb_load_interfaces(extcap_callback_info_t cb_info)
1521 {
1522     GList * interfaces = NULL, * control_items = NULL, * walker = NULL;
1523     extcap_interface * int_iter = NULL;
1524     extcap_info * element = NULL;
1525     iface_toolbar * toolbar_entry = NULL;
1526     gchar * toolname = g_path_get_basename(cb_info.extcap);
1527
1528     GList * interface_keys = g_hash_table_get_keys(_loaded_interfaces);
1529
1530     /* Load interfaces from utility */
1531     interfaces = extcap_parse_interfaces(cb_info.output, &control_items);
1532
1533     if (control_items)
1534     {
1535         toolbar_entry = g_new0(iface_toolbar, 1);
1536         toolbar_entry->controls = control_items;
1537     }
1538
1539     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Loading interface list for %s ", cb_info.extcap);
1540
1541     /* Seems, that there where no interfaces to be loaded */
1542     if ( ! interfaces || g_list_length(interfaces) == 0 )
1543     {
1544         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Cannot load interfaces for %s", cb_info.extcap );
1545         /* Some utilities, androiddump for example, may actually don't present any interfaces, even
1546          * if the utility itself is present. In such a case, we return here, but do not return
1547          * FALSE, or otherwise further loading of other utilities will be stopped */
1548         g_list_free(interface_keys);
1549         g_free(toolname);
1550         return TRUE;
1551     }
1552
1553     /* Load or create the storage element for the tool */
1554     element = extcap_ensure_interface(toolname, TRUE);
1555     if ( element == NULL )
1556     {
1557         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_ERROR, "Cannot store interface %s, maybe duplicate?", cb_info.extcap );
1558         g_list_foreach(interfaces, remove_extcap_entry, NULL);
1559         g_list_free(interfaces);
1560         g_list_free(interface_keys);
1561         g_free(toolname);
1562         return FALSE;
1563     }
1564
1565     walker = interfaces;
1566     gchar* help = NULL;
1567     while (walker != NULL)
1568     {
1569         int_iter = (extcap_interface *)walker->data;
1570
1571         if (int_iter->call != NULL)
1572             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Interface found %s\n", int_iter->call);
1573
1574         /* Help is not necessarily stored with the interface, but rather with the version string.
1575          * As the version string allways comes in front of the interfaces, this ensures, that it get's
1576          * properly stored with the interface */
1577         if (int_iter->if_type == EXTCAP_SENTENCE_EXTCAP)
1578         {
1579             if (int_iter->call != NULL)
1580                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Extcap [%s] ", int_iter->call);
1581
1582             /* Only initialize values if none are set. Need to check only one element here */
1583             if ( ! element->version )
1584             {
1585                 element->version = g_strdup(int_iter->version);
1586                 element->basename = g_strdup(toolname);
1587                 element->full_path = g_strdup(cb_info.extcap);
1588                 element->help = g_strdup(int_iter->help);
1589             }
1590
1591             help = int_iter->help;
1592             if (toolbar_entry)
1593             {
1594                 toolbar_entry->menu_title = g_strdup(int_iter->display);
1595                 toolbar_entry->help = g_strdup(int_iter->help);
1596             }
1597
1598             walker = g_list_next(walker);
1599             continue;
1600         }
1601
1602         /* Only interface definitions will be parsed here. help is already set by the extcap element,
1603          * which makes it necessary to have version in the list before the interfaces. This is normally
1604          * the case by design, but could be changed by separating the information in extcap-base. */
1605         if ( int_iter->if_type == EXTCAP_SENTENCE_INTERFACE )
1606         {
1607             if ( g_list_find(interface_keys, int_iter->call) )
1608             {
1609                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_WARNING, "Extcap interface \"%s\" is already provided by \"%s\" ",
1610                       int_iter->call, (gchar *)extcap_if_executable(int_iter->call));
1611                 walker = g_list_next(walker);
1612                 continue;
1613             }
1614
1615             if ((int_iter->call != NULL) && (int_iter->display))
1616                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Interface [%s] \"%s\" ", int_iter->call, int_iter->display);
1617
1618             int_iter->extcap_path = g_strdup(cb_info.extcap);
1619
1620             /* Only set the help, if it exists and no parsed help information is present */
1621             if ( ! int_iter->help && help )
1622                 int_iter->help = g_strdup(help);
1623
1624             element->interfaces = g_list_append(element->interfaces, int_iter);
1625             g_hash_table_insert(_tool_for_ifname, g_strdup(int_iter->call), g_strdup(toolname));
1626
1627             if (toolbar_entry)
1628             {
1629                 if (!toolbar_entry->menu_title)
1630                 {
1631                     toolbar_entry->menu_title = g_strdup(int_iter->display);
1632                 }
1633                 toolbar_entry->ifnames = g_list_append(toolbar_entry->ifnames, g_strdup(int_iter->call));
1634             }
1635         }
1636
1637         walker = g_list_next(walker);
1638     }
1639
1640     if (toolbar_entry && toolbar_entry->menu_title)
1641     {
1642         iface_toolbar_add(toolbar_entry);
1643         extcap_iface_toolbar_add(cb_info.extcap, toolbar_entry);
1644     }
1645
1646     g_list_foreach(interfaces, remove_extcap_entry, NULL);
1647     g_list_free(interfaces);
1648     g_list_free(interface_keys);
1649     g_free(toolname);
1650     return TRUE;
1651 }
1652
1653
1654 /* Handles loading of the interfaces.
1655  *
1656  * A list of interfaces can be obtained by calling \ref extcap_loaded_interfaces
1657  */
1658 static void
1659 extcap_load_interface_list(void)
1660 {
1661     gchar *argv;
1662     gchar *error;
1663
1664     if (_toolbars)
1665     {
1666         // Remove existing interface toolbars here instead of in extcap_clear_interfaces()
1667         // to avoid flicker in shown toolbars when refreshing interfaces.
1668         GList *toolbar_list = g_hash_table_get_values (_toolbars);
1669         for (GList *walker = toolbar_list; walker; walker = walker->next)
1670         {
1671             iface_toolbar *toolbar = (iface_toolbar *) walker->data;
1672             iface_toolbar_remove(toolbar->menu_title);
1673         }
1674         g_hash_table_remove_all(_toolbars);
1675     } else {
1676         _toolbars = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_toolbar);
1677     }
1678
1679     if (_loaded_interfaces == NULL)
1680     {
1681         _loaded_interfaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_interface_info);
1682         /* Cleanup lookup table */
1683         if ( _tool_for_ifname )
1684         {
1685             g_hash_table_remove_all(_tool_for_ifname);
1686             _tool_for_ifname = 0;
1687         } else {
1688             _tool_for_ifname = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
1689         }
1690
1691         argv = g_strdup(EXTCAP_ARGUMENT_LIST_INTERFACES);
1692
1693         extcap_callback_info_t cb_info;
1694         cb_info.data = NULL;
1695         cb_info.ifname = NULL;
1696         cb_info.err_str = &error;
1697
1698         extcap_foreach(1, &argv, cb_load_interfaces, cb_info);
1699
1700         g_free(argv);
1701     }
1702 }
1703
1704 /*
1705  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1706  *
1707  * Local variables:
1708  * c-basic-offset: 4
1709  * tab-width: 8
1710  * indent-tabs-mode: nil
1711  * End:
1712  *
1713  * vi: set shiftwidth=4 tabstop=8 expandtab:
1714  * :indentSize=4:tabSize=8:noTabs=true:
1715  */