]> git.sesse.net Git - vlc/blob - src/modules/configuration.c
Changing the order of parameters may be needed, but changing the parameters themselve...
[vlc] / src / modules / configuration.c
1 /*****************************************************************************
2  * configuration.c management of the modules configuration
3  *****************************************************************************
4  * Copyright (C) 2001-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 #include <vlc/vlc.h>
25 #include "../libvlc.h"
26 #include "vlc_keys.h"
27 #include "vlc_charset.h"
28
29 #include <errno.h>                                                  /* errno */
30
31 #ifdef HAVE_LIMITS_H
32 #   include <limits.h>
33 #endif
34
35 #ifdef HAVE_UNISTD_H
36 #    include <unistd.h>                                          /* getuid() */
37 #endif
38
39 #ifdef HAVE_GETOPT_LONG
40 #   ifdef HAVE_GETOPT_H
41 #       include <getopt.h>                                       /* getopt() */
42 #   endif
43 #else
44 #   include "../extras/getopt.h"
45 #endif
46
47 #if defined(HAVE_GETPWUID)
48 #   include <pwd.h>                                            /* getpwuid() */
49 #endif
50
51 #if defined( HAVE_SYS_STAT_H )
52 #   include <sys/stat.h>
53 #endif
54 #if defined( HAVE_SYS_TYPES_H )
55 #   include <sys/types.h>
56 #endif
57 #if defined( WIN32 )
58 #   if !defined( UNDER_CE )
59 #       include <direct.h>
60 #   endif
61 #include <tchar.h>
62 #endif
63
64 #include "configuration.h"
65 #include "modules/modules.h"
66
67 static int ConfigStringToKey( const char * );
68 static char *ConfigKeyToString( int );
69
70 static inline char *strdupnull (const char *src)
71 {
72     if (src == NULL)
73         return NULL;
74     return strdup (src);
75 }
76
77 static inline char *_strdupnull (const char *src)
78 {
79     if (src == NULL)
80         return NULL;
81     return strdup (_(src));
82 }
83
84 /* Item types that use a string value (i.e. serialized in the module cache) */
85 int IsConfigStringType (int type)
86 {
87     static const unsigned char config_types[] =
88     {
89         CONFIG_ITEM_STRING, CONFIG_ITEM_FILE, CONFIG_ITEM_MODULE,
90         CONFIG_ITEM_DIRECTORY, CONFIG_ITEM_MODULE_CAT, CONFIG_ITEM_PASSWORD,
91         CONFIG_ITEM_MODULE_LIST, CONFIG_ITEM_MODULE_LIST_CAT
92     };
93
94     /* NOTE: this needs to be changed if we ever get more than 255 types */
95     return memchr (config_types, type, sizeof (config_types)) != NULL;
96 }
97
98
99 static int IsConfigIntegerType (int type)
100 {
101     static const unsigned char config_types[] =
102     {
103         CONFIG_ITEM_INTEGER, CONFIG_ITEM_KEY, CONFIG_ITEM_BOOL,
104         CONFIG_CATEGORY, CONFIG_SUBCATEGORY
105     };
106
107     return memchr (config_types, type, sizeof (config_types)) != NULL;
108 }
109
110
111 static inline int IsConfigFloatType (int type)
112 {
113     return type == CONFIG_ITEM_FLOAT;
114 }
115
116
117 /*****************************************************************************
118  * config_GetType: get the type of a variable (bool, int, float, string)
119  *****************************************************************************
120  * This function is used to get the type of a variable from its name.
121  * Beware, this is quite slow.
122  *****************************************************************************/
123 int __config_GetType( vlc_object_t *p_this, const char *psz_name )
124 {
125     module_config_t *p_config;
126     int i_type;
127
128     p_config = config_FindConfig( p_this, psz_name );
129
130     /* sanity checks */
131     if( !p_config )
132     {
133         return 0;
134     }
135
136     switch( p_config->i_type )
137     {
138     case CONFIG_ITEM_BOOL:
139         i_type = VLC_VAR_BOOL;
140         break;
141
142     case CONFIG_ITEM_INTEGER:
143         i_type = VLC_VAR_INTEGER;
144         break;
145
146     case CONFIG_ITEM_FLOAT:
147         i_type = VLC_VAR_FLOAT;
148         break;
149
150     case CONFIG_ITEM_MODULE:
151     case CONFIG_ITEM_MODULE_CAT:
152     case CONFIG_ITEM_MODULE_LIST:
153     case CONFIG_ITEM_MODULE_LIST_CAT:
154         i_type = VLC_VAR_MODULE;
155         break;
156
157     case CONFIG_ITEM_STRING:
158         i_type = VLC_VAR_STRING;
159         break;
160
161     case CONFIG_ITEM_PASSWORD:
162         i_type = VLC_VAR_STRING;
163         break;
164
165     case CONFIG_ITEM_FILE:
166         i_type = VLC_VAR_FILE;
167         break;
168
169     case CONFIG_ITEM_DIRECTORY:
170         i_type = VLC_VAR_DIRECTORY;
171         break;
172
173     default:
174         i_type = 0;
175         break;
176     }
177
178     return i_type;
179 }
180
181 /*****************************************************************************
182  * config_GetInt: get the value of an int variable
183  *****************************************************************************
184  * This function is used to get the value of variables which are internally
185  * represented by an integer (CONFIG_ITEM_INTEGER and
186  * CONFIG_ITEM_BOOL).
187  *****************************************************************************/
188 int __config_GetInt( vlc_object_t *p_this, const char *psz_name )
189 {
190     module_config_t *p_config;
191
192     p_config = config_FindConfig( p_this, psz_name );
193
194     /* sanity checks */
195     if( !p_config )
196     {
197         msg_Err( p_this, "option %s does not exist", psz_name );
198         return -1;
199     }
200
201     if (!IsConfigIntegerType (p_config->i_type))
202     {
203         msg_Err( p_this, "option %s does not refer to an int", psz_name );
204         return -1;
205     }
206
207     return p_config->value.i;
208 }
209
210 /*****************************************************************************
211  * config_GetFloat: get the value of a float variable
212  *****************************************************************************
213  * This function is used to get the value of variables which are internally
214  * represented by a float (CONFIG_ITEM_FLOAT).
215  *****************************************************************************/
216 float __config_GetFloat( vlc_object_t *p_this, const char *psz_name )
217 {
218     module_config_t *p_config;
219
220     p_config = config_FindConfig( p_this, psz_name );
221
222     /* sanity checks */
223     if( !p_config )
224     {
225         msg_Err( p_this, "option %s does not exist", psz_name );
226         return -1;
227     }
228
229     if (!IsConfigFloatType (p_config->i_type))
230     {
231         msg_Err( p_this, "option %s does not refer to a float", psz_name );
232         return -1;
233     }
234
235     return p_config->value.f;
236 }
237
238 /*****************************************************************************
239  * config_GetPsz: get the string value of a string variable
240  *****************************************************************************
241  * This function is used to get the value of variables which are internally
242  * represented by a string (CONFIG_ITEM_STRING, CONFIG_ITEM_FILE,
243  * CONFIG_ITEM_DIRECTORY, CONFIG_ITEM_PASSWORD, and CONFIG_ITEM_MODULE).
244  *
245  * Important note: remember to free() the returned char* because it's a
246  *   duplicate of the actual value. It isn't safe to return a pointer to the
247  *   actual value as it can be modified at any time.
248  *****************************************************************************/
249 char * __config_GetPsz( vlc_object_t *p_this, const char *psz_name )
250 {
251     module_config_t *p_config;
252
253     p_config = config_FindConfig( p_this, psz_name );
254
255     /* sanity checks */
256     if( !p_config )
257     {
258         msg_Err( p_this, "option %s does not exist", psz_name );
259         return NULL;
260     }
261
262     if (!IsConfigStringType (p_config->i_type))
263     {
264         msg_Err( p_this, "option %s does not refer to a string", psz_name );
265         return NULL;
266     }
267
268     /* return a copy of the string */
269     vlc_mutex_lock( p_config->p_lock );
270     char *psz_value = strdupnull (p_config->value.psz);
271     vlc_mutex_unlock( p_config->p_lock );
272
273     return psz_value;
274 }
275
276 /*****************************************************************************
277  * config_PutPsz: set the string value of a string variable
278  *****************************************************************************
279  * This function is used to set the value of variables which are internally
280  * represented by a string (CONFIG_ITEM_STRING, CONFIG_ITEM_FILE,
281  * CONFIG_ITEM_DIRECTORY, CONFIG_ITEM_PASSWORD, and CONFIG_ITEM_MODULE).
282  *****************************************************************************/
283 void __config_PutPsz( vlc_object_t *p_this,
284                       const char *psz_name, const char *psz_value )
285 {
286     module_config_t *p_config;
287     vlc_value_t oldval, val;
288
289     p_config = config_FindConfig( p_this, psz_name );
290
291
292     /* sanity checks */
293     if( !p_config )
294     {
295         msg_Warn( p_this, "option %s does not exist", psz_name );
296         return;
297     }
298
299     if (!IsConfigStringType (p_config->i_type))
300     {
301         msg_Err( p_this, "option %s does not refer to a string", psz_name );
302         return;
303     }
304
305     vlc_mutex_lock( p_config->p_lock );
306
307     /* backup old value */
308     oldval.psz_string = (char *)p_config->value.psz;
309
310     if ((psz_value != NULL) && *psz_value)
311         p_config->value.psz = strdup (psz_value);
312     else
313         p_config->value.psz = NULL;
314
315     p_config->b_dirty = VLC_TRUE;
316
317     val.psz_string = (char *)p_config->value.psz;
318
319     vlc_mutex_unlock( p_config->p_lock );
320
321     if( p_config->pf_callback )
322     {
323         p_config->pf_callback( p_this, psz_name, oldval, val,
324                                p_config->p_callback_data );
325     }
326
327     /* free old string */
328     if( oldval.psz_string ) free( oldval.psz_string );
329 }
330
331 /*****************************************************************************
332  * config_PutInt: set the integer value of an int variable
333  *****************************************************************************
334  * This function is used to set the value of variables which are internally
335  * represented by an integer (CONFIG_ITEM_INTEGER and
336  * CONFIG_ITEM_BOOL).
337  *****************************************************************************/
338 void __config_PutInt( vlc_object_t *p_this, const char *psz_name, int i_value )
339 {
340     module_config_t *p_config;
341     vlc_value_t oldval, val;
342
343     p_config = config_FindConfig( p_this, psz_name );
344
345     /* sanity checks */
346     if( !p_config )
347     {
348         msg_Warn( p_this, "option %s does not exist", psz_name );
349         return;
350     }
351
352     if (!IsConfigIntegerType (p_config->i_type))
353     {
354         msg_Err( p_this, "option %s does not refer to an int", psz_name );
355         return;
356     }
357
358     /* backup old value */
359     oldval.i_int = p_config->value.i;
360
361     /* if i_min == i_max == 0, then do not use them */
362     if ((p_config->min.i == 0) && (p_config->max.i == 0))
363     {
364         p_config->value.i = i_value;
365     }
366     else if (i_value < p_config->min.i)
367     {
368         p_config->value.i = p_config->min.i;
369     }
370     else if (i_value > p_config->max.i)
371     {
372         p_config->value.i = p_config->max.i;
373     }
374     else
375     {
376         p_config->value.i = i_value;
377     }
378
379     p_config->b_dirty = VLC_TRUE;
380
381     val.i_int = p_config->value.i;
382
383     if( p_config->pf_callback )
384     {
385         p_config->pf_callback( p_this, psz_name, oldval, val,
386                                p_config->p_callback_data );
387     }
388 }
389
390 /*****************************************************************************
391  * config_PutFloat: set the value of a float variable
392  *****************************************************************************
393  * This function is used to set the value of variables which are internally
394  * represented by a float (CONFIG_ITEM_FLOAT).
395  *****************************************************************************/
396 void __config_PutFloat( vlc_object_t *p_this,
397                         const char *psz_name, float f_value )
398 {
399     module_config_t *p_config;
400     vlc_value_t oldval, val;
401
402     p_config = config_FindConfig( p_this, psz_name );
403
404     /* sanity checks */
405     if( !p_config )
406     {
407         msg_Warn( p_this, "option %s does not exist", psz_name );
408         return;
409     }
410
411     if (!IsConfigFloatType (p_config->i_type))
412     {
413         msg_Err( p_this, "option %s does not refer to a float", psz_name );
414         return;
415     }
416
417     /* backup old value */
418     oldval.f_float = p_config->value.f;
419
420     /* if f_min == f_max == 0, then do not use them */
421     if ((p_config->min.f == 0) && (p_config->max.f == 0))
422     {
423         p_config->value.f = f_value;
424     }
425     else if (f_value < p_config->min.f)
426     {
427         p_config->value.f = p_config->min.f;
428     }
429     else if (f_value > p_config->max.f)
430     {
431         p_config->value.f = p_config->max.f;
432     }
433     else
434     {
435         p_config->value.f = f_value;
436     }
437
438     p_config->b_dirty = VLC_TRUE;
439
440     val.f_float = p_config->value.f;
441
442     if( p_config->pf_callback )
443     {
444         p_config->pf_callback( p_this, psz_name, oldval, val,
445                                p_config->p_callback_data );
446     }
447 }
448
449 /*****************************************************************************
450  * config_FindConfig: find the config structure associated with an option.
451  *****************************************************************************
452  * FIXME: This function really needs to be optimized.
453  * FIXME: And now even more.
454  *****************************************************************************/
455 module_config_t *config_FindConfig( vlc_object_t *p_this, const char *psz_name )
456 {
457     vlc_list_t *p_list;
458     int i_index;
459
460     if( !psz_name ) return NULL;
461
462     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
463
464     for( i_index = 0; i_index < p_list->i_count; i_index++ )
465     {
466         module_config_t *p_item, *p_end;
467         module_t *p_parser = (module_t *)p_list->p_values[i_index].p_object;
468
469         if( !p_parser->i_config_items )
470             continue;
471
472         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
473              p_item < p_end;
474              p_item++ )
475         {
476             if( p_item->i_type & CONFIG_HINT )
477                 /* ignore hints */
478                 continue;
479             if( !strcmp( psz_name, p_item->psz_name ) )
480             {
481                 vlc_list_release( p_list );
482                 return p_item;
483             }
484         }
485     }
486
487     vlc_list_release( p_list );
488
489     return NULL;
490 }
491
492 /*****************************************************************************
493  * config_FindModule: find a specific module structure.
494  *****************************************************************************/
495 module_t *config_FindModule( vlc_object_t *p_this, const char *psz_name )
496 {
497     vlc_list_t *p_list;
498     module_t *p_module, *p_result = NULL;
499     int i_index;
500
501     if( !psz_name ) return NULL;
502
503     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
504
505     for( i_index = 0; i_index < p_list->i_count; i_index++ )
506     {
507         p_module = (module_t *)p_list->p_values[i_index].p_object;
508         if( !strcmp( p_module->psz_object_name, psz_name ) )
509         {
510              p_result = p_module;
511              break;
512         }
513     }
514
515     vlc_list_release( p_list );
516
517     return p_result;
518 }
519
520 /*****************************************************************************
521  * config_Duplicate: creates a duplicate of a module's configuration data.
522  *****************************************************************************
523  * Unfortunatly we cannot work directly with the module's config data as
524  * this module might be unloaded from memory at any time (remember HideModule).
525  * This is why we need to create an exact copy of the config data.
526  *****************************************************************************/
527 int config_Duplicate( module_t *p_module, const module_config_t *p_orig,
528                       size_t n )
529 {
530     int j;
531     const module_config_t *p_item, *p_end = p_orig + n;
532
533     /* Calculate the structure length */
534     p_module->i_config_items = 0;
535     p_module->i_bool_items = 0;
536
537     for( p_item = p_orig; p_item < p_end; p_item++ )
538     {
539         if( p_item->i_type & CONFIG_ITEM )
540         {
541             p_module->i_config_items++;
542         }
543
544         if( p_item->i_type == CONFIG_ITEM_BOOL )
545         {
546             p_module->i_bool_items++;
547         }
548     }
549
550     /* Allocate memory */
551     p_module->p_config = (module_config_t *)calloc( n, sizeof(*p_orig) );
552     if( p_module->p_config == NULL )
553     {
554         msg_Err( p_module, "config error: can't duplicate p_config" );
555         return VLC_ENOMEM;
556     }
557     p_module->confsize = n;
558
559     /* Do the duplication job */
560     for( size_t i = 0; i < n ; i++ )
561     {
562         p_module->p_config[i] = p_orig[i];
563
564         if (IsConfigIntegerType (p_module->p_config[i].i_type))
565         {
566             p_module->p_config[i].orig.i = p_orig[i].value.i;
567             p_module->p_config[i].saved.i = p_orig[i].value.i;
568         }
569         else
570         if (IsConfigFloatType (p_module->p_config[i].i_type))
571         {
572             p_module->p_config[i].orig.f = p_orig[i].value.f;
573             p_module->p_config[i].saved.f = p_orig[i].value.f;
574         }
575         else
576         if (IsConfigStringType (p_module->p_config[i].i_type))
577         {
578             p_module->p_config[i].value.psz = strdupnull (p_orig[i].value.psz);
579             p_module->p_config[i].orig.psz = strdupnull (p_orig[i].value.psz);
580             p_module->p_config[i].saved.psz = NULL;
581         }
582
583         p_module->p_config[i].psz_type = strdupnull (p_orig[i].psz_type);
584         p_module->p_config[i].psz_name = strdupnull (p_orig[i].psz_name);
585         p_module->p_config[i].psz_current = strdupnull (p_orig[i].psz_current);
586         p_module->p_config[i].psz_text = _strdupnull (p_orig[i].psz_text);
587         p_module->p_config[i].psz_longtext = _strdupnull (p_orig[i].psz_longtext);
588
589         p_module->p_config[i].p_lock = &p_module->object_lock;
590
591         /* duplicate the string list */
592         if( p_orig[i].i_list )
593         {
594             if( p_orig[i].ppsz_list )
595             {
596                 p_module->p_config[i].ppsz_list =
597                     malloc( (p_orig[i].i_list + 1) * sizeof(char *) );
598                 if( p_module->p_config[i].ppsz_list )
599                 {
600                     for( j = 0; j < p_orig[i].i_list; j++ )
601                         p_module->p_config[i].ppsz_list[j] =
602                                 strdupnull (p_orig[i].ppsz_list[j]);
603                     p_module->p_config[i].ppsz_list[j] = NULL;
604                 }
605             }
606             if( p_orig[i].ppsz_list_text )
607             {
608                 p_module->p_config[i].ppsz_list_text =
609                     calloc( (p_orig[i].i_list + 1), sizeof(char *) );
610                 if( p_module->p_config[i].ppsz_list_text )
611                 {
612                     for( j = 0; j < p_orig[i].i_list; j++ )
613                         p_module->p_config[i].ppsz_list_text[j] =
614                                 strdupnull (_(p_orig[i].ppsz_list_text[j]));
615                     p_module->p_config[i].ppsz_list_text[j] = NULL;
616                 }
617             }
618             if( p_orig[i].pi_list )
619             {
620                 p_module->p_config[i].pi_list =
621                     malloc( (p_orig[i].i_list + 1) * sizeof(int) );
622                 if( p_module->p_config[i].pi_list )
623                 {
624                     for( j = 0; j < p_orig[i].i_list; j++ )
625                         p_module->p_config[i].pi_list[j] =
626                             p_orig[i].pi_list[j];
627                 }
628             }
629         }
630
631         /* duplicate the actions list */
632         if( p_orig[i].i_action )
633         {
634             int j;
635
636             p_module->p_config[i].ppf_action =
637                 malloc( p_orig[i].i_action * sizeof(void *) );
638             p_module->p_config[i].ppsz_action_text =
639                 malloc( p_orig[i].i_action * sizeof(char *) );
640
641             for( j = 0; j < p_orig[i].i_action; j++ )
642             {
643                 p_module->p_config[i].ppf_action[j] =
644                     p_orig[i].ppf_action[j];
645                 p_module->p_config[i].ppsz_action_text[j] =
646                     strdupnull (p_orig[i].ppsz_action_text[j]);
647             }
648         }
649
650         p_module->p_config[i].pf_callback = p_orig[i].pf_callback;
651     }
652     return VLC_SUCCESS;
653 }
654
655
656 /*****************************************************************************
657  * config_Free: frees a duplicated module's configuration data.
658  *****************************************************************************
659  * This function frees all the data duplicated by config_Duplicate.
660  *****************************************************************************/
661 void config_Free( module_t *p_module )
662 {
663     int i;
664
665     for (size_t j = 0; j < p_module->confsize; j++)
666     {
667         module_config_t *p_item = p_module->p_config + j;
668
669         free( (char*) p_item->psz_type );
670         free( (char*) p_item->psz_name );
671         free( (char*) p_item->psz_current );
672         free( (char*) p_item->psz_text );
673         free( (char*) p_item->psz_longtext );
674
675         if (IsConfigStringType (p_item->i_type))
676         {
677             free ((char *)p_item->value.psz);
678             free ((char *)p_item->orig.psz);
679             free ((char *)p_item->saved.psz);
680         }
681
682         if( p_item->i_list )
683         {
684             for( i = 0; i < p_item->i_list; i++ )
685             {
686                 if( p_item->ppsz_list && p_item->ppsz_list[i] )
687                     free( (char*) p_item->ppsz_list[i] );
688                 if( p_item->ppsz_list_text && p_item->ppsz_list_text[i] )
689                     free( (char*) p_item->ppsz_list_text[i] );
690             }
691             if( p_item->ppsz_list ) free( p_item->ppsz_list );
692             if( p_item->ppsz_list_text ) free( p_item->ppsz_list_text );
693             if( p_item->pi_list ) free( p_item->pi_list );
694         }
695
696         if( p_item->i_action )
697         {
698             for( i = 0; i < p_item->i_action; i++ )
699             {
700                 free( (char*) p_item->ppsz_action_text[i] );
701             }
702             if( p_item->ppf_action ) free( p_item->ppf_action );
703             if( p_item->ppsz_action_text ) free( p_item->ppsz_action_text );
704         }
705     }
706
707     if (p_module->p_config != NULL)
708     {
709         free (p_module->p_config);
710         p_module->p_config = NULL;
711     }
712 }
713
714 /*****************************************************************************
715  * config_SetCallbacks: sets callback functions in the duplicate p_config.
716  *****************************************************************************
717  * Unfortunatly we cannot work directly with the module's config data as
718  * this module might be unloaded from memory at any time (remember HideModule).
719  * This is why we need to duplicate callbacks each time we reload the module.
720  *****************************************************************************/
721 void config_SetCallbacks( module_config_t *p_new, module_config_t *p_orig,
722                           size_t n )
723 {
724     for (size_t i = 0; i < n; i++)
725     {
726         p_new->pf_callback = p_orig->pf_callback;
727         p_new++;
728         p_orig++;
729     }
730 }
731
732 /*****************************************************************************
733  * config_UnsetCallbacks: unsets callback functions in the duplicate p_config.
734  *****************************************************************************
735  * We simply undo what we did in config_SetCallbacks.
736  *****************************************************************************/
737 void config_UnsetCallbacks( module_config_t *p_new, size_t n )
738 {
739     for (size_t i = 0; i < n; i++)
740     {
741         p_new->pf_callback = NULL;
742         p_new++;
743     }
744 }
745
746 /*****************************************************************************
747  * config_ResetAll: reset the configuration data for all the modules.
748  *****************************************************************************/
749 void __config_ResetAll( vlc_object_t *p_this )
750 {
751     int i_index;
752     vlc_list_t *p_list;
753     module_t *p_module;
754
755     /* Acquire config file lock */
756     vlc_mutex_lock( &p_this->p_libvlc->config_lock );
757
758     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
759
760     for( i_index = 0; i_index < p_list->i_count; i_index++ )
761     {
762         p_module = (module_t *)p_list->p_values[i_index].p_object ;
763         if( p_module->b_submodule ) continue;
764
765         for (size_t i = 0; i < p_module->confsize; i++ )
766         {
767             if (IsConfigIntegerType (p_module->p_config[i].i_type))
768                 p_module->p_config[i].value.i = p_module->p_config[i].orig.i;
769             else
770             if (IsConfigFloatType (p_module->p_config[i].i_type))
771                 p_module->p_config[i].value.f = p_module->p_config[i].orig.f;
772             else
773             if (IsConfigStringType (p_module->p_config[i].i_type))
774             {
775                 free ((char *)p_module->p_config[i].value.psz);
776                 p_module->p_config[i].value.psz =
777                         strdupnull (p_module->p_config[i].orig.psz);
778             }
779         }
780     }
781
782     vlc_list_release( p_list );
783     vlc_mutex_unlock( &p_this->p_libvlc->config_lock );
784 }
785
786
787 static FILE *config_OpenConfigFile( vlc_object_t *p_obj, const char *mode )
788 {
789     char *psz_filename = p_obj->p_libvlc->psz_configfile;
790     FILE *p_stream;
791
792     if( !psz_filename )
793     {
794         psz_filename = config_GetConfigFile( p_obj->p_libvlc );
795     }
796
797     msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
798
799     p_stream = utf8_fopen( psz_filename, mode );
800     if( p_stream == NULL && errno != ENOENT )
801     {
802         msg_Err( p_obj, "cannot open config file (%s): %m",
803                  psz_filename );
804
805     }
806 #if !( defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS) )
807     else if( p_stream == NULL && errno == ENOENT && mode[0] == 'r' )
808     {
809         /* This is the fallback for pre XDG Base Directory
810          * Specification configs */
811         char *psz_old;
812         if( asprintf( &psz_old, "%s" DIR_SEP CONFIG_DIR DIR_SEP CONFIG_FILE,
813                   p_obj->p_libvlc->psz_homedir ) != -1 )
814         {
815             p_stream = utf8_fopen( psz_old, mode );
816             if( p_stream )
817             {
818                 /* Old config file found. We want to write it at the
819                  * new location now. */
820                 msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
821                           "VLC will now use %s.", psz_old, psz_filename );
822                 char *psz_readme;
823                 if( asprintf(&psz_readme,"%s"DIR_SEP CONFIG_DIR DIR_SEP"README",
824                               p_obj->p_libvlc->psz_homedir ) != -1 )
825                 {
826                     FILE *p_readme = utf8_fopen( psz_readme, "wt" );
827                     if( p_readme )
828                     {
829                         fputs( "The VLC media player configuration folder has "
830                                "moved to comply with the XDG Base "
831                                "Directory Specification version 0.6. Your "
832                                "configuration has been copied to the new "
833                                "location (", p_readme );
834                         fputs( p_obj->p_libvlc->psz_configdir, p_readme );
835                         fputs( "). You can delete this directory and "
836                                "all its contents.", p_readme );
837                         fclose( p_readme );
838                     }
839                     free( psz_readme );
840                 }
841             }
842             free( psz_old );
843         }
844     }
845 #endif
846     else if( p_stream != NULL )
847     {
848         p_obj->p_libvlc->psz_configfile = psz_filename;
849     }
850
851     return p_stream;
852 }
853
854
855 static int strtoi (const char *str)
856 {
857     char *end;
858     long l;
859
860     errno = 0;
861     l = strtol (str, &end, 0);
862
863     if (!errno)
864     {
865         if ((l > INT_MAX) || (l < INT_MIN))
866             errno = ERANGE;
867         if (*end)
868             errno = EINVAL;
869     }
870     return (int)l;
871 }
872
873
874 /*****************************************************************************
875  * config_LoadConfigFile: loads the configuration file.
876  *****************************************************************************
877  * This function is called to load the config options stored in the config
878  * file.
879  *****************************************************************************/
880 int __config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
881 {
882     vlc_list_t *p_list;
883     FILE *file;
884
885     file = config_OpenConfigFile (p_this, "rt");
886     if (file == NULL)
887         return VLC_EGENERIC;
888
889     /* Acquire config file lock */
890     vlc_mutex_lock( &p_this->p_libvlc->config_lock );
891
892     /* Look for the selected module, if NULL then save everything */
893     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
894
895     /* Look for UTF-8 Byte Order Mark */
896     char * (*convert) (const char *) = strdupnull;
897     char bom[3];
898
899     if ((fread (bom, 1, 3, file) != 3)
900      || memcmp (bom, "\xEF\xBB\xBF", 3))
901     {
902         convert = FromLocaleDup;
903         rewind (file); /* no BOM, rewind */
904     }
905
906     module_t *module = NULL;
907     char line[1024], section[1022];
908     section[0] = '\0';
909
910     while (fgets (line, 1024, file) != NULL)
911     {
912         /* Ignore comments and empty lines */
913         switch (line[0])
914         {
915             case '#':
916             case '\n':
917             case '\0':
918                 continue;
919         }
920
921         if (line[0] == '[')
922         {
923             char *ptr = strchr (line, ']');
924             if (ptr == NULL)
925                 continue; /* syntax error; */
926             *ptr = '\0';
927
928             /* New section ( = a given module) */
929             strcpy (section, line + 1);
930             module = NULL;
931
932             if ((psz_module_name == NULL)
933              || (strcmp (psz_module_name, section) == 0))
934             {
935                 for (int i = 0; i < p_list->i_count; i++)
936                 {
937                     module_t *m = (module_t *)p_list->p_values[i].p_object;
938
939                     if ((strcmp (section, m->psz_object_name) == 0)
940                      && (m->i_config_items > 0)) /* ignore config-less modules */
941                     {
942                         module = m;
943                         if (psz_module_name != NULL)
944                             msg_Dbg (p_this,
945                                      "loading config for module \"%s\"",
946                                      section);
947                         break;
948                     }
949                 }
950             }
951
952             continue;
953         }
954
955         if (module == NULL)
956             continue; /* no need to parse if there is no matching module */
957
958         char *ptr = strchr (line, '\n');
959         if (ptr != NULL)
960             *ptr = '\0';
961
962         /* look for option name */
963         const char *psz_option_name = line;
964
965         ptr = strchr (line, '=');
966         if (ptr == NULL)
967             continue; /* syntax error */
968
969         *ptr = '\0';
970         const char *psz_option_value = ptr + 1;
971
972         /* try to match this option with one of the module's options */
973         for (size_t i = 0; i < module->confsize; i++)
974         {
975             module_config_t *p_item = module->p_config + i;
976
977             if ((p_item->i_type & CONFIG_HINT)
978              || strcmp (p_item->psz_name, psz_option_name))
979                 continue;
980
981             /* We found it */
982             errno = 0;
983
984             switch( p_item->i_type )
985             {
986                 case CONFIG_ITEM_BOOL:
987                 case CONFIG_ITEM_INTEGER:
988                 {
989                     long l = strtoi (psz_option_value);
990                     if (errno)
991                         msg_Warn (p_this, "Integer value (%s) for %s: %m",
992                                   psz_option_value, psz_option_name);
993                     else
994                         p_item->saved.i = p_item->value.i = (int)l;
995                     break;
996                 }
997
998                 case CONFIG_ITEM_FLOAT:
999                     if( !*psz_option_value )
1000                         break;                    /* ignore empty option */
1001                     p_item->value.f = (float)i18n_atof( psz_option_value);
1002                     p_item->saved.f = p_item->value.f;
1003                     break;
1004
1005                 case CONFIG_ITEM_KEY:
1006                     if( !*psz_option_value )
1007                         break;                    /* ignore empty option */
1008                     p_item->value.i = ConfigStringToKey(psz_option_value);
1009                     p_item->saved.i = p_item->value.i;
1010                     break;
1011
1012                 default:
1013                     vlc_mutex_lock( p_item->p_lock );
1014
1015                     /* free old string */
1016                     free( (char*) p_item->value.psz );
1017                     free( (char*) p_item->saved.psz );
1018
1019                     p_item->value.psz = convert (psz_option_value);
1020                     p_item->saved.psz = strdupnull (p_item->value.psz);
1021
1022                     vlc_mutex_unlock( p_item->p_lock );
1023                     break;
1024             }
1025
1026             break;
1027         }
1028     }
1029
1030     if (ferror (file))
1031     {
1032         msg_Err (p_this, "error reading configuration: %m");
1033         clearerr (file);
1034     }
1035     fclose (file);
1036
1037     vlc_list_release( p_list );
1038
1039     vlc_mutex_unlock( &p_this->p_libvlc->config_lock );
1040     return 0;
1041 }
1042
1043 /*****************************************************************************
1044  * config_CreateDir: Create configuration directory if it doesn't exist.
1045  *****************************************************************************/
1046 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
1047 {
1048     if( !psz_dirname && !*psz_dirname ) return -1;
1049
1050     if( utf8_mkdir( psz_dirname, 0700 ) == 0 )
1051         return 0;
1052
1053     switch( errno )
1054     {
1055         case EEXIST:
1056             return 0;
1057
1058         case ENOENT:
1059         {
1060             /* Let's try to create the parent directory */
1061             char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
1062             strcpy( psz_parent, psz_dirname );
1063
1064             psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
1065             if( psz_end && psz_end != psz_parent )
1066             {
1067                 *psz_end = '\0';
1068                 if( config_CreateDir( p_this, psz_parent ) == 0 )
1069                 {
1070                     if( !utf8_mkdir( psz_dirname, 0700 ) )
1071                         return 0;
1072                 }
1073             }
1074         }
1075     }
1076
1077     msg_Err( p_this, "could not create %s: %m", psz_dirname );
1078     return -1;
1079 }
1080
1081 /*****************************************************************************
1082  * config_SaveConfigFile: Save a module's config options.
1083  *****************************************************************************
1084  * This will save the specified module's config options to the config file.
1085  * If psz_module_name is NULL then we save all the modules config options.
1086  * It's no use to save the config options that kept their default values, so
1087  * we'll try to be a bit clever here.
1088  *
1089  * When we save we mustn't delete the config options of the modules that
1090  * haven't been loaded. So we cannot just create a new config file with the
1091  * config structures we've got in memory.
1092  * I don't really know how to deal with this nicely, so I will use a completly
1093  * dumb method ;-)
1094  * I will load the config file in memory, but skipping all the sections of the
1095  * modules we want to save. Then I will create a brand new file, dump the file
1096  * loaded in memory and then append the sections of the modules we want to
1097  * save.
1098  * Really stupid no ?
1099  *****************************************************************************/
1100 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
1101                            vlc_bool_t b_autosave )
1102 {
1103     module_t *p_parser;
1104     vlc_list_t *p_list;
1105     FILE *file;
1106     char p_line[1024], *p_index2;
1107     int i_sizebuf = 0;
1108     char *p_bigbuffer, *p_index;
1109     vlc_bool_t b_backup;
1110     int i_index;
1111
1112     /* Acquire config file lock */
1113     vlc_mutex_lock( &p_this->p_libvlc->config_lock );
1114
1115     if( p_this->p_libvlc->psz_configfile == NULL )
1116     {
1117         const char *psz_configdir = p_this->p_libvlc->psz_configdir;
1118         if( !psz_configdir ) /* XXX: This should never happen */
1119         {
1120             msg_Err( p_this, "no configuration directory defined" );
1121             vlc_mutex_unlock( &p_this->p_libvlc->config_lock );
1122             return -1;
1123         }
1124
1125         config_CreateDir( p_this, psz_configdir );
1126     }
1127
1128     file = config_OpenConfigFile( p_this, "rt" );
1129     if( file != NULL )
1130     {
1131         /* look for file size */
1132         fseek( file, 0L, SEEK_END );
1133         i_sizebuf = ftell( file );
1134         fseek( file, 0L, SEEK_SET );
1135     }
1136
1137     p_bigbuffer = p_index = malloc( i_sizebuf+1 );
1138     if( !p_bigbuffer )
1139     {
1140         msg_Err( p_this, "out of memory" );
1141         if( file ) fclose( file );
1142         vlc_mutex_unlock( &p_this->p_libvlc->config_lock );
1143         return -1;
1144     }
1145     p_bigbuffer[0] = 0;
1146
1147     /* List all available modules */
1148     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1149
1150     /* backup file into memory, we only need to backup the sections we won't
1151      * save later on */
1152     b_backup = 0;
1153     while( file && fgets( p_line, 1024, file ) )
1154     {
1155         if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
1156         {
1157
1158             /* we found a section, check if we need to do a backup */
1159             for( i_index = 0; i_index < p_list->i_count; i_index++ )
1160             {
1161                 p_parser = (module_t *)p_list->p_values[i_index].p_object ;
1162
1163                 if( ((p_index2 - &p_line[1])
1164                        == (int)strlen(p_parser->psz_object_name) )
1165                     && !memcmp( &p_line[1], p_parser->psz_object_name,
1166                                 strlen(p_parser->psz_object_name) ) )
1167                 {
1168                     if( !psz_module_name )
1169                         break;
1170                     else if( !strcmp( psz_module_name,
1171                                       p_parser->psz_object_name ) )
1172                         break;
1173                 }
1174             }
1175
1176             if( i_index == p_list->i_count )
1177             {
1178                 /* we don't have this section in our list so we need to back
1179                  * it up */
1180                 *p_index2 = 0;
1181 #if 0
1182                 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
1183                                  &p_line[1] );
1184 #endif
1185                 *p_index2 = ']';
1186
1187                 b_backup = 1;
1188             }
1189             else
1190             {
1191                 b_backup = 0;
1192             }
1193         }
1194
1195         /* save line if requested and line is valid (doesn't begin with a
1196          * space, tab, or eol) */
1197         if( b_backup && (p_line[0] != '\n') && (p_line[0] != ' ')
1198             && (p_line[0] != '\t') )
1199         {
1200             strcpy( p_index, p_line );
1201             p_index += strlen( p_line );
1202         }
1203     }
1204     if( file ) fclose( file );
1205
1206
1207     /*
1208      * Save module config in file
1209      */
1210
1211     file = config_OpenConfigFile (p_this, "wt");
1212     if( !file )
1213     {
1214         vlc_list_release( p_list );
1215         free( p_bigbuffer );
1216         vlc_mutex_unlock( &p_this->p_libvlc->config_lock );
1217         return -1;
1218     }
1219
1220     fprintf( file, "\xEF\xBB\xBF###\n###  " COPYRIGHT_MESSAGE "\n###\n\n"
1221        "###\n### lines begining with a '#' character are comments\n###\n\n" );
1222
1223     /* Look for the selected module, if NULL then save everything */
1224     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1225     {
1226         module_config_t *p_item, *p_end;
1227         p_parser = (module_t *)p_list->p_values[i_index].p_object ;
1228
1229         if( psz_module_name && strcmp( psz_module_name,
1230                                        p_parser->psz_object_name ) )
1231             continue;
1232
1233         if( !p_parser->i_config_items )
1234             continue;
1235
1236         if( psz_module_name )
1237             msg_Dbg( p_this, "saving config for module \"%s\"",
1238                      p_parser->psz_object_name );
1239
1240         fprintf( file, "[%s]", p_parser->psz_object_name );
1241         if( p_parser->psz_longname )
1242             fprintf( file, " # %s\n\n", p_parser->psz_longname );
1243         else
1244             fprintf( file, "\n\n" );
1245
1246         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
1247              p_item < p_end;
1248              p_item++ )
1249         {
1250             char  *psz_key;
1251             int   i_value = p_item->value.i;
1252             float f_value = p_item->value.f;
1253             const char  *psz_value = p_item->value.psz;
1254
1255             if( p_item->i_type & CONFIG_HINT )
1256                 /* ignore hints */
1257                 continue;
1258             /* Ignore deprecated options */
1259             if( p_item->psz_current )
1260                 continue;
1261             if( p_item->b_unsaveable )
1262                 /*obvious*/
1263                 continue;
1264
1265             if( b_autosave && !p_item->b_autosave )
1266             {
1267                 i_value = p_item->saved.i;
1268                 f_value = p_item->saved.f;
1269                 psz_value = p_item->saved.psz;
1270                 if( !psz_value ) psz_value = p_item->orig.psz;
1271             }
1272             else
1273             {
1274                 p_item->b_dirty = VLC_FALSE;
1275             }
1276
1277             switch( p_item->i_type )
1278             {
1279             case CONFIG_ITEM_BOOL:
1280             case CONFIG_ITEM_INTEGER:
1281                 if( p_item->psz_text )
1282                     fprintf( file, "# %s (%s)\n", p_item->psz_text,
1283                              (p_item->i_type == CONFIG_ITEM_BOOL) ?
1284                              _("boolean") : _("integer") );
1285                 if( i_value == p_item->orig.i )
1286                     fputc ('#', file);
1287                 fprintf( file, "%s=%i\n", p_item->psz_name, i_value );
1288
1289                 p_item->saved.i = i_value;
1290                 break;
1291
1292             case CONFIG_ITEM_KEY:
1293                 if( p_item->psz_text )
1294                     fprintf( file, "# %s (%s)\n", p_item->psz_text,
1295                              _("key") );
1296                 if( i_value == p_item->orig.i )
1297                     fputc ('#', file);
1298                 psz_key = ConfigKeyToString( i_value );
1299                 fprintf( file, "%s=%s\n", p_item->psz_name,
1300                          psz_key ? psz_key : "" );
1301                 free (psz_key);
1302
1303                 p_item->saved.i = i_value;
1304                 break;
1305
1306             case CONFIG_ITEM_FLOAT:
1307                 if( p_item->psz_text )
1308                     fprintf( file, "# %s (%s)\n", p_item->psz_text,
1309                              _("float") );
1310                 if( f_value == p_item->orig.f )
1311                     fputc ('#', file);
1312                 fprintf( file, "%s=%f\n", p_item->psz_name, (double)f_value );
1313
1314                 p_item->saved.f = f_value;
1315                 break;
1316
1317             default:
1318                 if( p_item->psz_text )
1319                     fprintf( file, "# %s (%s)\n", p_item->psz_text,
1320                              _("string") );
1321                 if( (!psz_value && !p_item->orig.psz) ||
1322                     (psz_value && p_item->orig.psz &&
1323                      !strcmp( psz_value, p_item->orig.psz )) )
1324                     fputc ('#', file);
1325                 fprintf( file, "%s=%s\n", p_item->psz_name,
1326                          psz_value ?: "" );
1327
1328                 if( b_autosave && !p_item->b_autosave ) break;
1329
1330                 free ((char *)p_item->saved.psz);
1331                 if( (psz_value && p_item->orig.psz &&
1332                      strcmp( psz_value, p_item->orig.psz )) ||
1333                     !psz_value || !p_item->orig.psz)
1334                     p_item->saved.psz = strdupnull (psz_value);
1335                 else
1336                     p_item->saved.psz = NULL;
1337             }
1338         }
1339
1340         fputc ('\n', file);
1341     }
1342
1343     vlc_list_release( p_list );
1344
1345     /*
1346      * Restore old settings from the config in file
1347      */
1348     fputs( p_bigbuffer, file );
1349     free( p_bigbuffer );
1350
1351     fclose( file );
1352     vlc_mutex_unlock( &p_this->p_libvlc->config_lock );
1353
1354     return 0;
1355 }
1356
1357 int config_AutoSaveConfigFile( vlc_object_t *p_this )
1358 {
1359     vlc_list_t *p_list;
1360     int i_index, i_count;
1361
1362     if( !p_this ) return -1;
1363
1364     /* Check if there's anything to save */
1365     vlc_mutex_lock( &p_this->p_libvlc->config_lock );
1366     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1367     i_count = p_list->i_count;
1368     for( i_index = 0; i_index < i_count; i_index++ )
1369     {
1370         module_t *p_parser = (module_t *)p_list->p_values[i_index].p_object ;
1371         module_config_t *p_item, *p_end;
1372
1373         if( !p_parser->i_config_items ) continue;
1374
1375         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
1376              p_item < p_end;
1377              p_item++ )
1378         {
1379             if( p_item->b_autosave && p_item->b_dirty ) break;
1380         }
1381         break;
1382     }
1383     vlc_list_release( p_list );
1384     vlc_mutex_unlock( &p_this->p_libvlc->config_lock );
1385
1386     if( i_index == i_count ) return VLC_SUCCESS;
1387     return SaveConfigFile( p_this, 0, VLC_TRUE );
1388 }
1389
1390 int __config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
1391 {
1392     return SaveConfigFile( p_this, psz_module_name, VLC_FALSE );
1393 }
1394
1395 /*****************************************************************************
1396  * config_LoadCmdLine: parse command line
1397  *****************************************************************************
1398  * Parse command line for configuration options.
1399  * Now that the module_bank has been initialized, we can dynamically
1400  * generate the longopts structure used by getops. We have to do it this way
1401  * because we don't know (and don't want to know) in advance the configuration
1402  * options used (ie. exported) by each module.
1403  *****************************************************************************/
1404 int __config_LoadCmdLine( vlc_object_t *p_this, int *pi_argc,
1405                           const char *ppsz_argv[],
1406                           vlc_bool_t b_ignore_errors )
1407 {
1408     int i_cmd, i_index, i_opts, i_shortopts, flag, i_verbose = 0;
1409     module_t *p_parser;
1410     vlc_list_t *p_list;
1411     struct option *p_longopts;
1412     int i_modules_index;
1413
1414     /* Short options */
1415     module_config_t *pp_shortopts[256];
1416     char *psz_shortopts;
1417
1418     /* Set default configuration and copy arguments */
1419     p_this->p_libvlc->i_argc    = *pi_argc;
1420     p_this->p_libvlc->ppsz_argv = ppsz_argv;
1421
1422 #ifdef __APPLE__
1423     /* When VLC.app is run by double clicking in Mac OS X, the 2nd arg
1424      * is the PSN - process serial number (a unique PID-ish thingie)
1425      * still ok for real Darwin & when run from command line */
1426     if ( (*pi_argc > 1) && (strncmp( ppsz_argv[ 1 ] , "-psn" , 4 ) == 0) )
1427                                         /* for example -psn_0_9306113 */
1428     {
1429         /* GDMF!... I can't do this or else the MacOSX window server will
1430          * not pick up the PSN and not register the app and we crash...
1431          * hence the following kludge otherwise we'll get confused w/ argv[1]
1432          * being an input file name */
1433 #if 0
1434         ppsz_argv[ 1 ] = NULL;
1435 #endif
1436         *pi_argc = *pi_argc - 1;
1437         pi_argc--;
1438         return 0;
1439     }
1440 #endif
1441
1442     /* List all modules */
1443     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1444
1445     /*
1446      * Generate the longopts and shortopts structures used by getopt_long
1447      */
1448
1449     i_opts = 0;
1450     for( i_modules_index = 0; i_modules_index < p_list->i_count;
1451          i_modules_index++ )
1452     {
1453         p_parser = (module_t *)p_list->p_values[i_modules_index].p_object ;
1454
1455         /* count the number of exported configuration options (to allocate
1456          * longopts). We also need to allocate space for two options when
1457          * dealing with boolean to allow for --foo and --no-foo */
1458         i_opts += p_parser->i_config_items
1459                      + 2 * p_parser->i_bool_items;
1460     }
1461
1462     p_longopts = malloc( sizeof(struct option) * (i_opts + 1) );
1463     if( p_longopts == NULL )
1464     {
1465         msg_Err( p_this, "out of memory" );
1466         vlc_list_release( p_list );
1467         return -1;
1468     }
1469
1470     psz_shortopts = malloc( sizeof( char ) * (2 * i_opts + 1) );
1471     if( psz_shortopts == NULL )
1472     {
1473         msg_Err( p_this, "out of memory" );
1474         free( p_longopts );
1475         vlc_list_release( p_list );
1476         return -1;
1477     }
1478
1479     /* If we are requested to ignore errors, then we must work on a copy
1480      * of the ppsz_argv array, otherwise getopt_long will reorder it for
1481      * us, ignoring the arity of the options */
1482     if( b_ignore_errors )
1483     {
1484         ppsz_argv = (const char**)malloc( *pi_argc * sizeof(char *) );
1485         if( ppsz_argv == NULL )
1486         {
1487             msg_Err( p_this, "out of memory" );
1488             free( psz_shortopts );
1489             free( p_longopts );
1490             vlc_list_release( p_list );
1491             return -1;
1492         }
1493         memcpy( ppsz_argv, p_this->p_libvlc->ppsz_argv,
1494                 *pi_argc * sizeof(char *) );
1495     }
1496
1497     i_shortopts = 0;
1498     for( i_index = 0; i_index < 256; i_index++ )
1499     {
1500         pp_shortopts[i_index] = NULL;
1501     }
1502
1503     /* Fill the p_longopts and psz_shortopts structures */
1504     i_index = 0;
1505     for( i_modules_index = 0; i_modules_index < p_list->i_count;
1506          i_modules_index++ )
1507     {
1508         module_config_t *p_item, *p_end;
1509         p_parser = (module_t *)p_list->p_values[i_modules_index].p_object ;
1510
1511         if( !p_parser->i_config_items )
1512             continue;
1513
1514         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
1515              p_item < p_end;
1516              p_item++ )
1517         {
1518             /* Ignore hints */
1519             if( p_item->i_type & CONFIG_HINT )
1520                 continue;
1521
1522             /* Add item to long options */
1523             p_longopts[i_index].name = strdup( p_item->psz_name );
1524             if( p_longopts[i_index].name == NULL ) continue;
1525             p_longopts[i_index].has_arg =
1526                 (p_item->i_type == CONFIG_ITEM_BOOL)?
1527                                                no_argument : required_argument;
1528             p_longopts[i_index].flag = &flag;
1529             p_longopts[i_index].val = 0;
1530             i_index++;
1531
1532             /* When dealing with bools we also need to add the --no-foo
1533              * option */
1534             if( p_item->i_type == CONFIG_ITEM_BOOL )
1535             {
1536                 char *psz_name = malloc( strlen(p_item->psz_name) + 3 );
1537                 if( psz_name == NULL ) continue;
1538                 strcpy( psz_name, "no" );
1539                 strcat( psz_name, p_item->psz_name );
1540
1541                 p_longopts[i_index].name = psz_name;
1542                 p_longopts[i_index].has_arg = no_argument;
1543                 p_longopts[i_index].flag = &flag;
1544                 p_longopts[i_index].val = 1;
1545                 i_index++;
1546
1547                 psz_name = malloc( strlen(p_item->psz_name) + 4 );
1548                 if( psz_name == NULL ) continue;
1549                 strcpy( psz_name, "no-" );
1550                 strcat( psz_name, p_item->psz_name );
1551
1552                 p_longopts[i_index].name = psz_name;
1553                 p_longopts[i_index].has_arg = no_argument;
1554                 p_longopts[i_index].flag = &flag;
1555                 p_longopts[i_index].val = 1;
1556                 i_index++;
1557             }
1558
1559             /* If item also has a short option, add it */
1560             if( p_item->i_short )
1561             {
1562                 pp_shortopts[(int)p_item->i_short] = p_item;
1563                 psz_shortopts[i_shortopts] = p_item->i_short;
1564                 i_shortopts++;
1565                 if( p_item->i_type != CONFIG_ITEM_BOOL )
1566                 {
1567                     psz_shortopts[i_shortopts] = ':';
1568                     i_shortopts++;
1569
1570                     if( p_item->i_short == 'v' )
1571                     {
1572                         psz_shortopts[i_shortopts] = ':';
1573                         i_shortopts++;
1574                     }
1575                 }
1576             }
1577         }
1578     }
1579
1580     /* We don't need the module list anymore */
1581     vlc_list_release( p_list );
1582
1583     /* Close the longopts and shortopts structures */
1584     memset( &p_longopts[i_index], 0, sizeof(struct option) );
1585     psz_shortopts[i_shortopts] = '\0';
1586
1587     /*
1588      * Parse the command line options
1589      */
1590     opterr = 0;
1591     optind = 0; /* set to 0 to tell GNU getopt to reinitialize */
1592     while( ( i_cmd = getopt_long( *pi_argc, (char **)ppsz_argv, psz_shortopts,
1593                                   p_longopts, &i_index ) ) != -1 )
1594     {
1595         /* A long option has been recognized */
1596         if( i_cmd == 0 )
1597         {
1598             module_config_t *p_conf;
1599             char *psz_name = (char *)p_longopts[i_index].name;
1600
1601             /* Check if we deal with a --nofoo or --no-foo long option */
1602             if( flag ) psz_name += psz_name[2] == '-' ? 3 : 2;
1603
1604             /* Store the configuration option */
1605             p_conf = config_FindConfig( p_this, psz_name );
1606             if( p_conf )
1607             {
1608                 /* Check if the option is deprecated */
1609                 if( p_conf->psz_current )
1610                 {
1611                     if( p_conf->b_strict )
1612                     {
1613                         fprintf(stderr,
1614                                 "Warning: option --%s no longer exists.\n",
1615                                 p_conf->psz_name);
1616                        continue;
1617                     }
1618
1619                     fprintf( stderr,
1620                              "%s: option --%s is deprecated. Use --%s instead.\n",
1621                              b_ignore_errors ? "Warning" : "Error",
1622                              p_conf->psz_name, p_conf->psz_current);
1623                     if( !b_ignore_errors )
1624                     {
1625                         /*free */
1626                         for( i_index = 0; p_longopts[i_index].name; i_index++ )
1627                              free( (char *)p_longopts[i_index].name );
1628
1629                         free( p_longopts );
1630                         free( psz_shortopts );
1631                         return -1;
1632                     }
1633
1634                     psz_name = (char *)p_conf->psz_current;
1635                     p_conf = config_FindConfig( p_this, psz_name );
1636                 }
1637
1638                 switch( p_conf->i_type )
1639                 {
1640                     case CONFIG_ITEM_STRING:
1641                     case CONFIG_ITEM_PASSWORD:
1642                     case CONFIG_ITEM_FILE:
1643                     case CONFIG_ITEM_DIRECTORY:
1644                     case CONFIG_ITEM_MODULE:
1645                     case CONFIG_ITEM_MODULE_LIST:
1646                     case CONFIG_ITEM_MODULE_LIST_CAT:
1647                     case CONFIG_ITEM_MODULE_CAT:
1648                         config_PutPsz( p_this, psz_name, optarg );
1649                         break;
1650                     case CONFIG_ITEM_INTEGER:
1651                         config_PutInt( p_this, psz_name, strtol(optarg, 0, 0));
1652                         break;
1653                     case CONFIG_ITEM_FLOAT:
1654                         config_PutFloat( p_this, psz_name, (float)atof(optarg) );
1655                         break;
1656                     case CONFIG_ITEM_KEY:
1657                         config_PutInt( p_this, psz_name, ConfigStringToKey( optarg ) );
1658                         break;
1659                     case CONFIG_ITEM_BOOL:
1660                         config_PutInt( p_this, psz_name, !flag );
1661                         break;
1662                 }
1663                 continue;
1664             }
1665         }
1666
1667         /* A short option has been recognized */
1668         if( pp_shortopts[i_cmd] != NULL )
1669         {
1670             switch( pp_shortopts[i_cmd]->i_type )
1671             {
1672                 case CONFIG_ITEM_STRING:
1673                 case CONFIG_ITEM_PASSWORD:
1674                 case CONFIG_ITEM_FILE:
1675                 case CONFIG_ITEM_DIRECTORY:
1676                 case CONFIG_ITEM_MODULE:
1677                 case CONFIG_ITEM_MODULE_CAT:
1678                 case CONFIG_ITEM_MODULE_LIST:
1679                 case CONFIG_ITEM_MODULE_LIST_CAT:
1680                     config_PutPsz( p_this, pp_shortopts[i_cmd]->psz_name, optarg );
1681                     break;
1682                 case CONFIG_ITEM_INTEGER:
1683                     if( i_cmd == 'v' )
1684                     {
1685                         if( optarg )
1686                         {
1687                             if( *optarg == 'v' ) /* eg. -vvv */
1688                             {
1689                                 i_verbose++;
1690                                 while( *optarg == 'v' )
1691                                 {
1692                                     i_verbose++;
1693                                     optarg++;
1694                                 }
1695                             }
1696                             else
1697                             {
1698                                 i_verbose += atoi( optarg ); /* eg. -v2 */
1699                             }
1700                         }
1701                         else
1702                         {
1703                             i_verbose++; /* -v */
1704                         }
1705                         config_PutInt( p_this, pp_shortopts[i_cmd]->psz_name,
1706                                                i_verbose );
1707                     }
1708                     else
1709                     {
1710                         config_PutInt( p_this, pp_shortopts[i_cmd]->psz_name,
1711                                                strtol(optarg, 0, 0) );
1712                     }
1713                     break;
1714                 case CONFIG_ITEM_BOOL:
1715                     config_PutInt( p_this, pp_shortopts[i_cmd]->psz_name, 1 );
1716                     break;
1717             }
1718
1719             continue;
1720         }
1721
1722         /* Internal error: unknown option */
1723         if( !b_ignore_errors )
1724         {
1725             fprintf( stderr, "%s: unknown option"
1726                      " or missing mandatory argument ",
1727                      p_this->p_libvlc->psz_object_name );
1728             if( optopt )
1729             {
1730                 fprintf( stderr, "`-%c'\n", optopt );
1731             }
1732             else
1733             {
1734                 fprintf( stderr, "`%s'\n", ppsz_argv[optind-1] );
1735             }
1736             fprintf( stderr, "Try `%s --help' for more information.\n",
1737                              p_this->p_libvlc->psz_object_name );
1738
1739             for( i_index = 0; p_longopts[i_index].name; i_index++ )
1740                 free( (char *)p_longopts[i_index].name );
1741             free( p_longopts );
1742             free( psz_shortopts );
1743             return -1;
1744         }
1745     }
1746
1747     /* Free allocated resources */
1748     for( i_index = 0; p_longopts[i_index].name; i_index++ )
1749         free( (char *)p_longopts[i_index].name );
1750     free( p_longopts );
1751     free( psz_shortopts );
1752     if( b_ignore_errors ) free( ppsz_argv );
1753
1754     return 0;
1755 }
1756
1757 /**
1758  * config_GetDataDir: find directory where shared data is installed
1759  *
1760  * @return a string (always succeeds).
1761  */
1762 const char *config_GetDataDir( void )
1763 {
1764 #if defined (WIN32) || defined (UNDER_CE)
1765     return vlc_global()->psz_vlcpath;
1766 #elif defined(__APPLE__) || defined (SYS_BEOS)
1767     static char path[PATH_MAX] = "";
1768
1769     if( *path == '\0' )
1770     {
1771         snprintf( path, sizeof( path ), "%s/share",
1772                   vlc_global()->psz_vlcpath );
1773         path[sizeof( path ) - 1] = '\0';
1774     }
1775     return path;
1776 #else
1777     return DATA_PATH;
1778 #endif
1779 }
1780
1781 /*****************************************************************************
1782  * config_GetHomeDir, config_GetUserDir: find the user's home directory.
1783  *****************************************************************************
1784  * This function will try by different ways to find the user's home path.
1785  * Note that this function is not reentrant, it should be called only once
1786  * at the beginning of main where the result will be stored for later use.
1787  *****************************************************************************/
1788 static char *GetDir( vlc_bool_t b_appdata )
1789 {
1790     const char *psz_localhome = NULL;
1791
1792 #if defined(WIN32) && !defined(UNDER_CE)
1793     typedef HRESULT (WINAPI *SHGETFOLDERPATH)( HWND, int, HANDLE, DWORD,
1794                                                LPWSTR );
1795 #ifndef CSIDL_FLAG_CREATE
1796 #   define CSIDL_FLAG_CREATE 0x8000
1797 #endif
1798 #ifndef CSIDL_APPDATA
1799 #   define CSIDL_APPDATA 0x1A
1800 #endif
1801 #ifndef CSIDL_PROFILE
1802 #   define CSIDL_PROFILE 0x28
1803 #endif
1804 #ifndef SHGFP_TYPE_CURRENT
1805 #   define SHGFP_TYPE_CURRENT 0
1806 #endif
1807
1808     HINSTANCE shfolder_dll;
1809     SHGETFOLDERPATH SHGetFolderPath ;
1810
1811     /* load the shfolder dll to retrieve SHGetFolderPath */
1812     if( ( shfolder_dll = LoadLibrary( _T("SHFolder.dll") ) ) != NULL )
1813     {
1814         SHGetFolderPath = (void *)GetProcAddress( shfolder_dll,
1815                                                   _T("SHGetFolderPathW") );
1816         if ( SHGetFolderPath != NULL )
1817         {
1818             wchar_t whomedir[MAX_PATH];
1819
1820             /* get the "Application Data" folder for the current user */
1821             if( S_OK == SHGetFolderPath( NULL,
1822                                          (b_appdata ? CSIDL_APPDATA :
1823                                            CSIDL_PROFILE) | CSIDL_FLAG_CREATE,
1824                                          NULL, SHGFP_TYPE_CURRENT,
1825                                          whomedir ) )
1826             {
1827                 FreeLibrary( shfolder_dll );
1828                 return FromWide( whomedir );
1829             }
1830         }
1831         FreeLibrary( shfolder_dll );
1832     }
1833
1834 #elif defined(UNDER_CE)
1835
1836 #ifndef CSIDL_APPDATA
1837 #   define CSIDL_APPDATA 0x1A
1838 #endif
1839
1840     wchar_t whomedir[MAX_PATH];
1841
1842     /* get the "Application Data" folder for the current user */
1843     if( SHGetSpecialFolderPath( NULL, whomedir, CSIDL_APPDATA, 1 ) )
1844         return FromWide( whomedir );
1845 #endif
1846
1847     psz_localhome = getenv( "HOME" );
1848     if( psz_localhome == NULL )
1849     {
1850 #if defined(HAVE_GETPWUID)
1851         struct passwd *p_pw;
1852         (void)b_appdata;
1853
1854         if( ( p_pw = getpwuid( getuid() ) ) != NULL )
1855             psz_localhome = p_pw->pw_dir;
1856         else
1857 #endif
1858         {
1859             psz_localhome = getenv( "TMP" );
1860             if( psz_localhome == NULL )
1861                 psz_localhome = "/tmp";
1862         }
1863     }
1864
1865     return FromLocaleDup( psz_localhome );
1866 }
1867
1868 /**
1869  * Get the user's home directory
1870  */
1871 char *config_GetHomeDir( void )
1872 {
1873     return GetDir( VLC_FALSE );
1874 }
1875
1876 /**
1877  * Get the user's main data and config directory:
1878  *   - on windows that's the App Data directory;
1879  *   - on other OSes it's the same as the home directory.
1880  */
1881 char *config_GetUserDir( void );
1882 char *config_GetUserDir( void )
1883 {
1884     return GetDir( VLC_TRUE );
1885 }
1886
1887 /**
1888  * Get the user's VLC configuration directory
1889  */
1890 char *config_GetConfigDir( libvlc_int_t *p_libvlc )
1891 {
1892     char *psz_dir;
1893 #if defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS)
1894     char *psz_parent = config_GetUserDir();
1895     if( !psz_parent ) psz_parent = p_libvlc->psz_homedir;
1896     if( asprintf( &psz_dir, "%s" DIR_SEP CONFIG_DIR, psz_parent ) == -1 )
1897         return NULL;
1898     return psz_dir;
1899 #else
1900     /* XDG Base Directory Specification - Version 0.6 */
1901     char *psz_env = getenv( "XDG_CONFIG_HOME" );
1902     if( psz_env )
1903     {
1904         if( asprintf( &psz_dir, "%s/vlc", psz_env ) == -1 )
1905             return NULL;
1906         return psz_dir;
1907     }
1908     psz_env = getenv( "HOME" );
1909     if( !psz_env ) psz_env = p_libvlc->psz_homedir; /* not part of XDG spec but we want a sensible fallback */
1910     if( asprintf( &psz_dir, "%s/.config/vlc", psz_env ) == -1 )
1911         return NULL;
1912     return psz_dir;
1913 #endif
1914 }
1915
1916 /**
1917  * Get the user's VLC data directory
1918  * (used for stuff like the skins, custom lua modules, ...)
1919  */
1920 char *config_GetUserDataDir( libvlc_int_t *p_libvlc )
1921 {
1922     char *psz_dir;
1923 #if defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS)
1924     char *psz_parent = config_GetUserDir();
1925     if( !psz_parent ) psz_parent = p_libvlc->psz_homedir;
1926     if( asprintf( &psz_dir, "%s" DIR_SEP CONFIG_DIR, psz_parent ) == -1 )
1927         return NULL;
1928     return psz_dir;
1929 #else
1930     /* XDG Base Directory Specification - Version 0.6 */
1931     char *psz_env = getenv( "XDG_DATA_HOME" );
1932     if( psz_env )
1933     {
1934         if( asprintf( &psz_dir, "%s/vlc", psz_env ) == -1 )
1935             return NULL;
1936         return psz_dir;
1937     }
1938     psz_env = getenv( "HOME" );
1939     if( !psz_env ) psz_env = p_libvlc->psz_homedir; /* not part of XDG spec but we want a sensible fallback */
1940     if( asprintf( &psz_dir, "%s/.local/share/vlc", psz_env ) == -1 )
1941         return NULL;
1942     return psz_dir;
1943 #endif
1944 }
1945
1946 /**
1947  * Get the user's VLC cache directory
1948  * (used for stuff like the modules cache, the album art cache, ...)
1949  */
1950 char *config_GetCacheDir( libvlc_int_t *p_libvlc )
1951 {
1952     char *psz_dir;
1953 #if defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS)
1954     char *psz_parent = config_GetUserDir();
1955     if( !psz_parent ) psz_parent = p_libvlc->psz_homedir;
1956     if( asprintf( &psz_dir, "%s" DIR_SEP CONFIG_DIR, psz_parent ) == -1 )
1957         return NULL;
1958     return psz_dir;
1959 #else
1960     /* XDG Base Directory Specification - Version 0.6 */
1961     char *psz_env = getenv( "XDG_CACHE_HOME" );
1962     if( psz_env )
1963     {
1964         if( asprintf( &psz_dir, "%s/vlc", psz_env ) == -1 )
1965             return NULL;
1966         return psz_dir;
1967     }
1968     psz_env = getenv( "HOME" );
1969     if( !psz_env ) psz_env = p_libvlc->psz_homedir; /* not part of XDG spec but we want a sensible fallback */
1970     if( asprintf( &psz_dir, "%s/.cache/vlc", psz_env ) == -1 )
1971         return NULL;
1972     return psz_dir;
1973 #endif
1974 }
1975
1976 /**
1977  * Get the user's configuration file
1978  */
1979 char *config_GetConfigFile( libvlc_int_t *p_libvlc )
1980 {
1981     char *psz_configfile;
1982     if( asprintf( &psz_configfile, "%s" DIR_SEP CONFIG_FILE,
1983                   p_libvlc->psz_configdir ) == -1 )
1984         return NULL;
1985     return psz_configfile;
1986 }
1987
1988 /**
1989  * Get the user's configuration file when given with the --config option
1990  */
1991 char *config_GetCustomConfigFile( libvlc_int_t *p_libvlc )
1992 {
1993     char *psz_configfile = config_GetPsz( p_libvlc, "config" );
1994     if( psz_configfile != NULL )
1995     {
1996         if( psz_configfile[0] == '~' && psz_configfile[1] == '/' )
1997         {
1998             /* This is incomplete: we should also support the ~cmassiot/ syntax */
1999             char *psz_buf;
2000             if( asprintf( &psz_buf, "%s/%s", p_libvlc->psz_homedir,
2001                           psz_configfile + 2 ) == -1 )
2002             {
2003                 free( psz_configfile );
2004                 return NULL;
2005             }
2006             free( psz_configfile );
2007             psz_configfile = psz_buf;
2008         }
2009     }
2010     return psz_configfile;
2011 }
2012
2013 static int ConfigStringToKey( const char *psz_key )
2014 {
2015     int i_key = 0;
2016     unsigned int i;
2017     const char *psz_parser = strchr( psz_key, '-' );
2018     while( psz_parser && psz_parser != psz_key )
2019     {
2020         for( i = 0; i < sizeof(vlc_modifiers) / sizeof(key_descriptor_t); i++ )
2021         {
2022             if( !strncasecmp( vlc_modifiers[i].psz_key_string, psz_key,
2023                               strlen( vlc_modifiers[i].psz_key_string ) ) )
2024             {
2025                 i_key |= vlc_modifiers[i].i_key_code;
2026             }
2027         }
2028         psz_key = psz_parser + 1;
2029         psz_parser = strchr( psz_key, '-' );
2030     }
2031     for( i = 0; i < sizeof(vlc_keys) / sizeof( key_descriptor_t ); i++ )
2032     {
2033         if( !strcasecmp( vlc_keys[i].psz_key_string, psz_key ) )
2034         {
2035             i_key |= vlc_keys[i].i_key_code;
2036             break;
2037         }
2038     }
2039     return i_key;
2040 }
2041
2042 static char *ConfigKeyToString( int i_key )
2043 {
2044     char *psz_key = malloc( 100 );
2045     char *p;
2046     size_t index;
2047
2048     if ( !psz_key )
2049     {
2050         return NULL;
2051     }
2052     *psz_key = '\0';
2053     p = psz_key;
2054     for( index = 0; index < (sizeof(vlc_modifiers) / sizeof(key_descriptor_t));
2055          index++ )
2056     {
2057         if( i_key & vlc_modifiers[index].i_key_code )
2058         {
2059             p += sprintf( p, "%s-", vlc_modifiers[index].psz_key_string );
2060         }
2061     }
2062     for( index = 0; index < (sizeof(vlc_keys) / sizeof( key_descriptor_t));
2063          index++)
2064     {
2065         if( (int)( i_key & ~KEY_MODIFIER ) == vlc_keys[index].i_key_code )
2066         {
2067             p += sprintf( p, "%s", vlc_keys[index].psz_key_string );
2068             break;
2069         }
2070     }
2071     return psz_key;
2072 }