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