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