plugin: add accessor for release date time string in plugin description
[platform/upstream/gstreamer.git] / gst / gstplugin.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *
5  * gstplugin.c: Plugin subsystem for loading elements, types, and libs
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gstplugin
25  * @short_description: Container for features loaded from a shared object module
26  * @see_also: #GstPluginFeature, #GstElementFactory
27  *
28  * GStreamer is extensible, so #GstElement instances can be loaded at runtime.
29  * A plugin system can provide one or more of the basic
30  * <application>GStreamer</application> #GstPluginFeature subclasses.
31  *
32  * A plugin should export a symbol <symbol>gst_plugin_desc</symbol> that is a
33  * struct of type #GstPluginDesc.
34  * the plugin loader will check the version of the core library the plugin was
35  * linked against and will create a new #GstPlugin. It will then call the
36  * #GstPluginInitFunc function that was provided in the
37  * <symbol>gst_plugin_desc</symbol>.
38  *
39  * Once you have a handle to a #GstPlugin (e.g. from the #GstRegistry), you
40  * can add any object that subclasses #GstPluginFeature.
41  *
42  * Usually plugins are always automaticlly loaded so you don't need to call
43  * gst_plugin_load() explicitly to bring it into memory. There are options to
44  * statically link plugins to an app or even use GStreamer without a plugin
45  * repository in which case gst_plugin_load() can be needed to bring the plugin
46  * into memory.
47  */
48
49 #ifdef HAVE_CONFIG_H
50 #include "config.h"
51 #endif
52
53 #include "gst_private.h"
54
55 #include <glib/gstdio.h>
56 #include <sys/types.h>
57 #ifdef HAVE_DIRENT_H
58 #include <dirent.h>
59 #endif
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #endif
63 #include <signal.h>
64 #include <errno.h>
65 #include <string.h>
66
67 #include "glib-compat-private.h"
68
69 #include <gst/gst.h>
70
71 #define GST_CAT_DEFAULT GST_CAT_PLUGIN_LOADING
72
73 static guint _num_static_plugins;       /* 0    */
74 static GstPluginDesc *_static_plugins;  /* NULL */
75 static gboolean _gst_plugin_inited;
76 static gchar **_plugin_loading_whitelist;       /* NULL */
77
78 /* static variables for segfault handling of plugin loading */
79 static char *_gst_plugin_fault_handler_filename = NULL;
80
81 /* list of valid licenses.
82  * One of these must be specified or the plugin won't be loaded
83  * Contact gstreamer-devel@lists.sourceforge.net if your license should be
84  * added.
85  *
86  * GPL: http://www.gnu.org/copyleft/gpl.html
87  * LGPL: http://www.gnu.org/copyleft/lesser.html
88  * QPL: http://www.trolltech.com/licenses/qpl.html
89  * MPL: http://www.opensource.org/licenses/mozilla1.1.php
90  * MIT/X11: http://www.opensource.org/licenses/mit-license.php
91  * 3-clause BSD: http://www.opensource.org/licenses/bsd-license.php
92  */
93 static const gchar *const valid_licenses[] = {
94   "LGPL",                       /* GNU Lesser General Public License */
95   "GPL",                        /* GNU General Public License */
96   "QPL",                        /* Trolltech Qt Public License */
97   "GPL/QPL",                    /* Combi-license of GPL + QPL */
98   "MPL",                        /* MPL 1.1 license */
99   "BSD",                        /* 3-clause BSD license */
100   "MIT/X11",                    /* MIT/X11 license */
101   "Proprietary",                /* Proprietary license */
102   GST_LICENSE_UNKNOWN,          /* some other license */
103   NULL
104 };
105
106 static GstPlugin *gst_plugin_register_func (GstPlugin * plugin,
107     const GstPluginDesc * desc, gpointer user_data);
108 static void gst_plugin_desc_copy (GstPluginDesc * dest,
109     const GstPluginDesc * src);
110
111 static void gst_plugin_ext_dep_free (GstPluginDep * dep);
112
113 G_DEFINE_TYPE (GstPlugin, gst_plugin, GST_TYPE_OBJECT);
114
115 static void
116 gst_plugin_init (GstPlugin * plugin)
117 {
118   plugin->priv =
119       G_TYPE_INSTANCE_GET_PRIVATE (plugin, GST_TYPE_PLUGIN, GstPluginPrivate);
120 }
121
122 static void
123 gst_plugin_finalize (GObject * object)
124 {
125   GstPlugin *plugin = GST_PLUGIN_CAST (object);
126
127   GST_DEBUG ("finalizing plugin %" GST_PTR_FORMAT, plugin);
128
129   /* FIXME: make registry add a weak ref instead */
130 #if 0
131   GstRegistry *registry = gst_registry_get ();
132   GList *g;
133   for (g = registry->plugins; g; g = g->next) {
134     if (g->data == (gpointer) plugin) {
135       g_warning ("removing plugin that is still in registry");
136     }
137   }
138 #endif
139
140   g_free (plugin->filename);
141   g_free (plugin->basename);
142
143   g_list_foreach (plugin->priv->deps, (GFunc) gst_plugin_ext_dep_free, NULL);
144   g_list_free (plugin->priv->deps);
145   plugin->priv->deps = NULL;
146
147   if (plugin->priv->cache_data) {
148     gst_structure_free (plugin->priv->cache_data);
149   }
150
151   G_OBJECT_CLASS (gst_plugin_parent_class)->finalize (object);
152 }
153
154 static void
155 gst_plugin_class_init (GstPluginClass * klass)
156 {
157   G_OBJECT_CLASS (klass)->finalize = gst_plugin_finalize;
158
159   g_type_class_add_private (klass, sizeof (GstPluginPrivate));
160 }
161
162 GQuark
163 gst_plugin_error_quark (void)
164 {
165   static GQuark quark = 0;
166
167   if (!quark)
168     quark = g_quark_from_static_string ("gst_plugin_error");
169   return quark;
170 }
171
172 /**
173  * gst_plugin_register_static:
174  * @major_version: the major version number of the GStreamer core that the
175  *     plugin was compiled for, you can just use GST_VERSION_MAJOR here
176  * @minor_version: the minor version number of the GStreamer core that the
177  *     plugin was compiled for, you can just use GST_VERSION_MINOR here
178  * @name: a unique name of the plugin (ideally prefixed with an application- or
179  *     library-specific namespace prefix in order to avoid name conflicts in
180  *     case a similar plugin with the same name ever gets added to GStreamer)
181  * @description: description of the plugin
182  * @init_func: (scope call): pointer to the init function of this plugin.
183  * @version: version string of the plugin
184  * @license: effective license of plugin. Must be one of the approved licenses
185  *     (see #GstPluginDesc above) or the plugin will not be registered.
186  * @source: source module plugin belongs to
187  * @package: shipped package plugin belongs to
188  * @origin: URL to provider of plugin
189  *
190  * Registers a static plugin, ie. a plugin which is private to an application
191  * or library and contained within the application or library (as opposed to
192  * being shipped as a separate module file).
193  *
194  * You must make sure that GStreamer has been initialised (with gst_init() or
195  * via gst_init_get_option_group()) before calling this function.
196  *
197  * Returns: TRUE if the plugin was registered correctly, otherwise FALSE.
198  *
199  * Since: 0.10.16
200  */
201 gboolean
202 gst_plugin_register_static (gint major_version, gint minor_version,
203     const gchar * name, const gchar * description, GstPluginInitFunc init_func,
204     const gchar * version, const gchar * license, const gchar * source,
205     const gchar * package, const gchar * origin)
206 {
207   GstPluginDesc desc = { major_version, minor_version, name, description,
208     init_func, version, license, source, package, origin, NULL,
209   };
210   GstPlugin *plugin;
211   gboolean res = FALSE;
212
213   g_return_val_if_fail (name != NULL, FALSE);
214   g_return_val_if_fail (description != NULL, FALSE);
215   g_return_val_if_fail (init_func != NULL, FALSE);
216   g_return_val_if_fail (version != NULL, FALSE);
217   g_return_val_if_fail (license != NULL, FALSE);
218   g_return_val_if_fail (source != NULL, FALSE);
219   g_return_val_if_fail (package != NULL, FALSE);
220   g_return_val_if_fail (origin != NULL, FALSE);
221
222   /* make sure gst_init() has been called */
223   g_return_val_if_fail (_gst_plugin_inited != FALSE, FALSE);
224
225   GST_LOG ("attempting to load static plugin \"%s\" now...", name);
226   plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
227   if (gst_plugin_register_func (plugin, &desc, NULL) != NULL) {
228     GST_INFO ("registered static plugin \"%s\"", name);
229     res = gst_registry_add_plugin (gst_registry_get (), plugin);
230     GST_INFO ("added static plugin \"%s\", result: %d", name, res);
231   }
232   return res;
233 }
234
235 /**
236  * gst_plugin_register_static_full:
237  * @major_version: the major version number of the GStreamer core that the
238  *     plugin was compiled for, you can just use GST_VERSION_MAJOR here
239  * @minor_version: the minor version number of the GStreamer core that the
240  *     plugin was compiled for, you can just use GST_VERSION_MINOR here
241  * @name: a unique name of the plugin (ideally prefixed with an application- or
242  *     library-specific namespace prefix in order to avoid name conflicts in
243  *     case a similar plugin with the same name ever gets added to GStreamer)
244  * @description: description of the plugin
245  * @init_full_func: (scope call): pointer to the init function with user data
246  *     of this plugin.
247  * @version: version string of the plugin
248  * @license: effective license of plugin. Must be one of the approved licenses
249  *     (see #GstPluginDesc above) or the plugin will not be registered.
250  * @source: source module plugin belongs to
251  * @package: shipped package plugin belongs to
252  * @origin: URL to provider of plugin
253  * @user_data: gpointer to user data
254  *
255  * Registers a static plugin, ie. a plugin which is private to an application
256  * or library and contained within the application or library (as opposed to
257  * being shipped as a separate module file) with a #GstPluginInitFullFunc
258  * which allows user data to be passed to the callback function (useful
259  * for bindings).
260  *
261  * You must make sure that GStreamer has been initialised (with gst_init() or
262  * via gst_init_get_option_group()) before calling this function.
263  *
264  * Returns: TRUE if the plugin was registered correctly, otherwise FALSE.
265  *
266  * Since: 0.10.24
267  *
268  */
269 gboolean
270 gst_plugin_register_static_full (gint major_version, gint minor_version,
271     const gchar * name, const gchar * description,
272     GstPluginInitFullFunc init_full_func, const gchar * version,
273     const gchar * license, const gchar * source, const gchar * package,
274     const gchar * origin, gpointer user_data)
275 {
276   GstPluginDesc desc = { major_version, minor_version, name, description,
277     (GstPluginInitFunc) init_full_func, version, license, source, package,
278     origin, NULL,
279   };
280   GstPlugin *plugin;
281   gboolean res = FALSE;
282
283   g_return_val_if_fail (name != NULL, FALSE);
284   g_return_val_if_fail (description != NULL, FALSE);
285   g_return_val_if_fail (init_full_func != NULL, FALSE);
286   g_return_val_if_fail (version != NULL, FALSE);
287   g_return_val_if_fail (license != NULL, FALSE);
288   g_return_val_if_fail (source != NULL, FALSE);
289   g_return_val_if_fail (package != NULL, FALSE);
290   g_return_val_if_fail (origin != NULL, FALSE);
291
292   /* make sure gst_init() has been called */
293   g_return_val_if_fail (_gst_plugin_inited != FALSE, FALSE);
294
295   GST_LOG ("attempting to load static plugin \"%s\" now...", name);
296   plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
297   if (gst_plugin_register_func (plugin, &desc, user_data) != NULL) {
298     GST_INFO ("registered static plugin \"%s\"", name);
299     res = gst_registry_add_plugin (gst_registry_get (), plugin);
300     GST_INFO ("added static plugin \"%s\", result: %d", name, res);
301   }
302   return res;
303 }
304
305 void
306 _priv_gst_plugin_initialize (void)
307 {
308   const gchar *whitelist;
309   guint i;
310
311   _gst_plugin_inited = TRUE;
312
313   whitelist = g_getenv ("GST_PLUGIN_LOADING_WHITELIST");
314   if (whitelist != NULL && *whitelist != '\0') {
315     _plugin_loading_whitelist = g_strsplit (whitelist,
316         G_SEARCHPATH_SEPARATOR_S, -1);
317     for (i = 0; _plugin_loading_whitelist[i] != NULL; ++i) {
318       GST_INFO ("plugins whitelist entry: %s", _plugin_loading_whitelist[i]);
319     }
320   }
321
322   /* now register all static plugins */
323   GST_INFO ("registering %u static plugins", _num_static_plugins);
324   for (i = 0; i < _num_static_plugins; ++i) {
325     gst_plugin_register_static (_static_plugins[i].major_version,
326         _static_plugins[i].minor_version, _static_plugins[i].name,
327         _static_plugins[i].description, _static_plugins[i].plugin_init,
328         _static_plugins[i].version, _static_plugins[i].license,
329         _static_plugins[i].source, _static_plugins[i].package,
330         _static_plugins[i].origin);
331   }
332
333   if (_static_plugins) {
334     free (_static_plugins);
335     _static_plugins = NULL;
336     _num_static_plugins = 0;
337   }
338 }
339
340 /* Whitelist entry format:
341  *
342  *   plugin1,plugin2@pathprefix or
343  *   plugin1,plugin2@* or just
344  *   plugin1,plugin2 or
345  *   source-package@pathprefix or
346  *   source-package@* or just
347  *   source-package
348  *
349  * ie. the bit before the path will be checked against both the plugin
350  * name and the plugin's source package name, to keep the format simple.
351  */
352 static gboolean
353 gst_plugin_desc_matches_whitelist_entry (GstPluginDesc * desc,
354     const gchar * filename, const gchar * pattern)
355 {
356   const gchar *sep;
357   gboolean ret = FALSE;
358   gchar *name;
359
360   GST_LOG ("Whitelist pattern '%s', plugin: %s of %s@%s", pattern, desc->name,
361       desc->source, GST_STR_NULL (filename));
362
363   /* do we have a path prefix? */
364   sep = strchr (pattern, '@');
365   if (sep != NULL && strcmp (sep, "@*") != 0 && strcmp (sep, "@") != 0) {
366     /* paths are not canonicalised or treated with realpath() here. This
367      * should be good enough for our use case, since we just use the paths
368      * autotools uses, and those will be constructed from the same prefix. */
369     if (filename != NULL && !g_str_has_prefix (filename, sep + 1))
370       return FALSE;
371
372     GST_LOG ("%s matches path prefix %s", GST_STR_NULL (filename), sep + 1);
373   }
374
375   if (sep != NULL) {
376     name = g_strndup (pattern, (gsize) (sep - pattern));
377   } else {
378     name = g_strdup (pattern);
379   }
380
381   g_strstrip (name);
382   if (!g_ascii_isalnum (*name)) {
383     GST_WARNING ("Invalid whitelist pattern: %s", pattern);
384     goto done;
385   }
386
387   /* now check plugin names / source package name */
388   if (strchr (name, ',') == NULL) {
389     /* only a single name: either a plugin name or the source package name */
390     ret = (strcmp (desc->source, name) == 0 || strcmp (desc->name, name) == 0);
391   } else {
392     gchar **n, **names;
393
394     /* multiple names: assume these are plugin names */
395     names = g_strsplit (name, ",", -1);
396     for (n = names; n != NULL && *n != NULL; ++n) {
397       g_strstrip (*n);
398       if (strcmp (desc->name, *n) == 0) {
399         ret = TRUE;
400         break;
401       }
402     }
403     g_strfreev (names);
404   }
405
406   GST_LOG ("plugin / source package name match: %d", ret);
407
408 done:
409
410   g_free (name);
411   return ret;
412 }
413
414 gboolean
415 priv_gst_plugin_desc_is_whitelisted (GstPluginDesc * desc,
416     const gchar * filename)
417 {
418   gchar **entry;
419
420   if (_plugin_loading_whitelist == NULL)
421     return TRUE;
422
423   for (entry = _plugin_loading_whitelist; *entry != NULL; ++entry) {
424     if (gst_plugin_desc_matches_whitelist_entry (desc, filename, *entry)) {
425       GST_LOG ("Plugin %s is in whitelist", filename);
426       return TRUE;
427     }
428   }
429
430   GST_LOG ("Plugin %s (package %s, file %s) not in whitelist", desc->name,
431       desc->source, filename);
432   return FALSE;
433 }
434
435 gboolean
436 priv_gst_plugin_loading_have_whitelist (void)
437 {
438   return (_plugin_loading_whitelist != NULL);
439 }
440
441 guint32
442 priv_gst_plugin_loading_get_whitelist_hash (void)
443 {
444   guint32 hash = 0;
445
446   if (_plugin_loading_whitelist != NULL) {
447     gchar **w;
448
449     for (w = _plugin_loading_whitelist; *w != NULL; ++w)
450       hash = (hash << 1) ^ g_str_hash (*w);
451   }
452
453   return hash;
454 }
455
456 /* this function could be extended to check if the plugin license matches the
457  * applications license (would require the app to register its license somehow).
458  * We'll wait for someone who's interested in it to code it :)
459  */
460 static gboolean
461 gst_plugin_check_license (const gchar * license)
462 {
463   const gchar *const *check_license = valid_licenses;
464
465   g_assert (check_license);
466
467   while (*check_license) {
468     if (strcmp (license, *check_license) == 0)
469       return TRUE;
470     check_license++;
471   }
472   return FALSE;
473 }
474
475 static gboolean
476 gst_plugin_check_version (gint major, gint minor)
477 {
478   /* return NULL if the major and minor version numbers are not compatible */
479   /* with ours. */
480   if (major != GST_VERSION_MAJOR || minor > GST_VERSION_MINOR)
481     return FALSE;
482
483   return TRUE;
484 }
485
486 static GstPlugin *
487 gst_plugin_register_func (GstPlugin * plugin, const GstPluginDesc * desc,
488     gpointer user_data)
489 {
490   if (!gst_plugin_check_version (desc->major_version, desc->minor_version)) {
491     if (GST_CAT_DEFAULT)
492       GST_WARNING ("plugin \"%s\" has incompatible version, not loading",
493           plugin->filename);
494     return NULL;
495   }
496
497   if (!desc->license || !desc->description || !desc->source ||
498       !desc->package || !desc->origin) {
499     if (GST_CAT_DEFAULT)
500       GST_WARNING ("plugin \"%s\" has incorrect GstPluginDesc, not loading",
501           plugin->filename);
502     return NULL;
503   }
504
505   if (!gst_plugin_check_license (desc->license)) {
506     if (GST_CAT_DEFAULT)
507       GST_WARNING ("plugin \"%s\" has invalid license \"%s\", not loading",
508           plugin->filename, desc->license);
509     return NULL;
510   }
511
512   if (GST_CAT_DEFAULT)
513     GST_LOG ("plugin \"%s\" looks good", GST_STR_NULL (plugin->filename));
514
515   gst_plugin_desc_copy (&plugin->desc, desc);
516
517   /* make resident so we're really sure it never gets unloaded again.
518    * Theoretically this is not needed, but practically it doesn't hurt.
519    * And we're rather safe than sorry. */
520   if (plugin->module)
521     g_module_make_resident (plugin->module);
522
523   if (user_data) {
524     if (!(((GstPluginInitFullFunc) (desc->plugin_init)) (plugin, user_data))) {
525       if (GST_CAT_DEFAULT)
526         GST_WARNING ("plugin \"%s\" failed to initialise", plugin->filename);
527       return NULL;
528     }
529   } else {
530     if (!((desc->plugin_init) (plugin))) {
531       if (GST_CAT_DEFAULT)
532         GST_WARNING ("plugin \"%s\" failed to initialise", plugin->filename);
533       return NULL;
534     }
535   }
536
537   if (GST_CAT_DEFAULT)
538     GST_LOG ("plugin \"%s\" initialised", GST_STR_NULL (plugin->filename));
539
540   return plugin;
541 }
542
543 #ifdef HAVE_SIGACTION
544 static struct sigaction oldaction;
545 static gboolean _gst_plugin_fault_handler_is_setup = FALSE;
546
547 /*
548  * _gst_plugin_fault_handler_restore:
549  * segfault handler restorer
550  */
551 static void
552 _gst_plugin_fault_handler_restore (void)
553 {
554   if (!_gst_plugin_fault_handler_is_setup)
555     return;
556
557   _gst_plugin_fault_handler_is_setup = FALSE;
558
559   sigaction (SIGSEGV, &oldaction, NULL);
560 }
561
562 /*
563  * _gst_plugin_fault_handler_sighandler:
564  * segfault handler implementation
565  */
566 static void
567 _gst_plugin_fault_handler_sighandler (int signum)
568 {
569   /* We need to restore the fault handler or we'll keep getting it */
570   _gst_plugin_fault_handler_restore ();
571
572   switch (signum) {
573     case SIGSEGV:
574       g_print ("\nERROR: ");
575       g_print ("Caught a segmentation fault while loading plugin file:\n");
576       g_print ("%s\n\n", _gst_plugin_fault_handler_filename);
577       g_print ("Please either:\n");
578       g_print ("- remove it and restart.\n");
579       g_print
580           ("- run with --gst-disable-segtrap --gst-disable-registry-fork and debug.\n");
581       exit (-1);
582       break;
583     default:
584       g_print ("Caught unhandled signal on plugin loading\n");
585       break;
586   }
587 }
588
589 /*
590  * _gst_plugin_fault_handler_setup:
591  * sets up the segfault handler
592  */
593 static void
594 _gst_plugin_fault_handler_setup (void)
595 {
596   struct sigaction action;
597
598   /* if asked to leave segfaults alone, just return */
599   if (!gst_segtrap_is_enabled ())
600     return;
601
602   if (_gst_plugin_fault_handler_is_setup)
603     return;
604
605   _gst_plugin_fault_handler_is_setup = TRUE;
606
607   memset (&action, 0, sizeof (action));
608   action.sa_handler = _gst_plugin_fault_handler_sighandler;
609
610   sigaction (SIGSEGV, &action, &oldaction);
611 }
612 #else /* !HAVE_SIGACTION */
613 static void
614 _gst_plugin_fault_handler_restore (void)
615 {
616 }
617
618 static void
619 _gst_plugin_fault_handler_setup (void)
620 {
621 }
622 #endif /* HAVE_SIGACTION */
623
624 /* g_time_val_from_iso8601() doesn't do quite what we want */
625 static gboolean
626 check_release_datetime (const gchar * date_time)
627 {
628   guint64 val;
629
630   /* we require YYYY-MM-DD or YYYY-MM-DDTHH:MMZ format */
631   if (!g_ascii_isdigit (*date_time))
632     return FALSE;
633
634   val = g_ascii_strtoull (date_time, (gchar **) & date_time, 10);
635   if (val < 2000 || val > 2100 || *date_time != '-')
636     return FALSE;
637
638   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
639   if (val == 0 || val > 12 || *date_time != '-')
640     return FALSE;
641
642   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
643   if (val == 0 || val > 32)
644     return FALSE;
645
646   /* end of string or date/time separator + HH:MMZ */
647   if (*date_time == 'T' || *date_time == ' ') {
648     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
649     if (val > 24 || *date_time != ':')
650       return FALSE;
651
652     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
653     if (val > 59 || *date_time != 'Z')
654       return FALSE;
655
656     ++date_time;
657   }
658
659   return (*date_time == '\0');
660 }
661
662 static GMutex gst_plugin_loading_mutex;
663
664 #define CHECK_PLUGIN_DESC_FIELD(desc,field,fn)                               \
665   if (G_UNLIKELY ((desc)->field == NULL)) {                                  \
666     GST_ERROR ("GstPluginDesc for '%s' has no %s", fn, G_STRINGIFY (field)); \
667   }
668
669 /**
670  * gst_plugin_load_file:
671  * @filename: the plugin filename to load
672  * @error: pointer to a NULL-valued GError
673  *
674  * Loads the given plugin and refs it.  Caller needs to unref after use.
675  *
676  * Returns: (transfer full): a reference to the existing loaded GstPlugin, a 
677  * reference to the newly-loaded GstPlugin, or NULL if an error occurred.
678  */
679 GstPlugin *
680 gst_plugin_load_file (const gchar * filename, GError ** error)
681 {
682   GstPluginDesc *desc;
683   GstPlugin *plugin;
684   GModule *module;
685   gboolean ret;
686   gpointer ptr;
687   GStatBuf file_status;
688   GstRegistry *registry;
689   gboolean new_plugin = TRUE;
690   GModuleFlags flags;
691
692   g_return_val_if_fail (filename != NULL, NULL);
693
694   registry = gst_registry_get ();
695   g_mutex_lock (&gst_plugin_loading_mutex);
696
697   plugin = gst_registry_lookup (registry, filename);
698   if (plugin) {
699     if (plugin->module) {
700       /* already loaded */
701       g_mutex_unlock (&gst_plugin_loading_mutex);
702       return plugin;
703     } else {
704       /* load plugin and update fields */
705       new_plugin = FALSE;
706     }
707   }
708
709   GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "attempt to load plugin \"%s\"",
710       filename);
711
712   if (g_module_supported () == FALSE) {
713     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "module loading not supported");
714     g_set_error (error,
715         GST_PLUGIN_ERROR,
716         GST_PLUGIN_ERROR_MODULE, "Dynamic loading not supported");
717     goto return_error;
718   }
719
720   if (g_stat (filename, &file_status)) {
721     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "problem accessing file");
722     g_set_error (error,
723         GST_PLUGIN_ERROR,
724         GST_PLUGIN_ERROR_MODULE, "Problem accessing file %s: %s", filename,
725         g_strerror (errno));
726     goto return_error;
727   }
728
729   flags = G_MODULE_BIND_LOCAL;
730   /* libgstpython.so is the gst-python plugin loader. It needs to be loaded with
731    * G_MODULE_BIND_LAZY.
732    *
733    * Ideally there should be a generic way for plugins to specify that they
734    * need to be loaded with _LAZY.
735    * */
736   if (strstr (filename, "libgstpython"))
737     flags |= G_MODULE_BIND_LAZY;
738
739   module = g_module_open (filename, flags);
740   if (module == NULL) {
741     GST_CAT_WARNING (GST_CAT_PLUGIN_LOADING, "module_open failed: %s",
742         g_module_error ());
743     g_set_error (error,
744         GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE, "Opening module failed: %s",
745         g_module_error ());
746     /* If we failed to open the shared object, then it's probably because a
747      * plugin is linked against the wrong libraries. Print out an easy-to-see
748      * message in this case. */
749     g_warning ("Failed to load plugin '%s': %s", filename, g_module_error ());
750     goto return_error;
751   }
752
753   ret = g_module_symbol (module, "gst_plugin_desc", &ptr);
754   if (!ret) {
755     GST_DEBUG ("Could not find plugin entry point in \"%s\"", filename);
756     g_set_error (error,
757         GST_PLUGIN_ERROR,
758         GST_PLUGIN_ERROR_MODULE,
759         "File \"%s\" is not a GStreamer plugin", filename);
760     g_module_close (module);
761     goto return_error;
762   }
763
764   desc = (GstPluginDesc *) ptr;
765
766   if (priv_gst_plugin_loading_have_whitelist () &&
767       !priv_gst_plugin_desc_is_whitelisted (desc, filename)) {
768     GST_INFO ("Whitelist specified and plugin not in whitelist, not loading: "
769         "name=%s, package=%s, file=%s", desc->name, desc->source, filename);
770     g_set_error (error, GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE,
771         "Not loading plugin file \"%s\", not in whitelist", filename);
772     g_module_close (module);
773     goto return_error;
774   }
775
776   if (new_plugin) {
777     plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
778     plugin->file_mtime = file_status.st_mtime;
779     plugin->file_size = file_status.st_size;
780     plugin->filename = g_strdup (filename);
781     plugin->basename = g_path_get_basename (filename);
782   }
783
784   plugin->module = module;
785   plugin->orig_desc = desc;
786
787   if (new_plugin) {
788     /* check plugin description: complain about bad values but accept them, to
789      * maintain backwards compatibility (FIXME: 0.11) */
790     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, name, filename);
791     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, description, filename);
792     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, version, filename);
793     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, license, filename);
794     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, source, filename);
795     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, package, filename);
796     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, origin, filename);
797
798     if (plugin->orig_desc->release_datetime != NULL &&
799         !check_release_datetime (plugin->orig_desc->release_datetime)) {
800       GST_ERROR ("GstPluginDesc for '%s' has invalid datetime '%s'",
801           filename, plugin->orig_desc->release_datetime);
802       plugin->orig_desc->release_datetime = NULL;
803     }
804   }
805
806   GST_LOG ("Plugin %p for file \"%s\" prepared, calling entry function...",
807       plugin, filename);
808
809   /* this is where we load the actual .so, so let's trap SIGSEGV */
810   _gst_plugin_fault_handler_setup ();
811   _gst_plugin_fault_handler_filename = plugin->filename;
812
813   GST_LOG ("Plugin %p for file \"%s\" prepared, registering...",
814       plugin, filename);
815
816   if (!gst_plugin_register_func (plugin, plugin->orig_desc, NULL)) {
817     /* remove signal handler */
818     _gst_plugin_fault_handler_restore ();
819     GST_DEBUG ("gst_plugin_register_func failed for plugin \"%s\"", filename);
820     /* plugin == NULL */
821     g_set_error (error,
822         GST_PLUGIN_ERROR,
823         GST_PLUGIN_ERROR_MODULE,
824         "File \"%s\" appears to be a GStreamer plugin, but it failed to initialize",
825         filename);
826     goto return_error;
827   }
828
829   /* remove signal handler */
830   _gst_plugin_fault_handler_restore ();
831   _gst_plugin_fault_handler_filename = NULL;
832   GST_INFO ("plugin \"%s\" loaded", plugin->filename);
833
834   if (new_plugin) {
835     gst_object_ref (plugin);
836     gst_registry_add_plugin (gst_registry_get (), plugin);
837   }
838
839   g_mutex_unlock (&gst_plugin_loading_mutex);
840   return plugin;
841
842 return_error:
843   {
844     if (plugin)
845       gst_object_unref (plugin);
846     g_mutex_unlock (&gst_plugin_loading_mutex);
847     return NULL;
848   }
849 }
850
851 static void
852 gst_plugin_desc_copy (GstPluginDesc * dest, const GstPluginDesc * src)
853 {
854   dest->major_version = src->major_version;
855   dest->minor_version = src->minor_version;
856   dest->name = g_intern_string (src->name);
857   dest->description = g_intern_string (src->description);
858   dest->plugin_init = src->plugin_init;
859   dest->version = g_intern_string (src->version);
860   dest->license = g_intern_string (src->license);
861   dest->source = g_intern_string (src->source);
862   dest->package = g_intern_string (src->package);
863   dest->origin = g_intern_string (src->origin);
864   dest->release_datetime = g_intern_string (src->release_datetime);
865 }
866
867 /**
868  * gst_plugin_get_name:
869  * @plugin: plugin to get the name of
870  *
871  * Get the short name of the plugin
872  *
873  * Returns: the name of the plugin
874  */
875 const gchar *
876 gst_plugin_get_name (GstPlugin * plugin)
877 {
878   g_return_val_if_fail (plugin != NULL, NULL);
879
880   return plugin->desc.name;
881 }
882
883 /**
884  * gst_plugin_get_description:
885  * @plugin: plugin to get long name of
886  *
887  * Get the long descriptive name of the plugin
888  *
889  * Returns: the long name of the plugin
890  */
891 const gchar *
892 gst_plugin_get_description (GstPlugin * plugin)
893 {
894   g_return_val_if_fail (plugin != NULL, NULL);
895
896   return plugin->desc.description;
897 }
898
899 /**
900  * gst_plugin_get_filename:
901  * @plugin: plugin to get the filename of
902  *
903  * get the filename of the plugin
904  *
905  * Returns: the filename of the plugin
906  */
907 const gchar *
908 gst_plugin_get_filename (GstPlugin * plugin)
909 {
910   g_return_val_if_fail (plugin != NULL, NULL);
911
912   return plugin->filename;
913 }
914
915 /**
916  * gst_plugin_get_version:
917  * @plugin: plugin to get the version of
918  *
919  * get the version of the plugin
920  *
921  * Returns: the version of the plugin
922  */
923 const gchar *
924 gst_plugin_get_version (GstPlugin * plugin)
925 {
926   g_return_val_if_fail (plugin != NULL, NULL);
927
928   return plugin->desc.version;
929 }
930
931 /**
932  * gst_plugin_get_license:
933  * @plugin: plugin to get the license of
934  *
935  * get the license of the plugin
936  *
937  * Returns: the license of the plugin
938  */
939 const gchar *
940 gst_plugin_get_license (GstPlugin * plugin)
941 {
942   g_return_val_if_fail (plugin != NULL, NULL);
943
944   return plugin->desc.license;
945 }
946
947 /**
948  * gst_plugin_get_source:
949  * @plugin: plugin to get the source of
950  *
951  * get the source module the plugin belongs to.
952  *
953  * Returns: the source of the plugin
954  */
955 const gchar *
956 gst_plugin_get_source (GstPlugin * plugin)
957 {
958   g_return_val_if_fail (plugin != NULL, NULL);
959
960   return plugin->desc.source;
961 }
962
963 /**
964  * gst_plugin_get_package:
965  * @plugin: plugin to get the package of
966  *
967  * get the package the plugin belongs to.
968  *
969  * Returns: the package of the plugin
970  */
971 const gchar *
972 gst_plugin_get_package (GstPlugin * plugin)
973 {
974   g_return_val_if_fail (plugin != NULL, NULL);
975
976   return plugin->desc.package;
977 }
978
979 /**
980  * gst_plugin_get_origin:
981  * @plugin: plugin to get the origin of
982  *
983  * get the URL where the plugin comes from
984  *
985  * Returns: the origin of the plugin
986  */
987 const gchar *
988 gst_plugin_get_origin (GstPlugin * plugin)
989 {
990   g_return_val_if_fail (plugin != NULL, NULL);
991
992   return plugin->desc.origin;
993 }
994
995 /**
996  * gst_plugin_get_release_date_string:
997  * @plugin: plugin to get the release date of
998  *
999  * Get the release date (and possibly time) in form of a string, if available.
1000  *
1001  * For normal GStreamer plugin releases this will usually just be a date in
1002  * the form of "YYYY-MM-DD", while pre-releases and builds from git may contain
1003  * a time component after the date as well, in which case the string will be
1004  * formatted like "YYYY-MM-DDTHH:MMZ" (e.g. "2012-04-30T09:30Z").
1005  *
1006  * There may be plugins that do not have a valid release date set on them.
1007  *
1008  * Returns: the date string of the plugin, or %NULL if not available.
1009  */
1010 const gchar *
1011 gst_plugin_get_release_date_string (GstPlugin * plugin)
1012 {
1013   g_return_val_if_fail (plugin != NULL, NULL);
1014
1015   return plugin->desc.release_datetime;
1016 }
1017
1018 /**
1019  * gst_plugin_get_module:
1020  * @plugin: plugin to query
1021  *
1022  * Gets the #GModule of the plugin. If the plugin isn't loaded yet, NULL is
1023  * returned.
1024  *
1025  * Returns: (transfer none): module belonging to the plugin or NULL if the
1026  *          plugin isn't loaded yet.
1027  */
1028 GModule *
1029 gst_plugin_get_module (GstPlugin * plugin)
1030 {
1031   g_return_val_if_fail (plugin != NULL, NULL);
1032
1033   return plugin->module;
1034 }
1035
1036 /**
1037  * gst_plugin_is_loaded:
1038  * @plugin: plugin to query
1039  *
1040  * queries if the plugin is loaded into memory
1041  *
1042  * Returns: TRUE is loaded, FALSE otherwise
1043  */
1044 gboolean
1045 gst_plugin_is_loaded (GstPlugin * plugin)
1046 {
1047   g_return_val_if_fail (plugin != NULL, FALSE);
1048
1049   return (plugin->module != NULL || plugin->filename == NULL);
1050 }
1051
1052 /**
1053  * gst_plugin_get_cache_data:
1054  * @plugin: a plugin
1055  *
1056  * Gets the plugin specific data cache. If it is %NULL there is no cached data
1057  * stored. This is the case when the registry is getting rebuilt.
1058  *
1059  * Returns: (transfer none): The cached data as a #GstStructure or %NULL.
1060  *
1061  * Since: 0.10.24
1062  */
1063 const GstStructure *
1064 gst_plugin_get_cache_data (GstPlugin * plugin)
1065 {
1066   g_return_val_if_fail (GST_IS_PLUGIN (plugin), NULL);
1067
1068   return plugin->priv->cache_data;
1069 }
1070
1071 /**
1072  * gst_plugin_set_cache_data:
1073  * @plugin: a plugin
1074  * @cache_data: (transfer full): a structure containing the data to cache
1075  *
1076  * Adds plugin specific data to cache. Passes the ownership of the structure to
1077  * the @plugin.
1078  *
1079  * The cache is flushed every time the registry is rebuilt.
1080  *
1081  * Since: 0.10.24
1082  */
1083 void
1084 gst_plugin_set_cache_data (GstPlugin * plugin, GstStructure * cache_data)
1085 {
1086   g_return_if_fail (GST_IS_PLUGIN (plugin));
1087   g_return_if_fail (GST_IS_STRUCTURE (cache_data));
1088
1089   if (plugin->priv->cache_data) {
1090     gst_structure_free (plugin->priv->cache_data);
1091   }
1092   plugin->priv->cache_data = cache_data;
1093 }
1094
1095 #if 0
1096 /**
1097  * gst_plugin_feature_list:
1098  * @plugin: plugin to query
1099  * @filter: the filter to use
1100  * @first: only return first match
1101  * @user_data: user data passed to the filter function
1102  *
1103  * Runs a filter against all plugin features and returns a GList with
1104  * the results. If the first flag is set, only the first match is
1105  * returned (as a list with a single object).
1106  *
1107  * Returns: a GList of features, g_list_free after use.
1108  */
1109 GList *
1110 gst_plugin_feature_filter (GstPlugin * plugin,
1111     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1112 {
1113   GList *list;
1114   GList *g;
1115
1116   list = gst_filter_run (plugin->features, (GstFilterFunc) filter, first,
1117       user_data);
1118   for (g = list; g; g = g->next) {
1119     gst_object_ref (plugin);
1120   }
1121
1122   return list;
1123 }
1124
1125 typedef struct
1126 {
1127   GstPluginFeatureFilter filter;
1128   gboolean first;
1129   gpointer user_data;
1130   GList *result;
1131 }
1132 FeatureFilterData;
1133
1134 static gboolean
1135 _feature_filter (GstPlugin * plugin, gpointer user_data)
1136 {
1137   GList *result;
1138   FeatureFilterData *data = (FeatureFilterData *) user_data;
1139
1140   result = gst_plugin_feature_filter (plugin, data->filter, data->first,
1141       data->user_data);
1142   if (result) {
1143     data->result = g_list_concat (data->result, result);
1144     return TRUE;
1145   }
1146   return FALSE;
1147 }
1148
1149 /**
1150  * gst_plugin_list_feature_filter:
1151  * @list: a #GList of plugins to query
1152  * @filter: the filter function to use
1153  * @first: only return first match
1154  * @user_data: user data passed to the filter function
1155  *
1156  * Runs a filter against all plugin features of the plugins in the given
1157  * list and returns a GList with the results.
1158  * If the first flag is set, only the first match is
1159  * returned (as a list with a single object).
1160  *
1161  * Returns: a GList of features, g_list_free after use.
1162  */
1163 GList *
1164 gst_plugin_list_feature_filter (GList * list,
1165     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1166 {
1167   FeatureFilterData data;
1168   GList *result;
1169
1170   data.filter = filter;
1171   data.first = first;
1172   data.user_data = user_data;
1173   data.result = NULL;
1174
1175   result = gst_filter_run (list, (GstFilterFunc) _feature_filter, first, &data);
1176   g_list_free (result);
1177
1178   return data.result;
1179 }
1180 #endif
1181
1182 /**
1183  * gst_plugin_name_filter:
1184  * @plugin: the plugin to check
1185  * @name: the name of the plugin
1186  *
1187  * A standard filter that returns TRUE when the plugin is of the
1188  * given name.
1189  *
1190  * Returns: TRUE if the plugin is of the given name.
1191  */
1192 gboolean
1193 gst_plugin_name_filter (GstPlugin * plugin, const gchar * name)
1194 {
1195   return (plugin->desc.name && !strcmp (plugin->desc.name, name));
1196 }
1197
1198 #if 0
1199 /**
1200  * gst_plugin_find_feature:
1201  * @plugin: plugin to get the feature from
1202  * @name: The name of the feature to find
1203  * @type: The type of the feature to find
1204  *
1205  * Find a feature of the given name and type in the given plugin.
1206  *
1207  * Returns: a GstPluginFeature or NULL if the feature was not found.
1208  */
1209 GstPluginFeature *
1210 gst_plugin_find_feature (GstPlugin * plugin, const gchar * name, GType type)
1211 {
1212   GList *walk;
1213   GstPluginFeature *result = NULL;
1214   GstTypeNameData data;
1215
1216   g_return_val_if_fail (name != NULL, NULL);
1217
1218   data.type = type;
1219   data.name = name;
1220
1221   walk = gst_filter_run (plugin->features,
1222       (GstFilterFunc) gst_plugin_feature_type_name_filter, TRUE, &data);
1223
1224   if (walk) {
1225     result = GST_PLUGIN_FEATURE (walk->data);
1226
1227     gst_object_ref (result);
1228     gst_plugin_feature_list_free (walk);
1229   }
1230
1231   return result;
1232 }
1233 #endif
1234
1235 #if 0
1236 static gboolean
1237 gst_plugin_feature_name_filter (GstPluginFeature * feature, const gchar * name)
1238 {
1239   return !strcmp (name, GST_PLUGIN_FEATURE_NAME (feature));
1240 }
1241 #endif
1242
1243 #if 0
1244 /**
1245  * gst_plugin_find_feature_by_name:
1246  * @plugin: plugin to get the feature from
1247  * @name: The name of the feature to find
1248  *
1249  * Find a feature of the given name in the given plugin.
1250  *
1251  * Returns: a GstPluginFeature or NULL if the feature was not found.
1252  */
1253 GstPluginFeature *
1254 gst_plugin_find_feature_by_name (GstPlugin * plugin, const gchar * name)
1255 {
1256   GList *walk;
1257   GstPluginFeature *result = NULL;
1258
1259   g_return_val_if_fail (name != NULL, NULL);
1260
1261   walk = gst_filter_run (plugin->features,
1262       (GstFilterFunc) gst_plugin_feature_name_filter, TRUE, (void *) name);
1263
1264   if (walk) {
1265     result = GST_PLUGIN_FEATURE (walk->data);
1266
1267     gst_object_ref (result);
1268     gst_plugin_feature_list_free (walk);
1269   }
1270
1271   return result;
1272 }
1273 #endif
1274
1275 /**
1276  * gst_plugin_load_by_name:
1277  * @name: name of plugin to load
1278  *
1279  * Load the named plugin. Refs the plugin.
1280  *
1281  * Returns: (transfer full): a reference to a loaded plugin, or NULL on error.
1282  */
1283 GstPlugin *
1284 gst_plugin_load_by_name (const gchar * name)
1285 {
1286   GstPlugin *plugin, *newplugin;
1287   GError *error = NULL;
1288
1289   GST_DEBUG ("looking up plugin %s in default registry", name);
1290   plugin = gst_registry_find_plugin (gst_registry_get (), name);
1291   if (plugin) {
1292     GST_DEBUG ("loading plugin %s from file %s", name, plugin->filename);
1293     newplugin = gst_plugin_load_file (plugin->filename, &error);
1294     gst_object_unref (plugin);
1295
1296     if (!newplugin) {
1297       GST_WARNING ("load_plugin error: %s", error->message);
1298       g_error_free (error);
1299       return NULL;
1300     }
1301     /* newplugin was reffed by load_file */
1302     return newplugin;
1303   }
1304
1305   GST_DEBUG ("Could not find plugin %s in registry", name);
1306   return NULL;
1307 }
1308
1309 /**
1310  * gst_plugin_load:
1311  * @plugin: (transfer none): plugin to load
1312  *
1313  * Loads @plugin. Note that the *return value* is the loaded plugin; @plugin is
1314  * untouched. The normal use pattern of this function goes like this:
1315  *
1316  * <programlisting>
1317  * GstPlugin *loaded_plugin;
1318  * loaded_plugin = gst_plugin_load (plugin);
1319  * // presumably, we're no longer interested in the potentially-unloaded plugin
1320  * gst_object_unref (plugin);
1321  * plugin = loaded_plugin;
1322  * </programlisting>
1323  *
1324  * Returns: (transfer full): a reference to a loaded plugin, or NULL on error.
1325  */
1326 GstPlugin *
1327 gst_plugin_load (GstPlugin * plugin)
1328 {
1329   GError *error = NULL;
1330   GstPlugin *newplugin;
1331
1332   if (gst_plugin_is_loaded (plugin)) {
1333     return plugin;
1334   }
1335
1336   if (!(newplugin = gst_plugin_load_file (plugin->filename, &error)))
1337     goto load_error;
1338
1339   return newplugin;
1340
1341 load_error:
1342   {
1343     GST_WARNING ("load_plugin error: %s", error->message);
1344     g_error_free (error);
1345     return NULL;
1346   }
1347 }
1348
1349 /**
1350  * gst_plugin_list_free:
1351  * @list: (transfer full) (element-type Gst.Plugin): list of #GstPlugin
1352  *
1353  * Unrefs each member of @list, then frees the list.
1354  */
1355 void
1356 gst_plugin_list_free (GList * list)
1357 {
1358   GList *g;
1359
1360   for (g = list; g; g = g->next) {
1361     gst_object_unref (GST_PLUGIN_CAST (g->data));
1362   }
1363   g_list_free (list);
1364 }
1365
1366 /* ===== plugin dependencies ===== */
1367
1368 /* Scenarios:
1369  * ENV + xyz     where ENV can contain multiple values separated by SEPARATOR
1370  *               xyz may be "" (if ENV contains path to file rather than dir)
1371  * ENV + *xyz   same as above, but xyz acts as suffix filter
1372  * ENV + xyz*   same as above, but xyz acts as prefix filter (is this needed?)
1373  * ENV + *xyz*  same as above, but xyz acts as strstr filter (is this needed?)
1374  * 
1375  * same as above, with additional paths hard-coded at compile-time:
1376  *   - only check paths + ... if ENV is not set or yields not paths
1377  *   - always check paths + ... in addition to ENV
1378  *
1379  * When user specifies set of environment variables, he/she may also use e.g.
1380  * "HOME/.mystuff/plugins", and we'll expand the content of $HOME with the
1381  * remainder 
1382  */
1383
1384 /* we store in registry:
1385  *  sets of:
1386  *   { 
1387  *     - environment variables (array of strings)
1388  *     - last hash of env variable contents (uint) (so we can avoid doing stats
1389  *       if one of the env vars has changed; premature optimisation galore)
1390  *     - hard-coded paths (array of strings)
1391  *     - xyz filename/suffix/prefix strings (array of strings)
1392  *     - flags (int)
1393  *     - last hash of file/dir stats (int)
1394  *   }
1395  *   (= struct GstPluginDep)
1396  */
1397
1398 static guint
1399 gst_plugin_ext_dep_get_env_vars_hash (GstPlugin * plugin, GstPluginDep * dep)
1400 {
1401   gchar **e;
1402   guint hash;
1403
1404   /* there's no deeper logic to what we do here; all we want to know (when
1405    * checking if the plugin needs to be rescanned) is whether the content of
1406    * one of the environment variables in the list is different from when it
1407    * was last scanned */
1408   hash = 0;
1409   for (e = dep->env_vars; e != NULL && *e != NULL; ++e) {
1410     const gchar *val;
1411     gchar env_var[256];
1412
1413     /* order matters: "val",NULL needs to yield a different hash than
1414      * NULL,"val", so do a shift here whether the var is set or not */
1415     hash = hash << 5;
1416
1417     /* want environment variable at beginning of string */
1418     if (!g_ascii_isalnum (**e)) {
1419       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1420           "variable string: %s", *e);
1421       continue;
1422     }
1423
1424     /* user is allowed to specify e.g. "HOME/.pitivi/plugins" */
1425     g_strlcpy (env_var, *e, sizeof (env_var));
1426     g_strdelimit (env_var, "/\\", '\0');
1427
1428     if ((val = g_getenv (env_var)))
1429       hash += g_str_hash (val);
1430   }
1431
1432   return hash;
1433 }
1434
1435 gboolean
1436 _priv_plugin_deps_env_vars_changed (GstPlugin * plugin)
1437 {
1438   GList *l;
1439
1440   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1441     GstPluginDep *dep = l->data;
1442
1443     if (dep->env_hash != gst_plugin_ext_dep_get_env_vars_hash (plugin, dep))
1444       return TRUE;
1445   }
1446
1447   return FALSE;
1448 }
1449
1450 static void
1451 gst_plugin_ext_dep_extract_env_vars_paths (GstPlugin * plugin,
1452     GstPluginDep * dep, GQueue * paths)
1453 {
1454   gchar **evars;
1455
1456   for (evars = dep->env_vars; evars != NULL && *evars != NULL; ++evars) {
1457     const gchar *e;
1458     gchar **components;
1459
1460     /* want environment variable at beginning of string */
1461     if (!g_ascii_isalnum (**evars)) {
1462       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1463           "variable string: %s", *evars);
1464       continue;
1465     }
1466
1467     /* user is allowed to specify e.g. "HOME/.pitivi/plugins", which we want to
1468      * split into the env_var name component and the path component */
1469     components = g_strsplit_set (*evars, "/\\", 2);
1470     g_assert (components != NULL);
1471
1472     e = g_getenv (components[0]);
1473     GST_LOG_OBJECT (plugin, "expanding %s = '%s' (path suffix: %s)",
1474         components[0], GST_STR_NULL (e), GST_STR_NULL (components[1]));
1475
1476     if (components[1] != NULL) {
1477       g_strdelimit (components[1], "/\\", G_DIR_SEPARATOR);
1478     }
1479
1480     if (e != NULL && *e != '\0') {
1481       gchar **arr;
1482       guint i;
1483
1484       arr = g_strsplit (e, G_SEARCHPATH_SEPARATOR_S, -1);
1485
1486       for (i = 0; arr != NULL && arr[i] != NULL; ++i) {
1487         gchar *full_path;
1488
1489         if (!g_path_is_absolute (arr[i])) {
1490           GST_INFO_OBJECT (plugin, "ignoring environment variable content '%s'"
1491               ": either not an absolute path or not a path at all", arr[i]);
1492           continue;
1493         }
1494
1495         if (components[1] != NULL) {
1496           full_path = g_build_filename (arr[i], components[1], NULL);
1497         } else {
1498           full_path = g_strdup (arr[i]);
1499         }
1500
1501         if (!g_queue_find_custom (paths, full_path, (GCompareFunc) strcmp)) {
1502           GST_LOG_OBJECT (plugin, "path: '%s'", full_path);
1503           g_queue_push_tail (paths, full_path);
1504           full_path = NULL;
1505         } else {
1506           GST_LOG_OBJECT (plugin, "path: '%s' (duplicate,ignoring)", full_path);
1507           g_free (full_path);
1508         }
1509       }
1510
1511       g_strfreev (arr);
1512     }
1513
1514     g_strfreev (components);
1515   }
1516
1517   GST_LOG_OBJECT (plugin, "Extracted %d paths from environment", paths->length);
1518 }
1519
1520 static guint
1521 gst_plugin_ext_dep_get_hash_from_stat_entry (GStatBuf * s)
1522 {
1523   if (!(s->st_mode & (S_IFDIR | S_IFREG)))
1524     return (guint) - 1;
1525
1526   /* completely random formula */
1527   return ((s->st_size << 3) + (s->st_mtime << 5)) ^ s->st_ctime;
1528 }
1529
1530 static gboolean
1531 gst_plugin_ext_dep_direntry_matches (GstPlugin * plugin, const gchar * entry,
1532     const gchar ** filenames, GstPluginDependencyFlags flags)
1533 {
1534   /* no filenames specified, match all entries for now (could probably
1535    * optimise by just taking the dir stat hash or so) */
1536   if (filenames == NULL || *filenames == NULL || **filenames == '\0')
1537     return TRUE;
1538
1539   while (*filenames != NULL) {
1540     /* suffix match? */
1541     if (((flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX)) &&
1542         g_str_has_suffix (entry, *filenames)) {
1543       return TRUE;
1544       /* else it's an exact match that's needed */
1545     } else if (strcmp (entry, *filenames) == 0) {
1546       return TRUE;
1547     }
1548     GST_LOG ("%s does not match %s, flags=0x%04x", entry, *filenames, flags);
1549     ++filenames;
1550   }
1551   return FALSE;
1552 }
1553
1554 static guint
1555 gst_plugin_ext_dep_scan_dir_and_match_names (GstPlugin * plugin,
1556     const gchar * path, const gchar ** filenames,
1557     GstPluginDependencyFlags flags, int depth)
1558 {
1559   const gchar *entry;
1560   gboolean recurse_dirs;
1561   GError *err = NULL;
1562   GDir *dir;
1563   guint hash = 0;
1564
1565   recurse_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1566
1567   dir = g_dir_open (path, 0, &err);
1568   if (dir == NULL) {
1569     GST_DEBUG_OBJECT (plugin, "g_dir_open(%s) failed: %s", path, err->message);
1570     g_error_free (err);
1571     return (guint) - 1;
1572   }
1573
1574   /* FIXME: we're assuming here that we always get the directory entries in
1575    * the same order, and not in a random order */
1576   while ((entry = g_dir_read_name (dir))) {
1577     gboolean have_match;
1578     GStatBuf s;
1579     gchar *full_path;
1580     guint fhash;
1581
1582     have_match =
1583         gst_plugin_ext_dep_direntry_matches (plugin, entry, filenames, flags);
1584
1585     /* avoid the stat if possible */
1586     if (!have_match && !recurse_dirs)
1587       continue;
1588
1589     full_path = g_build_filename (path, entry, NULL);
1590     if (g_stat (full_path, &s) < 0) {
1591       fhash = (guint) - 1;
1592       GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1593           g_strerror (errno));
1594     } else if (have_match) {
1595       fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1596       GST_LOG_OBJECT (plugin, "stat: %s (result: %u)", full_path, fhash);
1597     } else if ((s.st_mode & (S_IFDIR))) {
1598       fhash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, full_path,
1599           filenames, flags, depth + 1);
1600     } else {
1601       /* it's not a name match, we want to recurse, but it's not a directory */
1602       g_free (full_path);
1603       continue;
1604     }
1605
1606     hash = (hash + fhash) << 1;
1607     g_free (full_path);
1608   }
1609
1610   g_dir_close (dir);
1611   return hash;
1612 }
1613
1614 static guint
1615 gst_plugin_ext_dep_scan_path_with_filenames (GstPlugin * plugin,
1616     const gchar * path, const gchar ** filenames,
1617     GstPluginDependencyFlags flags)
1618 {
1619   const gchar *empty_filenames[] = { "", NULL };
1620   gboolean recurse_into_dirs, partial_names;
1621   guint i, hash = 0;
1622
1623   /* to avoid special-casing below (FIXME?) */
1624   if (filenames == NULL || *filenames == NULL)
1625     filenames = empty_filenames;
1626
1627   recurse_into_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1628   partial_names = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX);
1629
1630   /* if we can construct the exact paths to check with the data we have, just
1631    * stat them one by one; this is more efficient than opening the directory
1632    * and going through each entry to see if it matches one of our filenames. */
1633   if (!recurse_into_dirs && !partial_names) {
1634     for (i = 0; filenames[i] != NULL; ++i) {
1635       GStatBuf s;
1636       gchar *full_path;
1637       guint fhash;
1638
1639       full_path = g_build_filename (path, filenames[i], NULL);
1640       if (g_stat (full_path, &s) < 0) {
1641         fhash = (guint) - 1;
1642         GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1643             g_strerror (errno));
1644       } else {
1645         fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1646         GST_LOG_OBJECT (plugin, "stat: %s (result: %08x)", full_path, fhash);
1647       }
1648       hash = (hash + fhash) << 1;
1649       g_free (full_path);
1650     }
1651   } else {
1652     hash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, path,
1653         filenames, flags, 0);
1654   }
1655
1656   return hash;
1657 }
1658
1659 static guint
1660 gst_plugin_ext_dep_get_stat_hash (GstPlugin * plugin, GstPluginDep * dep)
1661 {
1662   gboolean paths_are_default_only;
1663   GQueue scan_paths = G_QUEUE_INIT;
1664   guint scan_hash = 0;
1665   gchar *path;
1666
1667   GST_LOG_OBJECT (plugin, "start");
1668
1669   paths_are_default_only =
1670       dep->flags & GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_DEFAULT_ONLY;
1671
1672   gst_plugin_ext_dep_extract_env_vars_paths (plugin, dep, &scan_paths);
1673
1674   if (g_queue_is_empty (&scan_paths) || !paths_are_default_only) {
1675     gchar **paths;
1676
1677     for (paths = dep->paths; paths != NULL && *paths != NULL; ++paths) {
1678       const gchar *path = *paths;
1679
1680       if (!g_queue_find_custom (&scan_paths, path, (GCompareFunc) strcmp)) {
1681         GST_LOG_OBJECT (plugin, "path: '%s'", path);
1682         g_queue_push_tail (&scan_paths, g_strdup (path));
1683       } else {
1684         GST_LOG_OBJECT (plugin, "path: '%s' (duplicate, ignoring)", path);
1685       }
1686     }
1687   }
1688
1689   while ((path = g_queue_pop_head (&scan_paths))) {
1690     scan_hash += gst_plugin_ext_dep_scan_path_with_filenames (plugin, path,
1691         (const gchar **) dep->names, dep->flags);
1692     scan_hash = scan_hash << 1;
1693     g_free (path);
1694   }
1695
1696   GST_LOG_OBJECT (plugin, "done, scan_hash: %08x", scan_hash);
1697   return scan_hash;
1698 }
1699
1700 gboolean
1701 _priv_plugin_deps_files_changed (GstPlugin * plugin)
1702 {
1703   GList *l;
1704
1705   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1706     GstPluginDep *dep = l->data;
1707
1708     if (dep->stat_hash != gst_plugin_ext_dep_get_stat_hash (plugin, dep))
1709       return TRUE;
1710   }
1711
1712   return FALSE;
1713 }
1714
1715 static void
1716 gst_plugin_ext_dep_free (GstPluginDep * dep)
1717 {
1718   g_strfreev (dep->env_vars);
1719   g_strfreev (dep->paths);
1720   g_strfreev (dep->names);
1721   g_slice_free (GstPluginDep, dep);
1722 }
1723
1724 static gboolean
1725 gst_plugin_ext_dep_strv_equal (gchar ** arr1, gchar ** arr2)
1726 {
1727   if (arr1 == arr2)
1728     return TRUE;
1729   if (arr1 == NULL || arr2 == NULL)
1730     return FALSE;
1731   for (; *arr1 != NULL && *arr2 != NULL; ++arr1, ++arr2) {
1732     if (strcmp (*arr1, *arr2) != 0)
1733       return FALSE;
1734   }
1735   return (*arr1 == *arr2);
1736 }
1737
1738 static gboolean
1739 gst_plugin_ext_dep_equals (GstPluginDep * dep, const gchar ** env_vars,
1740     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1741 {
1742   if (dep->flags != flags)
1743     return FALSE;
1744
1745   return gst_plugin_ext_dep_strv_equal (dep->env_vars, (gchar **) env_vars) &&
1746       gst_plugin_ext_dep_strv_equal (dep->paths, (gchar **) paths) &&
1747       gst_plugin_ext_dep_strv_equal (dep->names, (gchar **) names);
1748 }
1749
1750 /**
1751  * gst_plugin_add_dependency:
1752  * @plugin: a #GstPlugin
1753  * @env_vars: NULL-terminated array of environment variables affecting the
1754  *     feature set of the plugin (e.g. an environment variable containing
1755  *     paths where to look for additional modules/plugins of a library),
1756  *     or NULL. Environment variable names may be followed by a path component
1757  *      which will be added to the content of the environment variable, e.g.
1758  *      "HOME/.mystuff/plugins".
1759  * @paths: NULL-terminated array of directories/paths where dependent files
1760  *     may be.
1761  * @names: NULL-terminated array of file names (or file name suffixes,
1762  *     depending on @flags) to be used in combination with the paths from
1763  *     @paths and/or the paths extracted from the environment variables in
1764  *     @env_vars, or NULL.
1765  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1766  *
1767  * Make GStreamer aware of external dependencies which affect the feature
1768  * set of this plugin (ie. the elements or typefinders associated with it).
1769  *
1770  * GStreamer will re-inspect plugins with external dependencies whenever any
1771  * of the external dependencies change. This is useful for plugins which wrap
1772  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1773  * library and makes visualisations available as GStreamer elements, or a
1774  * codec loader which exposes elements and/or caps dependent on what external
1775  * codec libraries are currently installed.
1776  *
1777  * Since: 0.10.22
1778  */
1779 void
1780 gst_plugin_add_dependency (GstPlugin * plugin, const gchar ** env_vars,
1781     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1782 {
1783   GstPluginDep *dep;
1784   GList *l;
1785
1786   g_return_if_fail (GST_IS_PLUGIN (plugin));
1787
1788   if ((env_vars == NULL || env_vars[0] == NULL) &&
1789       (paths == NULL || paths[0] == NULL)) {
1790     GST_DEBUG_OBJECT (plugin,
1791         "plugin registered empty dependency set. Ignoring");
1792     return;
1793   }
1794
1795   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1796     if (gst_plugin_ext_dep_equals (l->data, env_vars, paths, names, flags)) {
1797       GST_LOG_OBJECT (plugin, "dependency already registered");
1798       return;
1799     }
1800   }
1801
1802   dep = g_slice_new (GstPluginDep);
1803
1804   dep->env_vars = g_strdupv ((gchar **) env_vars);
1805   dep->paths = g_strdupv ((gchar **) paths);
1806   dep->names = g_strdupv ((gchar **) names);
1807   dep->flags = flags;
1808
1809   dep->env_hash = gst_plugin_ext_dep_get_env_vars_hash (plugin, dep);
1810   dep->stat_hash = gst_plugin_ext_dep_get_stat_hash (plugin, dep);
1811
1812   plugin->priv->deps = g_list_append (plugin->priv->deps, dep);
1813
1814   GST_DEBUG_OBJECT (plugin, "added dependency:");
1815   for (; env_vars != NULL && *env_vars != NULL; ++env_vars)
1816     GST_DEBUG_OBJECT (plugin, " evar: %s", *env_vars);
1817   for (; paths != NULL && *paths != NULL; ++paths)
1818     GST_DEBUG_OBJECT (plugin, " path: %s", *paths);
1819   for (; names != NULL && *names != NULL; ++names)
1820     GST_DEBUG_OBJECT (plugin, " name: %s", *names);
1821 }
1822
1823 /**
1824  * gst_plugin_add_dependency_simple:
1825  * @plugin: the #GstPlugin
1826  * @env_vars: one or more environment variables (separated by ':', ';' or ','),
1827  *      or NULL. Environment variable names may be followed by a path component
1828  *      which will be added to the content of the environment variable, e.g.
1829  *      "HOME/.mystuff/plugins:MYSTUFF_PLUGINS_PATH"
1830  * @paths: one ore more directory paths (separated by ':' or ';' or ','),
1831  *      or NULL. Example: "/usr/lib/mystuff/plugins"
1832  * @names: one or more file names or file name suffixes (separated by commas),
1833  *   or NULL
1834  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1835  *
1836  * Make GStreamer aware of external dependencies which affect the feature
1837  * set of this plugin (ie. the elements or typefinders associated with it).
1838  *
1839  * GStreamer will re-inspect plugins with external dependencies whenever any
1840  * of the external dependencies change. This is useful for plugins which wrap
1841  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1842  * library and makes visualisations available as GStreamer elements, or a
1843  * codec loader which exposes elements and/or caps dependent on what external
1844  * codec libraries are currently installed.
1845  *
1846  * Convenience wrapper function for gst_plugin_add_dependency() which
1847  * takes simple strings as arguments instead of string arrays, with multiple
1848  * arguments separated by predefined delimiters (see above).
1849  *
1850  * Since: 0.10.22
1851  */
1852 void
1853 gst_plugin_add_dependency_simple (GstPlugin * plugin,
1854     const gchar * env_vars, const gchar * paths, const gchar * names,
1855     GstPluginDependencyFlags flags)
1856 {
1857   gchar **a_evars = NULL;
1858   gchar **a_paths = NULL;
1859   gchar **a_names = NULL;
1860
1861   if (env_vars)
1862     a_evars = g_strsplit_set (env_vars, ":;,", -1);
1863   if (paths)
1864     a_paths = g_strsplit_set (paths, ":;,", -1);
1865   if (names)
1866     a_names = g_strsplit_set (names, ",", -1);
1867
1868   gst_plugin_add_dependency (plugin, (const gchar **) a_evars,
1869       (const gchar **) a_paths, (const gchar **) a_names, flags);
1870
1871   if (a_evars)
1872     g_strfreev (a_evars);
1873   if (a_paths)
1874     g_strfreev (a_paths);
1875   if (a_names)
1876     g_strfreev (a_names);
1877 }