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