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