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