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