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