[GTPv2] Fix dissection of MM Context fpr EPS
[metze/wireshark/wip.git] / extcap.c
1 /* extcap.c
2  *
3  * Routines for extcap external capture
4  * Copyright 2013, Mike Ryan <mikeryan@lacklustre.net>
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include <config.h>
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #ifdef _WIN32
32 #include <windows.h>
33 #include <process.h>
34 #include <time.h>
35 #else
36 /* Include for unlink */
37 #include <unistd.h>
38 #endif
39
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43 #ifdef HAVE_SYS_WAIT_H
44 #include <sys/wait.h>
45 #endif
46
47 #include <glib.h>
48 #include <log.h>
49
50 #include <epan/prefs.h>
51 #include <epan/prefs-int.h>
52
53 #include <wsutil/file_util.h>
54 #include <wsutil/filesystem.h>
55 #include <wsutil/tempfile.h>
56
57 #include "capture_opts.h"
58
59 #include "extcap.h"
60 #include "extcap_parser.h"
61 #include "extcap_spawn.h"
62
63 #ifdef _WIN32
64 static HANDLE pipe_h = NULL;
65 #endif
66
67 static void extcap_child_watch_cb(GPid pid, gint status, gpointer user_data);
68
69 /* internal container, for all the extcap interfaces that have been found.
70  * will be resetted by every call to extcap_interface_list() and is being
71  * used in extcap_get_if_* as well as extcap_init_interfaces to ensure,
72  * that only extcap interfaces are being given to underlying extcap programs
73  */
74 static GHashTable *ifaces = NULL;
75
76 /* internal container, for all the extcap executables that have been found.
77  * will be resetted by every call to extcap_interface_list() and is being
78  * used for printing information about all extcap interfaces found
79  */
80 static GHashTable *tools = NULL;
81
82 /* internal container, to map preference names to pointers that hold preference
83  * values. These ensure that preferences can survive extcap if garbage
84  * collection, and does not lead to dangling pointers in the prefs subsystem.
85  */
86 static GHashTable *extcap_prefs_dynamic_vals = NULL;
87
88 /* Callback definition for extcap_foreach */
89 typedef gboolean(*extcap_cb_t)(const gchar *extcap, const gchar *ifname, gchar *output, void *data,
90                                gchar **err_str);
91
92 static gboolean
93 extcap_if_exists(const gchar *ifname)
94 {
95     if (!ifname || !ifaces)
96     {
97         return FALSE;
98     }
99
100     if (g_hash_table_lookup(ifaces, ifname))
101     {
102         return TRUE;
103     }
104
105     return FALSE;
106 }
107
108 static gboolean
109 extcap_if_exists_for_extcap(const gchar *ifname, const gchar *extcap)
110 {
111     extcap_interface *entry = (extcap_interface *)g_hash_table_lookup(ifaces, ifname);
112
113     if (entry && strcmp(entry->extcap_path, extcap) == 0)
114     {
115         return TRUE;
116     }
117
118     return FALSE;
119 }
120
121 static gchar *
122 extcap_if_executable(const gchar *ifname)
123 {
124     extcap_interface *interface = (extcap_interface *)g_hash_table_lookup(ifaces, ifname);
125     return interface != NULL ? interface->extcap_path : NULL;
126 }
127
128 static gboolean
129 extcap_if_add(extcap_interface *interface)
130 {
131     if (g_hash_table_lookup(ifaces, interface->call))
132     {
133         return FALSE;
134     }
135
136     g_hash_table_insert(ifaces, g_strdup(interface->call), interface);
137     return TRUE;
138 }
139
140 static void
141 extcap_free_info(gpointer data)
142 {
143     extcap_info *info = (extcap_info *)data;
144
145     g_free(info->basename);
146     g_free(info->full_path);
147     g_free(info->version);
148     g_free(info);
149 }
150
151 static void
152 extcap_tool_add(const gchar *extcap, const extcap_interface *interface)
153 {
154     char *toolname;
155
156     if (!extcap || !interface)
157     {
158         return;
159     }
160
161     toolname = g_path_get_basename(extcap);
162
163     if (!g_hash_table_lookup(tools, toolname))
164     {
165         extcap_info *store = (extcap_info *)g_new0(extcap_info, 1);
166         store->version = g_strdup(interface->version);
167         store->full_path = g_strdup(extcap);
168         store->basename = g_strdup(toolname);
169
170         g_hash_table_insert(tools, g_strdup(toolname), store);
171     }
172
173     g_free(toolname);
174 }
175
176 /* Note: args does not need to be NULL-terminated. */
177 static void extcap_foreach(gint argc, gchar **args, extcap_cb_t cb,
178                            void *cb_data, char **err_str, const char *ifname _U_)
179 {
180     const char *dirname = get_extcap_dir();
181     GDir *dir;
182     const gchar *file;
183     gboolean keep_going;
184
185     keep_going = TRUE;
186
187     if ((dir = g_dir_open(dirname, 0, NULL)) != NULL)
188     {
189         GString *extcap_path = NULL;
190
191         extcap_path = g_string_new("");
192         while (keep_going && (file = g_dir_read_name(dir)) != NULL)
193         {
194             gchar *command_output = NULL;
195
196             /* full path to extcap binary */
197             g_string_printf(extcap_path, "%s" G_DIR_SEPARATOR_S "%s", dirname, file);
198             if (extcap_if_exists(ifname) && !extcap_if_exists_for_extcap(ifname, extcap_path->str))
199             {
200                 continue;
201             }
202
203             if (extcap_spawn_sync((gchar *) dirname, extcap_path->str, argc, args, &command_output))
204             {
205                 keep_going = cb(extcap_path->str, ifname, command_output, cb_data, err_str);
206             }
207
208             g_free(command_output);
209         }
210
211         g_dir_close(dir);
212         g_string_free(extcap_path, TRUE);
213     }
214
215 }
216
217 static void extcap_free_dlt(gpointer d, gpointer user_data _U_)
218 {
219     if (d == NULL)
220     {
221         return;
222     }
223
224     g_free(((extcap_dlt *)d)->name);
225     g_free(((extcap_dlt *)d)->display);
226     g_free(d);
227 }
228
229 static void extcap_free_dlts(GList *dlts)
230 {
231     g_list_foreach(dlts, extcap_free_dlt, NULL);
232     g_list_free(dlts);
233 }
234
235 static gboolean dlt_cb(const gchar *extcap _U_, const gchar *ifname _U_, gchar *output, void *data,
236                        char **err_str)
237 {
238     GList *dlts = NULL, *temp = NULL;
239
240     if_capabilities_t *caps;
241     GList *linktype_list = NULL;
242     data_link_info_t *data_link_info;
243     extcap_dlt *dlt_item;
244
245     dlts = extcap_parse_dlts(output);
246     temp = dlts;
247
248     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap pipe %s ", extcap);
249
250     /*
251      * Allocate the interface capabilities structure.
252      */
253     caps = (if_capabilities_t *) g_malloc(sizeof * caps);
254     caps->can_set_rfmon = FALSE;
255
256     while (dlts)
257     {
258         dlt_item = (extcap_dlt *)dlts->data;
259         if (dlt_item)
260         {
261             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
262                   "  DLT %d name=\"%s\" display=\"%s\" ", dlt_item->number,
263                   dlt_item->name, dlt_item->display);
264
265             data_link_info = g_new(data_link_info_t, 1);
266             data_link_info->dlt = dlt_item->number;
267             data_link_info->name = g_strdup(dlt_item->name);
268             data_link_info->description = g_strdup(dlt_item->display);
269             linktype_list = g_list_append(linktype_list, data_link_info);
270         }
271
272         dlts = g_list_next(dlts);
273     }
274
275     /* Check to see if we built a list */
276     if (linktype_list != NULL && data != NULL)
277     {
278         caps->data_link_types = linktype_list;
279         *(if_capabilities_t **) data = caps;
280     }
281     else
282     {
283         if (err_str)
284         {
285             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  returned no DLTs");
286             *err_str = g_strdup("Extcap returned no DLTs");
287         }
288         g_free(caps);
289     }
290
291     extcap_free_dlts(temp);
292
293     return FALSE;
294 }
295
296 if_capabilities_t *
297 extcap_get_if_dlts(const gchar *ifname, char **err_str)
298 {
299     gchar *argv[3];
300     gint i;
301     if_capabilities_t *caps = NULL;
302
303     if (err_str != NULL)
304     {
305         *err_str = NULL;
306     }
307
308     if (extcap_if_exists(ifname))
309     {
310         argv[0] = g_strdup(EXTCAP_ARGUMENT_LIST_DLTS);
311         argv[1] = g_strdup(EXTCAP_ARGUMENT_INTERFACE);
312         argv[2] = g_strdup(ifname);
313
314         extcap_foreach(3, argv, dlt_cb, &caps, err_str, ifname);
315
316         for (i = 0; i < 3; ++i)
317         {
318             g_free(argv[i]);
319         }
320     }
321
322     return caps;
323 }
324
325 static void extcap_free_interface(gpointer i)
326 {
327
328     extcap_interface *interface = (extcap_interface *)i;
329
330     if (i == NULL)
331     {
332         return;
333     }
334
335     g_free(interface->call);
336     g_free(interface->display);
337     g_free(interface->version);
338     g_free(interface->help);
339     g_free(interface->extcap_path);
340     g_free(interface);
341 }
342
343 static void extcap_free_interfaces(GList *interfaces)
344 {
345     if (interfaces == NULL)
346     {
347         return;
348     }
349
350     g_list_foreach(interfaces, (GFunc)extcap_free_interface, NULL);
351     g_list_free(interfaces);
352 }
353
354 static gboolean interfaces_cb(const gchar *extcap, const gchar *ifname _U_, gchar *output, void *data,
355                               char **err_str _U_)
356 {
357     GList **il = (GList **) data;
358     GList *interfaces = NULL, *walker = NULL, *tmp = NULL;
359     extcap_interface *int_iter = NULL;
360     if_info_t *if_info = NULL;
361
362     interfaces = extcap_parse_interfaces(output);
363
364     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap pipe %s ", extcap);
365
366     walker = interfaces;
367     char* help = NULL;
368     while (walker != NULL)
369     {
370         /* Whether the interface information needs to be preserved or not. */
371         gboolean preserve_interface = FALSE;
372
373         int_iter = (extcap_interface *)walker->data;
374         if (int_iter->if_type == EXTCAP_SENTENCE_INTERFACE && extcap_if_exists(int_iter->call))
375         {
376             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_WARNING, "Extcap interface \"%s\" is already provided by \"%s\" ",
377                   int_iter->call, (gchar *)extcap_if_executable(int_iter->call));
378             walker = g_list_next(walker);
379             continue;
380         }
381
382         if (int_iter->if_type == EXTCAP_SENTENCE_INTERFACE)
383             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Interface [%s] \"%s\" ",
384                   int_iter->call, int_iter->display);
385         else if (int_iter->if_type == EXTCAP_SENTENCE_EXTCAP)
386         {
387             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "  Extcap [%s] ", int_iter->call);
388             help = int_iter->help;
389         }
390
391         if (int_iter->if_type == EXTCAP_SENTENCE_INTERFACE)
392         {
393             if (il != NULL)
394             {
395                 if_info = g_new0(if_info_t, 1);
396                 if_info->name = g_strdup(int_iter->call);
397                 if_info->friendly_name = g_strdup(int_iter->display);
398
399                 if_info->type = IF_EXTCAP;
400
401                 if_info->extcap = g_strdup(extcap);
402                 *il = g_list_append(*il, if_info);
403             }
404
405             int_iter->extcap_path = g_strdup(extcap);
406             int_iter->help = g_strdup(help);
407             preserve_interface = extcap_if_add(int_iter);
408         }
409
410         /* Call for interfaces and tools alike. Multiple calls (because a tool has multiple
411          * interfaces) are handled internally */
412         extcap_tool_add(extcap, int_iter);
413
414         tmp = walker;
415         walker = g_list_next(walker);
416
417         /* If interface was added to ifaces hash list then the hash list will free
418          * the resources. Remove the interface from interfaces list so it won't be
419          * freed when exiting this function */
420         if (preserve_interface)
421         {
422             interfaces = g_list_delete_link(interfaces, tmp);
423         }
424     }
425     extcap_free_interfaces(interfaces);
426
427     return TRUE;
428 }
429
430 static gint
431 if_info_compare(gconstpointer a, gconstpointer b)
432 {
433     gint comp = 0;
434     const if_info_t *if_a = (const if_info_t *)a;
435     const if_info_t *if_b = (const if_info_t *)b;
436
437     if ((comp = g_strcmp0(if_a->name, if_b->name)) == 0)
438     {
439         return g_strcmp0(if_a->friendly_name, if_b->friendly_name);
440     }
441
442     return comp;
443 }
444
445 static void
446 extcap_reload_interface_list(GList **retp, char **err_str)
447 {
448     gchar *argv;
449
450     if (err_str != NULL)
451     {
452         *err_str = NULL;
453     }
454
455     /* ifaces is used as cache, do not destroy its contents when
456      * returning or no extcap interfaces can be queried for options */
457     if (ifaces == NULL)
458     {
459         ifaces = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_interface);
460     }
461     else
462     {
463         g_hash_table_remove_all(ifaces);
464     }
465
466     if (tools == NULL)
467     {
468         tools = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, extcap_free_info);
469     }
470     else
471     {
472         g_hash_table_remove_all(tools);
473     }
474
475     argv = g_strdup(EXTCAP_ARGUMENT_LIST_INTERFACES);
476
477     extcap_foreach(1, &argv, interfaces_cb, retp, err_str, NULL);
478
479     g_free(argv);
480 }
481
482 gchar *
483 extcap_get_help_for_ifname(const char *ifname)
484 {
485     extcap_interface *interface = (extcap_interface *)g_hash_table_lookup(ifaces, ifname);
486     return interface != NULL ? interface->help : NULL;
487 }
488
489 GHashTable *
490 extcap_tools_list(void)
491 {
492     if (tools == NULL || g_hash_table_size(tools) == 0)
493     {
494         extcap_reload_interface_list(NULL, NULL);
495     }
496
497     return tools;
498 }
499
500 GList *
501 append_extcap_interface_list(GList *list, char **err_str)
502 {
503     GList *ret = NULL;
504     GList *entry;
505     void *data;
506
507     /* Update the extcap interfaces and get a list of their if_infos */
508     extcap_reload_interface_list(&ret, err_str);
509
510     /* Sort that list */
511     ret = g_list_sort(ret, if_info_compare);
512
513     /* Append the interfaces in that list to the list we're handed. */
514     while (ret != NULL)
515     {
516         entry = g_list_first(ret);
517         data = entry->data;
518         ret = g_list_delete_link(ret, entry);
519         list = g_list_append(list, data);
520     }
521     return list;
522 }
523
524 static void
525 extcap_register_preferences_callback(gpointer key, gpointer value _U_, gpointer user_data _U_)
526 {
527     GList *arguments;
528
529     arguments = extcap_get_if_configuration((gchar *)key);
530     /* Memory for prefs are external to an interface, they are part of
531      * extcap core, so the parsed arguments can be freed. */
532     extcap_free_if_configuration(arguments, TRUE);
533 }
534
535 void extcap_register_preferences(void)
536 {
537     module_t *dev_module = prefs_find_module("extcap");
538
539     if (!dev_module)
540     {
541         return;
542     }
543
544     if (!ifaces || g_hash_table_size(ifaces) == 0)
545     {
546         extcap_reload_interface_list(NULL, NULL);
547     }
548
549     g_hash_table_foreach(ifaces, extcap_register_preferences_callback, NULL);
550 }
551
552 /**
553  * Releases the dynamic preference value pointers. Must not be called before
554  * prefs_cleanup since these pointers could still be in use.
555  */
556 void extcap_cleanup(void)
557 {
558     if (extcap_prefs_dynamic_vals)
559     {
560         g_hash_table_destroy(extcap_prefs_dynamic_vals);
561     }
562 }
563
564 void extcap_pref_store(extcap_arg *arg, const char *newval)
565 {
566     if (arg && arg->pref_valptr != NULL)
567     {
568         g_free(*arg->pref_valptr);
569         *arg->pref_valptr = g_strdup(newval);
570     }
571
572 }
573
574 /**
575  * Obtains a pointer which can store a value for the given preference name.
576  * The preference name that can be passed to the prefs API is stored into
577  * 'prefs_name'.
578  *
579  * Extcap interfaces (and their preferences) are dynamic, they can be created
580  * and destroyed at will. Thus their data structures are insufficient to pass to
581  * the preferences APIs which require pointers which are valid until the
582  * preferences are removed (at exit).
583  */
584 static gchar **extcap_prefs_dynamic_valptr(const char *name, char **pref_name)
585 {
586     gchar **valp;
587     if (!extcap_prefs_dynamic_vals)
588     {
589         /* Initialize table only as needed, most preferences are not dynamic */
590         extcap_prefs_dynamic_vals = g_hash_table_new_full(g_str_hash, g_str_equal,
591                                     g_free, g_free);
592     }
593     if (!g_hash_table_lookup_extended(extcap_prefs_dynamic_vals, name,
594                                       (gpointer *)pref_name, (gpointer *)&valp))
595     {
596         /* New dynamic pref, allocate, initialize and store. */
597         valp = g_new0(gchar *, 1);
598         *pref_name = g_strdup(name);
599         g_hash_table_insert(extcap_prefs_dynamic_vals, *pref_name, valp);
600     }
601     return valp;
602 }
603
604 void extcap_free_if_configuration(GList *list, gboolean free_args)
605 {
606     GList *elem, *sl;
607
608     for (elem = g_list_first(list); elem; elem = elem->next)
609     {
610         if (elem->data != NULL)
611         {
612             sl = g_list_first((GList *)elem->data);
613             if (free_args)
614             {
615                 extcap_free_arg_list(sl);
616             }
617             else
618             {
619                 g_list_free(sl);
620             }
621         }
622     }
623     g_list_free(list);
624 }
625
626 struct preference *
627 extcap_pref_for_argument(const gchar *ifname, struct _extcap_arg *arg)
628 {
629     struct preference *pref = NULL;
630
631     GRegex *regex_name = g_regex_new("[-]+", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
632     GRegex *regex_ifname = g_regex_new("(?![a-zA-Z1-9_]).", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
633     if (regex_name && regex_ifname)
634     {
635         if (prefs_find_module("extcap"))
636         {
637             gchar *pref_name = g_regex_replace(regex_name, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL);
638             gchar *ifname_underscore = g_regex_replace(regex_ifname, ifname, strlen(ifname), 0, "_", (GRegexMatchFlags) 0, NULL);
639             gchar *ifname_lowercase = g_ascii_strdown(ifname_underscore, -1);
640             gchar *pref_ifname = g_strconcat(ifname_lowercase, ".", pref_name, NULL);
641
642             pref = prefs_find_preference(prefs_find_module("extcap"), pref_ifname);
643
644             g_free(pref_name);
645             g_free(ifname_underscore);
646             g_free(ifname_lowercase);
647             g_free(pref_ifname);
648         }
649     }
650     if (regex_name)
651     {
652         g_regex_unref(regex_name);
653     }
654     if (regex_ifname)
655     {
656         g_regex_unref(regex_ifname);
657     }
658
659     return pref;
660 }
661
662 static gboolean search_cb(const gchar *extcap _U_, const gchar *ifname _U_, gchar *output, void *data,
663                           char **err_str _U_)
664 {
665     GList *arguments = NULL;
666     GList **il = (GList **) data;
667     module_t *dev_module = NULL;
668
669     arguments = extcap_parse_args(output);
670
671     dev_module = prefs_find_module("extcap");
672
673     if (dev_module)
674     {
675         GList *walker = arguments;
676
677         GRegex *regex_name = g_regex_new("[-]+", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
678         GRegex *regex_ifname = g_regex_new("(?![a-zA-Z1-9_]).", (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
679         if (regex_name && regex_ifname)
680         {
681             while (walker != NULL)
682             {
683                 extcap_arg *arg = (extcap_arg *)walker->data;
684                 arg->device_name = g_strdup(ifname);
685
686                 if (arg->save)
687                 {
688                     struct preference *pref = NULL;
689
690                     gchar *pref_name = g_regex_replace(regex_name, arg->call, strlen(arg->call), 0, "", (GRegexMatchFlags) 0, NULL);
691                     gchar *ifname_underscore = g_regex_replace(regex_ifname, ifname, strlen(ifname), 0, "_", (GRegexMatchFlags) 0, NULL);
692                     gchar *ifname_lowercase = g_ascii_strdown(ifname_underscore, -1);
693                     gchar *pref_ifname = g_strconcat(ifname_lowercase, ".", pref_name, NULL);
694
695                     if ((pref = prefs_find_preference(dev_module, pref_ifname)) == NULL)
696                     {
697                         char *pref_name_for_prefs;
698                         char *pref_title = wmem_strdup(wmem_epan_scope(), arg->display);
699
700                         arg->pref_valptr = extcap_prefs_dynamic_valptr(pref_ifname, &pref_name_for_prefs);
701                         /* Set an initial value if any (the string will be copied at registration) */
702                         if (arg->default_complex)
703                         {
704                             *arg->pref_valptr = arg->default_complex->_val;
705                         }
706
707                         prefs_register_string_preference(dev_module, pref_name_for_prefs,
708                                                          pref_title, pref_title, (const char **)arg->pref_valptr);
709                     }
710                     else
711                     {
712                         /* Been here before, restore stored value */
713                         if (! arg->pref_valptr && pref->varp.string && strlen(*pref->varp.string))
714                         {
715                             arg->pref_valptr = pref->varp.string;
716                         }
717                     }
718
719                     g_free(pref_name);
720                     g_free(ifname_underscore);
721                     g_free(ifname_lowercase);
722                     g_free(pref_ifname);
723                 }
724
725                 walker = g_list_next(walker);
726             }
727         }
728         if (regex_name)
729         {
730             g_regex_unref(regex_name);
731         }
732         if (regex_ifname)
733         {
734             g_regex_unref(regex_ifname);
735         }
736     }
737
738     *il = g_list_append(*il, arguments);
739
740     /* By returning false, extcap_foreach will break on first found */
741     return TRUE;
742 }
743
744 GList *
745 extcap_get_if_configuration(const char *ifname)
746 {
747     gchar *argv[3];
748     GList *ret = NULL;
749     gchar **err_str = NULL;
750     int i;
751
752     if (extcap_if_exists(ifname))
753     {
754         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "Extcap path %s",
755               get_extcap_dir());
756
757         argv[0] = g_strdup(EXTCAP_ARGUMENT_CONFIG);
758         argv[1] = g_strdup(EXTCAP_ARGUMENT_INTERFACE);
759         argv[2] = g_strdup(ifname);
760
761         extcap_foreach(3, argv, search_cb, &ret, err_str, ifname);
762
763         for (i = 0; i < 3; i++)
764         {
765             g_free(argv[i]);
766         }
767     }
768
769     return ret;
770 }
771
772 /**
773  * If is_required is FALSE: returns TRUE if the extcap interface has
774  * configurable options.
775  * If is_required is TRUE: returns TRUE when the extcap interface has
776  * configurable options that required modification. (For example, when an
777  * argument is required but empty.)
778  */
779 gboolean
780 extcap_has_configuration(const char *ifname, gboolean is_required)
781 {
782     GList *arguments = 0;
783     GList *walker = 0, * item = 0;
784
785     gboolean found = FALSE;
786
787     arguments = extcap_get_if_configuration((const char *)(ifname));
788     walker = g_list_first(arguments);
789
790     while (walker != NULL && !found)
791     {
792         item = g_list_first((GList *)(walker->data));
793         while (item != NULL && !found)
794         {
795             if ((extcap_arg *)(item->data) != NULL)
796             {
797                 extcap_arg *arg = (extcap_arg *)(item->data);
798                 /* Should required options be present, or any kind of options */
799                 if (!is_required)
800                 {
801                     found = TRUE;
802                 }
803                 else if (arg->is_required)
804                 {
805                     const gchar *stored = NULL;
806                     const gchar *defval = NULL;
807
808                     if (arg->pref_valptr != NULL)
809                     {
810                         stored = *arg->pref_valptr;
811                     }
812
813                     if (arg->default_complex != NULL && arg->default_complex->_val != NULL)
814                     {
815                         defval = arg->default_complex->_val;
816                     }
817
818                     if (arg->is_required)
819                     {
820                         /* If stored and defval is identical and the argument is required,
821                          * configuration is needed */
822                         if (defval && stored && g_strcmp0(stored, defval) == 0)
823                         {
824                             found = TRUE;
825                         }
826                         else if (!defval && (!stored || !*stored))
827                         {
828                             found = TRUE;
829                         }
830                     }
831
832                     if (arg->arg_type == EXTCAP_ARG_FILESELECT)
833                     {
834                         if (arg->fileexists && !(file_exists(defval) || file_exists(stored)))
835                         {
836                             found = TRUE;
837                         }
838                     }
839                 }
840             }
841
842             item = item->next;
843         }
844         walker = walker->next;
845     }
846     extcap_free_if_configuration(arguments, TRUE);
847
848     return found;
849 }
850
851 /* taken from capchild/capture_sync.c */
852 static gboolean pipe_data_available(int pipe_fd)
853 {
854 #ifdef _WIN32 /* PeekNamedPipe */
855     HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
856     DWORD bytes_avail;
857
858     if (hPipe == INVALID_HANDLE_VALUE)
859     {
860         return FALSE;
861     }
862
863     if (! PeekNamedPipe(hPipe, NULL, 0, NULL, &bytes_avail, NULL))
864     {
865         return FALSE;
866     }
867
868     if (bytes_avail > 0)
869     {
870         return TRUE;
871     }
872     return FALSE;
873 #else /* select */
874     fd_set rfds;
875     struct timeval timeout;
876
877     FD_ZERO(&rfds);
878     FD_SET(pipe_fd, &rfds);
879     timeout.tv_sec = 0;
880     timeout.tv_usec = 0;
881
882     if (select(pipe_fd + 1, &rfds, NULL, NULL, &timeout) > 0)
883     {
884         return TRUE;
885     }
886
887     return FALSE;
888 #endif
889 }
890
891 void extcap_if_cleanup(capture_options *capture_opts, gchar **errormsg)
892 {
893     interface_options interface_opts;
894     extcap_userdata *userdata;
895     guint icnt = 0;
896     gboolean overwrite_exitcode;
897     gchar *buffer;
898 #define STDERR_BUFFER_SIZE 1024
899
900     for (icnt = 0; icnt < capture_opts->ifaces->len; icnt++)
901     {
902         interface_opts = g_array_index(capture_opts->ifaces, interface_options,
903                                        icnt);
904
905         /* skip native interfaces */
906         if (interface_opts.if_type != IF_EXTCAP)
907         {
908             continue;
909         }
910
911         overwrite_exitcode = FALSE;
912
913         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
914               "Extcap [%s] - Cleaning up fifo: %s; PID: %d", interface_opts.name,
915               interface_opts.extcap_fifo, interface_opts.extcap_pid);
916 #ifdef _WIN32
917         if (pipe_h)
918         {
919             g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
920                   "Extcap [%s] - Closing pipe", interface_opts.name);
921             FlushFileBuffers(pipe_h);
922             DisconnectNamedPipe(pipe_h);
923             CloseHandle(pipe_h);
924         }
925 #else
926         if (interface_opts.extcap_fifo != NULL && file_exists(interface_opts.extcap_fifo))
927         {
928             /* the fifo will not be freed here, but with the other capture_opts in capture_sync */
929             ws_unlink(interface_opts.extcap_fifo);
930             interface_opts.extcap_fifo = NULL;
931         }
932 #endif
933         /* Maybe the client closed and removed fifo, but ws should check if
934          * pid should be closed */
935         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
936               "Extcap [%s] - Closing spawned PID: %d", interface_opts.name,
937               interface_opts.extcap_pid);
938
939         userdata = (extcap_userdata *) interface_opts.extcap_userdata;
940         if (userdata)
941         {
942             if (userdata->extcap_stderr_rd > 0 && pipe_data_available(userdata->extcap_stderr_rd))
943             {
944                 buffer = (gchar *)g_malloc0(sizeof(gchar) * STDERR_BUFFER_SIZE + 1);
945 #ifdef _WIN32
946                 win32_readfrompipe((HANDLE)_get_osfhandle(userdata->extcap_stderr_rd), STDERR_BUFFER_SIZE, buffer);
947 #else
948                 if (read(userdata->extcap_stderr_rd, buffer, sizeof(gchar) * STDERR_BUFFER_SIZE) <= 0)
949                 {
950                     buffer[0] = '\0';
951                 }
952 #endif
953                 if (strlen(buffer) > 0)
954                 {
955                     userdata->extcap_stderr = g_strdup_printf("%s", buffer);
956                     userdata->exitcode = 1;
957                 }
958                 g_free(buffer);
959             }
960
961 #ifndef _WIN32
962             /* Final child watch may not have been called */
963             if (interface_opts.extcap_child_watch != 0)
964             {
965                 extcap_child_watch_cb(userdata->pid, 0, capture_opts);
966                 /* it will have changed in extcap_child_watch_cb */
967                 interface_opts = g_array_index(capture_opts->ifaces, interface_options,
968                                                icnt);
969             }
970 #endif
971
972             if (userdata->extcap_stderr != NULL)
973             {
974                 overwrite_exitcode = TRUE;
975             }
976
977             if (overwrite_exitcode || userdata->exitcode != 0)
978             {
979                 if (userdata->extcap_stderr != 0)
980                 {
981                     if (*errormsg == NULL)
982                     {
983                         *errormsg = g_strdup_printf("Error by extcap pipe: %s", userdata->extcap_stderr);
984                     }
985                     else
986                     {
987                         gchar *temp = g_strconcat(*errormsg, "\nError by extcap pipe: " , userdata->extcap_stderr, NULL);
988                         g_free(*errormsg);
989                         *errormsg = temp;
990                     }
991                     g_free(userdata->extcap_stderr);
992                 }
993
994                 userdata->extcap_stderr = NULL;
995                 userdata->exitcode = 0;
996             }
997         }
998
999         if (interface_opts.extcap_child_watch > 0)
1000         {
1001             g_source_remove(interface_opts.extcap_child_watch);
1002             interface_opts.extcap_child_watch = 0;
1003         }
1004
1005         if (interface_opts.extcap_pid != INVALID_EXTCAP_PID)
1006         {
1007 #ifdef _WIN32
1008             TerminateProcess(interface_opts.extcap_pid, 0);
1009 #endif
1010             g_spawn_close_pid(interface_opts.extcap_pid);
1011             interface_opts.extcap_pid = INVALID_EXTCAP_PID;
1012
1013             g_free(interface_opts.extcap_userdata);
1014             interface_opts.extcap_userdata = NULL;
1015         }
1016
1017         /* Make sure modified interface_opts is saved in capture_opts. */
1018         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, icnt);
1019         g_array_insert_val(capture_opts->ifaces, icnt, interface_opts);
1020     }
1021 }
1022
1023 static gboolean
1024 extcap_add_arg_and_remove_cb(gpointer key, gpointer value, gpointer data)
1025 {
1026     GPtrArray *args = (GPtrArray *)data;
1027
1028     if (key != NULL)
1029     {
1030         g_ptr_array_add(args, g_strdup((const gchar *)key));
1031
1032         if (value != NULL)
1033         {
1034             g_ptr_array_add(args, g_strdup((const gchar *)value));
1035         }
1036
1037         return TRUE;
1038     }
1039
1040     return FALSE;
1041 }
1042
1043 void extcap_child_watch_cb(GPid pid, gint status, gpointer user_data)
1044 {
1045     guint i;
1046     interface_options interface_opts;
1047     extcap_userdata *userdata = NULL;
1048     capture_options *capture_opts = (capture_options *)(user_data);
1049
1050     if (capture_opts == NULL || capture_opts->ifaces == NULL || capture_opts->ifaces->len == 0)
1051     {
1052         return;
1053     }
1054
1055     /* Close handle to child process. */
1056     g_spawn_close_pid(pid);
1057
1058     /* Update extcap_pid in interface options structure. */
1059     for (i = 0; i < capture_opts->ifaces->len; i++)
1060     {
1061         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
1062         if (interface_opts.extcap_pid == pid)
1063         {
1064             userdata = (extcap_userdata *)interface_opts.extcap_userdata;
1065             if (userdata != NULL)
1066             {
1067                 interface_opts.extcap_pid = INVALID_EXTCAP_PID;
1068                 userdata->exitcode = 0;
1069 #ifndef _WIN32
1070                 if (WIFEXITED(status))
1071                 {
1072                     if (WEXITSTATUS(status) != 0)
1073                     {
1074                         userdata->exitcode = WEXITSTATUS(status);
1075                     }
1076                 }
1077                 else
1078                 {
1079                     userdata->exitcode = G_SPAWN_ERROR_FAILED;
1080                 }
1081 #else
1082                 if (status != 0)
1083                 {
1084                     userdata->exitcode = status;
1085                 }
1086 #endif
1087                 if (status == 0 && userdata->extcap_stderr != NULL)
1088                 {
1089                     userdata->exitcode = 1;
1090                 }
1091             }
1092             g_source_remove(interface_opts.extcap_child_watch);
1093             interface_opts.extcap_child_watch = 0;
1094
1095             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
1096             g_array_insert_val(capture_opts->ifaces, i, interface_opts);
1097             break;
1098         }
1099     }
1100 }
1101
1102 static
1103 GPtrArray *extcap_prepare_arguments(interface_options interface_opts)
1104 {
1105     GPtrArray *result = NULL;
1106
1107     if (interface_opts.if_type == IF_EXTCAP)
1108     {
1109         result = g_ptr_array_new();
1110
1111 #define add_arg(X) g_ptr_array_add(result, g_strdup(X))
1112
1113         add_arg(interface_opts.extcap);
1114         add_arg(EXTCAP_ARGUMENT_RUN_CAPTURE);
1115         add_arg(EXTCAP_ARGUMENT_INTERFACE);
1116         add_arg(interface_opts.name);
1117         if (interface_opts.cfilter && strlen(interface_opts.cfilter) > 0)
1118         {
1119             add_arg(EXTCAP_ARGUMENT_CAPTURE_FILTER);
1120             add_arg(interface_opts.cfilter);
1121         }
1122         add_arg(EXTCAP_ARGUMENT_RUN_PIPE);
1123         add_arg(interface_opts.extcap_fifo);
1124         if (interface_opts.extcap_args == NULL || g_hash_table_size(interface_opts.extcap_args) == 0)
1125         {
1126             /* User did not perform interface configuration.
1127              *
1128              * Check if there are any boolean flags that are set by default
1129              * and hence their argument should be added.
1130              */
1131             GList *arglist;
1132             GList *elem;
1133
1134             arglist = extcap_get_if_configuration(interface_opts.name);
1135             for (elem = g_list_first(arglist); elem; elem = elem->next)
1136             {
1137                 GList *arg_list;
1138                 extcap_arg *arg_iter;
1139
1140                 if (elem->data == NULL)
1141                 {
1142                     continue;
1143                 }
1144
1145                 arg_list = g_list_first((GList *)elem->data);
1146                 while (arg_list != NULL)
1147                 {
1148                     const gchar *stored = NULL, * defval = NULL;
1149                     /* In case of boolflags only first element in arg_list is relevant. */
1150                     arg_iter = (extcap_arg *)(arg_list->data);
1151                     if (arg_iter->pref_valptr != NULL)
1152                     {
1153                         stored = *arg_iter->pref_valptr;
1154                     }
1155
1156                     if (arg_iter->default_complex != NULL && arg_iter->default_complex->_val != NULL)
1157                     {
1158                         defval = arg_iter->default_complex->_val;
1159                     }
1160
1161                     /* Different data in storage then set for default */
1162                     if (g_strcmp0(stored, defval) != 0)
1163                     {
1164                         if (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG)
1165                         {
1166                             if (g_strcmp0(stored, "true") == 0)
1167                             {
1168                                 add_arg(arg_iter->call);
1169                             }
1170                         }
1171                         else
1172                         {
1173                             add_arg(arg_iter->call);
1174                             add_arg(stored);
1175                         }
1176                     }
1177                     else if (arg_iter->arg_type == EXTCAP_ARG_BOOLFLAG)
1178                     {
1179                         if (extcap_complex_get_bool(arg_iter->default_complex))
1180                         {
1181                             add_arg(arg_iter->call);
1182                         }
1183                     }
1184
1185                     arg_list = arg_list->next;
1186                 }
1187             }
1188
1189             extcap_free_if_configuration(arglist, TRUE);
1190         }
1191         else
1192         {
1193             g_hash_table_foreach_remove(interface_opts.extcap_args, extcap_add_arg_and_remove_cb, result);
1194         }
1195         add_arg(NULL);
1196 #undef add_arg
1197
1198     }
1199
1200     return result;
1201 }
1202
1203 /* call mkfifo for each extcap,
1204  * returns FALSE if there's an error creating a FIFO */
1205 gboolean
1206 extcap_init_interfaces(capture_options *capture_opts)
1207 {
1208     guint i;
1209     interface_options interface_opts;
1210     extcap_userdata *userdata;
1211
1212     for (i = 0; i < capture_opts->ifaces->len; i++)
1213     {
1214         GPtrArray *args = NULL;
1215         GPid pid = INVALID_EXTCAP_PID;
1216
1217         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
1218
1219         /* skip native interfaces */
1220         if (interface_opts.if_type != IF_EXTCAP)
1221         {
1222             continue;
1223         }
1224
1225         /* create pipe for fifo */
1226         if (!extcap_create_pipe(&interface_opts.extcap_fifo))
1227         {
1228             return FALSE;
1229         }
1230
1231         /* Create extcap call */
1232         args = extcap_prepare_arguments(interface_opts);
1233
1234         userdata = g_new0(extcap_userdata, 1);
1235
1236         pid = extcap_spawn_async(userdata, args);
1237
1238         g_ptr_array_foreach(args, (GFunc)g_free, NULL);
1239         g_ptr_array_free(args, TRUE);
1240
1241         if (pid == INVALID_EXTCAP_PID)
1242         {
1243             g_free(userdata);
1244             continue;
1245         }
1246
1247         interface_opts.extcap_pid = pid;
1248
1249         interface_opts.extcap_child_watch =
1250             g_child_watch_add(pid, extcap_child_watch_cb, (gpointer)capture_opts);
1251
1252 #ifdef _WIN32
1253         /* On Windows, wait for extcap to connect to named pipe.
1254          * Some extcaps will present UAC screen to user.
1255          * 30 second timeout should be reasonable timeout for extcap to
1256          * connect to named pipe (including user interaction).
1257          * Wait on multiple object in case of extcap termination
1258          * without opening pipe.
1259          *
1260          * Minimum supported version of Windows: XP / Server 2003.
1261          */
1262         if (pid != INVALID_EXTCAP_PID)
1263         {
1264             extcap_wait_for_pipe(pipe_h, pid);
1265         }
1266
1267 #endif
1268
1269         interface_opts.extcap_userdata = (gpointer) userdata;
1270
1271         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
1272         g_array_insert_val(capture_opts->ifaces, i, interface_opts);
1273     }
1274
1275     return TRUE;
1276 }
1277
1278 #ifdef _WIN32
1279 /* called by capture_sync to get the CreatNamedPipe handle*/
1280 HANDLE
1281 extcap_get_win32_handle()
1282 {
1283     return pipe_h;
1284 }
1285 #endif
1286
1287 gboolean extcap_create_pipe(char **fifo)
1288 {
1289 #ifdef _WIN32
1290     gchar timestr[ 14 + 1 ];
1291     time_t current_time;
1292
1293     gchar *pipename = NULL;
1294
1295     SECURITY_ATTRIBUTES security;
1296     /* create pipename */
1297     current_time = time(NULL);
1298     /*
1299      * XXX - we trust Windows not to return a time before the Epoch here,
1300      * so we won't get a null pointer back from localtime().
1301      */
1302     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
1303     pipename = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, "_", timestr, NULL);
1304
1305     /* Security struct to enable Inheritable HANDLE */
1306     memset(&security, 0, sizeof(SECURITY_ATTRIBUTES));
1307     security.nLength = sizeof(SECURITY_ATTRIBUTES);
1308     security.bInheritHandle = TRUE;
1309     security.lpSecurityDescriptor = NULL;
1310
1311     /* create a namedPipe*/
1312     pipe_h = CreateNamedPipe(
1313                  utf_8to16(pipename),
1314                  PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1315                  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
1316                  5, 65536, 65536,
1317                  300,
1318                  &security);
1319
1320     if (pipe_h == INVALID_HANDLE_VALUE)
1321     {
1322         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nError creating pipe => (%d)", GetLastError());
1323         return FALSE;
1324     }
1325     else
1326     {
1327         g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG, "\nWireshark Created pipe =>(%s)", pipename);
1328         *fifo = g_strdup(pipename);
1329     }
1330 #else
1331     gchar *temp_name = NULL;
1332     int fd = 0;
1333
1334     if ((fd = create_tempfile(&temp_name, EXTCAP_PIPE_PREFIX, NULL)) < 0)
1335     {
1336         return FALSE;
1337     }
1338
1339     ws_close(fd);
1340
1341     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_DEBUG,
1342           "Extcap - Creating fifo: %s", temp_name);
1343
1344     if (file_exists(temp_name))
1345     {
1346         ws_unlink(temp_name);
1347     }
1348
1349     if (mkfifo(temp_name, 0600) == 0)
1350     {
1351         *fifo = g_strdup(temp_name);
1352     }
1353 #endif
1354
1355     return TRUE;
1356 }
1357
1358 /*
1359  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1360  *
1361  * Local variables:
1362  * c-basic-offset: 4
1363  * tab-width: 8
1364  * indent-tabs-mode: nil
1365  * End:
1366  *
1367  * vi: set shiftwidth=4 tabstop=8 expandtab:
1368  * :indentSize=4:tabSize=8:noTabs=true:
1369  */