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