]> git.sesse.net Git - vlc/blob - modules/lua/vlc.c
f8ab309d8fe51d438cdd312e720dce79a0c11664
[vlc] / modules / lua / vlc.c
1 /*****************************************************************************
2  * vlc.c: Generic lua interface functions
3  *****************************************************************************
4  * Copyright (C) 2007-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Antoine Cellerier <dionoea at videolan tod org>
8  *          Pierre d'Herbemont <pdherbemont # videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <assert.h>
33 #include <sys/stat.h>
34
35 #include "vlc.h"
36
37 #include <vlc_plugin.h>
38 #include <vlc_charset.h>
39 #include <vlc_fs.h>
40 #include <vlc_services_discovery.h>
41 #include <vlc_stream.h>
42
43 /*****************************************************************************
44  * Module descriptor
45  *****************************************************************************/
46 #define INTF_TEXT N_("Lua interface")
47 #define INTF_LONGTEXT N_("Lua interface module to load")
48
49 #define CONFIG_TEXT N_("Lua interface configuration")
50 #define CONFIG_LONGTEXT N_("Lua interface configuration string. Format is: '[\"<interface module name>\"] = { <option> = <value>, ...}, ...'.")
51 #define PASS_TEXT N_( "Password" )
52 #define PASS_LONGTEXT N_( "A single password restricts access " \
53     "to this interface." )
54 #define SRC_TEXT N_( "Source directory" )
55 #define SRC_LONGTEXT N_( "Source directory" )
56 #define INDEX_TEXT N_( "Directory index" )
57 #define INDEX_LONGTEXT N_( "Allow to build directory index" )
58
59 #define TELNETHOST_TEXT N_( "Host" )
60 #define TELNETHOST_LONGTEXT N_( "This is the host on which the " \
61     "interface will listen. It defaults to all network interfaces (0.0.0.0)." \
62     " If you want this interface to be available only on the local " \
63     "machine, enter \"127.0.0.1\"." )
64 #define TELNETPORT_TEXT N_( "Port" )
65 #define TELNETPORT_LONGTEXT N_( "This is the TCP port on which this " \
66     "interface will listen. It defaults to 4212." )
67 #define TELNETPWD_TEXT N_( "Password" )
68 #define TELNETPWD_LONGTEXT N_( "A single password restricts access " \
69     "to this interface." )
70 #define RCHOST_TEXT N_("TCP command input")
71 #define RCHOST_LONGTEXT N_("Accept commands over a socket rather than stdin. " \
72             "You can set the address and port the interface will bind to." )
73 #define CLIHOST_TEXT N_("CLI input")
74 #define CLIHOST_LONGTEXT N_( "Accept commands from this source. " \
75     "The CLI defaults to stdin (\"*console\"), but can also bind to a " \
76     "plain TCP socket (\"localhost:4212\") or use the telnet protocol " \
77     "(\"telnet://0.0.0.0:4212\")" )
78
79 static int vlc_sd_probe_Open( vlc_object_t * );
80
81 vlc_module_begin ()
82         set_shortname( N_("Lua") )
83         set_description( N_("Lua interpreter") )
84         set_category( CAT_INTERFACE )
85         set_subcategory( SUBCAT_INTERFACE_MAIN )
86
87         add_string( "lua-intf", "dummy", INTF_TEXT, INTF_LONGTEXT, false )
88         add_string( "lua-config", "", CONFIG_TEXT, CONFIG_LONGTEXT, false )
89         set_capability( "interface", 0 )
90         set_callbacks( Open_LuaIntf, Close_LuaIntf )
91         add_shortcut( "luaintf" )
92
93     add_submodule ()
94         set_section( N_("Lua HTTP"), 0 )
95             add_password ( "http-password", NULL, PASS_TEXT, PASS_LONGTEXT, false )
96             add_string ( "http-src",  NULL, SRC_TEXT,  SRC_LONGTEXT,  true )
97             add_bool   ( "http-index", false, INDEX_TEXT, INDEX_LONGTEXT, true )
98         set_capability( "interface", 0 )
99         set_callbacks( Open_LuaHTTP, Close_LuaIntf )
100         add_shortcut( "luahttp", "http" )
101         set_description( N_("Lua HTTP") )
102
103     add_submodule ()
104         set_section( N_("Lua CLI"), 0 )
105             add_string( "rc-host", NULL, RCHOST_TEXT, RCHOST_LONGTEXT, true )
106             add_string( "cli-host", NULL, CLIHOST_TEXT, CLIHOST_LONGTEXT, true )
107         set_capability( "interface", 25 )
108         set_description( N_("Command-line interface") )
109         set_callbacks( Open_LuaCLI, Close_LuaIntf )
110 #ifndef _WIN32
111         add_shortcut( "luacli", "luarc", "cli", "rc" )
112 #else
113         add_shortcut( "luacli", "luarc" )
114 #endif
115
116     add_submodule ()
117         set_section( N_("Lua Telnet"), 0 )
118             add_string( "telnet-host", "localhost", TELNETHOST_TEXT,
119                         TELNETHOST_LONGTEXT, true )
120             add_integer( "telnet-port", TELNETPORT_DEFAULT, TELNETPORT_TEXT,
121                          TELNETPORT_LONGTEXT, true )
122                 change_integer_range( 1, 65535 )
123             add_password( "telnet-password", NULL, TELNETPWD_TEXT,
124
125                           TELNETPWD_LONGTEXT, true )
126         set_capability( "interface", 0 )
127         set_callbacks( Open_LuaTelnet, Close_LuaIntf )
128         set_description( N_("Lua Telnet") )
129         add_shortcut( "luatelnet", "telnet" )
130
131     add_submodule ()
132         set_shortname( N_( "Lua Meta Fetcher" ) )
133         set_description( N_("Fetch meta data using lua scripts") )
134         set_capability( "meta fetcher", 10 )
135         set_callbacks( FetchMeta, NULL )
136
137     add_submodule ()
138         set_shortname( N_( "Lua Meta Reader" ) )
139         set_description( N_("Read meta data using lua scripts") )
140         set_capability( "meta reader", 10 )
141         set_callbacks( ReadMeta, NULL )
142
143     add_submodule ()
144         add_shortcut( "luaplaylist" )
145         set_shortname( N_("Lua Playlist") )
146         set_description( N_("Lua Playlist Parser Interface") )
147         set_capability( "demux", 2 )
148         set_callbacks( Import_LuaPlaylist, Close_LuaPlaylist )
149
150     add_submodule ()
151         set_shortname( N_( "Lua Art" ) )
152         set_description( N_("Fetch artwork using lua scripts") )
153         set_capability( "art finder", 10 )
154         set_callbacks( FindArt, NULL )
155
156     add_submodule ()
157         set_shortname( N_("Lua Extension") )
158         set_description( N_("Lua Extension") )
159         add_shortcut( "luaextension" )
160         set_capability( "extension", 1 )
161         set_callbacks( Open_Extension, Close_Extension )
162
163     add_submodule ()
164         set_description( N_("Lua SD Module") )
165         add_shortcut( "luasd" )
166         set_capability( "services_discovery", 0 )
167         add_string( "lua-sd", "", NULL, NULL, false )
168             change_volatile()
169         add_string( "lua-longname", "", NULL, NULL, false )
170             change_volatile()
171         set_callbacks( Open_LuaSD, Close_LuaSD )
172
173     VLC_SD_PROBE_SUBMODULE
174
175 vlc_module_end ()
176
177 /*****************************************************************************
178  *
179  *****************************************************************************/
180 static const char *ppsz_lua_exts[] = { ".luac", ".lua", ".vle", NULL };
181 static int file_select( const char *file )
182 {
183     int i = strlen( file );
184     int j;
185     for( j = 0; ppsz_lua_exts[j]; j++ )
186     {
187         int l = strlen( ppsz_lua_exts[j] );
188         if( i >= l && !strcmp( file+i-l, ppsz_lua_exts[j] ) )
189             return 1;
190     }
191     return 0;
192 }
193
194 static int file_compare( const char **a, const char **b )
195 {
196     return strcmp( *a, *b );
197 }
198
199 int vlclua_dir_list( const char *luadirname, char ***pppsz_dir_list )
200 {
201 #define MAX_DIR_LIST_SIZE 5
202     *pppsz_dir_list = malloc(MAX_DIR_LIST_SIZE*sizeof(char *));
203     if (!*pppsz_dir_list)
204         return VLC_EGENERIC;
205     char **ppsz_dir_list = *pppsz_dir_list;
206
207     int i = 0;
208     char *datadir = config_GetUserDir( VLC_DATA_DIR );
209
210     if( likely(datadir != NULL)
211      && likely(asprintf( &ppsz_dir_list[i], "%s"DIR_SEP"lua"DIR_SEP"%s",
212                          datadir, luadirname ) != -1) )
213         i++;
214     free( datadir );
215
216 #if !(defined(__APPLE__) || defined(_WIN32))
217     char *psz_libpath = config_GetLibDir();
218     if( likely(psz_libpath != NULL) )
219     {
220         if( likely(asprintf( &ppsz_dir_list[i], "%s"DIR_SEP"lua"DIR_SEP"%s",
221                              psz_libpath, luadirname ) != -1) )
222             i++;
223         free( psz_libpath );
224     }
225 #endif
226
227     char *psz_datapath = config_GetDataDir();
228     if( likely(psz_datapath != NULL) )
229     {
230         if( likely(asprintf( &ppsz_dir_list[i], "%s"DIR_SEP"lua"DIR_SEP"%s",
231                               psz_datapath, luadirname ) != -1) )
232             i++;
233
234 #if defined(__APPLE__)
235         if( likely(asprintf( &ppsz_dir_list[i],
236                              "%s"DIR_SEP"share"DIR_SEP"lua"DIR_SEP"%s",
237                              psz_datapath, luadirname ) != -1) )
238             i++;
239 #endif
240         free( psz_datapath );
241     }
242
243     ppsz_dir_list[i] = NULL;
244
245     assert( i < MAX_DIR_LIST_SIZE);
246
247     return VLC_SUCCESS;
248 }
249
250 void vlclua_dir_list_free( char **ppsz_dir_list )
251 {
252     for( char **ppsz_dir = ppsz_dir_list; *ppsz_dir; ppsz_dir++ )
253         free( *ppsz_dir );
254     free( ppsz_dir_list );
255 }
256
257 /*****************************************************************************
258  * Will execute func on all scripts in luadirname, and stop if func returns
259  * success.
260  *****************************************************************************/
261 int vlclua_scripts_batch_execute( vlc_object_t *p_this,
262                                   const char * luadirname,
263                                   int (*func)(vlc_object_t *, const char *, const luabatch_context_t *),
264                                   void * user_data)
265 {
266     char **ppsz_dir_list = NULL;
267     int i_ret;
268
269     if( (i_ret = vlclua_dir_list( luadirname, &ppsz_dir_list )) != VLC_SUCCESS)
270         return i_ret;
271
272     i_ret = VLC_EGENERIC;
273     for( char **ppsz_dir = ppsz_dir_list; *ppsz_dir; ppsz_dir++ )
274     {
275         char **ppsz_filelist;
276
277         msg_Dbg( p_this, "Trying Lua scripts in %s", *ppsz_dir );
278         int i_files = vlc_scandir( *ppsz_dir, &ppsz_filelist, file_select,
279                                    file_compare );
280         if( i_files < 0 )
281             continue;
282
283         char **ppsz_file = ppsz_filelist;
284         char **ppsz_fileend = ppsz_filelist + i_files;
285
286         while( ppsz_file < ppsz_fileend )
287         {
288             char *psz_filename;
289
290             if( asprintf( &psz_filename,
291                           "%s" DIR_SEP "%s", *ppsz_dir, *ppsz_file ) == -1 )
292                 psz_filename = NULL;
293             free( *(ppsz_file++) );
294
295             if( likely(psz_filename != NULL) )
296             {
297                 msg_Dbg( p_this, "Trying Lua playlist script %s", psz_filename );
298                 i_ret = func( p_this, psz_filename, user_data );
299                 free( psz_filename );
300                 if( i_ret == VLC_SUCCESS )
301                     break;
302             }
303         }
304
305         while( ppsz_file < ppsz_fileend )
306             free( *(ppsz_file++) );
307         free( ppsz_filelist );
308
309         if( i_ret == VLC_SUCCESS )
310             break;
311     }
312     vlclua_dir_list_free( ppsz_dir_list );
313     return i_ret;
314 }
315
316 char *vlclua_find_file( const char *psz_luadirname, const char *psz_name )
317 {
318     char **ppsz_dir_list = NULL;
319     vlclua_dir_list( psz_luadirname, &ppsz_dir_list );
320
321     for( char **ppsz_dir = ppsz_dir_list; *ppsz_dir; ppsz_dir++ )
322     {
323         for( const char **ppsz_ext = ppsz_lua_exts; *ppsz_ext; ppsz_ext++ )
324         {
325             char *psz_filename;
326             struct stat st;
327
328             if( asprintf( &psz_filename, "%s"DIR_SEP"%s%s", *ppsz_dir,
329                           psz_name, *ppsz_ext ) < 0 )
330             {
331                 vlclua_dir_list_free( ppsz_dir_list );
332                 return NULL;
333             }
334
335             if( vlc_stat( psz_filename, &st ) == 0
336                 && S_ISREG( st.st_mode ) )
337             {
338                 vlclua_dir_list_free( ppsz_dir_list );
339                 return psz_filename;
340             }
341             free( psz_filename );
342         }
343     }
344     vlclua_dir_list_free( ppsz_dir_list );
345     return NULL;
346 }
347
348 /*****************************************************************************
349  * Meta data setters utility.
350  * Playlist item table should be on top of the stack when these are called
351  *****************************************************************************/
352 #undef vlclua_read_meta_data
353 void vlclua_read_meta_data( vlc_object_t *p_this, lua_State *L,
354                             input_item_t *p_input )
355 {
356 #define TRY_META( a, b )                                        \
357     lua_getfield( L, -1, a );                                   \
358     if( lua_isstring( L, -1 ) &&                                \
359         strcmp( lua_tostring( L, -1 ), "" ) )                   \
360     {                                                           \
361         char *psz_value = strdup( lua_tostring( L, -1 ) );      \
362         EnsureUTF8( psz_value );                                \
363         msg_Dbg( p_this, #b ": %s", psz_value );                \
364         input_item_Set ## b ( p_input, psz_value );             \
365         free( psz_value );                                      \
366     }                                                           \
367     lua_pop( L, 1 ); /* pop a */
368     TRY_META( "title", Title );
369     TRY_META( "artist", Artist );
370     TRY_META( "genre", Genre );
371     TRY_META( "copyright", Copyright );
372     TRY_META( "album", Album );
373     TRY_META( "tracknum", TrackNum );
374     TRY_META( "description", Description );
375     TRY_META( "rating", Rating );
376     TRY_META( "date", Date );
377     TRY_META( "setting", Setting );
378     TRY_META( "url", URL );
379     TRY_META( "language",  Language );
380     TRY_META( "nowplaying", NowPlaying );
381     TRY_META( "publisher",  Publisher );
382     TRY_META( "encodedby",  EncodedBy );
383     TRY_META( "arturl",     ArtURL );
384     TRY_META( "trackid",    TrackID );
385     TRY_META( "director",   Director );
386     TRY_META( "season",     Season );
387     TRY_META( "episode",    Episode );
388     TRY_META( "show_name",  ShowName );
389     TRY_META( "actors",     Actors );
390 }
391
392 #undef vlclua_read_custom_meta_data
393 void vlclua_read_custom_meta_data( vlc_object_t *p_this, lua_State *L,
394                                      input_item_t *p_input )
395 {
396     /* Lock the input item and create the meta table if needed */
397     vlc_mutex_lock( &p_input->lock );
398
399     if( !p_input->p_meta )
400         p_input->p_meta = vlc_meta_New();
401
402     /* ... item */
403     lua_getfield( L, -1, "meta" );
404     /* ... item meta */
405     if( lua_istable( L, -1 ) )
406     {
407         lua_pushnil( L );
408         /* ... item meta nil */
409         while( lua_next( L, -2 ) )
410         {
411             /* ... item meta key value */
412             if( !lua_isstring( L, -2 ) || !lua_isstring( L, -1 ) )
413             {
414                 msg_Err( p_this, "'meta' keys and values must be strings");
415                 lua_pop( L, 1 ); /* pop "value" */
416                 continue;
417             }
418             const char *psz_key = lua_tostring( L, -2 );
419             const char *psz_value = lua_tostring( L, -1 );
420
421             vlc_meta_AddExtra( p_input->p_meta, psz_key, psz_value );
422
423             lua_pop( L, 1 ); /* pop "value" */
424         }
425     }
426     lua_pop( L, 1 ); /* pop "meta" */
427     /* ... item -> back to original stack */
428
429     vlc_mutex_unlock( &p_input->lock );
430 }
431
432 /*****************************************************************************
433  * Playlist utilities
434  ****************************************************************************/
435 /**
436  * Playlist item table should be on top of the stack when this is called
437  */
438 #undef vlclua_read_options
439 void vlclua_read_options( vlc_object_t *p_this, lua_State *L,
440                             int *pi_options, char ***pppsz_options )
441 {
442     lua_getfield( L, -1, "options" );
443     if( lua_istable( L, -1 ) )
444     {
445         lua_pushnil( L );
446         while( lua_next( L, -2 ) )
447         {
448             if( lua_isstring( L, -1 ) )
449             {
450                 char *psz_option = strdup( lua_tostring( L, -1 ) );
451                 msg_Dbg( p_this, "Option: %s", psz_option );
452                 INSERT_ELEM( *pppsz_options, *pi_options, *pi_options,
453                              psz_option );
454             }
455             else
456             {
457                 msg_Warn( p_this, "Option should be a string" );
458             }
459             lua_pop( L, 1 ); /* pop option */
460         }
461     }
462     lua_pop( L, 1 ); /* pop "options" */
463 }
464
465 #undef vlclua_playlist_add_internal
466 int vlclua_playlist_add_internal( vlc_object_t *p_this, lua_State *L,
467                                     playlist_t *p_playlist,
468                                     input_item_t *p_parent, bool b_play )
469 {
470     int i_count = 0;
471     input_item_node_t *p_parent_node = NULL;
472
473     assert( p_parent || p_playlist );
474
475     /* playlist */
476     if( lua_istable( L, -1 ) )
477     {
478         if( p_parent ) p_parent_node = input_item_node_Create( p_parent );
479         lua_pushnil( L );
480         /* playlist nil */
481         while( lua_next( L, -2 ) )
482         {
483             /* playlist key item */
484             /* <Parse playlist item> */
485             if( lua_istable( L, -1 ) )
486             {
487                 lua_getfield( L, -1, "path" );
488                 /* playlist key item path */
489                 if( lua_isstring( L, -1 ) )
490                 {
491                     char         *psz_oldurl   = NULL;
492                     const char   *psz_path     = NULL;
493                     char         *psz_u8path   = NULL;
494                     const char   *psz_name     = NULL;
495                     char        **ppsz_options = NULL;
496                     int           i_options    = 0;
497                     mtime_t       i_duration   = -1;
498                     input_item_t *p_input;
499
500                     /* Read path and name */
501                     if (p_parent) {
502                         psz_oldurl = input_item_GetURI( p_parent );
503                         msg_Dbg( p_this, "old path: %s", psz_oldurl );
504                     }
505                     psz_path = lua_tostring( L, -1 );
506                     msg_Dbg( p_this, "Path: %s", psz_path );
507                     lua_getfield( L, -2, "name" );
508                     /* playlist key item path name */
509                     if( lua_isstring( L, -1 ) )
510                     {
511                         psz_name = lua_tostring( L, -1 );
512                         msg_Dbg( p_this, "Name: %s", psz_name );
513                     }
514                     else
515                     {
516                         if( !lua_isnil( L, -1 ) )
517                             msg_Warn( p_this, "Playlist item name should be a string." );
518                         psz_name = NULL;
519                     }
520
521                     /* Read duration */
522                     lua_getfield( L, -3, "duration" );
523                     /* playlist key item path name duration */
524                     if( lua_isnumber( L, -1 ) )
525                     {
526                         i_duration = (mtime_t)(lua_tonumber( L, -1 )*1e6);
527                     }
528                     else if( !lua_isnil( L, -1 ) )
529                     {
530                         msg_Warn( p_this, "Playlist item duration should be a number (in seconds)." );
531                     }
532                     lua_pop( L, 1 ); /* pop "duration" */
533
534                     /* playlist key item path name */
535
536                     /* Read options: item must be on top of stack */
537                     lua_pushvalue( L, -3 );
538                     /* playlist key item path name item */
539                     vlclua_read_options( p_this, L, &i_options, &ppsz_options );
540
541                     /* Create input item */
542                     p_input = input_item_NewExt( psz_path, psz_name, i_options,
543                                                 (const char **)ppsz_options,
544                                                 VLC_INPUT_OPTION_TRUSTED,
545                                                 i_duration );
546                     lua_pop( L, 3 ); /* pop "path name item" */
547                     /* playlist key item */
548
549                     /* Read meta data: item must be on top of stack */
550                     vlclua_read_meta_data( p_this, L, p_input );
551
552                     /* copy the original URL to the meta data, if "URL" is still empty */
553                     char* url = input_item_GetURL( p_input );
554                     if( url == NULL && p_parent)
555                     {
556                         EnsureUTF8( psz_oldurl );
557                         msg_Dbg( p_this, "meta-URL: %s", psz_oldurl );
558                         input_item_SetURL ( p_input, psz_oldurl );
559                     }
560                     free( psz_oldurl );
561                     free( url );
562
563                     /* copy the psz_name to the meta data, if "Title" is still empty */
564                     char* title = input_item_GetTitle( p_input );
565                     if( title == NULL )
566                         input_item_SetTitle ( p_input, psz_name );
567                     free( title );
568
569                     /* Read custom meta data: item must be on top of stack*/
570                     vlclua_read_custom_meta_data( p_this, L, p_input );
571
572                     /* Append item to playlist */
573                     if( p_parent ) /* Add to node */
574                     {
575                         input_item_CopyOptions( p_parent, p_input );
576                         input_item_node_AppendItem( p_parent_node, p_input );
577                     }
578                     else /* Play or Enqueue (preparse) */
579                         /* FIXME: playlist_AddInput() can fail */
580                         playlist_AddInput( p_playlist, p_input,
581                                PLAYLIST_APPEND |
582                                ( b_play ? PLAYLIST_GO : PLAYLIST_PREPARSE ),
583                                PLAYLIST_END, true, false );
584                     i_count ++; /* increment counter */
585                     vlc_gc_decref( p_input );
586                     while( i_options > 0 )
587                         free( ppsz_options[--i_options] );
588                     free( ppsz_options );
589                     free( psz_u8path );
590                 }
591                 else
592                 {
593                     lua_pop( L, 1 ); /* pop "path" */
594                     msg_Warn( p_this,
595                              "Playlist item's path should be a string" );
596                 }
597                 /* playlist key item */
598             }
599             else
600             {
601                 msg_Warn( p_this, "Playlist item should be a table" );
602             }
603             /* <Parse playlist item> */
604             lua_pop( L, 1 ); /* pop the value, keep the key for
605                               * the next lua_next() call */
606             /* playlist key */
607         }
608         /* playlist */
609         if( p_parent )
610         {
611             if( i_count ) input_item_node_PostAndDelete( p_parent_node );
612             else input_item_node_Delete( p_parent_node );
613         }
614     }
615     else
616     {
617         msg_Warn( p_this, "Playlist should be a table." );
618     }
619     return i_count;
620 }
621
622 static int vlc_sd_probe_Open( vlc_object_t *obj )
623 {
624     vlc_probe_t *probe = (vlc_probe_t *)obj;
625     char **ppsz_filelist = NULL;
626     char **ppsz_fileend  = NULL;
627     char **ppsz_file;
628     char *psz_name;
629     char **ppsz_dir_list = NULL;
630     char **ppsz_dir;
631     lua_State *L = NULL;
632     vlclua_dir_list( "sd", &ppsz_dir_list );
633     for( ppsz_dir = ppsz_dir_list; *ppsz_dir; ppsz_dir++ )
634     {
635         int i_files;
636         if( ppsz_filelist )
637         {
638             for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend;
639                  ppsz_file++ )
640                 free( *ppsz_file );
641             free( ppsz_filelist );
642             ppsz_filelist = NULL;
643         }
644         i_files = vlc_scandir( *ppsz_dir, &ppsz_filelist, file_select,
645                                 file_compare );
646         if( i_files < 1 ) continue;
647         ppsz_fileend = ppsz_filelist + i_files;
648         for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend; ppsz_file++ )
649         {
650             char  *psz_filename;
651             if( asprintf( &psz_filename,
652                           "%s" DIR_SEP "%s", *ppsz_dir, *ppsz_file ) < 0 )
653             {
654                 goto error;
655             }
656             L = luaL_newstate();
657             if( !L )
658             {
659                 msg_Err( probe, "Could not create new Lua State" );
660                 free( psz_filename );
661                 goto error;
662             }
663             luaL_openlibs( L );
664             if( vlclua_add_modules_path( L, psz_filename ) )
665             {
666                 msg_Err( probe, "Error while setting the module search path for %s",
667                           psz_filename );
668                 free( psz_filename );
669                 goto error;
670             }
671             if( vlclua_dofile( VLC_OBJECT(probe), L, psz_filename ) )
672             {
673
674                 msg_Err( probe, "Error loading script %s: %s", psz_filename,
675                           lua_tostring( L, lua_gettop( L ) ) );
676                 lua_pop( L, 1 );
677                 free( psz_filename );
678                 lua_close( L );
679                 continue;
680             }
681             char *psz_longname;
682             char *temp = strchr( *ppsz_file, '.' );
683             if( temp )
684                 *temp = '\0';
685             lua_getglobal( L, "descriptor" );
686             if( !lua_isfunction( L, lua_gettop( L ) ) || lua_pcall( L, 0, 1, 0 ) )
687             {
688                 msg_Warn( probe, "No 'descriptor' function in '%s'", psz_filename );
689                 lua_pop( L, 1 );
690                 if( !( psz_longname = strdup( *ppsz_file ) ) )
691                 {
692                     free( psz_filename );
693                     goto error;
694                 }
695             }
696             else
697             {
698                 lua_getfield( L, -1, "title" );
699                 if( !lua_isstring( L, -1 ) ||
700                     !( psz_longname = strdup( lua_tostring( L, -1 ) ) ) )
701                 {
702                     free( psz_filename );
703                     goto error;
704                 }
705             }
706
707             char *psz_file_esc = config_StringEscape( *ppsz_file );
708             char *psz_longname_esc = config_StringEscape( psz_longname );
709             if( asprintf( &psz_name, "lua{sd='%s',longname='%s'}",
710                           psz_file_esc, psz_longname_esc ) < 0 )
711             {
712                 free( psz_file_esc );
713                 free( psz_longname_esc );
714                 free( psz_filename );
715                 free( psz_longname );
716                 goto error;
717             }
718             free( psz_file_esc );
719             free( psz_longname_esc );
720             vlc_sd_probe_Add( probe, psz_name, psz_longname, SD_CAT_INTERNET );
721             free( psz_name );
722             free( psz_longname );
723             free( psz_filename );
724             lua_close( L );
725         }
726     }
727     if( ppsz_filelist )
728     {
729         for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend;
730              ppsz_file++ )
731             free( *ppsz_file );
732         free( ppsz_filelist );
733     }
734     vlclua_dir_list_free( ppsz_dir_list );
735     return VLC_PROBE_CONTINUE;
736 error:
737     if( ppsz_filelist )
738     {
739         for( ppsz_file = ppsz_filelist; ppsz_file < ppsz_fileend;
740              ppsz_file++ )
741             free( *ppsz_file );
742         free( ppsz_filelist );
743     }
744     if( L )
745         lua_close( L );
746     vlclua_dir_list_free( ppsz_dir_list );
747     return VLC_ENOMEM;
748 }
749
750 static int vlclua_add_modules_path_inner( lua_State *L, const char *psz_path )
751 {
752     int count = 0;
753     for( const char **ppsz_ext = ppsz_lua_exts; *ppsz_ext; ppsz_ext++ )
754     {
755         lua_pushfstring( L, "%s"DIR_SEP"modules"DIR_SEP"?%s;",
756                          psz_path, *ppsz_ext );
757         count ++;
758     }
759
760     return count;
761 }
762
763 int vlclua_add_modules_path( lua_State *L, const char *psz_filename )
764 {
765     /* Setup the module search path:
766      *   * "The script's directory"/modules
767      *   * "The script's parent directory"/modules
768      *   * and so on for all the next directories in the directory list
769      */
770     char *psz_path = strdup( psz_filename );
771     if( !psz_path )
772         return 1;
773
774     char *psz_char = strrchr( psz_path, DIR_SEP_CHAR );
775     if( !psz_char )
776     {
777         free( psz_path );
778         return 1;
779     }
780     *psz_char = '\0';
781
782     /* psz_path now holds the file's directory */
783     psz_char = strrchr( psz_path, DIR_SEP_CHAR );
784     if( !psz_char )
785     {
786         free( psz_path );
787         return 1;
788     }
789     *psz_char = '\0';
790
791     /* Push package on stack */
792     int count = 0;
793     lua_getglobal( L, "package" );
794
795     /* psz_path now holds the file's parent directory */
796     count += vlclua_add_modules_path_inner( L, psz_path );
797     *psz_char = DIR_SEP_CHAR;
798
799     /* psz_path now holds the file's directory */
800     count += vlclua_add_modules_path_inner( L, psz_path );
801
802     char **ppsz_dir_list = NULL;
803     vlclua_dir_list( psz_char+1/* gruik? */, &ppsz_dir_list );
804     char **ppsz_dir = ppsz_dir_list;
805
806     for( ; *ppsz_dir && strcmp( *ppsz_dir, psz_path ); ppsz_dir++ );
807     free( psz_path );
808
809     for( ; *ppsz_dir; ppsz_dir++ )
810     {
811         psz_path = *ppsz_dir;
812         /* FIXME: doesn't work well with meta/... modules due to the double
813          * directory depth */
814         psz_char = strrchr( psz_path, DIR_SEP_CHAR );
815         if( !psz_char )
816         {
817             vlclua_dir_list_free( ppsz_dir_list );
818             return 1;
819         }
820
821         *psz_char = '\0';
822         count += vlclua_add_modules_path_inner( L, psz_path );
823         *psz_char = DIR_SEP_CHAR;
824         count += vlclua_add_modules_path_inner( L, psz_path );
825     }
826
827     lua_getfield( L, -(count+1), "path" ); /* Get package.path */
828     lua_concat( L, count+1 ); /* Concat vlc module paths and package.path */
829     lua_setfield( L, -2, "path"); /* Set package.path */
830     lua_pop( L, 1 ); /* Pop the package module */
831
832     vlclua_dir_list_free( ppsz_dir_list );
833     return 0;
834 }
835
836 /** Replacement for luaL_dofile, using VLC's input capabilities */
837 int vlclua_dofile( vlc_object_t *p_this, lua_State *L, const char *curi )
838 {
839     char *uri = ToLocaleDup( curi );
840     if( !strstr( uri, "://" ) ) {
841         int ret = luaL_dofile( L, uri );
842         free( uri );
843         return ret;
844     }
845     if( !strncasecmp( uri, "file://", 7 ) ) {
846         int ret = luaL_dofile( L, uri + 7 );
847         free( uri );
848         return ret;
849     }
850     stream_t *s = stream_UrlNew( p_this, uri );
851     if( !s )
852     {
853         free( uri );
854         return 1;
855     }
856     int64_t i_size = stream_Size( s );
857     char *p_buffer = ( i_size > 0 ) ? malloc( i_size ) : NULL;
858     if( !p_buffer )
859     {
860         // FIXME: read the whole stream until we reach the end (if no size)
861         stream_Delete( s );
862         free( uri );
863         return 1;
864     }
865     int64_t i_read = stream_Read( s, p_buffer, (int) i_size );
866     int i_ret = ( i_read == i_size ) ? 0 : 1;
867     if( !i_ret )
868         i_ret = luaL_loadbuffer( L, p_buffer, (size_t) i_size, uri );
869     if( !i_ret )
870         i_ret = lua_pcall( L, 0, LUA_MULTRET, 0 );
871     stream_Delete( s );
872     free( p_buffer );
873     free( uri );
874     return i_ret;
875 }