extcap: add null check (CID 1364683).
[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 + 1);
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 )
755         {
756             if ( userdata->extcap_stderr != NULL )
757                 overwrite_exitcode = TRUE;
758
759             if ( overwrite_exitcode || userdata->exitcode != 0 )
760             {
761                 if ( userdata->extcap_stderr != 0 )
762                 {
763                     if ( *errormsg == NULL )
764                         *errormsg = g_strdup_printf("Error by extcap pipe: %s", userdata->extcap_stderr);
765                     else
766                     {
767                         gchar * temp = g_strconcat ( *errormsg, "\nError by extcap pipe: " ,userdata->extcap_stderr, NULL );
768                         g_free(*errormsg);
769                         *errormsg = temp;
770                     }
771                     g_free (userdata->extcap_stderr );
772                 }
773
774                 userdata->extcap_stderr = NULL;
775                 userdata->exitcode = 0;
776             }
777         }
778
779         if (interface_opts.extcap_child_watch > 0)
780         {
781             g_source_remove(interface_opts.extcap_child_watch);
782             interface_opts.extcap_child_watch = 0;
783         }
784
785         if (interface_opts.extcap_pid != INVALID_EXTCAP_PID)
786         {
787 #ifdef _WIN32
788             TerminateProcess(interface_opts.extcap_pid, 0);
789 #endif
790             g_spawn_close_pid(interface_opts.extcap_pid);
791             interface_opts.extcap_pid = INVALID_EXTCAP_PID;
792
793             g_free(interface_opts.extcap_userdata);
794             interface_opts.extcap_userdata = NULL;
795         }
796
797         /* Make sure modified interface_opts is saved in capture_opts. */
798         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, icnt);
799         g_array_insert_val(capture_opts->ifaces, icnt, interface_opts);
800     }
801 }
802
803 static gboolean
804 extcap_add_arg_and_remove_cb(gpointer key, gpointer value, gpointer data) {
805     GPtrArray *args = (GPtrArray *)data;
806
807     if ( key != NULL )
808     {
809         g_ptr_array_add(args, g_strdup((const gchar*)key));
810
811         if ( value != NULL )
812             g_ptr_array_add(args, g_strdup((const gchar*)value));
813
814         return TRUE;
815     }
816
817     return FALSE;
818 }
819
820 void extcap_child_watch_cb(GPid pid, gint status _U_, gpointer user_data)
821 {
822     guint i;
823     interface_options interface_opts;
824     GError * error = 0;
825     extcap_userdata * userdata = NULL;
826     capture_options * capture_opts = (capture_options *)(user_data);
827
828     if ( capture_opts == NULL || capture_opts->ifaces == NULL || capture_opts->ifaces->len == 0 )
829         return;
830
831     /* Close handle to child process. */
832     g_spawn_close_pid(pid);
833
834     /* Update extcap_pid in interface options structure. */
835     for (i = 0; i < capture_opts->ifaces->len; i++)
836     {
837         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
838         if (interface_opts.extcap_pid == pid)
839         {
840             userdata = (extcap_userdata *)interface_opts.extcap_userdata;
841             if ( userdata != NULL )
842             {
843                 interface_opts.extcap_pid = INVALID_EXTCAP_PID;
844                 userdata->exitcode = 0;
845                 if ( ! g_spawn_check_exit_status(status, &error) )
846                     userdata->exitcode = error->code;
847                 if ( status == 0 && userdata->extcap_stderr != NULL )
848                     userdata->exitcode = 1;
849             }
850             g_source_remove(interface_opts.extcap_child_watch);
851             interface_opts.extcap_child_watch = 0;
852
853             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
854             g_array_insert_val(capture_opts->ifaces, i, interface_opts);
855             break;
856         }
857     }
858 }
859
860 static
861 GPtrArray * extcap_prepare_arguments(interface_options interface_opts)
862 {
863     GPtrArray *result = NULL;
864 #if ARG_DEBUG
865     gchar **tmp;
866     int tmp_i;
867 #endif
868
869     if (interface_opts.if_type == IF_EXTCAP )
870     {
871         result = g_ptr_array_new();
872
873 #define add_arg(X) g_ptr_array_add(result, g_strdup(X))
874
875         add_arg(interface_opts.extcap);
876         add_arg(EXTCAP_ARGUMENT_RUN_CAPTURE);
877         add_arg(EXTCAP_ARGUMENT_INTERFACE);
878         add_arg(interface_opts.name);
879         if (interface_opts.cfilter && strlen(interface_opts.cfilter) > 0) {
880             add_arg(EXTCAP_ARGUMENT_CAPTURE_FILTER);
881             add_arg(interface_opts.cfilter);
882         }
883         add_arg(EXTCAP_ARGUMENT_RUN_PIPE);
884         add_arg(interface_opts.extcap_fifo);
885         if (interface_opts.extcap_args == NULL || g_hash_table_size(interface_opts.extcap_args) == 0)
886         {
887             /* User did not perform interface configuration.
888              *
889              * Check if there are any boolean flags that are set by default
890              * and hence their argument should be added.
891              */
892             GList *arglist;
893             GList *elem;
894
895             arglist = extcap_get_if_configuration(interface_opts.name);
896             for (elem = g_list_first(arglist); elem; elem = elem->next)
897             {
898                 GList * arg_list;
899                 extcap_arg *arg_iter;
900
901                 if (elem->data == NULL)
902                 {
903                     continue;
904                 }
905
906                 arg_list = g_list_first((GList *)elem->data);
907                 while (arg_list != NULL) {
908                     gchar * stored = NULL, * defval = NULL;
909                     /* In case of boolflags only first element in arg_list is relevant. */
910                     arg_iter = (extcap_arg*) (arg_list->data);
911                     if ( arg_iter->storeval != NULL )
912                         stored = arg_iter->storeval;
913
914                     if ( arg_iter->default_complex != NULL && arg_iter->default_complex->_val != NULL )
915                         defval = arg_iter->default_complex->_val;
916
917                     /* Different data in storage then set for default */
918                     if ( g_strcmp0(stored, defval) != 0 ) {
919                         if ( arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG ) {
920                             if ( g_strcmp0(stored, "true") == 0 )
921                                 add_arg(arg_iter->call);
922                         } else {
923                             gchar * call = g_strconcat(arg_iter->call, " ", stored, NULL);
924                             add_arg(call);
925                             g_free(call);
926                         }
927                     } else if  (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG) {
928                         if (extcap_complex_get_bool(arg_iter->default_complex))
929                             add_arg(arg_iter->call);
930                     }
931
932                     arg_list = arg_list->next;
933                 }
934             }
935
936             extcap_free_if_configuration(arglist);
937         }
938         else
939         {
940             g_hash_table_foreach_remove(interface_opts.extcap_args, extcap_add_arg_and_remove_cb, result);
941         }
942         add_arg(NULL);
943 #undef add_arg
944
945 #if ARG_DEBUG
946         /* Dump commandline parameters sent to extcap. */
947         for (tmp = (gchar **)result->pdata, tmp_i = 0; *tmp && **tmp; ++tmp_i, ++tmp)
948         {
949             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "argv[%d]: %s", tmp_i, *tmp);
950         }
951 #endif
952
953     }
954
955     return result;
956 }
957
958 /* call mkfifo for each extcap,
959  * returns FALSE if there's an error creating a FIFO */
960 gboolean
961 extcap_init_interfaces(capture_options *capture_opts)
962 {
963     guint i;
964     interface_options interface_opts;
965     extcap_userdata * userdata;
966
967     for (i = 0; i < capture_opts->ifaces->len; i++)
968     {
969         GPtrArray *args = NULL;
970         GPid pid = INVALID_EXTCAP_PID;
971
972         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
973
974         /* skip native interfaces */
975         if (interface_opts.if_type != IF_EXTCAP )
976             continue;
977
978         /* create pipe for fifo */
979         if ( ! extcap_create_pipe ( &interface_opts.extcap_fifo ) )
980             return FALSE;
981
982         /* Create extcap call */
983         args = extcap_prepare_arguments(interface_opts);
984
985         userdata = g_new0(extcap_userdata, 1);
986
987         pid = extcap_spawn_async(userdata, args );
988
989         g_ptr_array_foreach(args, (GFunc)g_free, NULL);
990         g_ptr_array_free(args, TRUE);
991
992         if ( pid == INVALID_EXTCAP_PID )
993         {
994             g_free(userdata);
995             continue;
996         }
997
998         interface_opts.extcap_pid = pid;
999
1000         interface_opts.extcap_child_watch =
1001             g_child_watch_add(pid, extcap_child_watch_cb, (gpointer)capture_opts);
1002
1003 #ifdef _WIN32
1004         /* On Windows, wait for extcap to connect to named pipe.
1005          * Some extcaps will present UAC screen to user.
1006          * 30 second timeout should be reasonable timeout for extcap to
1007          * connect to named pipe (including user interaction).
1008          * Wait on multiple object in case of extcap termination
1009          * without opening pipe.
1010          *
1011          * Minimum supported version of Windows: XP / Server 2003.
1012          */
1013         if (pid != INVALID_EXTCAP_PID)
1014         {
1015             extcap_wait_for_pipe(pipe_h, pid);
1016         }
1017
1018 #endif
1019
1020         interface_opts.extcap_userdata = (gpointer) userdata;
1021
1022         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
1023         g_array_insert_val(capture_opts->ifaces, i, interface_opts);
1024     }
1025
1026     return TRUE;
1027 }
1028
1029 #ifdef _WIN32
1030 /* called by capture_sync to get the CreatNamedPipe handle*/
1031 HANDLE
1032 extcap_get_win32_handle()
1033 {
1034     return pipe_h;
1035 }
1036 #endif
1037
1038 gboolean extcap_create_pipe(char ** fifo)
1039 {
1040 #ifdef _WIN32
1041     gchar timestr[ 14+1 ];
1042     time_t current_time;
1043
1044     gchar *pipename = NULL;
1045
1046     SECURITY_ATTRIBUTES security;
1047     /* create pipename */
1048     current_time = time(NULL);
1049     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
1050     pipename = g_strconcat ( "\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, "_", timestr, NULL );
1051
1052     /* Security struct to enable Inheritable HANDLE */
1053     memset(&security, 0, sizeof(SECURITY_ATTRIBUTES));
1054     security.nLength = sizeof(SECURITY_ATTRIBUTES);
1055     security.bInheritHandle = TRUE;
1056     security.lpSecurityDescriptor = NULL;
1057
1058     /* create a namedPipe*/
1059     pipe_h = CreateNamedPipe(
1060                 utf_8to16(pipename),
1061                 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1062                 PIPE_TYPE_MESSAGE| PIPE_READMODE_MESSAGE | PIPE_WAIT,
1063                 5, 65536, 65536,
1064                 300,
1065                 &security);
1066
1067     if (pipe_h == INVALID_HANDLE_VALUE)
1068     {
1069         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,"\nError creating pipe => (%d)", GetLastError());
1070         return FALSE;
1071     }
1072     else
1073     {
1074         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,"\nWireshark Created pipe =>(%s)",pipename);
1075         *fifo = g_strdup(pipename);
1076     }
1077 #else
1078     gchar *temp_name = NULL;
1079     int fd = 0;
1080
1081     if ((fd = create_tempfile(&temp_name, EXTCAP_PIPE_PREFIX, NULL)) < 0 )
1082         return FALSE;
1083
1084     ws_close(fd);
1085
1086     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1087             "Extcap - Creating fifo: %s", temp_name);
1088
1089     if ( file_exists(temp_name) )
1090         ws_unlink(temp_name);
1091
1092     if (mkfifo(temp_name, 0600) == 0)
1093         *fifo = g_strdup(temp_name);
1094 #endif
1095
1096     return TRUE;
1097 }
1098
1099 #if ARG_DEBUG
1100 void extcap_debug_arguments ( extcap_arg *arg_iter )
1101 {
1102     extcap_value *v = NULL;
1103     GList *walker = NULL;
1104
1105     printf("debug - parser dump\n");
1106     while (arg_iter != NULL) {
1107         printf("ARG %d call=%s display=\"%s\" type=", arg_iter->arg_num, arg_iter->call, arg_iter->display);
1108
1109         switch (arg_iter->arg_type) {
1110             case EXTCAP_ARG_INTEGER:
1111             printf("int\n");
1112             break;
1113             case EXTCAP_ARG_UNSIGNED:
1114             printf("unsigned\n");
1115             break;
1116             case EXTCAP_ARG_LONG:
1117             printf("long\n");
1118             break;
1119             case EXTCAP_ARG_DOUBLE:
1120             printf("double\n");
1121             break;
1122             case EXTCAP_ARG_BOOLEAN:
1123             printf("boolean\n");
1124             break;
1125             case EXTCAP_ARG_MENU:
1126             printf("menu\n");
1127             break;
1128             case EXTCAP_ARG_RADIO:
1129             printf("radio\n");
1130             break;
1131             case EXTCAP_ARG_SELECTOR:
1132             printf("selctor\n");
1133             break;
1134             case EXTCAP_ARG_STRING:
1135             printf ( "string\n" );
1136             break;
1137             case EXTCAP_ARG_PASSWORD:
1138             printf ( "PASSWORD\n" );
1139             break;
1140             case EXTCAP_ARG_MULTICHECK:
1141             printf ( "unknown\n" );
1142             break;
1143             case EXTCAP_ARG_UNKNOWN:
1144             printf ( "unknown\n" );
1145             break;
1146         }
1147
1148         if (arg_iter->range_start != NULL && arg_iter->range_end != NULL) {
1149             printf("\tRange: ");
1150             extcap_printf_complex(arg_iter->range_start);
1151             printf(" - ");
1152             extcap_printf_complex(arg_iter->range_end);
1153             printf("\n");
1154         }
1155
1156         for ( walker = g_list_first ( arg_iter->value_list ); walker; walker = walker->next )
1157         {
1158             v = (extcap_value *)walker->data;
1159             if (v->is_default)
1160             printf("*");
1161             printf("\tcall=\"%p\" display=\"%p\"\n", v->call, v->display);
1162             printf("\tcall=\"%s\" display=\"%s\"\n", v->call, v->display);
1163         }
1164
1165         arg_iter = arg_iter->next_arg;
1166     }
1167 }
1168 #endif
1169
1170 /*
1171  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1172  *
1173  * Local variables:
1174  * c-basic-offset: 4
1175  * tab-width: 8
1176  * indent-tabs-mode: nil
1177  * End:
1178  *
1179  * vi: set shiftwidth=4 tabstop=8 expandtab:
1180  * :indentSize=4:tabSize=8:noTabs=true:
1181  */