]> git.sesse.net Git - vlc/blob - src/modules/modules.c
183b748803728d31e64747dd653843c6c8ed4f76
[vlc] / src / modules / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Sam Hocevar <sam@zoy.org>
8  *          Ethan C. Baldridge <BaldridgeE@cadmus.com>
9  *          Hans-Peter Jansen <hpj@urpla.net>
10  *          Gildas Bazin <gbazin@videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_memory.h>
34 #include "libvlc.h"
35
36 #include <stdlib.h>                                      /* free(), strtol() */
37 #include <stdio.h>                                              /* sprintf() */
38 #include <string.h>                                              /* strdup() */
39 #include <assert.h>
40
41 #ifdef HAVE_DIRENT_H
42 #   include <dirent.h>
43 #endif
44
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 #   include <sys/stat.h>
48 #endif
49 #ifdef HAVE_UNISTD_H
50 #   include <unistd.h>
51 #endif
52 #ifdef ENABLE_NLS
53 # include <libintl.h>
54 #endif
55
56 #include "config/configuration.h"
57
58 #include <vlc_fs.h>
59 #include "vlc_arrays.h"
60
61 #include "modules/modules.h"
62
63 static module_bank_t *p_module_bank = NULL;
64 static vlc_mutex_t module_lock = VLC_STATIC_MUTEX;
65
66 int vlc_entry__main( module_t * );
67
68 /*****************************************************************************
69  * Local prototypes
70  *****************************************************************************/
71 #ifdef HAVE_DYNAMIC_PLUGINS
72 static void AllocateAllPlugins( vlc_object_t *, module_bank_t * );
73 static void AllocatePluginDir( vlc_object_t *, module_bank_t *, const char *,
74                                unsigned );
75 static int  AllocatePluginFile( vlc_object_t *, module_bank_t *, const char *,
76                                 int64_t, int64_t );
77 static module_t * AllocatePlugin( vlc_object_t *, const char * );
78 #endif
79 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
80 static void DeleteModule ( module_bank_t *, module_t * );
81 #ifdef HAVE_DYNAMIC_PLUGINS
82 static void   DupModule        ( module_t * );
83 static void   UndupModule      ( module_t * );
84 #endif
85
86 #undef module_InitBank
87 /**
88  * Init bank
89  *
90  * Creates a module bank structure which will be filled later
91  * on with all the modules found.
92  * \param p_this vlc object structure
93  * \return nothing
94  */
95 void module_InitBank( vlc_object_t *p_this )
96 {
97     module_bank_t *p_bank = NULL;
98
99     vlc_mutex_lock( &module_lock );
100
101     if( p_module_bank == NULL )
102     {
103         p_bank = calloc (1, sizeof(*p_bank));
104         p_bank->i_usage = 1;
105         p_bank->i_cache = p_bank->i_loaded_cache = 0;
106         p_bank->pp_cache = p_bank->pp_loaded_cache = NULL;
107         p_bank->b_cache = p_bank->b_cache_dirty = false;
108         p_bank->head = NULL;
109
110         /* Everything worked, attach the object */
111         p_module_bank = p_bank;
112
113         /* Fills the module bank structure with the main module infos.
114          * This is very useful as it will allow us to consider the main
115          * library just as another module, and for instance the configuration
116          * options of main will be available in the module bank structure just
117          * as for every other module. */
118         AllocateBuiltinModule( p_this, vlc_entry__main );
119         vlc_rwlock_init (&config_lock);
120         config_SortConfig ();
121     }
122     else
123         p_module_bank->i_usage++;
124
125     /* We do retain the module bank lock until the plugins are loaded as well.
126      * This is ugly, this staged loading approach is needed: LibVLC gets
127      * some configuration parameters relevant to loading the plugins from
128      * the main (builtin) module. The module bank becomes shared read-only data
129      * once it is ready, so we need to fully serialize initialization.
130      * DO NOT UNCOMMENT the following line unless you managed to squeeze
131      * module_LoadPlugins() before you unlock the mutex. */
132     /*vlc_mutex_unlock( &module_lock );*/
133 }
134
135 #undef module_EndBank
136 /**
137  * Unloads all unused plugin modules and empties the module
138  * bank in case of success.
139  * \param p_this vlc object structure
140  * \return nothing
141  */
142 void module_EndBank( vlc_object_t *p_this, bool b_plugins )
143 {
144     module_bank_t *p_bank = p_module_bank;
145
146     assert (p_bank != NULL);
147
148     /* Save the configuration */
149     if( !var_InheritBool( p_this, "ignore-config" ) )
150         config_AutoSaveConfigFile( p_this );
151
152     /* If plugins were _not_ loaded, then the caller still has the bank lock
153      * from module_InitBank(). */
154     if( b_plugins )
155         vlc_mutex_lock( &module_lock );
156     /*else
157         vlc_assert_locked( &module_lock ); not for static mutexes :( */
158
159     if( --p_bank->i_usage > 0 )
160     {
161         vlc_mutex_unlock( &module_lock );
162         return;
163     }
164
165     config_UnsortConfig ();
166     vlc_rwlock_destroy (&config_lock);
167     p_module_bank = NULL;
168     vlc_mutex_unlock( &module_lock );
169
170 #ifdef HAVE_DYNAMIC_PLUGINS
171     while( p_bank->i_loaded_cache-- )
172     {
173         if( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] )
174         {
175             DeleteModule( p_bank,
176                     p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->p_module );
177             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->psz_file );
178             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] );
179         }
180     }
181     free( p_bank->pp_loaded_cache );
182     while( p_bank->i_cache-- )
183     {
184         free( p_bank->pp_cache[p_bank->i_cache]->psz_file );
185         free( p_bank->pp_cache[p_bank->i_cache] );
186     }
187     free( p_bank->pp_cache );
188 #endif
189
190     while( p_bank->head != NULL )
191         DeleteModule( p_bank, p_bank->head );
192
193     free( p_bank );
194 }
195
196 #undef module_LoadPlugins
197 /**
198  * Loads module descriptions for all available plugins.
199  * Fills the module bank structure with the plugin modules.
200  *
201  * \param p_this vlc object structure
202  * \return nothing
203  */
204 void module_LoadPlugins( vlc_object_t * p_this )
205 {
206     module_bank_t *p_bank = p_module_bank;
207
208     assert( p_bank );
209     /*vlc_assert_locked( &module_lock ); not for static mutexes :( */
210
211 #ifdef HAVE_DYNAMIC_PLUGINS
212     if( p_bank->i_usage == 1 )
213     {
214         msg_Dbg( p_this, "checking plugin modules" );
215         p_module_bank->b_cache = var_InheritBool( p_this, "plugins-cache" );
216
217         AllocateAllPlugins( p_this, p_module_bank );
218         config_UnsortConfig ();
219         config_SortConfig ();
220     }
221 #endif
222     vlc_mutex_unlock( &module_lock );
223 }
224
225 /**
226  * Checks whether a module implements a capability.
227  *
228  * \param m the module
229  * \param cap the capability to check
230  * \return TRUE if the module have the capability
231  */
232 bool module_provides( const module_t *m, const char *cap )
233 {
234     return !strcmp( m->psz_capability, cap );
235 }
236
237 /**
238  * Get the internal name of a module
239  *
240  * \param m the module
241  * \return the module name
242  */
243 const char *module_get_object( const module_t *m )
244 {
245     return m->psz_object_name;
246 }
247
248 /**
249  * Get the human-friendly name of a module.
250  *
251  * \param m the module
252  * \param long_name TRUE to have the long name of the module
253  * \return the short or long name of the module
254  */
255 const char *module_get_name( const module_t *m, bool long_name )
256 {
257     if( long_name && ( m->psz_longname != NULL) )
258         return m->psz_longname;
259
260     return m->psz_shortname ? m->psz_shortname : m->psz_object_name;
261 }
262
263 /**
264  * Get the help for a module
265  *
266  * \param m the module
267  * \return the help
268  */
269 const char *module_get_help( const module_t *m )
270 {
271     return m->psz_help;
272 }
273
274 /**
275  * Get the capability for a module
276  *
277  * \param m the module
278  * return the capability
279  */
280 const char *module_get_capability( const module_t *m )
281 {
282     return m->psz_capability;
283 }
284
285 /**
286  * Get the score for a module
287  *
288  * \param m the module
289  * return the score for the capability
290  */
291 int module_get_score( const module_t *m )
292 {
293     return m->i_score;
294 }
295
296 /**
297  * Translate a string using the module's text domain
298  *
299  * \param m the module
300  * \param str the American English ASCII string to localize
301  * \return the gettext-translated string
302  */
303 const char *module_gettext (const module_t *m, const char *str)
304 {
305 #ifdef ENABLE_NLS
306     const char *domain = m->domain ? m->domain : PACKAGE_NAME;
307     return dgettext (domain, str);
308 #else
309     (void)m;
310     return str;
311 #endif
312 }
313
314 module_t *module_hold (module_t *m)
315 {
316     vlc_hold (&m->vlc_gc_data);
317     return m;
318 }
319
320 void module_release (module_t *m)
321 {
322     vlc_release (&m->vlc_gc_data);
323 }
324
325 /**
326  * Frees the flat list of VLC modules.
327  * @param list list obtained by module_list_get()
328  * @param length number of items on the list
329  * @return nothing.
330  */
331 void module_list_free (module_t **list)
332 {
333     if (list == NULL)
334         return;
335
336     for (size_t i = 0; list[i] != NULL; i++)
337          module_release (list[i]);
338     free (list);
339 }
340
341 /**
342  * Gets the flat list of VLC modules.
343  * @param n [OUT] pointer to the number of modules or NULL
344  * @return NULL-terminated table of module pointers
345  *         (release with module_list_free()), or NULL in case of error.
346  */
347 module_t **module_list_get (size_t *n)
348 {
349     /* TODO: this whole module lookup is quite inefficient */
350     /* Remove this and improve module_need */
351     module_t **tab = NULL;
352     size_t i = 0;
353
354     assert (p_module_bank);
355     for (module_t *mod = p_module_bank->head; mod; mod = mod->next)
356     {
357          module_t **nt;
358          nt  = realloc (tab, (i + 2 + mod->submodule_count) * sizeof (*tab));
359          if (nt == NULL)
360          {
361              module_list_free (tab);
362              return NULL;
363          }
364
365          tab = nt;
366          tab[i++] = module_hold (mod);
367          for (module_t *subm = mod->submodule; subm; subm = subm->next)
368              tab[i++] = module_hold (subm);
369          tab[i] = NULL;
370     }
371     if (n != NULL)
372         *n = i;
373     return tab;
374 }
375
376 typedef struct module_list_t
377 {
378     module_t *p_module;
379     int16_t  i_score;
380     bool     b_force;
381 } module_list_t;
382
383 static int modulecmp (const void *a, const void *b)
384 {
385     const module_list_t *la = a, *lb = b;
386     /* Note that qsort() uses _ascending_ order,
387      * so the smallest module is the one with the biggest score. */
388     return lb->i_score - la->i_score;
389 }
390
391 #undef module_need
392 /**
393  * module Need
394  *
395  * Return the best module function, given a capability list.
396  *
397  * \param p_this the vlc object
398  * \param psz_capability list of capabilities needed
399  * \param psz_name name of the module asked
400  * \param b_strict if true, do not fallback to plugin with a different name
401  *                 but the same capability
402  * \return the module or NULL in case of a failure
403  */
404 module_t * module_need( vlc_object_t *p_this, const char *psz_capability,
405                         const char *psz_name, bool b_strict )
406 {
407     stats_TimerStart( p_this, "module_need()", STATS_TIMER_MODULE_NEED );
408
409     module_list_t *p_list;
410     module_t *p_module;
411     int i_shortcuts = 0;
412     char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL;
413     bool b_force_backup = p_this->b_force;
414
415     /* Deal with variables */
416     if( psz_name && psz_name[0] == '$' )
417     {
418         psz_name = psz_var = var_CreateGetString( p_this, psz_name + 1 );
419     }
420
421     /* Count how many different shortcuts were asked for */
422     if( psz_name && *psz_name )
423     {
424         char *psz_parser, *psz_last_shortcut;
425
426         /* If the user wants none, give him none. */
427         if( !strcmp( psz_name, "none" ) )
428         {
429             free( psz_var );
430             stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
431             stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
432             stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
433             return NULL;
434         }
435
436         i_shortcuts++;
437         psz_parser = psz_shortcuts = psz_last_shortcut = strdup( psz_name );
438
439         while( ( psz_parser = strchr( psz_parser, ',' ) ) )
440         {
441              *psz_parser = '\0';
442              i_shortcuts++;
443              psz_last_shortcut = ++psz_parser;
444         }
445
446         /* Check if the user wants to override the "strict" mode */
447         if( psz_last_shortcut )
448         {
449             if( !strcmp(psz_last_shortcut, "none") )
450             {
451                 b_strict = true;
452                 i_shortcuts--;
453             }
454             else if( !strcmp(psz_last_shortcut, "any") )
455             {
456                 b_strict = false;
457                 i_shortcuts--;
458             }
459         }
460     }
461
462     /* Sort the modules and test them */
463     size_t count;
464     module_t **p_all = module_list_get (&count);
465     p_list = malloc( count * sizeof( module_list_t ) );
466
467     /* Parse the module list for capabilities and probe each of them */
468     count = 0;
469     for (size_t i = 0; (p_module = p_all[i]) != NULL; i++)
470     {
471         int i_shortcut_bonus = 0;
472
473         /* Test that this module can do what we need */
474         if( !module_provides( p_module, psz_capability ) )
475             continue;
476
477         /* If we required a shortcut, check this plugin provides it. */
478         if( i_shortcuts > 0 )
479         {
480             const char *name = psz_shortcuts;
481
482             for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- )
483             {
484                 for( unsigned i = 0; p_module->pp_shortcuts[i]; i++ )
485                 {
486                     char *c;
487                     if( ( c = strchr( name, '@' ) )
488                         ? !strncasecmp( name, p_module->pp_shortcuts[i],
489                                         c-name )
490                         : !strcasecmp( name, p_module->pp_shortcuts[i] ) )
491                     {
492                         /* Found it */
493                         if( c && c[1] )
494                             psz_alias = c+1;
495                         i_shortcut_bonus = i_short * 10000;
496                         goto found_shortcut;
497                     }
498                 }
499
500                 /* Go to the next shortcut... This is so lame! */
501                 name += strlen( name ) + 1;
502             }
503
504             /* If we are in "strict" mode and we couldn't
505              * find the module in the list of provided shortcuts,
506              * then kick the bastard out of here!!! */
507             if( b_strict )
508                 continue;
509         }
510
511         /* Trash <= 0 scored plugins (they can only be selected by shortcut) */
512         if( p_module->i_score <= 0 )
513             continue;
514
515 found_shortcut:
516         /* Store this new module */
517         p_list[count].p_module = module_hold (p_module);
518         p_list[count].i_score = p_module->i_score + i_shortcut_bonus;
519         p_list[count].b_force = i_shortcut_bonus && b_strict;
520         count++;
521     }
522
523     /* We can release the list, interesting modules are held */
524     module_list_free (p_all);
525
526     /* Sort candidates by descending score */
527     qsort (p_list, count, sizeof (p_list[0]), modulecmp);
528     msg_Dbg( p_this, "looking for %s module: %zu candidate%s", psz_capability,
529              count, count == 1 ? "" : "s" );
530
531     /* Parse the linked list and use the first successful module */
532     p_module = NULL;
533     for (size_t i = 0; (i < count) && (p_module == NULL); i++)
534     {
535         module_t *p_cand = p_list[i].p_module;
536 #ifdef HAVE_DYNAMIC_PLUGINS
537         /* Make sure the module is loaded in mem */
538         module_t *p_real = p_cand->b_submodule ? p_cand->parent : p_cand;
539
540         if( !p_real->b_builtin && !p_real->b_loaded )
541         {
542             module_t *p_new_module =
543                 AllocatePlugin( p_this, p_real->psz_filename );
544             if( p_new_module == NULL )
545             {   /* Corrupted module */
546                 msg_Err( p_this, "possibly corrupt module cache" );
547                 module_release( p_cand );
548                 continue;
549             }
550             CacheMerge( p_this, p_real, p_new_module );
551             DeleteModule( p_module_bank, p_new_module );
552         }
553 #endif
554
555         p_this->b_force = p_list[i].b_force;
556
557         int ret = VLC_SUCCESS;
558         if( p_cand->pf_activate )
559             ret = p_cand->pf_activate( p_this );
560         switch( ret )
561         {
562         case VLC_SUCCESS:
563             /* good module! */
564             p_module = p_cand;
565             break;
566
567         case VLC_ETIMEOUT:
568             /* good module, but aborted */
569             module_release( p_cand );
570             break;
571
572         default: /* bad module */
573             module_release( p_cand );
574             continue;
575         }
576
577         /* Release the remaining modules */
578         while (++i < count)
579             module_release (p_list[i].p_module);
580     }
581
582     free( p_list );
583     p_this->b_force = b_force_backup;
584
585     if( p_module != NULL )
586     {
587         msg_Dbg( p_this, "using %s module \"%s\"",
588                  psz_capability, p_module->psz_object_name );
589         vlc_object_set_name( p_this, psz_alias ? psz_alias
590                                                : p_module->psz_object_name );
591     }
592     else if( count == 0 )
593         msg_Dbg( p_this, "no %s module matched \"%s\"",
594                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
595     else
596         msg_Dbg( p_this, "no %s module matching \"%s\" could be loaded",
597                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
598
599     free( psz_shortcuts );
600     free( psz_var );
601
602     stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
603     stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
604     stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
605
606     /* Don't forget that the module is still locked */
607     return p_module;
608 }
609
610 #undef module_unneed
611 /**
612  * Module unneed
613  *
614  * This function must be called by the thread that called module_need, to
615  * decrease the reference count and allow for hiding of modules.
616  * \param p_this vlc object structure
617  * \param p_module the module structure
618  * \return nothing
619  */
620 void module_unneed( vlc_object_t * p_this, module_t * p_module )
621 {
622     /* Use the close method */
623     if( p_module->pf_deactivate )
624     {
625         p_module->pf_deactivate( p_this );
626     }
627
628     msg_Dbg( p_this, "removing module \"%s\"", p_module->psz_object_name );
629
630     module_release( p_module );
631 }
632
633 /**
634  * Get a pointer to a module_t given it's name.
635  *
636  * \param psz_name the name of the module
637  * \return a pointer to the module or NULL in case of a failure
638  */
639 module_t *module_find( const char * psz_name )
640 {
641     module_t **list, *module;
642
643     list = module_list_get (NULL);
644     if (!list)
645         return NULL;
646
647     for (size_t i = 0; (module = list[i]) != NULL; i++)
648     {
649         const char *psz_module_name = module->psz_object_name;
650
651         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
652         {
653             module_hold (module);
654             break;
655         }
656     }
657     module_list_free (list);
658     return module;
659 }
660
661 /**
662  * Tell if a module exists and release it in thic case
663  *
664  * \param psz_name th name of the module
665  * \return TRUE if the module exists
666  */
667 bool module_exists (const char * psz_name)
668 {
669     module_t *p_module = module_find (psz_name);
670     if( p_module )
671         module_release (p_module);
672     return p_module != NULL;
673 }
674
675 /**
676  * Get a pointer to a module_t that matches a shortcut.
677  * This is a temporary hack for SD. Do not re-use (generally multiple modules
678  * can have the same shortcut, so this is *broken* - use module_need()!).
679  *
680  * \param psz_shortcut shortcut of the module
681  * \param psz_cap capability of the module
682  * \return a pointer to the module or NULL in case of a failure
683  */
684 module_t *module_find_by_shortcut (const char *psz_shortcut)
685 {
686     module_t **list, *module;
687
688     list = module_list_get (NULL);
689     if (!list)
690         return NULL;
691
692     for (size_t i = 0; (module = list[i]) != NULL; i++)
693     {
694         for (size_t j = 0;
695              (module->pp_shortcuts[j] != NULL) && (j < MODULE_SHORTCUT_MAX);
696              j++)
697         {
698             if (!strcmp (module->pp_shortcuts[j], psz_shortcut))
699             {
700                 module_hold (module);
701                 goto out;
702              }
703         }
704     }
705 out:
706     module_list_free (list);
707     return module;
708 }
709
710 /**
711  * Get the configuration of a module
712  *
713  * \param module the module
714  * \param psize the size of the configuration returned
715  * \return the configuration as an array
716  */
717 module_config_t *module_config_get( const module_t *module, unsigned *restrict psize )
718 {
719     unsigned i,j;
720     unsigned size = module->confsize;
721     module_config_t *config = malloc( size * sizeof( *config ) );
722
723     assert( psize != NULL );
724     *psize = 0;
725
726     if( !config )
727         return NULL;
728
729     for( i = 0, j = 0; i < size; i++ )
730     {
731         const module_config_t *item = module->p_config + i;
732         if( item->b_internal /* internal option */
733          || item->b_unsaveable /* non-modifiable option */
734          || item->b_removed /* removed option */ )
735             continue;
736
737         memcpy( config + j, item, sizeof( *config ) );
738         j++;
739     }
740     *psize = j;
741
742     return config;
743 }
744
745 /**
746  * Release the configuration
747  *
748  * \param the configuration
749  * \return nothing
750  */
751 void module_config_free( module_config_t *config )
752 {
753     free( config );
754 }
755
756 /*****************************************************************************
757  * Following functions are local.
758  *****************************************************************************/
759
760  /*****************************************************************************
761  * copy_next_paths_token: from a PATH_SEP_CHAR (a ':' or a ';') separated paths
762  * return first path.
763  *****************************************************************************/
764 static char * copy_next_paths_token( char * paths, char ** remaining_paths )
765 {
766     char * path;
767     int i, done;
768     bool escaped = false;
769
770     assert( paths );
771
772     /* Alloc a buffer to store the path */
773     path = malloc( strlen( paths ) + 1 );
774     if( !path ) return NULL;
775
776     /* Look for PATH_SEP_CHAR (a ':' or a ';') */
777     for( i = 0, done = 0 ; paths[i]; i++ )
778     {
779         /* Take care of \\ and \: or \; escapement */
780         if( escaped )
781         {
782             escaped = false;
783             path[done++] = paths[i];
784         }
785 #ifdef WIN32
786         else if( paths[i] == '/' )
787             escaped = true;
788 #else
789         else if( paths[i] == '\\' )
790             escaped = true;
791 #endif
792         else if( paths[i] == PATH_SEP_CHAR )
793             break;
794         else
795             path[done++] = paths[i];
796     }
797     path[done] = 0;
798
799     /* Return the remaining paths */
800     if( remaining_paths ) {
801         *remaining_paths = paths[i] ? &paths[i]+1 : NULL;
802     }
803
804     return path;
805 }
806
807 char *psz_vlcpath = NULL;
808
809 /*****************************************************************************
810  * AllocateAllPlugins: load all plugin modules we can find.
811  *****************************************************************************/
812 #ifdef HAVE_DYNAMIC_PLUGINS
813 static void AllocateAllPlugins( vlc_object_t *p_this, module_bank_t *p_bank )
814 {
815     const char *vlcpath = psz_vlcpath;
816     int count,i;
817     char * path;
818     vlc_array_t *arraypaths = vlc_array_new();
819     const bool b_reset = var_InheritBool( p_this, "reset-plugins-cache" );
820
821     /* Contruct the special search path for system that have a relocatable
822      * executable. Set it to <vlc path>/plugins. */
823     assert( vlcpath );
824 #ifndef WIN32
825     if( asprintf( &path, "%s" DIR_SEP "plugins", vlcpath ) != -1 )
826         vlc_array_append( arraypaths, path );
827 #else
828     /* Store the plugins cache in the common AppData folder */
829     char commonpath[PATH_MAX] = "";
830     int res = snprintf( commonpath, PATH_MAX -1, "%s\\VideoLAN\\VLC", config_GetConfDir());
831         if(res == -1 || res >= PATH_MAX)
832         {
833             vlc_array_destroy( arraypaths );
834             free(path);
835             return;
836         }
837 #endif
838
839     /* If the user provided a plugin path, we add it to the list */
840     char *userpaths = var_InheritString( p_this, "plugin-path" );
841     char *paths_iter;
842
843     for( paths_iter = userpaths; paths_iter; )
844     {
845         path = copy_next_paths_token( paths_iter, &paths_iter );
846         if( path )
847             vlc_array_append( arraypaths, path );
848     }
849
850     count = vlc_array_count( arraypaths );
851     for( i = 0 ; i < count ; i++ )
852     {
853         path = vlc_array_item_at_index( arraypaths, i );
854         if( !path )
855             continue;
856
857         size_t offset = p_module_bank->i_cache;
858         if( b_reset )
859 #ifndef WIN32
860             CacheDelete( p_this, path );
861 #else
862             CacheDelete( p_this, commonpath );
863 #endif
864         else
865 #ifndef WIN32
866             CacheLoad( p_this, p_module_bank, path );
867 #else
868              CacheLoad( p_this, p_module_bank, commonpath );
869 #endif
870
871         msg_Dbg( p_this, "recursively browsing `%s'", path );
872
873         /* Don't go deeper than 5 subdirectories */
874         AllocatePluginDir( p_this, p_bank, path, 5 );
875
876
877 #ifndef WIN32
878         CacheSave( p_this, path, p_module_bank->pp_cache + offset,
879                    p_module_bank->i_cache - offset );
880 #else
881         CacheSave( p_this, commonpath, p_module_bank->pp_cache + offset,
882                    p_module_bank->i_cache - offset );
883 #endif
884         free( path );
885     }
886
887     vlc_array_destroy( arraypaths );
888     free( userpaths );
889 }
890
891 /*****************************************************************************
892  * AllocatePluginDir: recursively parse a directory to look for plugins
893  *****************************************************************************/
894 static void AllocatePluginDir( vlc_object_t *p_this, module_bank_t *p_bank,
895                                const char *psz_dir, unsigned i_maxdepth )
896 {
897     if( i_maxdepth == 0 )
898         return;
899
900     DIR *dh = vlc_opendir (psz_dir);
901     if (dh == NULL)
902         return;
903
904     /* Parse the directory and try to load all files it contains. */
905     for (;;)
906     {
907         char *file = vlc_readdir (dh), *path;
908         struct stat st;
909
910         if (file == NULL)
911             break;
912
913         /* Skip ".", ".." */
914         if (!strcmp (file, ".") || !strcmp (file, "..")
915         /* Skip directories for unsupported optimizations */
916          || !vlc_CPU_CheckPluginDir (file))
917         {
918             free (file);
919             continue;
920         }
921
922         const int pathlen = asprintf (&path, "%s"DIR_SEP"%s", psz_dir, file);
923         free (file);
924         if (pathlen == -1 || vlc_stat (path, &st))
925             continue;
926
927         if (S_ISDIR (st.st_mode))
928             /* Recurse into another directory */
929             AllocatePluginDir (p_this, p_bank, path, i_maxdepth - 1);
930         else
931         if (S_ISREG (st.st_mode)
932          && strncmp (path, "lib", 3)
933          && ((size_t)pathlen >= sizeof ("_plugin"LIBEXT))
934          && !strncasecmp (path + pathlen - strlen ("_plugin"LIBEXT),
935                           "_plugin"LIBEXT, strlen ("_plugni"LIBEXT)))
936             /* ^^ We only load files matching "lib*_plugin"LIBEXT */
937             AllocatePluginFile (p_this, p_bank, path, st.st_mtime, st.st_size);
938
939         free (path);
940     }
941     closedir (dh);
942 }
943
944 /*****************************************************************************
945  * AllocatePluginFile: load a module into memory and initialize it.
946  *****************************************************************************
947  * This function loads a dynamically loadable module and allocates a structure
948  * for its information data. The module can then be handled by module_need
949  * and module_unneed. It can be removed by DeleteModule.
950  *****************************************************************************/
951 static int AllocatePluginFile( vlc_object_t * p_this, module_bank_t *p_bank,
952                                const char *psz_file,
953                                int64_t i_file_time, int64_t i_file_size )
954 {
955     module_t * p_module = NULL;
956     module_cache_t *p_cache_entry = NULL;
957
958     /*
959      * Check our plugins cache first then load plugin if needed
960      */
961     p_cache_entry = CacheFind( p_bank, psz_file, i_file_time, i_file_size );
962     if( !p_cache_entry )
963     {
964         p_module = AllocatePlugin( p_this, psz_file );
965     }
966     else
967     {
968         module_config_t *p_item = NULL, *p_end = NULL;
969
970         p_module = p_cache_entry->p_module;
971         p_module->b_loaded = false;
972
973         /* If plugin-path contains duplicate entries... */
974         if( p_module->next != NULL )
975             return 0; /* already taken care of that one */
976
977         /* For now we force loading if the module's config contains
978          * callbacks or actions.
979          * Could be optimized by adding an API call.*/
980         for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
981              p_item < p_end; p_item++ )
982         {
983             if( p_item->pf_callback || p_item->i_action )
984             {
985                 p_module = AllocatePlugin( p_this, psz_file );
986                 break;
987             }
988         }
989     }
990
991     if( p_module == NULL )
992         return -1;
993
994     /* We have not already scanned and inserted this module */
995     assert( p_module->next == NULL );
996
997     /* Everything worked fine !
998      * The module is ready to be added to the list. */
999     p_module->b_builtin = false;
1000
1001     /* msg_Dbg( p_this, "plugin \"%s\", %s",
1002                 p_module->psz_object_name, p_module->psz_longname ); */
1003     p_module->next = p_bank->head;
1004     p_bank->head = p_module;
1005     assert( p_module->next != NULL ); /* Insertion done */
1006
1007     if( !p_module_bank->b_cache )
1008         return 0;
1009
1010     /* Add entry to cache */
1011     module_cache_t **pp_cache = p_bank->pp_cache;
1012
1013     pp_cache = realloc_or_free( pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1014     if( pp_cache == NULL )
1015         return -1;
1016     pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1017     if( pp_cache[p_bank->i_cache] == NULL )
1018         return -1;
1019     pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
1020     pp_cache[p_bank->i_cache]->i_time = i_file_time;
1021     pp_cache[p_bank->i_cache]->i_size = i_file_size;
1022     pp_cache[p_bank->i_cache]->p_module = p_module;
1023     p_bank->pp_cache = pp_cache;
1024     p_bank->i_cache++;
1025     return  0;
1026 }
1027
1028 /*****************************************************************************
1029  * AllocatePlugin: load a module into memory and initialize it.
1030  *****************************************************************************
1031  * This function loads a dynamically loadable module and allocates a structure
1032  * for its information data. The module can then be handled by module_need
1033  * and module_unneed. It can be removed by DeleteModule.
1034  *****************************************************************************/
1035 static module_t * AllocatePlugin( vlc_object_t * p_this, const char *psz_file )
1036 {
1037     module_t * p_module = NULL;
1038     module_handle_t handle;
1039
1040     if( module_Load( p_this, psz_file, &handle ) )
1041         return NULL;
1042
1043     /* Now that we have successfully loaded the module, we can
1044      * allocate a structure for it */
1045     p_module = vlc_module_create( p_this );
1046     if( p_module == NULL )
1047     {
1048         module_Unload( handle );
1049         return NULL;
1050     }
1051
1052     p_module->psz_filename = strdup( psz_file );
1053     p_module->handle = handle;
1054     p_module->b_loaded = true;
1055
1056     /* Initialize the module: fill p_module, default config */
1057     if( module_Call( p_this, p_module ) != 0 )
1058     {
1059         /* We couldn't call module_init() */
1060         free( p_module->psz_filename );
1061         module_release( p_module );
1062         module_Unload( handle );
1063         return NULL;
1064     }
1065
1066     DupModule( p_module );
1067
1068     /* Everything worked fine ! The module is ready to be added to the list. */
1069     p_module->b_builtin = false;
1070
1071     return p_module;
1072 }
1073
1074 /*****************************************************************************
1075  * DupModule: make a plugin module standalone.
1076  *****************************************************************************
1077  * This function duplicates all strings in the module, so that the dynamic
1078  * object can be unloaded. It acts recursively on submodules.
1079  *****************************************************************************/
1080 static void DupModule( module_t *p_module )
1081 {
1082     char **pp_shortcut;
1083
1084     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1085     {
1086         *pp_shortcut = strdup( *pp_shortcut );
1087     }
1088
1089     /* We strdup() these entries so that they are still valid when the
1090      * module is unloaded. */
1091     p_module->psz_capability = strdup( p_module->psz_capability );
1092     p_module->psz_shortname = p_module->psz_shortname ?
1093                                  strdup( p_module->psz_shortname ) : NULL;
1094     p_module->psz_longname = strdup( p_module->psz_longname );
1095     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1096                                             : NULL;
1097     p_module->domain = p_module->domain ? strdup( p_module->domain ) : NULL;
1098
1099     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1100         DupModule (subm);
1101 }
1102
1103 /*****************************************************************************
1104  * UndupModule: free a duplicated module.
1105  *****************************************************************************
1106  * This function frees the allocations done in DupModule().
1107  *****************************************************************************/
1108 static void UndupModule( module_t *p_module )
1109 {
1110     char **pp_shortcut;
1111
1112     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1113         UndupModule (subm);
1114
1115     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1116     {
1117         free( *pp_shortcut );
1118     }
1119
1120     free( p_module->psz_capability );
1121     FREENULL( p_module->psz_shortname );
1122     free( p_module->psz_longname );
1123     FREENULL( p_module->psz_help );
1124     free( p_module->domain );
1125 }
1126
1127 #endif /* HAVE_DYNAMIC_PLUGINS */
1128
1129 /*****************************************************************************
1130  * AllocateBuiltinModule: initialize a builtin module.
1131  *****************************************************************************
1132  * This function registers a builtin module and allocates a structure
1133  * for its information data. The module can then be handled by module_need
1134  * and module_unneed. It can be removed by DeleteModule.
1135  *****************************************************************************/
1136 static int AllocateBuiltinModule( vlc_object_t * p_this,
1137                                   int ( *pf_entry ) ( module_t * ) )
1138 {
1139     module_t * p_module;
1140
1141     /* Now that we have successfully loaded the module, we can
1142      * allocate a structure for it */
1143     p_module = vlc_module_create( p_this );
1144     if( p_module == NULL )
1145         return -1;
1146
1147     /* Initialize the module : fill p_module->psz_object_name, etc. */
1148     if( pf_entry( p_module ) != 0 )
1149     {
1150         /* With a well-written module we shouldn't have to print an
1151          * additional error message here, but just make sure. */
1152         msg_Err( p_this, "failed calling entry point in builtin module" );
1153         module_release( p_module );
1154         return -1;
1155     }
1156
1157     /* Everything worked fine ! The module is ready to be added to the list. */
1158     p_module->b_builtin = true;
1159     /* LOCK */
1160     p_module->next = p_module_bank->head;
1161     p_module_bank->head = p_module;
1162     /* UNLOCK */
1163
1164     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1165                 p_module->psz_object_name, p_module->psz_longname ); */
1166
1167     return 0;
1168 }
1169
1170 /*****************************************************************************
1171  * DeleteModule: delete a module and its structure.
1172  *****************************************************************************
1173  * This function can only be called if the module isn't being used.
1174  *****************************************************************************/
1175 static void DeleteModule( module_bank_t *p_bank, module_t * p_module )
1176 {
1177     assert( p_module );
1178
1179     /* Unlist the module (if it is in the list) */
1180     module_t **pp_self = &p_bank->head;
1181     while (*pp_self != NULL && *pp_self != p_module)
1182         pp_self = &((*pp_self)->next);
1183     if (*pp_self)
1184         *pp_self = p_module->next;
1185
1186     /* We free the structures that we strdup()ed in Allocate*Module(). */
1187 #ifdef HAVE_DYNAMIC_PLUGINS
1188     if( !p_module->b_builtin )
1189     {
1190         if( p_module->b_loaded && p_module->b_unloadable )
1191         {
1192             module_Unload( p_module->handle );
1193         }
1194         UndupModule( p_module );
1195         free( p_module->psz_filename );
1196     }
1197 #endif
1198
1199     /* Free and detach the object's children */
1200     while (p_module->submodule)
1201     {
1202         module_t *submodule = p_module->submodule;
1203         p_module->submodule = submodule->next;
1204         module_release (submodule);
1205     }
1206
1207     config_Free( p_module );
1208     module_release( p_module );
1209 }