]> git.sesse.net Git - vlc/blob - modules/control/http/util.c
52cadd9b27a3c02e700cd23c737288f59847f04f
[vlc] / modules / control / http / util.c
1 /*****************************************************************************
2  * util.c : Utility functions for HTTP interface
3  *****************************************************************************
4  * Copyright (C) 2001-2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *          Laurent Aimar <fenrir@via.ecp.fr>
9  *          Christophe Massiot <massiot@via.ecp.fr>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <vlc_common.h>
31 #include "http.h"
32 #include "vlc_strings.h"
33
34 /****************************************************************************
35  * File and directory functions
36  ****************************************************************************/
37
38 /* ToUrl: create a good name for an url from filename */
39 char *FileToUrl( char *name, bool *pb_index )
40 {
41     char *url, *p;
42
43     url = p = malloc( strlen( name ) + 1 );
44
45     *pb_index = false;
46     if( !url || !p )
47     {
48         return NULL;
49     }
50
51 #ifdef WIN32
52     while( *name == '\\' || *name == '/' )
53 #else
54     while( *name == '/' )
55 #endif
56     {
57         name++;
58     }
59
60     *p++ = '/';
61     strcpy( p, name );
62
63 #ifdef WIN32
64     /* convert '\\' into '/' */
65     name = p;
66     while( *name )
67     {
68         if( *name == '\\' )
69             *name = '/';
70         name++;
71     }
72 #endif
73
74     /* index.* -> / */
75     if( ( p = strrchr( url, '/' ) ) != NULL )
76     {
77         if( !strncmp( p, "/index.", 7 ) )
78         {
79             p[1] = '\0';
80             *pb_index = true;
81         }
82     }
83     return url;
84 }
85
86 /* Load a file */
87 int FileLoad( FILE *f, char **pp_data, int *pi_data )
88 {
89     int i_read;
90
91     /* just load the file */
92     *pi_data = 0;
93     *pp_data = malloc( 1025 );  /* +1 for \0 */
94     while( ( i_read = fread( &(*pp_data)[*pi_data], 1, 1024, f ) ) == 1024 )
95     {
96         *pi_data += 1024;
97         *pp_data = realloc( *pp_data, *pi_data  + 1025 );
98     }
99     if( i_read > 0 )
100     {
101         *pi_data += i_read;
102     }
103     (*pp_data)[*pi_data] = '\0';
104
105     return VLC_SUCCESS;
106 }
107
108 /* Parse a directory and recursively add files */
109 int ParseDirectory( intf_thread_t *p_intf, char *psz_root,
110                         char *psz_dir )
111 {
112     intf_sys_t     *p_sys = p_intf->p_sys;
113     char           dir[MAX_DIR_SIZE];
114     DIR           *p_dir;
115     vlc_acl_t     *p_acl;
116     FILE          *file;
117
118     char          *user = NULL;
119     char          *password = NULL;
120
121     int           i_dirlen;
122
123     char sep;
124
125 #if defined( WIN32 )
126     sep = '\\';
127 #else
128     sep = '/';
129 #endif
130
131     if( ( p_dir = utf8_opendir( psz_dir ) ) == NULL )
132     {
133         if( errno != ENOENT && errno != ENOTDIR )
134             msg_Err( p_intf, "cannot open directory (%s)", psz_dir );
135         return VLC_EGENERIC;
136     }
137
138     i_dirlen = strlen( psz_dir );
139     if( i_dirlen + 10 > MAX_DIR_SIZE )
140     {
141         msg_Warn( p_intf, "skipping too deep directory (%s)", psz_dir );
142         closedir( p_dir );
143         return 0;
144     }
145
146     msg_Dbg( p_intf, "dir=%s", psz_dir );
147
148     snprintf( dir, sizeof( dir ), "%s%c.access", psz_dir, sep );
149     if( ( file = utf8_fopen( dir, "r" ) ) != NULL )
150     {
151         char line[1024];
152         int  i_size;
153
154         msg_Dbg( p_intf, "find .access in dir=%s", psz_dir );
155
156         i_size = fread( line, 1, 1023, file );
157         if( i_size > 0 )
158         {
159             char *p;
160             while( i_size > 0 && ( line[i_size-1] == '\n' ||
161                    line[i_size-1] == '\r' ) )
162             {
163                 i_size--;
164             }
165
166             line[i_size] = '\0';
167
168             p = strchr( line, ':' );
169             if( p )
170             {
171                 *p++ = '\0';
172                 user = strdup( line );
173                 password = strdup( p );
174             }
175         }
176         msg_Dbg( p_intf, "using user=%s password=%s (read=%d)",
177                  user, password, i_size );
178
179         fclose( file );
180     }
181
182     snprintf( dir, sizeof( dir ), "%s%c.hosts", psz_dir, sep );
183     p_acl = ACL_Create( p_intf, false );
184     if( ACL_LoadFile( p_acl, dir ) )
185     {
186         ACL_Destroy( p_acl );
187
188         struct stat st;
189         if( stat( dir, &st ) == 0 )
190         {
191             closedir( p_dir );
192             return VLC_EGENERIC;
193         }
194         p_acl = NULL;
195     }
196
197     for( ;; )
198     {
199         char *psz_filename;
200         /* parse psz_src dir */
201         if( ( psz_filename = utf8_readdir( p_dir ) ) == NULL )
202         {
203             break;
204         }
205
206         if( ( psz_filename[0] == '.' )
207          || ( i_dirlen + strlen( psz_filename ) > MAX_DIR_SIZE ) )
208         {
209             free( psz_filename );
210             continue;
211         }
212
213         snprintf( dir, sizeof( dir ), "%s%c%s", psz_dir, sep, psz_filename );
214         free( psz_filename );
215
216         if( ParseDirectory( p_intf, psz_root, dir ) )
217         {
218             httpd_file_sys_t *f = NULL;
219             httpd_handler_sys_t *h = NULL;
220             bool b_index;
221             char *psz_name, *psz_ext;
222
223             psz_name = FileToUrl( &dir[strlen( psz_root )], &b_index );
224             psz_ext = strrchr( dir, '.' );
225             if( psz_ext != NULL )
226             {
227                 int i;
228                 psz_ext++;
229                 for( i = 0; i < p_sys->i_handlers; i++ )
230                     if( !strcmp( p_sys->pp_handlers[i]->psz_ext, psz_ext ) )
231                         break;
232                 if( i < p_sys->i_handlers )
233                 {
234                     f = malloc( sizeof( httpd_handler_sys_t ) );
235                     h = (httpd_handler_sys_t *)f;
236                     f->b_handler = true;
237                     h->p_association = p_sys->pp_handlers[i];
238                 }
239             }
240             if( f == NULL )
241             {
242                 f = malloc( sizeof( httpd_file_sys_t ) );
243                 f->b_handler = false;
244             }
245
246             f->p_intf  = p_intf;
247             f->p_file = NULL;
248             f->p_redir = NULL;
249             f->p_redir2 = NULL;
250             f->file = strdup (dir);
251             f->name = psz_name;
252             f->b_html = strstr( &dir[strlen( psz_root )], ".htm" ) || strstr( &dir[strlen( psz_root )], ".xml" ) ? true : false;
253
254             if( !f->name )
255             {
256                 msg_Err( p_intf , "unable to parse directory" );
257                 closedir( p_dir );
258                 free( f );
259                 return( VLC_ENOMEM );
260             }
261             msg_Dbg( p_intf, "file=%s (url=%s)",
262                      f->file, f->name );
263
264             if( !f->b_handler )
265             {
266                 char *psz_type = strdup( "text/html; charset=UTF-8" );
267                 if( strstr( &dir[strlen( psz_root )], ".xml" ) )
268                 {
269                     char *psz = strstr( psz_type, "html;" );
270                     if( psz )
271                     {
272                         psz[0] = 'x';
273                         psz[1] = 'm';
274                         psz[2] = 'l';
275                         psz[3] = ';';
276                         psz[4] = ' ';
277                     }
278                 }
279                 f->p_file = httpd_FileNew( p_sys->p_httpd_host,
280                                            f->name,
281                                            f->b_html ? psz_type : NULL,
282                                            user, password, p_acl,
283                                            HttpCallback, f );
284                 free( psz_type );
285                 if( f->p_file != NULL )
286                 {
287                     TAB_APPEND( p_sys->i_files, p_sys->pp_files, f );
288                 }
289             }
290             else
291             {
292                 h->p_handler = httpd_HandlerNew( p_sys->p_httpd_host,
293                                                  f->name,
294                                                  user, password, p_acl,
295                                                  HandlerCallback, h );
296                 if( h->p_handler != NULL )
297                 {
298                     TAB_APPEND( p_sys->i_files, p_sys->pp_files,
299                                 (httpd_file_sys_t *)h );
300                 }
301             }
302
303             /* for url that ends by / add
304              *  - a redirect from rep to rep/
305              *  - in case of index.* rep/index.html to rep/ */
306             if( f && f->name[strlen(f->name) - 1] == '/' )
307             {
308                 char *psz_redir = strdup( f->name );
309                 char *p;
310                 psz_redir[strlen( psz_redir ) - 1] = '\0';
311
312                 msg_Dbg( p_intf, "redir=%s -> %s", psz_redir, f->name );
313                 f->p_redir = httpd_RedirectNew( p_sys->p_httpd_host, f->name, psz_redir );
314                 free( psz_redir );
315
316                 if( b_index && ( p = strstr( f->file, "index." ) ) )
317                 {
318                     if( asprintf( &psz_redir, "%s%s", f->name, p ) != -1 )
319                     {
320                         msg_Dbg( p_intf, "redir=%s -> %s", psz_redir, f->name );
321                         f->p_redir2 = httpd_RedirectNew( p_sys->p_httpd_host,
322                                                          f->name, psz_redir );
323
324                         free( psz_redir );
325                     }
326                 }
327             }
328         }
329     }
330
331     free( user );
332     free( password );
333
334     ACL_Destroy( p_acl );
335     closedir( p_dir );
336
337     return VLC_SUCCESS;
338 }
339
340
341 /*************************************************************************
342  * Playlist stuff
343  *************************************************************************/
344 void PlaylistListNode( intf_thread_t *p_intf, playlist_t *p_pl,
345                            playlist_item_t *p_node, char *name, mvar_t *s,
346                            int i_depth )
347 {
348     if( !p_node || !p_node->p_input )
349         return;
350
351     if( p_node->i_children == -1 )
352     {
353         char value[512];
354         char *psz;
355         playlist_item_t * p_item = playlist_CurrentPlayingItem( p_pl );
356         if( !p_item || !p_item->p_input )
357             return;
358
359         mvar_t *itm = mvar_New( name, "set" );
360         if( p_item->p_input->i_id == p_node->p_input->i_id )
361             mvar_AppendNewVar( itm, "current", "1" );
362         else
363             mvar_AppendNewVar( itm, "current", "0" );
364
365         sprintf( value, "%d", p_node->i_id );
366         mvar_AppendNewVar( itm, "index", value );
367
368         psz = input_item_GetName( p_node->p_input );
369         mvar_AppendNewVar( itm, "name", psz );
370         free( psz );
371
372         psz = input_item_GetURI( p_node->p_input );
373         mvar_AppendNewVar( itm, "uri", psz );
374         free( psz );
375
376         sprintf( value, "Item");
377         mvar_AppendNewVar( itm, "type", value );
378
379         sprintf( value, "%d", i_depth );
380         mvar_AppendNewVar( itm, "depth", value );
381
382         if( p_node->i_flags & PLAYLIST_RO_FLAG )
383             mvar_AppendNewVar( itm, "ro", "ro" );
384         else
385             mvar_AppendNewVar( itm, "ro", "rw" );
386
387         sprintf( value, "%"PRId64, input_item_GetDuration( p_node->p_input ) );
388         mvar_AppendNewVar( itm, "duration", value );
389
390         //Adding extra meta-information to each playlist item
391
392         psz = input_item_GetTitle( p_node->p_input );
393         mvar_AppendNewVar( itm, "title", psz );
394
395         psz = input_item_GetArtist( p_node->p_input );
396         mvar_AppendNewVar( itm, "artist", psz );
397
398         psz = input_item_GetGenre( p_node->p_input );
399         mvar_AppendNewVar( itm, "genre", psz );
400
401         psz = input_item_GetCopyright( p_node->p_input );
402         mvar_AppendNewVar( itm, "copyright", psz );
403
404         psz = input_item_GetAlbum( p_node->p_input );
405         mvar_AppendNewVar( itm, "album", psz );
406
407         psz = input_item_GetTrackNum( p_node->p_input );
408         mvar_AppendNewVar( itm, "track", psz );
409
410         psz = input_item_GetDescription( p_node->p_input );
411         mvar_AppendNewVar( itm, "description", psz );
412
413         psz = input_item_GetRating( p_node->p_input );
414         mvar_AppendNewVar( itm, "rating", psz );
415
416         psz = input_item_GetDate( p_node->p_input );
417         mvar_AppendNewVar( itm, "date", psz );
418
419         psz = input_item_GetURL( p_node->p_input );
420         mvar_AppendNewVar( itm, "url", psz );
421
422         psz = input_item_GetLanguage( p_node->p_input );
423         mvar_AppendNewVar( itm, "language", psz );
424
425         psz = input_item_GetNowPlaying( p_node->p_input );
426         mvar_AppendNewVar( itm, "now_playing", psz );
427
428         psz = input_item_GetPublisher( p_node->p_input );
429         mvar_AppendNewVar( itm, "publisher", psz );
430
431         psz = input_item_GetEncodedBy( p_node->p_input );
432         mvar_AppendNewVar( itm, "encoded_by", psz );
433
434         psz = input_item_GetArtURL( p_node->p_input );
435         mvar_AppendNewVar( itm, "art_url", psz );
436
437         psz = input_item_GetTrackID( p_node->p_input );
438         mvar_AppendNewVar( itm, "track_id", psz );
439
440         mvar_AppendVar( s, itm );
441     }
442     else
443     {
444         char value[512];
445         int i_child;
446         mvar_t *itm = mvar_New( name, "set" );
447
448         mvar_AppendNewVar( itm, "name", p_node->p_input->psz_name );
449         mvar_AppendNewVar( itm, "uri", p_node->p_input->psz_name );
450
451         sprintf( value, "Node" );
452         mvar_AppendNewVar( itm, "type", value );
453
454         sprintf( value, "%d", p_node->i_id );
455         mvar_AppendNewVar( itm, "index", value );
456
457         sprintf( value, "%d", p_node->i_children);
458         mvar_AppendNewVar( itm, "i_children", value );
459
460         sprintf( value, "%d", i_depth );
461         mvar_AppendNewVar( itm, "depth", value );
462
463         if( p_node->i_flags & PLAYLIST_RO_FLAG )
464             mvar_AppendNewVar( itm, "ro", "ro" );
465         else
466             mvar_AppendNewVar( itm, "ro", "rw" );
467
468         mvar_AppendVar( s, itm );
469
470         for( i_child = 0 ; i_child < p_node->i_children ; i_child++ )
471              PlaylistListNode( p_intf, p_pl, p_node->pp_children[i_child],
472                                name, s, i_depth + 1);
473     }
474 }
475
476 /****************************************************************************
477  * Seek command parsing handling
478  ****************************************************************************/
479 void HandleSeek( intf_thread_t *p_intf, char *p_value )
480 {
481     intf_sys_t     *p_sys = p_intf->p_sys;
482     vlc_value_t val;
483     int i_stock = 0;
484     uint64_t i_length;
485     int i_value = 0;
486     int i_relative = 0;
487 #define POSITION_ABSOLUTE 12
488 #define POSITION_REL_FOR 13
489 #define POSITION_REL_BACK 11
490 #define VL_TIME_ABSOLUTE 0
491 #define VL_TIME_REL_FOR 1
492 #define VL_TIME_REL_BACK -1
493     if( p_sys->p_input )
494     {
495         var_Get( p_sys->p_input, "length", &val );
496         i_length = val.i_time;
497
498         while( p_value[0] != '\0' )
499         {
500             switch(p_value[0])
501             {
502                 case '+':
503                 {
504                     i_relative = VL_TIME_REL_FOR;
505                     p_value++;
506                     break;
507                 }
508                 case '-':
509                 {
510                     i_relative = VL_TIME_REL_BACK;
511                     p_value++;
512                     break;
513                 }
514                 case '0': case '1': case '2': case '3': case '4':
515                 case '5': case '6': case '7': case '8': case '9':
516                 {
517                     i_stock = strtol( p_value , &p_value , 10 );
518                     break;
519                 }
520                 case '%': /* for percentage ie position */
521                 {
522                     i_relative += POSITION_ABSOLUTE;
523                     i_value = i_stock;
524                     i_stock = 0;
525                     p_value[0] = '\0';
526                     break;
527                 }
528                 case ':':
529                 {
530                     i_value = 60 * (i_value + i_stock) ;
531                     i_stock = 0;
532                     p_value++;
533                     break;
534                 }
535                 case 'h': case 'H': /* hours */
536                 {
537                     i_value += 3600 * i_stock;
538                     i_stock = 0;
539                     /* other characters which are not numbers are not
540                      * important */
541                     while( ((p_value[0] < '0') || (p_value[0] > '9'))
542                            && (p_value[0] != '\0') )
543                     {
544                         p_value++;
545                     }
546                     break;
547                 }
548                 case 'm': case 'M': case '\'': /* minutes */
549                 {
550                     i_value += 60 * i_stock;
551                     i_stock = 0;
552                     p_value++;
553                     while( ((p_value[0] < '0') || (p_value[0] > '9'))
554                            && (p_value[0] != '\0') )
555                     {
556                         p_value++;
557                     }
558                     break;
559                 }
560                 case 's': case 'S': case '"':  /* seconds */
561                 {
562                     i_value += i_stock;
563                     i_stock = 0;
564                     while( ((p_value[0] < '0') || (p_value[0] > '9'))
565                            && (p_value[0] != '\0') )
566                     {
567                         p_value++;
568                     }
569                     break;
570                 }
571                 default:
572                 {
573                     p_value++;
574                     break;
575                 }
576             }
577         }
578
579         /* if there is no known symbol, I consider it as seconds.
580          * Otherwise, i_stock = 0 */
581         i_value += i_stock;
582
583         switch(i_relative)
584         {
585             case VL_TIME_ABSOLUTE:
586             {
587                 if( (uint64_t)( i_value ) * 1000000 <= i_length )
588                     val.i_time = (uint64_t)( i_value ) * 1000000;
589                 else
590                     val.i_time = i_length;
591
592                 var_Set( p_sys->p_input, "time", val );
593                 msg_Dbg( p_intf, "requested seek position: %dsec", i_value );
594                 break;
595             }
596             case VL_TIME_REL_FOR:
597             {
598                 var_Get( p_sys->p_input, "time", &val );
599                 if( (uint64_t)( i_value ) * 1000000 + val.i_time <= i_length )
600                 {
601                     val.i_time = ((uint64_t)( i_value ) * 1000000) + val.i_time;
602                 } else
603                 {
604                     val.i_time = i_length;
605                 }
606                 var_Set( p_sys->p_input, "time", val );
607                 msg_Dbg( p_intf, "requested seek position forward: %dsec", i_value );
608                 break;
609             }
610             case VL_TIME_REL_BACK:
611             {
612                 var_Get( p_sys->p_input, "time", &val );
613                 if( (int64_t)( i_value ) * 1000000 > val.i_time )
614                 {
615                     val.i_time = 0;
616                 } else
617                 {
618                     val.i_time = val.i_time - ((uint64_t)( i_value ) * 1000000);
619                 }
620                 var_Set( p_sys->p_input, "time", val );
621                 msg_Dbg( p_intf, "requested seek position backward: %dsec", i_value );
622                 break;
623             }
624             case POSITION_ABSOLUTE:
625             {
626                 val.f_float = __MIN( __MAX( ((float) i_value ) / 100.0 ,
627                                             0.0 ), 100.0 );
628                 var_Set( p_sys->p_input, "position", val );
629                 msg_Dbg( p_intf, "requested seek percent: %d%%", i_value );
630                 break;
631             }
632             case POSITION_REL_FOR:
633             {
634                 var_Get( p_sys->p_input, "position", &val );
635                 val.f_float += __MIN( __MAX( ((float) i_value ) / 100.0,
636                                              0.0 ) , 100.0 );
637                 var_Set( p_sys->p_input, "position", val );
638                 msg_Dbg( p_intf, "requested seek percent forward: %d%%",
639                          i_value );
640                 break;
641             }
642             case POSITION_REL_BACK:
643             {
644                 var_Get( p_sys->p_input, "position", &val );
645                 val.f_float -= __MIN( __MAX( ((float) i_value ) / 100.0,
646                                              0.0 ) , 100.0 );
647                 var_Set( p_sys->p_input, "position", val );
648                 msg_Dbg( p_intf, "requested seek percent backward: %d%%",
649                          i_value );
650                 break;
651             }
652             default:
653             {
654                 msg_Dbg( p_intf, "invalid seek request" );
655                 break;
656             }
657         }
658     }
659 #undef POSITION_ABSOLUTE
660 #undef POSITION_REL_FOR
661 #undef POSITION_REL_BACK
662 #undef VL_TIME_ABSOLUTE
663 #undef VL_TIME_REL_FOR
664 #undef VL_TIME_REL_BACK
665 }
666
667
668 /****************************************************************************
669  * URI Parsing functions
670  ****************************************************************************/
671 int TestURIParam( char *psz_uri, const char *psz_name )
672 {
673     char *p = psz_uri;
674
675     while( (p = strstr( p, psz_name )) )
676     {
677         /* Verify that we are dealing with a post/get argument */
678         if( (p == psz_uri || *(p - 1) == '&' || *(p - 1) == '\n')
679               && p[strlen(psz_name)] == '=' )
680         {
681             return true;
682         }
683         p++;
684     }
685
686     return false;
687 }
688
689 static const char *FindURIValue( const char *psz_uri, const char *restrict psz_name,
690                            size_t *restrict p_len )
691 {
692     const char *p = psz_uri, *end;
693     size_t len;
694
695     while( (p = strstr( p, psz_name )) )
696     {
697         /* Verify that we are dealing with a post/get argument */
698         if( (p == psz_uri || *(p - 1) == '&' || *(p - 1) == '\n')
699               && p[strlen(psz_name)] == '=' )
700             break;
701         p++;
702     }
703
704     if( p == NULL )
705     {
706         *p_len = 0;
707         return NULL;
708     }
709
710     p += strlen( psz_name );
711     if( *p == '=' ) p++;
712
713     if( ( end = strchr( p, '\n' ) ) != NULL )
714     {
715         /* POST method */
716         if( ( end > p ) && ( end[-1] == '\r' ) )
717             end--;
718
719         len = end - p;
720     }
721     else
722     {
723         /* GET method */
724         if( ( end = strchr( p, '&' ) ) != NULL )
725             len = end - p;
726         else
727             len = strlen( p );
728     }
729
730     *p_len = len;
731     return p;
732 }
733
734 const char *ExtractURIValue( const char *restrict psz_uri,
735                            const char *restrict psz_name,
736                            char *restrict psz_buf, size_t bufsize )
737 {
738     size_t len;
739     const char *psz_value = FindURIValue( psz_uri, psz_name, &len );
740     const char *psz_next;
741
742     if( psz_value == NULL )
743     {
744         if( bufsize > 0 )
745             *psz_buf = '\0';
746         return NULL;
747     }
748
749     psz_next = psz_value + len;
750
751     if( len >= bufsize )
752         len = bufsize - 1;
753
754     if( len > 0 )
755         strncpy( psz_buf, psz_value, len );
756     if( bufsize > 0 )
757         psz_buf[len] = '\0';
758
759     return psz_next;
760 }
761
762 char *ExtractURIString( const char *restrict psz_uri,
763                             const char *restrict psz_name )
764 {
765     size_t len;
766     const char *psz_value = FindURIValue( psz_uri, psz_name, &len );
767
768     if( psz_value == NULL )
769         return NULL;
770
771     char *res = malloc( len + 1 );
772     if( res == NULL )
773         return NULL;
774
775     memcpy( res, psz_value, len );
776     res[len] = '\0';
777
778     return res;
779 }
780
781 /* Since the resulting string is smaller we can work in place, so it is
782  * permitted to have psz == new. new points to the first word of the
783  * string, the function returns the remaining string. */
784 char *FirstWord( char *psz, char *new )
785 {
786     bool b_end;
787
788     while( *psz == ' ' )
789         psz++;
790
791     while( *psz != '\0' && *psz != ' ' )
792     {
793         if( *psz == '\'' )
794         {
795             char c = *psz++;
796             while( *psz != '\0' && *psz != c )
797             {
798                 if( *psz == '\\' && psz[1] != '\0' )
799                     psz++;
800                 *new++ = *psz++;
801             }
802             if( *psz == c )
803                 psz++;
804         }
805         else
806         {
807             if( *psz == '\\' && psz[1] != '\0' )
808                 psz++;
809             *new++ = *psz++;
810         }
811     }
812     b_end = !*psz;
813
814     *new++ = '\0';
815     if( !b_end )
816         return psz + 1;
817     else
818         return NULL;
819 }
820
821 /**********************************************************************
822  * MRLParse: parse the MRL, find the MRL string and the options,
823  * create an item with all information in it, and return the item.
824  * return NULL if there is an error.
825  **********************************************************************/
826
827 /* Function analog to FirstWord except that it relies on colon instead
828  * of space to delimit option boundaries. */
829 static char *FirstOption( char *psz, char *new )
830 {
831     bool b_end, b_start = true;
832
833     while( *psz == ' ' )
834         psz++;
835
836     while( *psz != '\0' && (*psz != ' ' || psz[1] != ':') )
837     {
838         if( *psz == '\'' )
839         {
840             char c = *psz++;
841             while( *psz != '\0' && *psz != c )
842             {
843                 if( *psz == '\\' && psz[1] != '\0' )
844                     psz++;
845                 *new++ = *psz++;
846                 b_start = false;
847             }
848             if( *psz == c )
849                 psz++;
850         }
851         else
852         {
853             if( *psz == '\\' && psz[1] != '\0' )
854                 psz++;
855             *new++ = *psz++;
856             b_start = false;
857         }
858     }
859     b_end = !*psz;
860
861     if ( !b_start )
862         while (new[-1] == ' ')
863             new--;
864
865     *new++ = '\0';
866     if( !b_end )
867         return psz + 1;
868     else
869         return NULL;
870 }
871
872 input_item_t *MRLParse( intf_thread_t *p_intf, const char *mrl,
873                                    char *psz_name )
874 {
875     char *psz = strdup( mrl ), *s_mrl = psz, *s_temp;
876     if( psz == NULL )
877         return NULL;
878     /* extract the mrl */
879     s_temp = FirstOption( s_mrl, s_mrl );
880     if( s_temp == NULL )
881     {
882         s_temp = s_mrl + strlen( s_mrl );
883     }
884
885     input_item_t *p_input = input_item_New( p_intf, s_mrl, psz_name );
886     if( p_input == NULL )
887         return NULL;
888     s_mrl = s_temp;
889
890     /* now we can take care of the options */
891     while ( *s_mrl != '\0' )
892     {
893         s_temp = FirstOption( s_mrl, s_mrl );
894         if( s_mrl == '\0' )
895             break;
896         if( s_temp == NULL )
897         {
898             s_temp = s_mrl + strlen( s_mrl );
899         }
900         input_item_AddOption( p_input, s_mrl );
901         s_mrl = s_temp;
902     }
903
904     return p_input;
905 }
906
907 /**********************************************************************
908  * RealPath: parse ../, ~ and path stuff
909  **********************************************************************/
910 char *RealPath( const char *psz_src )
911 {
912     char *psz_dir;
913     char *p;
914     int i_len = strlen(psz_src);
915     const char sep = DIR_SEP_CHAR;
916
917     psz_dir = malloc( i_len + 2 );
918     strcpy( psz_dir, psz_src );
919
920     /* Add a trailing sep to ease the .. step */
921     psz_dir[i_len] = sep;
922     psz_dir[i_len + 1] = '\0';
923
924 #if (DIR_SEP_CHAR != '/')
925     /* Convert all / to native separator */
926     p = psz_dir;
927     while( (p = strchr( p, '/' )) != NULL )
928     {
929         *p = sep;
930     }
931 #endif
932
933     /* FIXME: this could be O(N) rather than O(N²)... */
934     /* Remove multiple separators and /./ */
935     p = psz_dir;
936     while( (p = strchr( p, sep )) != NULL )
937     {
938         if( p[1] == sep )
939             memmove( &p[1], &p[2], strlen(&p[2]) + 1 );
940         else if( p[1] == '.' && p[2] == sep )
941             memmove( &p[1], &p[3], strlen(&p[3]) + 1 );
942         else
943             p++;
944     }
945
946     if( psz_dir[0] == '~' )
947     {
948         char *dir;
949         asprintf( &dir, "%s%s", config_GetHomeDir(), psz_dir + 1 );
950         free( psz_dir );
951         psz_dir = dir;
952     }
953
954     if( strlen(psz_dir) > 2 )
955     {
956         /* Fix all .. dir */
957         p = psz_dir + 3;
958         while( (p = strchr( p, sep )) != NULL )
959         {
960             if( p[-1] == '.' && p[-2] == '.' && p[-3] == sep )
961             {
962                 char *q;
963                 p[-3] = '\0';
964                 if( (q = strrchr( psz_dir, sep )) != NULL )
965                 {
966                     memmove( q + 1, p + 1, strlen(p + 1) + 1 );
967                     p = q + 1;
968                 }
969                 else
970                 {
971                     memmove( psz_dir, p, strlen(p) + 1 );
972                     p = psz_dir + 3;
973                 }
974             }
975             else
976                 p++;
977         }
978     }
979
980     /* Remove trailing sep if there are at least 2 sep in the string
981      * (handles the C:\ stuff) */
982     p = strrchr( psz_dir, sep );
983     if( p != NULL && p[1] == '\0' && p != strchr( psz_dir, sep ) )
984         *p = '\0';
985
986     return psz_dir;
987 }