extcap: null terminate the string that will be used in strlen (CID 1364684).
[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                 ssize_t buffer_len;
1074                 buffer_len = read(userdata->extcap_stderr_rd, buffer, sizeof(gchar) * STDERR_BUFFER_SIZE);
1075                 if (buffer_len <= 0)
1076                 {
1077                     buffer[0] = '\0';
1078                 }
1079                 else
1080                 {
1081                     buffer[buffer_len] = '\0';
1082                 }
1083 #endif
1084                 if (strlen(buffer) > 0)
1085                 {
1086                     userdata->extcap_stderr = g_strdup_printf("%s", buffer);
1087                     userdata->exitcode = 1;
1088                 }
1089                 g_free(buffer);
1090             }
1091
1092 #ifndef _WIN32
1093             /* Final child watch may not have been called */
1094             if (interface_opts->extcap_child_watch != 0)
1095             {
1096                 extcap_child_watch_cb(userdata->pid, 0, capture_opts);
1097                 /* it will have changed in extcap_child_watch_cb */
1098                 interface_opts = &g_array_index(capture_opts->ifaces, interface_options,
1099                                                icnt);
1100             }
1101 #endif
1102
1103             if (userdata->extcap_stderr != NULL)
1104             {
1105                 overwrite_exitcode = TRUE;
1106             }
1107
1108             if (overwrite_exitcode || userdata->exitcode != 0)
1109             {
1110                 if (userdata->extcap_stderr != 0)
1111                 {
1112                     if (*errormsg == NULL)
1113                     {
1114                         *errormsg = g_strdup_printf("Error by extcap pipe: %s", userdata->extcap_stderr);
1115                     }
1116                     else
1117                     {
1118                         gchar *temp = g_strconcat(*errormsg, "\nError by extcap pipe: " , userdata->extcap_stderr, NULL);
1119                         g_free(*errormsg);
1120                         *errormsg = temp;
1121                     }
1122                     g_free(userdata->extcap_stderr);
1123                 }
1124
1125                 userdata->extcap_stderr = NULL;
1126                 userdata->exitcode = 0;
1127             }
1128         }
1129
1130         if (interface_opts->extcap_child_watch > 0)
1131         {
1132             g_source_remove(interface_opts->extcap_child_watch);
1133             interface_opts->extcap_child_watch = 0;
1134         }
1135
1136         if (interface_opts->extcap_pid != INVALID_EXTCAP_PID)
1137         {
1138 #ifdef _WIN32
1139             TerminateProcess(interface_opts->extcap_pid, 0);
1140 #endif
1141             g_spawn_close_pid(interface_opts->extcap_pid);
1142             interface_opts->extcap_pid = INVALID_EXTCAP_PID;
1143
1144             g_free(interface_opts->extcap_userdata);
1145             interface_opts->extcap_userdata = NULL;
1146         }
1147     }
1148 }
1149
1150 static gboolean
1151 extcap_add_arg_and_remove_cb(gpointer key, gpointer value, gpointer data)
1152 {
1153     GPtrArray *args = (GPtrArray *)data;
1154
1155     if (key != NULL)
1156     {
1157         g_ptr_array_add(args, g_strdup((const gchar *)key));
1158
1159         if (value != NULL)
1160         {
1161             g_ptr_array_add(args, g_strdup((const gchar *)value));
1162         }
1163
1164         return TRUE;
1165     }
1166
1167     return FALSE;
1168 }
1169
1170 void extcap_child_watch_cb(GPid pid, gint status, gpointer user_data)
1171 {
1172     guint i;
1173     interface_options *interface_opts;
1174     extcap_userdata *userdata = NULL;
1175     capture_options *capture_opts = (capture_options *)(user_data);
1176
1177     if (capture_opts == NULL || capture_opts->ifaces == NULL || capture_opts->ifaces->len == 0)
1178     {
1179         return;
1180     }
1181
1182     /* Close handle to child process. */
1183     g_spawn_close_pid(pid);
1184
1185     /* Update extcap_pid in interface options structure. */
1186     for (i = 0; i < capture_opts->ifaces->len; i++)
1187     {
1188         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
1189         if (interface_opts->extcap_pid == pid)
1190         {
1191             userdata = (extcap_userdata *)interface_opts->extcap_userdata;
1192             if (userdata != NULL)
1193             {
1194                 interface_opts->extcap_pid = INVALID_EXTCAP_PID;
1195                 userdata->exitcode = 0;
1196 #ifndef _WIN32
1197                 if (WIFEXITED(status))
1198                 {
1199                     if (WEXITSTATUS(status) != 0)
1200                     {
1201                         userdata->exitcode = WEXITSTATUS(status);
1202                     }
1203                 }
1204                 else
1205                 {
1206                     userdata->exitcode = G_SPAWN_ERROR_FAILED;
1207                 }
1208 #else
1209                 if (status != 0)
1210                 {
1211                     userdata->exitcode = status;
1212                 }
1213 #endif
1214                 if (status == 0 && userdata->extcap_stderr != NULL)
1215                 {
1216                     userdata->exitcode = 1;
1217                 }
1218             }
1219             g_source_remove(interface_opts->extcap_child_watch);
1220             interface_opts->extcap_child_watch = 0;
1221             break;
1222         }
1223     }
1224 }
1225
1226 static
1227 GPtrArray *extcap_prepare_arguments(interface_options *interface_opts)
1228 {
1229     GPtrArray *result = NULL;
1230
1231     if (interface_opts->if_type == IF_EXTCAP)
1232     {
1233         result = g_ptr_array_new();
1234
1235 #define add_arg(X) g_ptr_array_add(result, g_strdup(X))
1236
1237         add_arg(interface_opts->extcap);
1238         add_arg(EXTCAP_ARGUMENT_RUN_CAPTURE);
1239         add_arg(EXTCAP_ARGUMENT_INTERFACE);
1240         add_arg(interface_opts->name);
1241         if (interface_opts->cfilter && strlen(interface_opts->cfilter) > 0)
1242         {
1243             add_arg(EXTCAP_ARGUMENT_CAPTURE_FILTER);
1244             add_arg(interface_opts->cfilter);
1245         }
1246         add_arg(EXTCAP_ARGUMENT_RUN_PIPE);
1247         add_arg(interface_opts->extcap_fifo);
1248         if (interface_opts->extcap_control_in)
1249         {
1250             add_arg(EXTCAP_ARGUMENT_CONTROL_OUT);
1251             add_arg(interface_opts->extcap_control_in);
1252         }
1253         if (interface_opts->extcap_control_out)
1254         {
1255             add_arg(EXTCAP_ARGUMENT_CONTROL_IN);
1256             add_arg(interface_opts->extcap_control_out);
1257         }
1258         if (interface_opts->extcap_args == NULL || g_hash_table_size(interface_opts->extcap_args) == 0)
1259         {
1260             /* User did not perform interface configuration.
1261              *
1262              * Check if there are any boolean flags that are set by default
1263              * and hence their argument should be added.
1264              */
1265             GList *arglist;
1266             GList *elem;
1267
1268             arglist = extcap_get_if_configuration(interface_opts->name);
1269             for (elem = g_list_first(arglist); elem; elem = elem->next)
1270             {
1271                 GList *arg_list;
1272                 extcap_arg *arg_iter;
1273
1274                 if (elem->data == NULL)
1275                 {
1276                     continue;
1277                 }
1278
1279                 arg_list = g_list_first((GList *)elem->data);
1280                 while (arg_list != NULL)
1281                 {
1282                     const gchar *stored = NULL;
1283                     /* In case of boolflags only first element in arg_list is relevant. */
1284                     arg_iter = (extcap_arg *)(arg_list->data);
1285                     if (arg_iter->pref_valptr != NULL)
1286                     {
1287                         stored = *arg_iter->pref_valptr;
1288                     }
1289
1290                     if (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG)
1291                     {
1292                         if (extcap_complex_get_bool(arg_iter->default_complex))
1293                         {
1294                             add_arg(arg_iter->call);
1295                         }
1296                         else if (g_strcmp0(stored, "true") == 0)
1297                         {
1298                             add_arg(arg_iter->call);
1299                         }
1300                     }
1301                     else
1302                     {
1303                         if (stored && strlen(stored) > 0) {
1304                             add_arg(arg_iter->call);
1305                             add_arg(stored);
1306                         }
1307                     }
1308
1309                     arg_list = arg_list->next;
1310                 }
1311             }
1312
1313             extcap_free_if_configuration(arglist, TRUE);
1314         }
1315         else
1316         {
1317             g_hash_table_foreach_remove(interface_opts->extcap_args, extcap_add_arg_and_remove_cb, result);
1318         }
1319         add_arg(NULL);
1320 #undef add_arg
1321
1322     }
1323
1324     return result;
1325 }
1326
1327 /* call mkfifo for each extcap,
1328  * returns FALSE if there's an error creating a FIFO */
1329 gboolean
1330 extcap_init_interfaces(capture_options *capture_opts)
1331 {
1332     guint i;
1333     interface_options *interface_opts;
1334     extcap_userdata *userdata;
1335
1336     for (i = 0; i < capture_opts->ifaces->len; i++)
1337     {
1338         GPtrArray *args = NULL;
1339         GPid pid = INVALID_EXTCAP_PID;
1340
1341         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
1342
1343         /* skip native interfaces */
1344         if (interface_opts->if_type != IF_EXTCAP)
1345         {
1346             continue;
1347         }
1348
1349         /* create control pipes if having toolbar */
1350         if (extcap_has_toolbar(interface_opts->name))
1351         {
1352             extcap_create_pipe(interface_opts->name, &interface_opts->extcap_control_in,
1353                                EXTCAP_CONTROL_IN_PREFIX, FALSE);
1354 #ifdef _WIN32
1355             interface_opts->extcap_control_in_h = pipe_h;
1356 #endif
1357             extcap_create_pipe(interface_opts->name, &interface_opts->extcap_control_out,
1358                                EXTCAP_CONTROL_OUT_PREFIX, FALSE);
1359 #ifdef _WIN32
1360             interface_opts->extcap_control_out_h = pipe_h;
1361 #endif
1362         }
1363
1364         /* create pipe for fifo */
1365         if (!extcap_create_pipe(interface_opts->name, &interface_opts->extcap_fifo,
1366                                 EXTCAP_PIPE_PREFIX, TRUE))
1367         {
1368             return FALSE;
1369         }
1370 #ifdef _WIN32
1371         interface_opts->extcap_pipe_h = pipe_h;
1372 #endif
1373
1374         /* Create extcap call */
1375         args = extcap_prepare_arguments(interface_opts);
1376
1377         userdata = g_new0(extcap_userdata, 1);
1378
1379         pid = extcap_spawn_async(userdata, args);
1380
1381         g_ptr_array_foreach(args, (GFunc)g_free, NULL);
1382         g_ptr_array_free(args, TRUE);
1383
1384         if (pid == INVALID_EXTCAP_PID)
1385         {
1386             g_free(userdata);
1387             continue;
1388         }
1389
1390         interface_opts->extcap_pid = pid;
1391
1392         interface_opts->extcap_child_watch =
1393             g_child_watch_add(pid, extcap_child_watch_cb, (gpointer)capture_opts);
1394
1395 #ifdef _WIN32
1396         /* On Windows, wait for extcap to connect to named pipe.
1397          * Some extcaps will present UAC screen to user.
1398          * 30 second timeout should be reasonable timeout for extcap to
1399          * connect to named pipe (including user interaction).
1400          * Wait on multiple object in case of extcap termination
1401          * without opening pipe.
1402          *
1403          * Minimum supported version of Windows: XP / Server 2003.
1404          */
1405         if (pid != INVALID_EXTCAP_PID)
1406         {
1407             HANDLE pipe_handles[3];
1408             int num_pipe_handles = 1;
1409             pipe_handles[0] = interface_opts->extcap_pipe_h;
1410
1411             if (extcap_has_toolbar(interface_opts->name))
1412             {
1413                 pipe_handles[1] = interface_opts->extcap_control_in_h;
1414                 pipe_handles[2] = interface_opts->extcap_control_out_h;
1415                 num_pipe_handles += 2;
1416              }
1417
1418             extcap_wait_for_pipe(pipe_handles, num_pipe_handles, pid);
1419         }
1420 #endif
1421
1422         interface_opts->extcap_userdata = (gpointer) userdata;
1423     }
1424
1425     return TRUE;
1426 }
1427
1428 gboolean extcap_create_pipe(const gchar *ifname, gchar **fifo, const gchar *pipe_prefix, gboolean byte_mode _U_)
1429 {
1430 #ifdef _WIN32
1431     gchar timestr[ 14 + 1 ];
1432     time_t current_time;
1433     gchar *pipename = NULL;
1434     SECURITY_ATTRIBUTES security;
1435
1436     /* create pipename */
1437     current_time = time(NULL);
1438     /*
1439      * XXX - we trust Windows not to return a time before the Epoch here,
1440      * so we won't get a null pointer back from localtime().
1441      */
1442     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
1443     pipename = g_strconcat("\\\\.\\pipe\\", pipe_prefix, "_", ifname, "_", timestr, NULL);
1444
1445     /* Security struct to enable Inheritable HANDLE */
1446     memset(&security, 0, sizeof(SECURITY_ATTRIBUTES));
1447     security.nLength = sizeof(SECURITY_ATTRIBUTES);
1448     security.bInheritHandle = TRUE;
1449     security.lpSecurityDescriptor = NULL;
1450
1451     /* create a namedPipe */
1452     pipe_h = CreateNamedPipe(
1453                  utf_8to16(pipename),
1454                  PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1455                  byte_mode ? PIPE_TYPE_BYTE : PIPE_TYPE_MESSAGE | byte_mode ? PIPE_READMODE_BYTE : PIPE_READMODE_MESSAGE | PIPE_WAIT,
1456                  1, 65536, 65536,
1457                  300,
1458                  &security);
1459
1460     if (pipe_h == INVALID_HANDLE_VALUE)
1461     {
1462         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nError creating pipe => (%d)", GetLastError());
1463         g_free (pipename);
1464         return FALSE;
1465     }
1466     else
1467     {
1468         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nWireshark Created pipe =>(%s)", pipename);
1469         *fifo = g_strdup(pipename);
1470     }
1471 #else
1472     gchar *temp_name = NULL;
1473     int fd = 0;
1474
1475     gchar *pfx = g_strconcat(pipe_prefix, "_", ifname, NULL);
1476     if ((fd = create_tempfile(&temp_name, pfx, NULL)) < 0)
1477     {
1478         g_free(pfx);
1479         return FALSE;
1480     }
1481     g_free(pfx);
1482
1483     ws_close(fd);
1484
1485     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1486           "Extcap - Creating fifo: %s", temp_name);
1487
1488     if (file_exists(temp_name))
1489     {
1490         ws_unlink(temp_name);
1491     }
1492
1493     if (mkfifo(temp_name, 0600) == 0)
1494     {
1495         *fifo = g_strdup(temp_name);
1496     }
1497 #endif
1498
1499     return TRUE;
1500 }
1501
1502 /************* EXTCAP LOAD INTERFACE LIST ***************
1503  *
1504  * The following code handles loading and reloading the interface list. It is explicitly
1505  * kept separate from the rest
1506  */
1507
1508
1509 static void
1510 extcap_free_interface_info(gpointer data)
1511 {
1512     extcap_info *info = (extcap_info *)data;
1513
1514     g_free(info->basename);
1515     g_free(info->full_path);
1516     g_free(info->version);
1517     g_free(info->help);
1518
1519     extcap_free_interfaces(info->interfaces);
1520
1521     g_free(info);
1522 }
1523
1524 static extcap_info *
1525 extcap_ensure_interface(const gchar * toolname, gboolean create_if_nonexist)
1526 {
1527     extcap_info * element = 0;
1528
1529     if ( ! toolname )
1530         return element;
1531
1532     if ( ! _loaded_interfaces )
1533         _loaded_interfaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_interface);
1534
1535     element = (extcap_info *) g_hash_table_lookup(_loaded_interfaces, toolname );
1536     if ( ! element && create_if_nonexist )
1537     {
1538         g_hash_table_insert(_loaded_interfaces, g_strdup(toolname), g_new0(extcap_info, 1));
1539         element = (extcap_info *) g_hash_table_lookup(_loaded_interfaces, toolname );
1540     }
1541
1542     return element;
1543 }
1544
1545 extcap_info *
1546 extcap_get_tool_by_ifname(const gchar *ifname)
1547 {
1548     if ( ifname && _tool_for_ifname )
1549     {
1550         gchar * toolname = (gchar *)g_hash_table_lookup(_tool_for_ifname, ifname);
1551         if ( toolname )
1552             return extcap_ensure_interface(toolname, FALSE);
1553     }
1554
1555     return NULL;
1556 }
1557
1558 extcap_info *
1559 extcap_get_tool_info(const gchar * toolname)
1560 {
1561     return extcap_ensure_interface(toolname, FALSE);
1562 }
1563
1564 static void remove_extcap_entry(gpointer entry, gpointer data _U_)
1565 {
1566     extcap_interface *int_iter = (extcap_interface*)entry;
1567
1568     if (int_iter->if_type == EXTCAP_SENTENCE_EXTCAP)
1569         extcap_free_interface(entry);
1570 }
1571
1572 static gboolean cb_load_interfaces(extcap_callback_info_t cb_info)
1573 {
1574     GList * interfaces = NULL, * control_items = NULL, * walker = NULL;
1575     extcap_interface * int_iter = NULL;
1576     extcap_info * element = NULL;
1577     iface_toolbar * toolbar_entry = NULL;
1578     gchar * toolname = g_path_get_basename(cb_info.extcap);
1579
1580     GList * interface_keys = g_hash_table_get_keys(_loaded_interfaces);
1581
1582     /* Load interfaces from utility */
1583     interfaces = extcap_parse_interfaces(cb_info.output, &control_items);
1584
1585     if (control_items)
1586     {
1587         toolbar_entry = g_new0(iface_toolbar, 1);
1588         toolbar_entry->controls = control_items;
1589     }
1590
1591     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Loading interface list for %s ", cb_info.extcap);
1592
1593     /* Seems, that there where no interfaces to be loaded */
1594     if ( ! interfaces || g_list_length(interfaces) == 0 )
1595     {
1596         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Cannot load interfaces for %s", cb_info.extcap );
1597         /* Some utilities, androiddump for example, may actually don't present any interfaces, even
1598          * if the utility itself is present. In such a case, we return here, but do not return
1599          * FALSE, or otherwise further loading of other utilities will be stopped */
1600         g_list_free(interface_keys);
1601         g_free(toolname);
1602         return TRUE;
1603     }
1604
1605     /* Load or create the storage element for the tool */
1606     element = extcap_ensure_interface(toolname, TRUE);
1607     if ( element == NULL )
1608     {
1609         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_ERROR, "Cannot store interface %s, maybe duplicate?", cb_info.extcap );
1610         g_list_foreach(interfaces, remove_extcap_entry, NULL);
1611         g_list_free(interfaces);
1612         g_list_free(interface_keys);
1613         g_free(toolname);
1614         return FALSE;
1615     }
1616
1617     walker = interfaces;
1618     gchar* help = NULL;
1619     while (walker != NULL)
1620     {
1621         int_iter = (extcap_interface *)walker->data;
1622
1623         if (int_iter->call != NULL)
1624             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Interface found %s\n", int_iter->call);
1625
1626         /* Help is not necessarily stored with the interface, but rather with the version string.
1627          * As the version string allways comes in front of the interfaces, this ensures, that it get's
1628          * properly stored with the interface */
1629         if (int_iter->if_type == EXTCAP_SENTENCE_EXTCAP)
1630         {
1631             if (int_iter->call != NULL)
1632                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Extcap [%s] ", int_iter->call);
1633
1634             /* Only initialize values if none are set. Need to check only one element here */
1635             if ( ! element->version )
1636             {
1637                 element->version = g_strdup(int_iter->version);
1638                 element->basename = g_strdup(toolname);
1639                 element->full_path = g_strdup(cb_info.extcap);
1640                 element->help = g_strdup(int_iter->help);
1641             }
1642
1643             help = int_iter->help;
1644             if (toolbar_entry)
1645             {
1646                 toolbar_entry->menu_title = g_strdup(int_iter->display);
1647                 toolbar_entry->help = g_strdup(int_iter->help);
1648             }
1649
1650             walker = g_list_next(walker);
1651             continue;
1652         }
1653
1654         /* Only interface definitions will be parsed here. help is already set by the extcap element,
1655          * which makes it necessary to have version in the list before the interfaces. This is normally
1656          * the case by design, but could be changed by separating the information in extcap-base. */
1657         if ( int_iter->if_type == EXTCAP_SENTENCE_INTERFACE )
1658         {
1659             if ( g_list_find(interface_keys, int_iter->call) )
1660             {
1661                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_WARNING, "Extcap interface \"%s\" is already provided by \"%s\" ",
1662                       int_iter->call, (gchar *)extcap_if_executable(int_iter->call));
1663                 walker = g_list_next(walker);
1664                 continue;
1665             }
1666
1667             if ((int_iter->call != NULL) && (int_iter->display))
1668                 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Interface [%s] \"%s\" ", int_iter->call, int_iter->display);
1669
1670             int_iter->extcap_path = g_strdup(cb_info.extcap);
1671
1672             /* Only set the help, if it exists and no parsed help information is present */
1673             if ( ! int_iter->help && help )
1674                 int_iter->help = g_strdup(help);
1675
1676             element->interfaces = g_list_append(element->interfaces, int_iter);
1677             g_hash_table_insert(_tool_for_ifname, g_strdup(int_iter->call), g_strdup(toolname));
1678
1679             if (toolbar_entry)
1680             {
1681                 if (!toolbar_entry->menu_title)
1682                 {
1683                     toolbar_entry->menu_title = g_strdup(int_iter->display);
1684                 }
1685                 toolbar_entry->ifnames = g_list_append(toolbar_entry->ifnames, g_strdup(int_iter->call));
1686             }
1687         }
1688
1689         walker = g_list_next(walker);
1690     }
1691
1692     if (toolbar_entry && toolbar_entry->menu_title)
1693     {
1694         iface_toolbar_add(toolbar_entry);
1695         extcap_iface_toolbar_add(cb_info.extcap, toolbar_entry);
1696     }
1697
1698     g_list_foreach(interfaces, remove_extcap_entry, NULL);
1699     g_list_free(interfaces);
1700     g_list_free(interface_keys);
1701     g_free(toolname);
1702     return TRUE;
1703 }
1704
1705
1706 /* Handles loading of the interfaces.
1707  *
1708  * A list of interfaces can be obtained by calling \ref extcap_loaded_interfaces
1709  */
1710 static void
1711 extcap_load_interface_list(void)
1712 {
1713     gchar *argv;
1714     gchar *error;
1715
1716     if (_toolbars)
1717     {
1718         // Remove existing interface toolbars here instead of in extcap_clear_interfaces()
1719         // to avoid flicker in shown toolbars when refreshing interfaces.
1720         GList *toolbar_list = g_hash_table_get_values (_toolbars);
1721         for (GList *walker = toolbar_list; walker; walker = walker->next)
1722         {
1723             iface_toolbar *toolbar = (iface_toolbar *) walker->data;
1724             iface_toolbar_remove(toolbar->menu_title);
1725         }
1726         g_hash_table_remove_all(_toolbars);
1727     } else {
1728         _toolbars = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_toolbar);
1729     }
1730
1731     if (_loaded_interfaces == NULL)
1732     {
1733         _loaded_interfaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_interface_info);
1734         /* Cleanup lookup table */
1735         if ( _tool_for_ifname )
1736         {
1737             g_hash_table_remove_all(_tool_for_ifname);
1738             _tool_for_ifname = 0;
1739         } else {
1740             _tool_for_ifname = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
1741         }
1742
1743         argv = g_strdup(EXTCAP_ARGUMENT_LIST_INTERFACES);
1744
1745         extcap_callback_info_t cb_info;
1746         cb_info.data = NULL;
1747         cb_info.ifname = NULL;
1748         cb_info.err_str = &error;
1749
1750         extcap_foreach(1, &argv, cb_load_interfaces, cb_info);
1751
1752         g_free(argv);
1753     }
1754 }
1755
1756 /*
1757  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1758  *
1759  * Local variables:
1760  * c-basic-offset: 4
1761  * tab-width: 8
1762  * indent-tabs-mode: nil
1763  * End:
1764  *
1765  * vi: set shiftwidth=4 tabstop=8 expandtab:
1766  * :indentSize=4:tabSize=8:noTabs=true:
1767  */