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