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