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