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