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