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