78d357acd616c7db1da8b26124d35cf55439d0e8
[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 = g_regex_new ("[-]+", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL );
492     if (regex) {
493         if ( prefs_find_module("extcap") ) {
494             gchar * pref_name = g_regex_replace(regex, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL );
495             gchar * pref_ifname = g_strdup(g_strconcat(ifname, ".", pref_name, NULL));
496
497             pref = prefs_find_preference(prefs_find_module("extcap"), pref_ifname);
498
499             g_free(pref_name);
500             g_free(pref_ifname);
501         }
502         g_regex_unref(regex);
503     }
504
505     return pref;
506 }
507
508 static gboolean search_cb(const gchar *extcap _U_, const gchar *ifname _U_, gchar *output, void *data,
509         char **err_str _U_) {
510     extcap_token_sentence *tokens = NULL;
511     GList *arguments = NULL;
512     GList **il = (GList **) data;
513     module_t * dev_module = NULL;
514
515     tokens = extcap_tokenize_sentences(output);
516     arguments = extcap_parse_args(tokens);
517
518     extcap_free_tokenized_sentence_list(tokens);
519
520 #if ARG_DEBUG
521     extcap_debug_arguments ( arguments );
522 #endif
523
524     dev_module = prefs_find_module("extcap");
525
526     if ( dev_module ) {
527         GList * walker = arguments;
528
529         GRegex * regex = g_regex_new ("[-]+", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL );
530         if (regex) {
531             while ( walker != NULL ) {
532                 extcap_arg * arg = (extcap_arg *)walker->data;
533                 arg->device_name = g_strdup(ifname);
534
535                 if ( arg->save ) {
536                     struct preference * pref = NULL;
537
538                     gchar * pref_name = g_regex_replace(regex, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL );
539                     gchar * pref_ifname = g_strdup(g_strconcat(ifname, ".", pref_name, NULL));
540
541                     if ( ( pref = prefs_find_preference(dev_module, pref_ifname) ) == NULL ) {
542                         /* Set an initial value */
543                         if ( ! arg->storeval && arg->default_complex )
544                         {
545                             arg->storeval = extcap_prefs_dynamic_valptr(pref_ifname);
546                             g_snprintf(arg->storeval, EXTCAP_PREF_SIZE, "%s", arg->default_complex->_val);
547                         }
548
549                         prefs_register_string_preference(dev_module, g_strdup(pref_ifname),
550                                 arg->display, arg->display, (const gchar **)&(arg->storeval));
551                     } else {
552                         /* Been here before, restore stored value */
553                         if (! arg->storeval && pref->varp.string)
554                         {
555                             arg->storeval = extcap_prefs_dynamic_valptr(pref_ifname);
556                             g_snprintf(arg->storeval, EXTCAP_PREF_SIZE, "%s", *(pref->varp.string));
557                         }
558                     }
559
560                     g_free(pref_name);
561                     g_free(pref_ifname);
562                 }
563
564                 walker = g_list_next(walker);
565             }
566             g_regex_unref(regex);
567         }
568     }
569
570     *il = g_list_append(*il, arguments);
571
572     /* By returning false, extcap_foreach will break on first found */
573     return TRUE;
574 }
575
576 GList *
577 extcap_get_if_configuration(const char * ifname) {
578     gchar *argv[3];
579     GList *ret = NULL;
580     gchar **err_str = NULL;
581     int i;
582
583     if ( extcap_if_exists(ifname) )
584     {
585         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
586                 get_extcap_dir());
587
588         argv[0] = g_strdup(EXTCAP_ARGUMENT_CONFIG);
589         argv[1] = g_strdup(EXTCAP_ARGUMENT_INTERFACE);
590         argv[2] = g_strdup(ifname);
591
592         extcap_foreach(3, argv, search_cb, &ret, err_str, ifname);
593
594         for (i = 0; i < 3; i++)
595             g_free(argv[i]);
596     }
597
598     return ret;
599 }
600
601 gboolean
602 extcap_has_configuration(const char * ifname, gboolean is_required) {
603     GList * arguments = 0;
604     GList * walker = 0, * item = 0;
605
606     gboolean found = FALSE;
607
608     arguments = extcap_get_if_configuration((const char *)( ifname ) );
609     walker = g_list_first(arguments);
610
611     while ( walker != NULL && ! found ) {
612         item = g_list_first((GList *)(walker->data));
613         while ( item != NULL && ! found ) {
614             if ( (extcap_arg *)(item->data) != NULL ) {
615                 extcap_arg * arg = (extcap_arg *)(item->data);
616                 /* Should required options be present, or any kind of options */
617                 if ( ! is_required )
618                     found = TRUE;
619                 else if ( arg->is_required ) {
620                     gchar * stored = NULL;
621                     gchar * defval = NULL;
622
623                     if ( arg->storeval != NULL )
624                         stored = arg->storeval;
625
626                     if ( arg->default_complex != NULL && arg->default_complex->_val != NULL )
627                         defval = arg->default_complex->_val;
628
629                     if ( arg->is_required ) {
630                         /* If stored and defval is identical and the argument is required,
631                          * configuration is needed */
632                         if ( defval && stored && g_strcmp0(stored, defval) == 0 )
633                             found = TRUE;
634                         else if ( ! defval && (!stored || strlen(g_strchomp(stored)) <= (size_t)0) )
635                             found = TRUE;
636                     }
637
638                     if ( arg->arg_type == EXTCAP_ARG_FILESELECT ) {
639                         if ( arg->fileexists && ! ( file_exists(defval) || file_exists(stored) ) )
640                             found = TRUE;
641                     }
642                 }
643             }
644
645             item = item->next;
646         }
647         walker = walker->next;
648     }
649     extcap_free_if_configuration(arguments);
650
651     return found;
652 }
653
654 /* taken from capchild/capture_sync.c */
655 static gboolean pipe_data_available(int pipe_fd) {
656 #ifdef _WIN32 /* PeekNamedPipe */
657     HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
658     DWORD bytes_avail;
659
660     if (hPipe == INVALID_HANDLE_VALUE)
661         return FALSE;
662
663     if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
664         return FALSE;
665
666     if (bytes_avail > 0)
667         return TRUE;
668     return FALSE;
669 #else /* select */
670     fd_set rfds;
671     struct timeval timeout;
672
673     FD_ZERO(&rfds);
674     FD_SET(pipe_fd, &rfds);
675     timeout.tv_sec = 0;
676     timeout.tv_usec = 0;
677
678     if (select(pipe_fd+1, &rfds, NULL, NULL, &timeout) > 0)
679         return TRUE;
680
681     return FALSE;
682 #endif
683 }
684
685 void extcap_if_cleanup(capture_options * capture_opts, gchar ** errormsg) {
686     interface_options interface_opts;
687     extcap_userdata * userdata;
688     guint icnt = 0;
689     gboolean overwrite_exitcode;
690     gchar * buffer;
691 #define STDERR_BUFFER_SIZE 1024
692
693     for (icnt = 0; icnt < capture_opts->ifaces->len; icnt++) {
694         interface_opts = g_array_index(capture_opts->ifaces, interface_options,
695                 icnt);
696
697         /* skip native interfaces */
698         if (interface_opts.if_type != IF_EXTCAP)
699             continue;
700
701         overwrite_exitcode = FALSE;
702
703         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
704                 "Extcap [%s] - Cleaning up fifo: %s; PID: %d", interface_opts.name,
705                 interface_opts.extcap_fifo, interface_opts.extcap_pid);
706 #ifdef _WIN32
707         if (pipe_h)
708         {
709             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
710                 "Extcap [%s] - Closing pipe", interface_opts.name);
711             FlushFileBuffers(pipe_h);
712             DisconnectNamedPipe(pipe_h);
713             CloseHandle(pipe_h);
714         }
715 #else
716         if (interface_opts.extcap_fifo != NULL && file_exists(interface_opts.extcap_fifo))
717         {
718             /* the fifo will not be freed here, but with the other capture_opts in capture_sync */
719             ws_unlink(interface_opts.extcap_fifo);
720             interface_opts.extcap_fifo = NULL;
721         }
722 #endif
723         /* Maybe the client closed and removed fifo, but ws should check if
724          * pid should be closed */
725         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
726                 "Extcap [%s] - Closing spawned PID: %d", interface_opts.name,
727                 interface_opts.extcap_pid);
728
729         userdata = (extcap_userdata *) interface_opts.extcap_userdata;
730         if ( userdata )
731         {
732             if (userdata->extcap_stderr_rd > 0 && pipe_data_available(userdata->extcap_stderr_rd) )
733             {
734                 buffer = (gchar * )g_malloc0(sizeof(gchar) * STDERR_BUFFER_SIZE + 1);
735 #ifdef _WIN32
736                 win32_readfrompipe((HANDLE)_get_osfhandle(userdata->extcap_stderr_rd), STDERR_BUFFER_SIZE, buffer);
737 #else
738                 if (read(userdata->extcap_stderr_rd, buffer, sizeof(gchar) * STDERR_BUFFER_SIZE) <= 0 )
739                     buffer[0] = '\0';
740 #endif
741                 if ( strlen ( buffer) > 0 )
742                 {
743                     userdata->extcap_stderr = g_strdup_printf("%s", buffer);
744                     userdata->exitcode = 1;
745                 }
746                 g_free(buffer);
747             }
748         }
749
750 #ifndef _WIN32
751         /* Final child watch may not have been called */
752         if ( interface_opts.extcap_child_watch != 0 )
753         {
754             extcap_child_watch_cb(userdata->pid, 0, capture_opts);
755             /* it will have changed in extcap_child_watch_cb */
756             interface_opts = g_array_index(capture_opts->ifaces, interface_options,
757                             icnt);
758         }
759 #endif
760
761         if ( userdata )
762         {
763             if ( userdata->extcap_stderr != NULL )
764                 overwrite_exitcode = TRUE;
765
766             if ( overwrite_exitcode || userdata->exitcode != 0 )
767             {
768                 if ( userdata->extcap_stderr != 0 )
769                 {
770                     if ( *errormsg == NULL )
771                         *errormsg = g_strdup_printf("Error by extcap pipe: %s", userdata->extcap_stderr);
772                     else
773                     {
774                         gchar * temp = g_strconcat ( *errormsg, "\nError by extcap pipe: " ,userdata->extcap_stderr, NULL );
775                         g_free(*errormsg);
776                         *errormsg = temp;
777                     }
778                     g_free (userdata->extcap_stderr );
779                 }
780
781                 userdata->extcap_stderr = NULL;
782                 userdata->exitcode = 0;
783             }
784         }
785
786         if (interface_opts.extcap_child_watch > 0)
787         {
788             g_source_remove(interface_opts.extcap_child_watch);
789             interface_opts.extcap_child_watch = 0;
790         }
791
792         if (interface_opts.extcap_pid != INVALID_EXTCAP_PID)
793         {
794 #ifdef _WIN32
795             TerminateProcess(interface_opts.extcap_pid, 0);
796 #endif
797             g_spawn_close_pid(interface_opts.extcap_pid);
798             interface_opts.extcap_pid = INVALID_EXTCAP_PID;
799
800             g_free(interface_opts.extcap_userdata);
801             interface_opts.extcap_userdata = NULL;
802         }
803
804         /* Make sure modified interface_opts is saved in capture_opts. */
805         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, icnt);
806         g_array_insert_val(capture_opts->ifaces, icnt, interface_opts);
807     }
808 }
809
810 static gboolean
811 extcap_add_arg_and_remove_cb(gpointer key, gpointer value, gpointer data) {
812     GPtrArray *args = (GPtrArray *)data;
813
814     if ( key != NULL )
815     {
816         g_ptr_array_add(args, g_strdup((const gchar*)key));
817
818         if ( value != NULL )
819             g_ptr_array_add(args, g_strdup((const gchar*)value));
820
821         return TRUE;
822     }
823
824     return FALSE;
825 }
826
827 void extcap_child_watch_cb(GPid pid, gint status _U_, gpointer user_data)
828 {
829     guint i;
830     interface_options interface_opts;
831     extcap_userdata * userdata = NULL;
832     capture_options * capture_opts = (capture_options *)(user_data);
833
834     if ( capture_opts == NULL || capture_opts->ifaces == NULL || capture_opts->ifaces->len == 0 )
835         return;
836
837     /* Close handle to child process. */
838     g_spawn_close_pid(pid);
839
840     /* Update extcap_pid in interface options structure. */
841     for (i = 0; i < capture_opts->ifaces->len; i++)
842     {
843         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
844         if (interface_opts.extcap_pid == pid)
845         {
846             userdata = (extcap_userdata *)interface_opts.extcap_userdata;
847             if ( userdata != NULL )
848             {
849                 interface_opts.extcap_pid = INVALID_EXTCAP_PID;
850                 userdata->exitcode = 0;
851 #ifndef _WIN32
852                 if ( WIFEXITED(status) )
853                 {
854                     if ( WEXITSTATUS(status) != 0 )
855                         userdata->exitcode = WEXITSTATUS(status);
856                 }
857                 else
858                     userdata->exitcode = G_SPAWN_ERROR_FAILED;
859 #else
860                 if (status != 0)
861                     userdata->exitcode = status;
862 #endif
863                 if ( status == 0 && userdata->extcap_stderr != NULL )
864                     userdata->exitcode = 1;
865             }
866             g_source_remove(interface_opts.extcap_child_watch);
867             interface_opts.extcap_child_watch = 0;
868
869             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
870             g_array_insert_val(capture_opts->ifaces, i, interface_opts);
871             break;
872         }
873     }
874 }
875
876 static
877 GPtrArray * extcap_prepare_arguments(interface_options interface_opts)
878 {
879     GPtrArray *result = NULL;
880 #if ARG_DEBUG
881     gchar **tmp;
882     int tmp_i;
883 #endif
884
885     if (interface_opts.if_type == IF_EXTCAP )
886     {
887         result = g_ptr_array_new();
888
889 #define add_arg(X) g_ptr_array_add(result, g_strdup(X))
890
891         add_arg(interface_opts.extcap);
892         add_arg(EXTCAP_ARGUMENT_RUN_CAPTURE);
893         add_arg(EXTCAP_ARGUMENT_INTERFACE);
894         add_arg(interface_opts.name);
895         if (interface_opts.cfilter && strlen(interface_opts.cfilter) > 0) {
896             add_arg(EXTCAP_ARGUMENT_CAPTURE_FILTER);
897             add_arg(interface_opts.cfilter);
898         }
899         add_arg(EXTCAP_ARGUMENT_RUN_PIPE);
900         add_arg(interface_opts.extcap_fifo);
901         if (interface_opts.extcap_args == NULL || g_hash_table_size(interface_opts.extcap_args) == 0)
902         {
903             /* User did not perform interface configuration.
904              *
905              * Check if there are any boolean flags that are set by default
906              * and hence their argument should be added.
907              */
908             GList *arglist;
909             GList *elem;
910
911             arglist = extcap_get_if_configuration(interface_opts.name);
912             for (elem = g_list_first(arglist); elem; elem = elem->next)
913             {
914                 GList * arg_list;
915                 extcap_arg *arg_iter;
916
917                 if (elem->data == NULL)
918                 {
919                     continue;
920                 }
921
922                 arg_list = g_list_first((GList *)elem->data);
923                 while (arg_list != NULL) {
924                     gchar * stored = NULL, * defval = NULL;
925                     /* In case of boolflags only first element in arg_list is relevant. */
926                     arg_iter = (extcap_arg*) (arg_list->data);
927                     if ( arg_iter->storeval != NULL )
928                         stored = arg_iter->storeval;
929
930                     if ( arg_iter->default_complex != NULL && arg_iter->default_complex->_val != NULL )
931                         defval = arg_iter->default_complex->_val;
932
933                     /* Different data in storage then set for default */
934                     if ( g_strcmp0(stored, defval) != 0 ) {
935                         if ( arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG ) {
936                             if ( g_strcmp0(stored, "true") == 0 )
937                                 add_arg(arg_iter->call);
938                         } else {
939                             gchar * call = g_strconcat(arg_iter->call, " ", stored, NULL);
940                             add_arg(call);
941                             g_free(call);
942                         }
943                     } else if  (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG) {
944                         if (extcap_complex_get_bool(arg_iter->default_complex))
945                             add_arg(arg_iter->call);
946                     }
947
948                     arg_list = arg_list->next;
949                 }
950             }
951
952             extcap_free_if_configuration(arglist);
953         }
954         else
955         {
956             g_hash_table_foreach_remove(interface_opts.extcap_args, extcap_add_arg_and_remove_cb, result);
957         }
958         add_arg(NULL);
959 #undef add_arg
960
961 #if ARG_DEBUG
962         /* Dump commandline parameters sent to extcap. */
963         for (tmp = (gchar **)result->pdata, tmp_i = 0; *tmp && **tmp; ++tmp_i, ++tmp)
964         {
965             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", tmp_i, *tmp);
966         }
967 #endif
968
969     }
970
971     return result;
972 }
973
974 /* call mkfifo for each extcap,
975  * returns FALSE if there's an error creating a FIFO */
976 gboolean
977 extcap_init_interfaces(capture_options *capture_opts)
978 {
979     guint i;
980     interface_options interface_opts;
981     extcap_userdata * userdata;
982
983     for (i = 0; i < capture_opts->ifaces->len; i++)
984     {
985         GPtrArray *args = NULL;
986         GPid pid = INVALID_EXTCAP_PID;
987
988         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
989
990         /* skip native interfaces */
991         if (interface_opts.if_type != IF_EXTCAP )
992             continue;
993
994         /* create pipe for fifo */
995         if ( ! extcap_create_pipe ( &interface_opts.extcap_fifo ) )
996             return FALSE;
997
998         /* Create extcap call */
999         args = extcap_prepare_arguments(interface_opts);
1000
1001         userdata = g_new0(extcap_userdata, 1);
1002
1003         pid = extcap_spawn_async(userdata, args );
1004
1005         g_ptr_array_foreach(args, (GFunc)g_free, NULL);
1006         g_ptr_array_free(args, TRUE);
1007
1008         if ( pid == INVALID_EXTCAP_PID )
1009         {
1010             g_free(userdata);
1011             continue;
1012         }
1013
1014         interface_opts.extcap_pid = pid;
1015
1016         interface_opts.extcap_child_watch =
1017             g_child_watch_add(pid, extcap_child_watch_cb, (gpointer)capture_opts);
1018
1019 #ifdef _WIN32
1020         /* On Windows, wait for extcap to connect to named pipe.
1021          * Some extcaps will present UAC screen to user.
1022          * 30 second timeout should be reasonable timeout for extcap to
1023          * connect to named pipe (including user interaction).
1024          * Wait on multiple object in case of extcap termination
1025          * without opening pipe.
1026          *
1027          * Minimum supported version of Windows: XP / Server 2003.
1028          */
1029         if (pid != INVALID_EXTCAP_PID)
1030         {
1031             extcap_wait_for_pipe(pipe_h, pid);
1032         }
1033
1034 #endif
1035
1036         interface_opts.extcap_userdata = (gpointer) userdata;
1037
1038         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
1039         g_array_insert_val(capture_opts->ifaces, i, interface_opts);
1040     }
1041
1042     return TRUE;
1043 }
1044
1045 #ifdef _WIN32
1046 /* called by capture_sync to get the CreatNamedPipe handle*/
1047 HANDLE
1048 extcap_get_win32_handle()
1049 {
1050     return pipe_h;
1051 }
1052 #endif
1053
1054 gboolean extcap_create_pipe(char ** fifo)
1055 {
1056 #ifdef _WIN32
1057     gchar timestr[ 14+1 ];
1058     time_t current_time;
1059
1060     gchar *pipename = NULL;
1061
1062     SECURITY_ATTRIBUTES security;
1063     /* create pipename */
1064     current_time = time(NULL);
1065     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
1066     pipename = g_strconcat ( "\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, "_", timestr, NULL );
1067
1068     /* Security struct to enable Inheritable HANDLE */
1069     memset(&security, 0, sizeof(SECURITY_ATTRIBUTES));
1070     security.nLength = sizeof(SECURITY_ATTRIBUTES);
1071     security.bInheritHandle = TRUE;
1072     security.lpSecurityDescriptor = NULL;
1073
1074     /* create a namedPipe*/
1075     pipe_h = CreateNamedPipe(
1076                 utf_8to16(pipename),
1077                 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1078                 PIPE_TYPE_MESSAGE| PIPE_READMODE_MESSAGE | PIPE_WAIT,
1079                 5, 65536, 65536,
1080                 300,
1081                 &security);
1082
1083     if (pipe_h == INVALID_HANDLE_VALUE)
1084     {
1085         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,"\nError creating pipe => (%d)", GetLastError());
1086         return FALSE;
1087     }
1088     else
1089     {
1090         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,"\nWireshark Created pipe =>(%s)",pipename);
1091         *fifo = g_strdup(pipename);
1092     }
1093 #else
1094     gchar *temp_name = NULL;
1095     int fd = 0;
1096
1097     if ((fd = create_tempfile(&temp_name, EXTCAP_PIPE_PREFIX, NULL)) < 0 )
1098         return FALSE;
1099
1100     ws_close(fd);
1101
1102     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1103             "Extcap - Creating fifo: %s", temp_name);
1104
1105     if ( file_exists(temp_name) )
1106         ws_unlink(temp_name);
1107
1108     if (mkfifo(temp_name, 0600) == 0)
1109         *fifo = g_strdup(temp_name);
1110 #endif
1111
1112     return TRUE;
1113 }
1114
1115 #if ARG_DEBUG
1116 void extcap_debug_arguments ( extcap_arg *arg_iter )
1117 {
1118     extcap_value *v = NULL;
1119     GList *walker = NULL;
1120
1121     printf("debug - parser dump\n");
1122     while (arg_iter != NULL) {
1123         printf("ARG %d call=%s display=\"%s\" type=", arg_iter->arg_num, arg_iter->call, arg_iter->display);
1124
1125         switch (arg_iter->arg_type) {
1126             case EXTCAP_ARG_INTEGER:
1127             printf("int\n");
1128             break;
1129             case EXTCAP_ARG_UNSIGNED:
1130             printf("unsigned\n");
1131             break;
1132             case EXTCAP_ARG_LONG:
1133             printf("long\n");
1134             break;
1135             case EXTCAP_ARG_DOUBLE:
1136             printf("double\n");
1137             break;
1138             case EXTCAP_ARG_BOOLEAN:
1139             printf("boolean\n");
1140             break;
1141             case EXTCAP_ARG_MENU:
1142             printf("menu\n");
1143             break;
1144             case EXTCAP_ARG_RADIO:
1145             printf("radio\n");
1146             break;
1147             case EXTCAP_ARG_SELECTOR:
1148             printf("selctor\n");
1149             break;
1150             case EXTCAP_ARG_STRING:
1151             printf ( "string\n" );
1152             break;
1153             case EXTCAP_ARG_PASSWORD:
1154             printf ( "PASSWORD\n" );
1155             break;
1156             case EXTCAP_ARG_MULTICHECK:
1157             printf ( "unknown\n" );
1158             break;
1159             case EXTCAP_ARG_UNKNOWN:
1160             printf ( "unknown\n" );
1161             break;
1162         }
1163
1164         if (arg_iter->range_start != NULL && arg_iter->range_end != NULL) {
1165             printf("\tRange: ");
1166             extcap_printf_complex(arg_iter->range_start);
1167             printf(" - ");
1168             extcap_printf_complex(arg_iter->range_end);
1169             printf("\n");
1170         }
1171
1172         for ( walker = g_list_first ( arg_iter->value_list ); walker; walker = walker->next )
1173         {
1174             v = (extcap_value *)walker->data;
1175             if (v->is_default)
1176             printf("*");
1177             printf("\tcall=\"%p\" display=\"%p\"\n", v->call, v->display);
1178             printf("\tcall=\"%s\" display=\"%s\"\n", v->call, v->display);
1179         }
1180
1181         arg_iter = arg_iter->next_arg;
1182     }
1183 }
1184 #endif
1185
1186 /*
1187  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1188  *
1189  * Local variables:
1190  * c-basic-offset: 4
1191  * tab-width: 8
1192  * indent-tabs-mode: nil
1193  * End:
1194  *
1195  * vi: set shiftwidth=4 tabstop=8 expandtab:
1196  * :indentSize=4:tabSize=8:noTabs=true:
1197  */