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