plugin: warn if plugin name starts with a "
[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 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, not loading",
484           plugin->filename);
485     return NULL;
486   }
487
488   if (!desc->license || !desc->description || !desc->source ||
489       !desc->package || !desc->origin) {
490     if (GST_CAT_DEFAULT)
491       GST_WARNING ("plugin \"%s\" has incorrect GstPluginDesc, not loading",
492           plugin->filename);
493     return NULL;
494   }
495
496   if (!gst_plugin_check_license (desc->license)) {
497     if (GST_CAT_DEFAULT)
498       GST_WARNING ("plugin \"%s\" has invalid license \"%s\", not loading",
499           plugin->filename, desc->license);
500     return NULL;
501   }
502
503   if (GST_CAT_DEFAULT)
504     GST_LOG ("plugin \"%s\" looks good", GST_STR_NULL (plugin->filename));
505
506   gst_plugin_desc_copy (&plugin->desc, desc);
507
508   /* make resident so we're really sure it never gets unloaded again.
509    * Theoretically this is not needed, but practically it doesn't hurt.
510    * And we're rather safe than sorry. */
511   if (plugin->module)
512     g_module_make_resident (plugin->module);
513
514   if (user_data) {
515     if (!(((GstPluginInitFullFunc) (desc->plugin_init)) (plugin, user_data))) {
516       if (GST_CAT_DEFAULT)
517         GST_WARNING ("plugin \"%s\" failed to initialise", plugin->filename);
518       return NULL;
519     }
520   } else {
521     if (!((desc->plugin_init) (plugin))) {
522       if (GST_CAT_DEFAULT)
523         GST_WARNING ("plugin \"%s\" failed to initialise", plugin->filename);
524       return NULL;
525     }
526   }
527
528   if (GST_CAT_DEFAULT)
529     GST_LOG ("plugin \"%s\" initialised", GST_STR_NULL (plugin->filename));
530
531   return plugin;
532 }
533
534 #ifdef HAVE_SIGACTION
535 static struct sigaction oldaction;
536 static gboolean _gst_plugin_fault_handler_is_setup = FALSE;
537
538 /*
539  * _gst_plugin_fault_handler_restore:
540  * segfault handler restorer
541  */
542 static void
543 _gst_plugin_fault_handler_restore (void)
544 {
545   if (!_gst_plugin_fault_handler_is_setup)
546     return;
547
548   _gst_plugin_fault_handler_is_setup = FALSE;
549
550   sigaction (SIGSEGV, &oldaction, NULL);
551 }
552
553 /*
554  * _gst_plugin_fault_handler_sighandler:
555  * segfault handler implementation
556  */
557 static void
558 _gst_plugin_fault_handler_sighandler (int signum)
559 {
560   /* We need to restore the fault handler or we'll keep getting it */
561   _gst_plugin_fault_handler_restore ();
562
563   switch (signum) {
564     case SIGSEGV:
565       g_print ("\nERROR: ");
566       g_print ("Caught a segmentation fault while loading plugin file:\n");
567       g_print ("%s\n\n", _gst_plugin_fault_handler_filename);
568       g_print ("Please either:\n");
569       g_print ("- remove it and restart.\n");
570       g_print
571           ("- run with --gst-disable-segtrap --gst-disable-registry-fork and debug.\n");
572       exit (-1);
573       break;
574     default:
575       g_print ("Caught unhandled signal on plugin loading\n");
576       break;
577   }
578 }
579
580 /*
581  * _gst_plugin_fault_handler_setup:
582  * sets up the segfault handler
583  */
584 static void
585 _gst_plugin_fault_handler_setup (void)
586 {
587   struct sigaction action;
588
589   /* if asked to leave segfaults alone, just return */
590   if (!gst_segtrap_is_enabled ())
591     return;
592
593   if (_gst_plugin_fault_handler_is_setup)
594     return;
595
596   _gst_plugin_fault_handler_is_setup = TRUE;
597
598   memset (&action, 0, sizeof (action));
599   action.sa_handler = _gst_plugin_fault_handler_sighandler;
600
601   sigaction (SIGSEGV, &action, &oldaction);
602 }
603 #else /* !HAVE_SIGACTION */
604 static void
605 _gst_plugin_fault_handler_restore (void)
606 {
607 }
608
609 static void
610 _gst_plugin_fault_handler_setup (void)
611 {
612 }
613 #endif /* HAVE_SIGACTION */
614
615 /* g_time_val_from_iso8601() doesn't do quite what we want */
616 static gboolean
617 check_release_datetime (const gchar * date_time)
618 {
619   guint64 val;
620
621   /* we require YYYY-MM-DD or YYYY-MM-DDTHH:MMZ format */
622   if (!g_ascii_isdigit (*date_time))
623     return FALSE;
624
625   val = g_ascii_strtoull (date_time, (gchar **) & date_time, 10);
626   if (val < 2000 || val > 2100 || *date_time != '-')
627     return FALSE;
628
629   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
630   if (val == 0 || val > 12 || *date_time != '-')
631     return FALSE;
632
633   val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
634   if (val == 0 || val > 32)
635     return FALSE;
636
637   /* end of string or date/time separator + HH:MMZ */
638   if (*date_time == 'T' || *date_time == ' ') {
639     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
640     if (val > 24 || *date_time != ':')
641       return FALSE;
642
643     val = g_ascii_strtoull (date_time + 1, (gchar **) & date_time, 10);
644     if (val > 59 || *date_time != 'Z')
645       return FALSE;
646
647     ++date_time;
648   }
649
650   return (*date_time == '\0');
651 }
652
653 static GMutex gst_plugin_loading_mutex;
654
655 #define CHECK_PLUGIN_DESC_FIELD(desc,field,fn)                               \
656   if (G_UNLIKELY ((desc)->field == NULL)) {                                  \
657     GST_ERROR ("GstPluginDesc for '%s' has no %s", fn, G_STRINGIFY (field)); \
658   }
659
660 /**
661  * gst_plugin_load_file:
662  * @filename: the plugin filename to load
663  * @error: pointer to a NULL-valued GError
664  *
665  * Loads the given plugin and refs it.  Caller needs to unref after use.
666  *
667  * Returns: (transfer full): a reference to the existing loaded GstPlugin, a 
668  * reference to the newly-loaded GstPlugin, or NULL if an error occurred.
669  */
670 GstPlugin *
671 gst_plugin_load_file (const gchar * filename, GError ** error)
672 {
673   GstPluginDesc *desc;
674   GstPlugin *plugin;
675   GModule *module;
676   gboolean ret;
677   gpointer ptr;
678   GStatBuf file_status;
679   GstRegistry *registry;
680   gboolean new_plugin = TRUE;
681   GModuleFlags flags;
682
683   g_return_val_if_fail (filename != NULL, NULL);
684
685   registry = gst_registry_get ();
686   g_mutex_lock (&gst_plugin_loading_mutex);
687
688   plugin = gst_registry_lookup (registry, filename);
689   if (plugin) {
690     if (plugin->module) {
691       /* already loaded */
692       g_mutex_unlock (&gst_plugin_loading_mutex);
693       return plugin;
694     } else {
695       /* load plugin and update fields */
696       new_plugin = FALSE;
697     }
698   }
699
700   GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "attempt to load plugin \"%s\"",
701       filename);
702
703   if (g_module_supported () == FALSE) {
704     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "module loading not supported");
705     g_set_error (error,
706         GST_PLUGIN_ERROR,
707         GST_PLUGIN_ERROR_MODULE, "Dynamic loading not supported");
708     goto return_error;
709   }
710
711   if (g_stat (filename, &file_status)) {
712     GST_CAT_DEBUG (GST_CAT_PLUGIN_LOADING, "problem accessing file");
713     g_set_error (error,
714         GST_PLUGIN_ERROR,
715         GST_PLUGIN_ERROR_MODULE, "Problem accessing file %s: %s", filename,
716         g_strerror (errno));
717     goto return_error;
718   }
719
720   flags = G_MODULE_BIND_LOCAL;
721   /* libgstpython.so is the gst-python plugin loader. It needs to be loaded with
722    * G_MODULE_BIND_LAZY.
723    *
724    * Ideally there should be a generic way for plugins to specify that they
725    * need to be loaded with _LAZY.
726    * */
727   if (strstr (filename, "libgstpython"))
728     flags |= G_MODULE_BIND_LAZY;
729
730   module = g_module_open (filename, flags);
731   if (module == NULL) {
732     GST_CAT_WARNING (GST_CAT_PLUGIN_LOADING, "module_open failed: %s",
733         g_module_error ());
734     g_set_error (error,
735         GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE, "Opening module failed: %s",
736         g_module_error ());
737     /* If we failed to open the shared object, then it's probably because a
738      * plugin is linked against the wrong libraries. Print out an easy-to-see
739      * message in this case. */
740     g_warning ("Failed to load plugin '%s': %s", filename, g_module_error ());
741     goto return_error;
742   }
743
744   ret = g_module_symbol (module, "gst_plugin_desc", &ptr);
745   if (!ret) {
746     GST_DEBUG ("Could not find plugin entry point in \"%s\"", filename);
747     g_set_error (error,
748         GST_PLUGIN_ERROR,
749         GST_PLUGIN_ERROR_MODULE,
750         "File \"%s\" is not a GStreamer plugin", filename);
751     g_module_close (module);
752     goto return_error;
753   }
754
755   desc = (GstPluginDesc *) ptr;
756
757   if (priv_gst_plugin_loading_have_whitelist () &&
758       !priv_gst_plugin_desc_is_whitelisted (desc, filename)) {
759     GST_INFO ("Whitelist specified and plugin not in whitelist, not loading: "
760         "name=%s, package=%s, file=%s", desc->name, desc->source, filename);
761     g_set_error (error, GST_PLUGIN_ERROR, GST_PLUGIN_ERROR_MODULE,
762         "Not loading plugin file \"%s\", not in whitelist", filename);
763     g_module_close (module);
764     goto return_error;
765   }
766
767   if (new_plugin) {
768     plugin = g_object_newv (GST_TYPE_PLUGIN, 0, NULL);
769     plugin->file_mtime = file_status.st_mtime;
770     plugin->file_size = file_status.st_size;
771     plugin->filename = g_strdup (filename);
772     plugin->basename = g_path_get_basename (filename);
773   }
774
775   plugin->module = module;
776   plugin->orig_desc = desc;
777
778   if (new_plugin) {
779     /* check plugin description: complain about bad values but accept them, to
780      * maintain backwards compatibility (FIXME: 0.11) */
781     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, name, filename);
782     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, description, filename);
783     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, version, filename);
784     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, license, filename);
785     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, source, filename);
786     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, package, filename);
787     CHECK_PLUGIN_DESC_FIELD (plugin->orig_desc, origin, filename);
788
789     if (plugin->orig_desc->name != NULL && plugin->orig_desc->name[0] == '"') {
790       g_warning ("Invalid plugin name '%s' - fix your GST_PLUGIN_DEFINE "
791           "(remove quotes around plugin name)", plugin->orig_desc->name);
792     }
793
794     if (plugin->orig_desc->release_datetime != NULL &&
795         !check_release_datetime (plugin->orig_desc->release_datetime)) {
796       GST_ERROR ("GstPluginDesc for '%s' has invalid datetime '%s'",
797           filename, plugin->orig_desc->release_datetime);
798       plugin->orig_desc->release_datetime = NULL;
799     }
800   }
801
802   GST_LOG ("Plugin %p for file \"%s\" prepared, calling entry function...",
803       plugin, filename);
804
805   /* this is where we load the actual .so, so let's trap SIGSEGV */
806   _gst_plugin_fault_handler_setup ();
807   _gst_plugin_fault_handler_filename = plugin->filename;
808
809   GST_LOG ("Plugin %p for file \"%s\" prepared, registering...",
810       plugin, filename);
811
812   if (!gst_plugin_register_func (plugin, plugin->orig_desc, NULL)) {
813     /* remove signal handler */
814     _gst_plugin_fault_handler_restore ();
815     GST_DEBUG ("gst_plugin_register_func failed for plugin \"%s\"", filename);
816     /* plugin == NULL */
817     g_set_error (error,
818         GST_PLUGIN_ERROR,
819         GST_PLUGIN_ERROR_MODULE,
820         "File \"%s\" appears to be a GStreamer plugin, but it failed to initialize",
821         filename);
822     goto return_error;
823   }
824
825   /* remove signal handler */
826   _gst_plugin_fault_handler_restore ();
827   _gst_plugin_fault_handler_filename = NULL;
828   GST_INFO ("plugin \"%s\" loaded", plugin->filename);
829
830   if (new_plugin) {
831     gst_object_ref (plugin);
832     gst_registry_add_plugin (gst_registry_get (), plugin);
833   }
834
835   g_mutex_unlock (&gst_plugin_loading_mutex);
836   return plugin;
837
838 return_error:
839   {
840     if (plugin)
841       gst_object_unref (plugin);
842     g_mutex_unlock (&gst_plugin_loading_mutex);
843     return NULL;
844   }
845 }
846
847 static void
848 gst_plugin_desc_copy (GstPluginDesc * dest, const GstPluginDesc * src)
849 {
850   dest->major_version = src->major_version;
851   dest->minor_version = src->minor_version;
852   dest->name = g_intern_string (src->name);
853   dest->description = g_intern_string (src->description);
854   dest->plugin_init = src->plugin_init;
855   dest->version = g_intern_string (src->version);
856   dest->license = g_intern_string (src->license);
857   dest->source = g_intern_string (src->source);
858   dest->package = g_intern_string (src->package);
859   dest->origin = g_intern_string (src->origin);
860   dest->release_datetime = g_intern_string (src->release_datetime);
861 }
862
863 /**
864  * gst_plugin_get_name:
865  * @plugin: plugin to get the name of
866  *
867  * Get the short name of the plugin
868  *
869  * Returns: the name of the plugin
870  */
871 const gchar *
872 gst_plugin_get_name (GstPlugin * plugin)
873 {
874   g_return_val_if_fail (plugin != NULL, NULL);
875
876   return plugin->desc.name;
877 }
878
879 /**
880  * gst_plugin_get_description:
881  * @plugin: plugin to get long name of
882  *
883  * Get the long descriptive name of the plugin
884  *
885  * Returns: the long name of the plugin
886  */
887 const gchar *
888 gst_plugin_get_description (GstPlugin * plugin)
889 {
890   g_return_val_if_fail (plugin != NULL, NULL);
891
892   return plugin->desc.description;
893 }
894
895 /**
896  * gst_plugin_get_filename:
897  * @plugin: plugin to get the filename of
898  *
899  * get the filename of the plugin
900  *
901  * Returns: the filename of the plugin
902  */
903 const gchar *
904 gst_plugin_get_filename (GstPlugin * plugin)
905 {
906   g_return_val_if_fail (plugin != NULL, NULL);
907
908   return plugin->filename;
909 }
910
911 /**
912  * gst_plugin_get_version:
913  * @plugin: plugin to get the version of
914  *
915  * get the version of the plugin
916  *
917  * Returns: the version of the plugin
918  */
919 const gchar *
920 gst_plugin_get_version (GstPlugin * plugin)
921 {
922   g_return_val_if_fail (plugin != NULL, NULL);
923
924   return plugin->desc.version;
925 }
926
927 /**
928  * gst_plugin_get_license:
929  * @plugin: plugin to get the license of
930  *
931  * get the license of the plugin
932  *
933  * Returns: the license of the plugin
934  */
935 const gchar *
936 gst_plugin_get_license (GstPlugin * plugin)
937 {
938   g_return_val_if_fail (plugin != NULL, NULL);
939
940   return plugin->desc.license;
941 }
942
943 /**
944  * gst_plugin_get_source:
945  * @plugin: plugin to get the source of
946  *
947  * get the source module the plugin belongs to.
948  *
949  * Returns: the source of the plugin
950  */
951 const gchar *
952 gst_plugin_get_source (GstPlugin * plugin)
953 {
954   g_return_val_if_fail (plugin != NULL, NULL);
955
956   return plugin->desc.source;
957 }
958
959 /**
960  * gst_plugin_get_package:
961  * @plugin: plugin to get the package of
962  *
963  * get the package the plugin belongs to.
964  *
965  * Returns: the package of the plugin
966  */
967 const gchar *
968 gst_plugin_get_package (GstPlugin * plugin)
969 {
970   g_return_val_if_fail (plugin != NULL, NULL);
971
972   return plugin->desc.package;
973 }
974
975 /**
976  * gst_plugin_get_origin:
977  * @plugin: plugin to get the origin of
978  *
979  * get the URL where the plugin comes from
980  *
981  * Returns: the origin of the plugin
982  */
983 const gchar *
984 gst_plugin_get_origin (GstPlugin * plugin)
985 {
986   g_return_val_if_fail (plugin != NULL, NULL);
987
988   return plugin->desc.origin;
989 }
990
991 /**
992  * gst_plugin_get_release_date_string:
993  * @plugin: plugin to get the release date of
994  *
995  * Get the release date (and possibly time) in form of a string, if available.
996  *
997  * For normal GStreamer plugin releases this will usually just be a date in
998  * the form of "YYYY-MM-DD", while pre-releases and builds from git may contain
999  * a time component after the date as well, in which case the string will be
1000  * formatted like "YYYY-MM-DDTHH:MMZ" (e.g. "2012-04-30T09:30Z").
1001  *
1002  * There may be plugins that do not have a valid release date set on them.
1003  *
1004  * Returns: the date string of the plugin, or %NULL if not available.
1005  */
1006 const gchar *
1007 gst_plugin_get_release_date_string (GstPlugin * plugin)
1008 {
1009   g_return_val_if_fail (plugin != NULL, NULL);
1010
1011   return plugin->desc.release_datetime;
1012 }
1013
1014 /**
1015  * gst_plugin_is_loaded:
1016  * @plugin: plugin to query
1017  *
1018  * queries if the plugin is loaded into memory
1019  *
1020  * Returns: TRUE is loaded, FALSE otherwise
1021  */
1022 gboolean
1023 gst_plugin_is_loaded (GstPlugin * plugin)
1024 {
1025   g_return_val_if_fail (plugin != NULL, FALSE);
1026
1027   return (plugin->module != NULL || plugin->filename == NULL);
1028 }
1029
1030 /**
1031  * gst_plugin_get_cache_data:
1032  * @plugin: a plugin
1033  *
1034  * Gets the plugin specific data cache. If it is %NULL there is no cached data
1035  * stored. This is the case when the registry is getting rebuilt.
1036  *
1037  * Returns: (transfer none): The cached data as a #GstStructure or %NULL.
1038  */
1039 const GstStructure *
1040 gst_plugin_get_cache_data (GstPlugin * plugin)
1041 {
1042   g_return_val_if_fail (GST_IS_PLUGIN (plugin), NULL);
1043
1044   return plugin->priv->cache_data;
1045 }
1046
1047 /**
1048  * gst_plugin_set_cache_data:
1049  * @plugin: a plugin
1050  * @cache_data: (transfer full): a structure containing the data to cache
1051  *
1052  * Adds plugin specific data to cache. Passes the ownership of the structure to
1053  * the @plugin.
1054  *
1055  * The cache is flushed every time the registry is rebuilt.
1056  */
1057 void
1058 gst_plugin_set_cache_data (GstPlugin * plugin, GstStructure * cache_data)
1059 {
1060   g_return_if_fail (GST_IS_PLUGIN (plugin));
1061   g_return_if_fail (GST_IS_STRUCTURE (cache_data));
1062
1063   if (plugin->priv->cache_data) {
1064     gst_structure_free (plugin->priv->cache_data);
1065   }
1066   plugin->priv->cache_data = cache_data;
1067 }
1068
1069 #if 0
1070 /**
1071  * gst_plugin_feature_list:
1072  * @plugin: plugin to query
1073  * @filter: the filter to use
1074  * @first: only return first match
1075  * @user_data: user data passed to the filter function
1076  *
1077  * Runs a filter against all plugin features and returns a GList with
1078  * the results. If the first flag is set, only the first match is
1079  * returned (as a list with a single object).
1080  *
1081  * Returns: a GList of features, g_list_free after use.
1082  */
1083 GList *
1084 gst_plugin_feature_filter (GstPlugin * plugin,
1085     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1086 {
1087   GList *list;
1088   GList *g;
1089
1090   list = gst_filter_run (plugin->features, (GstFilterFunc) filter, first,
1091       user_data);
1092   for (g = list; g; g = g->next) {
1093     gst_object_ref (plugin);
1094   }
1095
1096   return list;
1097 }
1098
1099 typedef struct
1100 {
1101   GstPluginFeatureFilter filter;
1102   gboolean first;
1103   gpointer user_data;
1104   GList *result;
1105 }
1106 FeatureFilterData;
1107
1108 static gboolean
1109 _feature_filter (GstPlugin * plugin, gpointer user_data)
1110 {
1111   GList *result;
1112   FeatureFilterData *data = (FeatureFilterData *) user_data;
1113
1114   result = gst_plugin_feature_filter (plugin, data->filter, data->first,
1115       data->user_data);
1116   if (result) {
1117     data->result = g_list_concat (data->result, result);
1118     return TRUE;
1119   }
1120   return FALSE;
1121 }
1122
1123 /**
1124  * gst_plugin_list_feature_filter:
1125  * @list: a #GList of plugins to query
1126  * @filter: the filter function to use
1127  * @first: only return first match
1128  * @user_data: user data passed to the filter function
1129  *
1130  * Runs a filter against all plugin features of the plugins in the given
1131  * list and returns a GList with the results.
1132  * If the first flag is set, only the first match is
1133  * returned (as a list with a single object).
1134  *
1135  * Returns: a GList of features, g_list_free after use.
1136  */
1137 GList *
1138 gst_plugin_list_feature_filter (GList * list,
1139     GstPluginFeatureFilter filter, gboolean first, gpointer user_data)
1140 {
1141   FeatureFilterData data;
1142   GList *result;
1143
1144   data.filter = filter;
1145   data.first = first;
1146   data.user_data = user_data;
1147   data.result = NULL;
1148
1149   result = gst_filter_run (list, (GstFilterFunc) _feature_filter, first, &data);
1150   g_list_free (result);
1151
1152   return data.result;
1153 }
1154
1155 /**
1156  * gst_plugin_find_feature:
1157  * @plugin: plugin to get the feature from
1158  * @name: The name of the feature to find
1159  * @type: The type of the feature to find
1160  *
1161  * Find a feature of the given name and type in the given plugin.
1162  *
1163  * Returns: a GstPluginFeature or NULL if the feature was not found.
1164  */
1165 GstPluginFeature *
1166 gst_plugin_find_feature (GstPlugin * plugin, const gchar * name, GType type)
1167 {
1168   GList *walk;
1169   GstPluginFeature *result = NULL;
1170   GstTypeNameData data;
1171
1172   g_return_val_if_fail (name != NULL, NULL);
1173
1174   data.type = type;
1175   data.name = name;
1176
1177   walk = gst_filter_run (plugin->features,
1178       (GstFilterFunc) gst_plugin_feature_type_name_filter, TRUE, &data);
1179
1180   if (walk) {
1181     result = GST_PLUGIN_FEATURE (walk->data);
1182
1183     gst_object_ref (result);
1184     gst_plugin_feature_list_free (walk);
1185   }
1186
1187   return result;
1188 }
1189 #endif
1190
1191 #if 0
1192 static gboolean
1193 gst_plugin_feature_name_filter (GstPluginFeature * feature, const gchar * name)
1194 {
1195   return !strcmp (name, GST_PLUGIN_FEATURE_NAME (feature));
1196 }
1197 #endif
1198
1199 #if 0
1200 /**
1201  * gst_plugin_find_feature_by_name:
1202  * @plugin: plugin to get the feature from
1203  * @name: The name of the feature to find
1204  *
1205  * Find a feature of the given name 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_by_name (GstPlugin * plugin, const gchar * name)
1211 {
1212   GList *walk;
1213   GstPluginFeature *result = NULL;
1214
1215   g_return_val_if_fail (name != NULL, NULL);
1216
1217   walk = gst_filter_run (plugin->features,
1218       (GstFilterFunc) gst_plugin_feature_name_filter, TRUE, (void *) name);
1219
1220   if (walk) {
1221     result = GST_PLUGIN_FEATURE (walk->data);
1222
1223     gst_object_ref (result);
1224     gst_plugin_feature_list_free (walk);
1225   }
1226
1227   return result;
1228 }
1229 #endif
1230
1231 /**
1232  * gst_plugin_load_by_name:
1233  * @name: name of plugin to load
1234  *
1235  * Load the named plugin. Refs the plugin.
1236  *
1237  * Returns: (transfer full): a reference to a loaded plugin, or NULL on error.
1238  */
1239 GstPlugin *
1240 gst_plugin_load_by_name (const gchar * name)
1241 {
1242   GstPlugin *plugin, *newplugin;
1243   GError *error = NULL;
1244
1245   GST_DEBUG ("looking up plugin %s in default registry", name);
1246   plugin = gst_registry_find_plugin (gst_registry_get (), name);
1247   if (plugin) {
1248     GST_DEBUG ("loading plugin %s from file %s", name, plugin->filename);
1249     newplugin = gst_plugin_load_file (plugin->filename, &error);
1250     gst_object_unref (plugin);
1251
1252     if (!newplugin) {
1253       GST_WARNING ("load_plugin error: %s", error->message);
1254       g_error_free (error);
1255       return NULL;
1256     }
1257     /* newplugin was reffed by load_file */
1258     return newplugin;
1259   }
1260
1261   GST_DEBUG ("Could not find plugin %s in registry", name);
1262   return NULL;
1263 }
1264
1265 /**
1266  * gst_plugin_load:
1267  * @plugin: (transfer none): plugin to load
1268  *
1269  * Loads @plugin. Note that the *return value* is the loaded plugin; @plugin is
1270  * untouched. The normal use pattern of this function goes like this:
1271  *
1272  * <programlisting>
1273  * GstPlugin *loaded_plugin;
1274  * loaded_plugin = gst_plugin_load (plugin);
1275  * // presumably, we're no longer interested in the potentially-unloaded plugin
1276  * gst_object_unref (plugin);
1277  * plugin = loaded_plugin;
1278  * </programlisting>
1279  *
1280  * Returns: (transfer full): a reference to a loaded plugin, or NULL on error.
1281  */
1282 GstPlugin *
1283 gst_plugin_load (GstPlugin * plugin)
1284 {
1285   GError *error = NULL;
1286   GstPlugin *newplugin;
1287
1288   if (gst_plugin_is_loaded (plugin)) {
1289     return plugin;
1290   }
1291
1292   if (!(newplugin = gst_plugin_load_file (plugin->filename, &error)))
1293     goto load_error;
1294
1295   return newplugin;
1296
1297 load_error:
1298   {
1299     GST_WARNING ("load_plugin error: %s", error->message);
1300     g_error_free (error);
1301     return NULL;
1302   }
1303 }
1304
1305 /**
1306  * gst_plugin_list_free:
1307  * @list: (transfer full) (element-type Gst.Plugin): list of #GstPlugin
1308  *
1309  * Unrefs each member of @list, then frees the list.
1310  */
1311 void
1312 gst_plugin_list_free (GList * list)
1313 {
1314   GList *g;
1315
1316   for (g = list; g; g = g->next) {
1317     gst_object_unref (GST_PLUGIN_CAST (g->data));
1318   }
1319   g_list_free (list);
1320 }
1321
1322 /* ===== plugin dependencies ===== */
1323
1324 /* Scenarios:
1325  * ENV + xyz     where ENV can contain multiple values separated by SEPARATOR
1326  *               xyz may be "" (if ENV contains path to file rather than dir)
1327  * ENV + *xyz   same as above, but xyz acts as suffix filter
1328  * ENV + xyz*   same as above, but xyz acts as prefix filter (is this needed?)
1329  * ENV + *xyz*  same as above, but xyz acts as strstr filter (is this needed?)
1330  * 
1331  * same as above, with additional paths hard-coded at compile-time:
1332  *   - only check paths + ... if ENV is not set or yields not paths
1333  *   - always check paths + ... in addition to ENV
1334  *
1335  * When user specifies set of environment variables, he/she may also use e.g.
1336  * "HOME/.mystuff/plugins", and we'll expand the content of $HOME with the
1337  * remainder 
1338  */
1339
1340 /* we store in registry:
1341  *  sets of:
1342  *   { 
1343  *     - environment variables (array of strings)
1344  *     - last hash of env variable contents (uint) (so we can avoid doing stats
1345  *       if one of the env vars has changed; premature optimisation galore)
1346  *     - hard-coded paths (array of strings)
1347  *     - xyz filename/suffix/prefix strings (array of strings)
1348  *     - flags (int)
1349  *     - last hash of file/dir stats (int)
1350  *   }
1351  *   (= struct GstPluginDep)
1352  */
1353
1354 static guint
1355 gst_plugin_ext_dep_get_env_vars_hash (GstPlugin * plugin, GstPluginDep * dep)
1356 {
1357   gchar **e;
1358   guint hash;
1359
1360   /* there's no deeper logic to what we do here; all we want to know (when
1361    * checking if the plugin needs to be rescanned) is whether the content of
1362    * one of the environment variables in the list is different from when it
1363    * was last scanned */
1364   hash = 0;
1365   for (e = dep->env_vars; e != NULL && *e != NULL; ++e) {
1366     const gchar *val;
1367     gchar env_var[256];
1368
1369     /* order matters: "val",NULL needs to yield a different hash than
1370      * NULL,"val", so do a shift here whether the var is set or not */
1371     hash = hash << 5;
1372
1373     /* want environment variable at beginning of string */
1374     if (!g_ascii_isalnum (**e)) {
1375       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1376           "variable string: %s", *e);
1377       continue;
1378     }
1379
1380     /* user is allowed to specify e.g. "HOME/.pitivi/plugins" */
1381     g_strlcpy (env_var, *e, sizeof (env_var));
1382     g_strdelimit (env_var, "/\\", '\0');
1383
1384     if ((val = g_getenv (env_var)))
1385       hash += g_str_hash (val);
1386   }
1387
1388   return hash;
1389 }
1390
1391 gboolean
1392 _priv_plugin_deps_env_vars_changed (GstPlugin * plugin)
1393 {
1394   GList *l;
1395
1396   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1397     GstPluginDep *dep = l->data;
1398
1399     if (dep->env_hash != gst_plugin_ext_dep_get_env_vars_hash (plugin, dep))
1400       return TRUE;
1401   }
1402
1403   return FALSE;
1404 }
1405
1406 static void
1407 gst_plugin_ext_dep_extract_env_vars_paths (GstPlugin * plugin,
1408     GstPluginDep * dep, GQueue * paths)
1409 {
1410   gchar **evars;
1411
1412   for (evars = dep->env_vars; evars != NULL && *evars != NULL; ++evars) {
1413     const gchar *e;
1414     gchar **components;
1415
1416     /* want environment variable at beginning of string */
1417     if (!g_ascii_isalnum (**evars)) {
1418       GST_WARNING_OBJECT (plugin, "string prefix is not a valid environment "
1419           "variable string: %s", *evars);
1420       continue;
1421     }
1422
1423     /* user is allowed to specify e.g. "HOME/.pitivi/plugins", which we want to
1424      * split into the env_var name component and the path component */
1425     components = g_strsplit_set (*evars, "/\\", 2);
1426     g_assert (components != NULL);
1427
1428     e = g_getenv (components[0]);
1429     GST_LOG_OBJECT (plugin, "expanding %s = '%s' (path suffix: %s)",
1430         components[0], GST_STR_NULL (e), GST_STR_NULL (components[1]));
1431
1432     if (components[1] != NULL) {
1433       g_strdelimit (components[1], "/\\", G_DIR_SEPARATOR);
1434     }
1435
1436     if (e != NULL && *e != '\0') {
1437       gchar **arr;
1438       guint i;
1439
1440       arr = g_strsplit (e, G_SEARCHPATH_SEPARATOR_S, -1);
1441
1442       for (i = 0; arr != NULL && arr[i] != NULL; ++i) {
1443         gchar *full_path;
1444
1445         if (!g_path_is_absolute (arr[i])) {
1446           GST_INFO_OBJECT (plugin, "ignoring environment variable content '%s'"
1447               ": either not an absolute path or not a path at all", arr[i]);
1448           continue;
1449         }
1450
1451         if (components[1] != NULL) {
1452           full_path = g_build_filename (arr[i], components[1], NULL);
1453         } else {
1454           full_path = g_strdup (arr[i]);
1455         }
1456
1457         if (!g_queue_find_custom (paths, full_path, (GCompareFunc) strcmp)) {
1458           GST_LOG_OBJECT (plugin, "path: '%s'", full_path);
1459           g_queue_push_tail (paths, full_path);
1460           full_path = NULL;
1461         } else {
1462           GST_LOG_OBJECT (plugin, "path: '%s' (duplicate,ignoring)", full_path);
1463           g_free (full_path);
1464         }
1465       }
1466
1467       g_strfreev (arr);
1468     }
1469
1470     g_strfreev (components);
1471   }
1472
1473   GST_LOG_OBJECT (plugin, "Extracted %d paths from environment", paths->length);
1474 }
1475
1476 static guint
1477 gst_plugin_ext_dep_get_hash_from_stat_entry (GStatBuf * s)
1478 {
1479   if (!(s->st_mode & (S_IFDIR | S_IFREG)))
1480     return (guint) - 1;
1481
1482   /* completely random formula */
1483   return ((s->st_size << 3) + (s->st_mtime << 5)) ^ s->st_ctime;
1484 }
1485
1486 static gboolean
1487 gst_plugin_ext_dep_direntry_matches (GstPlugin * plugin, const gchar * entry,
1488     const gchar ** filenames, GstPluginDependencyFlags flags)
1489 {
1490   /* no filenames specified, match all entries for now (could probably
1491    * optimise by just taking the dir stat hash or so) */
1492   if (filenames == NULL || *filenames == NULL || **filenames == '\0')
1493     return TRUE;
1494
1495   while (*filenames != NULL) {
1496     /* suffix match? */
1497     if (((flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX)) &&
1498         g_str_has_suffix (entry, *filenames)) {
1499       return TRUE;
1500       /* else it's an exact match that's needed */
1501     } else if (strcmp (entry, *filenames) == 0) {
1502       return TRUE;
1503     }
1504     GST_LOG ("%s does not match %s, flags=0x%04x", entry, *filenames, flags);
1505     ++filenames;
1506   }
1507   return FALSE;
1508 }
1509
1510 static guint
1511 gst_plugin_ext_dep_scan_dir_and_match_names (GstPlugin * plugin,
1512     const gchar * path, const gchar ** filenames,
1513     GstPluginDependencyFlags flags, int depth)
1514 {
1515   const gchar *entry;
1516   gboolean recurse_dirs;
1517   GError *err = NULL;
1518   GDir *dir;
1519   guint hash = 0;
1520
1521   recurse_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1522
1523   dir = g_dir_open (path, 0, &err);
1524   if (dir == NULL) {
1525     GST_DEBUG_OBJECT (plugin, "g_dir_open(%s) failed: %s", path, err->message);
1526     g_error_free (err);
1527     return (guint) - 1;
1528   }
1529
1530   /* FIXME: we're assuming here that we always get the directory entries in
1531    * the same order, and not in a random order */
1532   while ((entry = g_dir_read_name (dir))) {
1533     gboolean have_match;
1534     GStatBuf s;
1535     gchar *full_path;
1536     guint fhash;
1537
1538     have_match =
1539         gst_plugin_ext_dep_direntry_matches (plugin, entry, filenames, flags);
1540
1541     /* avoid the stat if possible */
1542     if (!have_match && !recurse_dirs)
1543       continue;
1544
1545     full_path = g_build_filename (path, entry, NULL);
1546     if (g_stat (full_path, &s) < 0) {
1547       fhash = (guint) - 1;
1548       GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1549           g_strerror (errno));
1550     } else if (have_match) {
1551       fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1552       GST_LOG_OBJECT (plugin, "stat: %s (result: %u)", full_path, fhash);
1553     } else if ((s.st_mode & (S_IFDIR))) {
1554       fhash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, full_path,
1555           filenames, flags, depth + 1);
1556     } else {
1557       /* it's not a name match, we want to recurse, but it's not a directory */
1558       g_free (full_path);
1559       continue;
1560     }
1561
1562     hash = (hash + fhash) << 1;
1563     g_free (full_path);
1564   }
1565
1566   g_dir_close (dir);
1567   return hash;
1568 }
1569
1570 static guint
1571 gst_plugin_ext_dep_scan_path_with_filenames (GstPlugin * plugin,
1572     const gchar * path, const gchar ** filenames,
1573     GstPluginDependencyFlags flags)
1574 {
1575   const gchar *empty_filenames[] = { "", NULL };
1576   gboolean recurse_into_dirs, partial_names;
1577   guint i, hash = 0;
1578
1579   /* to avoid special-casing below (FIXME?) */
1580   if (filenames == NULL || *filenames == NULL)
1581     filenames = empty_filenames;
1582
1583   recurse_into_dirs = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_RECURSE);
1584   partial_names = ! !(flags & GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX);
1585
1586   /* if we can construct the exact paths to check with the data we have, just
1587    * stat them one by one; this is more efficient than opening the directory
1588    * and going through each entry to see if it matches one of our filenames. */
1589   if (!recurse_into_dirs && !partial_names) {
1590     for (i = 0; filenames[i] != NULL; ++i) {
1591       GStatBuf s;
1592       gchar *full_path;
1593       guint fhash;
1594
1595       full_path = g_build_filename (path, filenames[i], NULL);
1596       if (g_stat (full_path, &s) < 0) {
1597         fhash = (guint) - 1;
1598         GST_LOG_OBJECT (plugin, "stat: %s (error: %s)", full_path,
1599             g_strerror (errno));
1600       } else {
1601         fhash = gst_plugin_ext_dep_get_hash_from_stat_entry (&s);
1602         GST_LOG_OBJECT (plugin, "stat: %s (result: %08x)", full_path, fhash);
1603       }
1604       hash = (hash + fhash) << 1;
1605       g_free (full_path);
1606     }
1607   } else {
1608     hash = gst_plugin_ext_dep_scan_dir_and_match_names (plugin, path,
1609         filenames, flags, 0);
1610   }
1611
1612   return hash;
1613 }
1614
1615 static guint
1616 gst_plugin_ext_dep_get_stat_hash (GstPlugin * plugin, GstPluginDep * dep)
1617 {
1618   gboolean paths_are_default_only;
1619   GQueue scan_paths = G_QUEUE_INIT;
1620   guint scan_hash = 0;
1621   gchar *path;
1622
1623   GST_LOG_OBJECT (plugin, "start");
1624
1625   paths_are_default_only =
1626       dep->flags & GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_DEFAULT_ONLY;
1627
1628   gst_plugin_ext_dep_extract_env_vars_paths (plugin, dep, &scan_paths);
1629
1630   if (g_queue_is_empty (&scan_paths) || !paths_are_default_only) {
1631     gchar **paths;
1632
1633     for (paths = dep->paths; paths != NULL && *paths != NULL; ++paths) {
1634       const gchar *path = *paths;
1635
1636       if (!g_queue_find_custom (&scan_paths, path, (GCompareFunc) strcmp)) {
1637         GST_LOG_OBJECT (plugin, "path: '%s'", path);
1638         g_queue_push_tail (&scan_paths, g_strdup (path));
1639       } else {
1640         GST_LOG_OBJECT (plugin, "path: '%s' (duplicate, ignoring)", path);
1641       }
1642     }
1643   }
1644
1645   while ((path = g_queue_pop_head (&scan_paths))) {
1646     scan_hash += gst_plugin_ext_dep_scan_path_with_filenames (plugin, path,
1647         (const gchar **) dep->names, dep->flags);
1648     scan_hash = scan_hash << 1;
1649     g_free (path);
1650   }
1651
1652   GST_LOG_OBJECT (plugin, "done, scan_hash: %08x", scan_hash);
1653   return scan_hash;
1654 }
1655
1656 gboolean
1657 _priv_plugin_deps_files_changed (GstPlugin * plugin)
1658 {
1659   GList *l;
1660
1661   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1662     GstPluginDep *dep = l->data;
1663
1664     if (dep->stat_hash != gst_plugin_ext_dep_get_stat_hash (plugin, dep))
1665       return TRUE;
1666   }
1667
1668   return FALSE;
1669 }
1670
1671 static void
1672 gst_plugin_ext_dep_free (GstPluginDep * dep)
1673 {
1674   g_strfreev (dep->env_vars);
1675   g_strfreev (dep->paths);
1676   g_strfreev (dep->names);
1677   g_slice_free (GstPluginDep, dep);
1678 }
1679
1680 static gboolean
1681 gst_plugin_ext_dep_strv_equal (gchar ** arr1, gchar ** arr2)
1682 {
1683   if (arr1 == arr2)
1684     return TRUE;
1685   if (arr1 == NULL || arr2 == NULL)
1686     return FALSE;
1687   for (; *arr1 != NULL && *arr2 != NULL; ++arr1, ++arr2) {
1688     if (strcmp (*arr1, *arr2) != 0)
1689       return FALSE;
1690   }
1691   return (*arr1 == *arr2);
1692 }
1693
1694 static gboolean
1695 gst_plugin_ext_dep_equals (GstPluginDep * dep, const gchar ** env_vars,
1696     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1697 {
1698   if (dep->flags != flags)
1699     return FALSE;
1700
1701   return gst_plugin_ext_dep_strv_equal (dep->env_vars, (gchar **) env_vars) &&
1702       gst_plugin_ext_dep_strv_equal (dep->paths, (gchar **) paths) &&
1703       gst_plugin_ext_dep_strv_equal (dep->names, (gchar **) names);
1704 }
1705
1706 /**
1707  * gst_plugin_add_dependency:
1708  * @plugin: a #GstPlugin
1709  * @env_vars: NULL-terminated array of environment variables affecting the
1710  *     feature set of the plugin (e.g. an environment variable containing
1711  *     paths where to look for additional modules/plugins of a library),
1712  *     or NULL. Environment variable names may be followed by a path component
1713  *      which will be added to the content of the environment variable, e.g.
1714  *      "HOME/.mystuff/plugins".
1715  * @paths: NULL-terminated array of directories/paths where dependent files
1716  *     may be.
1717  * @names: NULL-terminated array of file names (or file name suffixes,
1718  *     depending on @flags) to be used in combination with the paths from
1719  *     @paths and/or the paths extracted from the environment variables in
1720  *     @env_vars, or NULL.
1721  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1722  *
1723  * Make GStreamer aware of external dependencies which affect the feature
1724  * set of this plugin (ie. the elements or typefinders associated with it).
1725  *
1726  * GStreamer will re-inspect plugins with external dependencies whenever any
1727  * of the external dependencies change. This is useful for plugins which wrap
1728  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1729  * library and makes visualisations available as GStreamer elements, or a
1730  * codec loader which exposes elements and/or caps dependent on what external
1731  * codec libraries are currently installed.
1732  */
1733 void
1734 gst_plugin_add_dependency (GstPlugin * plugin, const gchar ** env_vars,
1735     const gchar ** paths, const gchar ** names, GstPluginDependencyFlags flags)
1736 {
1737   GstPluginDep *dep;
1738   GList *l;
1739
1740   g_return_if_fail (GST_IS_PLUGIN (plugin));
1741
1742   if ((env_vars == NULL || env_vars[0] == NULL) &&
1743       (paths == NULL || paths[0] == NULL)) {
1744     GST_DEBUG_OBJECT (plugin,
1745         "plugin registered empty dependency set. Ignoring");
1746     return;
1747   }
1748
1749   for (l = plugin->priv->deps; l != NULL; l = l->next) {
1750     if (gst_plugin_ext_dep_equals (l->data, env_vars, paths, names, flags)) {
1751       GST_LOG_OBJECT (plugin, "dependency already registered");
1752       return;
1753     }
1754   }
1755
1756   dep = g_slice_new (GstPluginDep);
1757
1758   dep->env_vars = g_strdupv ((gchar **) env_vars);
1759   dep->paths = g_strdupv ((gchar **) paths);
1760   dep->names = g_strdupv ((gchar **) names);
1761   dep->flags = flags;
1762
1763   dep->env_hash = gst_plugin_ext_dep_get_env_vars_hash (plugin, dep);
1764   dep->stat_hash = gst_plugin_ext_dep_get_stat_hash (plugin, dep);
1765
1766   plugin->priv->deps = g_list_append (plugin->priv->deps, dep);
1767
1768   GST_DEBUG_OBJECT (plugin, "added dependency:");
1769   for (; env_vars != NULL && *env_vars != NULL; ++env_vars)
1770     GST_DEBUG_OBJECT (plugin, " evar: %s", *env_vars);
1771   for (; paths != NULL && *paths != NULL; ++paths)
1772     GST_DEBUG_OBJECT (plugin, " path: %s", *paths);
1773   for (; names != NULL && *names != NULL; ++names)
1774     GST_DEBUG_OBJECT (plugin, " name: %s", *names);
1775 }
1776
1777 /**
1778  * gst_plugin_add_dependency_simple:
1779  * @plugin: the #GstPlugin
1780  * @env_vars: one or more environment variables (separated by ':', ';' or ','),
1781  *      or NULL. Environment variable names may be followed by a path component
1782  *      which will be added to the content of the environment variable, e.g.
1783  *      "HOME/.mystuff/plugins:MYSTUFF_PLUGINS_PATH"
1784  * @paths: one ore more directory paths (separated by ':' or ';' or ','),
1785  *      or NULL. Example: "/usr/lib/mystuff/plugins"
1786  * @names: one or more file names or file name suffixes (separated by commas),
1787  *   or NULL
1788  * @flags: optional flags, or #GST_PLUGIN_DEPENDENCY_FLAG_NONE
1789  *
1790  * Make GStreamer aware of external dependencies which affect the feature
1791  * set of this plugin (ie. the elements or typefinders associated with it).
1792  *
1793  * GStreamer will re-inspect plugins with external dependencies whenever any
1794  * of the external dependencies change. This is useful for plugins which wrap
1795  * other plugin systems, e.g. a plugin which wraps a plugin-based visualisation
1796  * library and makes visualisations available as GStreamer elements, or a
1797  * codec loader which exposes elements and/or caps dependent on what external
1798  * codec libraries are currently installed.
1799  *
1800  * Convenience wrapper function for gst_plugin_add_dependency() which
1801  * takes simple strings as arguments instead of string arrays, with multiple
1802  * arguments separated by predefined delimiters (see above).
1803  */
1804 void
1805 gst_plugin_add_dependency_simple (GstPlugin * plugin,
1806     const gchar * env_vars, const gchar * paths, const gchar * names,
1807     GstPluginDependencyFlags flags)
1808 {
1809   gchar **a_evars = NULL;
1810   gchar **a_paths = NULL;
1811   gchar **a_names = NULL;
1812
1813   if (env_vars)
1814     a_evars = g_strsplit_set (env_vars, ":;,", -1);
1815   if (paths)
1816     a_paths = g_strsplit_set (paths, ":;,", -1);
1817   if (names)
1818     a_names = g_strsplit_set (names, ",", -1);
1819
1820   gst_plugin_add_dependency (plugin, (const gchar **) a_evars,
1821       (const gchar **) a_paths, (const gchar **) a_names, flags);
1822
1823   if (a_evars)
1824     g_strfreev (a_evars);
1825   if (a_paths)
1826     g_strfreev (a_paths);
1827   if (a_names)
1828     g_strfreev (a_names);
1829 }