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