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