]> git.sesse.net Git - vlc/blob - src/config/file.c
Tilde expansion is the shell's job. Don't do it *too* (= twice).
[vlc] / src / config / file.c
1 /*****************************************************************************
2  * file.c: configuration file handling
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 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <vlc_common.h>
29 #include "../libvlc.h"
30 #include "vlc_charset.h"
31 #include "vlc_keys.h"
32
33 #include <errno.h>                                                  /* errno */
34 #include <assert.h>
35 #include <limits.h>
36 #ifdef __APPLE__
37 #   include <xlocale.h>
38 #else
39 #include <locale.h>
40 #endif
41
42 #include "configuration.h"
43 #include "modules/modules.h"
44
45 static char *ConfigKeyToString( int );
46
47 static inline char *strdupnull (const char *src)
48 {
49     return src ? strdup (src) : NULL;
50 }
51
52 /**
53  * Get the user's configuration file
54  */
55 static char *config_GetConfigFile( void )
56 {
57     char *psz_dir = config_GetUserConfDir();
58     char *psz_configfile;
59
60     if( asprintf( &psz_configfile, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
61         psz_configfile = NULL;
62     free( psz_dir );
63     return psz_configfile;
64 }
65
66 static FILE *config_OpenConfigFile( vlc_object_t *p_obj, const char *mode )
67 {
68     char *psz_filename = config_GetPsz( p_obj, "config" );
69     if( !psz_filename )
70         psz_filename = config_GetConfigFile();
71
72     msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
73
74     FILE *p_stream = utf8_fopen( psz_filename, mode );
75     if( p_stream == NULL && errno != ENOENT )
76     {
77         msg_Err( p_obj, "cannot open config file (%s): %m",
78                  psz_filename );
79
80     }
81 #if !( defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS) )
82     else if( p_stream == NULL && errno == ENOENT && mode[0] == 'r' )
83     {
84         /* This is the fallback for pre XDG Base Directory
85          * Specification configs */
86         char *psz_old;
87         if( asprintf( &psz_old, "%s" DIR_SEP CONFIG_DIR DIR_SEP CONFIG_FILE,
88                       config_GetHomeDir() ) != -1 )
89         {
90             p_stream = utf8_fopen( psz_old, mode );
91             if( p_stream )
92             {
93                 /* Old config file found. We want to write it at the
94                  * new location now. */
95                 msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
96                           "VLC will now use %s.", psz_old, psz_filename );
97                 char *psz_readme;
98                 if( asprintf(&psz_readme,"%s"DIR_SEP CONFIG_DIR DIR_SEP"README",
99                               config_GetHomeDir() ) != -1 )
100                 {
101                     FILE *p_readme = utf8_fopen( psz_readme, "wt" );
102                     if( p_readme )
103                     {
104                         fprintf( p_readme, "The VLC media player "
105                                  "configuration folder has moved to comply\n"
106                                  "with the XDG Base Directory Specification "
107                                  "version 0.6. Your\nconfiguration has been "
108                                  "copied to the new location:\n%s\nYou can "
109                                  "delete this directory and all its contents.",
110                                   psz_filename);
111                         fclose( p_readme );
112                     }
113                     free( psz_readme );
114                 }
115             }
116             free( psz_old );
117         }
118     }
119 #endif
120     return p_stream;
121 }
122
123
124 static int strtoi (const char *str)
125 {
126     char *end;
127     long l;
128
129     errno = 0;
130     l = strtol (str, &end, 0);
131
132     if (!errno)
133     {
134         if ((l > INT_MAX) || (l < INT_MIN))
135             errno = ERANGE;
136         if (*end)
137             errno = EINVAL;
138     }
139     return (int)l;
140 }
141
142
143 /*****************************************************************************
144  * config_LoadConfigFile: loads the configuration file.
145  *****************************************************************************
146  * This function is called to load the config options stored in the config
147  * file.
148  *****************************************************************************/
149 int __config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
150 {
151     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
152     FILE *file;
153
154     file = config_OpenConfigFile (p_this, "rt");
155     if (file == NULL)
156         return VLC_EGENERIC;
157
158     /* Acquire config file lock */
159     vlc_mutex_lock( &priv->config_lock );
160
161     /* Look for the selected module, if NULL then save everything */
162     module_t **list = module_list_get (NULL);
163
164     /* Look for UTF-8 Byte Order Mark */
165     char * (*convert) (const char *) = strdupnull;
166     char bom[3];
167
168     if ((fread (bom, 1, 3, file) != 3)
169      || memcmp (bom, "\xEF\xBB\xBF", 3))
170     {
171         convert = FromLocaleDup;
172         rewind (file); /* no BOM, rewind */
173     }
174
175     module_t *module = NULL;
176     char line[1024], section[1022];
177     section[0] = '\0';
178
179     /* Ensure consistent number formatting... */
180     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
181     locale_t baseloc = uselocale (loc);
182
183     while (fgets (line, 1024, file) != NULL)
184     {
185         /* Ignore comments and empty lines */
186         switch (line[0])
187         {
188             case '#':
189             case '\n':
190             case '\0':
191                 continue;
192         }
193
194         if (line[0] == '[')
195         {
196             char *ptr = strchr (line, ']');
197             if (ptr == NULL)
198                 continue; /* syntax error; */
199             *ptr = '\0';
200
201             /* New section ( = a given module) */
202             strcpy (section, line + 1);
203             module = NULL;
204
205             if ((psz_module_name == NULL)
206              || (strcmp (psz_module_name, section) == 0))
207             {
208                 for (int i = 0; list[i]; i++)
209                 {
210                     module_t *m = list[i];
211
212                     if ((strcmp (section, m->psz_object_name) == 0)
213                      && (m->i_config_items > 0)) /* ignore config-less modules */
214                     {
215                         module = m;
216                         if (psz_module_name != NULL)
217                             msg_Dbg (p_this,
218                                      "loading config for module \"%s\"",
219                                      section);
220                         break;
221                     }
222                 }
223             }
224
225             continue;
226         }
227
228         if (module == NULL)
229             continue; /* no need to parse if there is no matching module */
230
231         char *ptr = strchr (line, '\n');
232         if (ptr != NULL)
233             *ptr = '\0';
234
235         /* look for option name */
236         const char *psz_option_name = line;
237
238         ptr = strchr (line, '=');
239         if (ptr == NULL)
240             continue; /* syntax error */
241
242         *ptr = '\0';
243         const char *psz_option_value = ptr + 1;
244
245         /* try to match this option with one of the module's options */
246         for (size_t i = 0; i < module->confsize; i++)
247         {
248             module_config_t *p_item = module->p_config + i;
249
250             if ((p_item->i_type & CONFIG_HINT)
251              || strcmp (p_item->psz_name, psz_option_name))
252                 continue;
253
254             /* We found it */
255             errno = 0;
256
257             switch( p_item->i_type )
258             {
259                 case CONFIG_ITEM_BOOL:
260                 case CONFIG_ITEM_INTEGER:
261                 {
262                     long l = strtoi (psz_option_value);
263                     if (errno)
264                         msg_Warn (p_this, "Integer value (%s) for %s: %m",
265                                   psz_option_value, psz_option_name);
266                     else
267                         p_item->saved.i = p_item->value.i = (int)l;
268                     break;
269                 }
270
271                 case CONFIG_ITEM_FLOAT:
272                     if( !*psz_option_value )
273                         break;                    /* ignore empty option */
274                     p_item->value.f = (float)atof (psz_option_value);
275                     p_item->saved.f = p_item->value.f;
276                     break;
277
278                 case CONFIG_ITEM_KEY:
279                     if( !*psz_option_value )
280                         break;                    /* ignore empty option */
281                     p_item->value.i = ConfigStringToKey(psz_option_value);
282                     p_item->saved.i = p_item->value.i;
283                     break;
284
285                 default:
286                     vlc_mutex_lock( p_item->p_lock );
287
288                     /* free old string */
289                     free( (char*) p_item->value.psz );
290                     free( (char*) p_item->saved.psz );
291
292                     p_item->value.psz = convert (psz_option_value);
293                     p_item->saved.psz = strdupnull (p_item->value.psz);
294
295                     vlc_mutex_unlock( p_item->p_lock );
296                     break;
297             }
298
299             break;
300         }
301     }
302
303     if (ferror (file))
304     {
305         msg_Err (p_this, "error reading configuration: %m");
306         clearerr (file);
307     }
308     fclose (file);
309
310     module_list_free (list);
311     if (loc != (locale_t)0)
312     {
313         uselocale (baseloc);
314         freelocale (loc);
315     }
316
317     vlc_mutex_unlock( &priv->config_lock );
318     return 0;
319 }
320
321 /*****************************************************************************
322  * config_CreateDir: Create configuration directory if it doesn't exist.
323  *****************************************************************************/
324 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
325 {
326     if( !psz_dirname || !*psz_dirname ) return -1;
327
328     if( utf8_mkdir( psz_dirname, 0700 ) == 0 )
329         return 0;
330
331     switch( errno )
332     {
333         case EEXIST:
334             return 0;
335
336         case ENOENT:
337         {
338             /* Let's try to create the parent directory */
339             char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
340             strcpy( psz_parent, psz_dirname );
341
342             psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
343             if( psz_end && psz_end != psz_parent )
344             {
345                 *psz_end = '\0';
346                 if( config_CreateDir( p_this, psz_parent ) == 0 )
347                 {
348                     if( !utf8_mkdir( psz_dirname, 0700 ) )
349                         return 0;
350                 }
351             }
352         }
353     }
354
355     msg_Err( p_this, "could not create %s: %m", psz_dirname );
356     return -1;
357 }
358
359 static int
360 config_Write (FILE *file, const char *type, const char *desc,
361               bool comment, const char *name, const char *fmt, ...)
362 {
363     va_list ap;
364     int ret;
365
366     if (desc == NULL)
367         desc = "?";
368
369     if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
370                  comment ? "#" : "", name) < 0)
371         return -1;
372
373     va_start (ap, fmt);
374     ret = vfprintf (file, fmt, ap);
375     va_end (ap);
376     if (ret < 0)
377         return -1;
378
379     if (fputs ("\n\n", file) == EOF)
380         return -1;
381     return 0;
382 }
383
384
385 static int config_PrepareDir (vlc_object_t *obj)
386 {
387     char *psz_configdir = config_GetUserConfDir ();
388     if (psz_configdir == NULL) /* XXX: This should never happen */
389         return -1;
390
391     int ret = config_CreateDir (obj, psz_configdir);
392     free (psz_configdir);
393     return ret;
394 }
395
396 /*****************************************************************************
397  * config_SaveConfigFile: Save a module's config options.
398  *****************************************************************************
399  * This will save the specified module's config options to the config file.
400  * If psz_module_name is NULL then we save all the modules config options.
401  * It's no use to save the config options that kept their default values, so
402  * we'll try to be a bit clever here.
403  *
404  * When we save we mustn't delete the config options of the modules that
405  * haven't been loaded. So we cannot just create a new config file with the
406  * config structures we've got in memory.
407  * I don't really know how to deal with this nicely, so I will use a completly
408  * dumb method ;-)
409  * I will load the config file in memory, but skipping all the sections of the
410  * modules we want to save. Then I will create a brand new file, dump the file
411  * loaded in memory and then append the sections of the modules we want to
412  * save.
413  * Really stupid no ?
414  *****************************************************************************/
415 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
416                            bool b_autosave )
417 {
418     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
419     module_t *p_parser;
420     FILE *file;
421     char p_line[1024], *p_index2;
422     int i_sizebuf = 0;
423     char *p_bigbuffer, *p_index;
424     bool b_backup;
425     int i_index;
426
427     /* Acquire config file lock */
428     vlc_mutex_lock( &priv->config_lock );
429
430     if( config_PrepareDir( p_this ) )
431     {
432         msg_Err( p_this, "no configuration directory" );
433         vlc_mutex_unlock( &priv->config_lock );
434         return -1;
435     }
436
437     file = config_OpenConfigFile( p_this, "rt" );
438     if( file != NULL )
439     {
440         /* look for file size */
441         fseek( file, 0L, SEEK_END );
442         i_sizebuf = ftell( file );
443         fseek( file, 0L, SEEK_SET );
444     }
445
446     p_bigbuffer = p_index = malloc( i_sizebuf+1 );
447     if( !p_bigbuffer )
448     {
449         if( file ) fclose( file );
450         vlc_mutex_unlock( &priv->config_lock );
451         return -1;
452     }
453     p_bigbuffer[0] = 0;
454
455     /* List all available modules */
456     module_t **list = module_list_get (NULL);
457
458     /* backup file into memory, we only need to backup the sections we won't
459      * save later on */
460     b_backup = 0;
461     while( file && fgets( p_line, 1024, file ) )
462     {
463         if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
464         {
465
466             /* we found a section, check if we need to do a backup */
467             for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
468             {
469                 if( ((p_index2 - &p_line[1])
470                        == (int)strlen(p_parser->psz_object_name) )
471                     && !memcmp( &p_line[1], p_parser->psz_object_name,
472                                 strlen(p_parser->psz_object_name) ) )
473                 {
474                     if( !psz_module_name )
475                         break;
476                     else if( !strcmp( psz_module_name,
477                                       p_parser->psz_object_name ) )
478                         break;
479                 }
480             }
481
482             if( list[i_index] == NULL )
483             {
484                 /* we don't have this section in our list so we need to back
485                  * it up */
486                 *p_index2 = 0;
487 #if 0
488                 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
489                                  &p_line[1] );
490 #endif
491                 *p_index2 = ']';
492
493                 b_backup = 1;
494             }
495             else
496             {
497                 b_backup = 0;
498             }
499         }
500
501         /* save line if requested and line is valid (doesn't begin with a
502          * space, tab, or eol) */
503         if( b_backup && (p_line[0] != '\n') && (p_line[0] != ' ')
504             && (p_line[0] != '\t') )
505         {
506             strcpy( p_index, p_line );
507             p_index += strlen( p_line );
508         }
509     }
510     if( file ) fclose( file );
511
512
513     /*
514      * Save module config in file
515      */
516
517     file = config_OpenConfigFile (p_this, "wt");
518     if( !file )
519     {
520         module_list_free (list);
521         free( p_bigbuffer );
522         vlc_mutex_unlock( &priv->config_lock );
523         return -1;
524     }
525
526     fprintf( file, "\xEF\xBB\xBF###\n###  " COPYRIGHT_MESSAGE "\n###\n\n"
527        "###\n### lines beginning with a '#' character are comments\n###\n\n" );
528
529     /* Ensure consistent number formatting... */
530     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
531     locale_t baseloc = uselocale (loc);
532
533     /* Look for the selected module, if NULL then save everything */
534     for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
535     {
536         module_config_t *p_item, *p_end;
537
538         if( psz_module_name && strcmp( psz_module_name,
539                                        p_parser->psz_object_name ) )
540             continue;
541
542         if( !p_parser->i_config_items )
543             continue;
544
545         if( psz_module_name )
546             msg_Dbg( p_this, "saving config for module \"%s\"",
547                      p_parser->psz_object_name );
548
549         fprintf( file, "[%s]", p_parser->psz_object_name );
550         if( p_parser->psz_longname )
551             fprintf( file, " # %s\n\n", p_parser->psz_longname );
552         else
553             fprintf( file, "\n\n" );
554
555         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
556              p_item < p_end;
557              p_item++ )
558         {
559             /* Do not save the new value in the configuration file
560              * if doing an autosave, and the item is not an "autosaved" one. */
561             bool b_retain = b_autosave && !p_item->b_autosave;
562
563             if ((p_item->i_type & CONFIG_HINT) /* ignore hint */
564              || p_item->b_removed              /* ignore deprecated option */
565              || p_item->b_unsaveable)          /* ignore volatile option */
566                 continue;
567
568             if (IsConfigIntegerType (p_item->i_type))
569             {
570                 int val = b_retain ? p_item->saved.i : p_item->value.i;
571                 if (p_item->i_type == CONFIG_ITEM_KEY)
572                 {
573                     char *psz_key = ConfigKeyToString (val);
574                     config_Write (file, p_item->psz_text, N_("key"),
575                                   val == p_item->orig.i,
576                                   p_item->psz_name, "%s",
577                                   psz_key ? psz_key : "");
578                     free (psz_key);
579                 }
580                 else
581                     config_Write (file, p_item->psz_text,
582                                   (p_item->i_type == CONFIG_ITEM_BOOL)
583                                       ? N_("boolean") : N_("integer"),
584                                   val == p_item->orig.i,
585                                   p_item->psz_name, "%d", val);
586                 p_item->saved.i = val;
587             }
588             else
589             if (IsConfigFloatType (p_item->i_type))
590             {
591                 float val = b_retain ? p_item->saved.f : p_item->value.f;
592                 config_Write (file, p_item->psz_text, N_("float"),
593                               val == p_item->orig.f,
594                               p_item->psz_name, "%f", val);
595                 p_item->saved.f = val;
596             }
597             else
598             {
599                 const char *psz_value = b_retain ? p_item->saved.psz
600                                                  : p_item->value.psz;
601                 bool modified;
602
603                 assert (IsConfigStringType (p_item->i_type));
604
605                 if (b_retain && (psz_value == NULL)) /* FIXME: hack */
606                     psz_value = p_item->orig.psz;
607
608                 modified =
609                     (psz_value != NULL)
610                         ? ((p_item->orig.psz != NULL)
611                             ? (strcmp (psz_value, p_item->orig.psz) != 0)
612                             : true)
613                         : (p_item->orig.psz != NULL);
614
615                 config_Write (file, p_item->psz_text, N_("string"),
616                               !modified, p_item->psz_name, "%s",
617                               psz_value ? psz_value : "");
618
619                 if ( !b_retain )
620                 {
621
622                     free ((char *)p_item->saved.psz);
623                     if( (psz_value && p_item->orig.psz &&
624                          strcmp( psz_value, p_item->orig.psz )) ||
625                         !psz_value || !p_item->orig.psz)
626                         p_item->saved.psz = strdupnull (psz_value);
627                     else
628                         p_item->saved.psz = NULL;
629                 }
630             }
631
632             if (!b_retain)
633                 p_item->b_dirty = false;
634         }
635     }
636
637     module_list_free (list);
638     if (loc != (locale_t)0)
639     {
640         uselocale (baseloc);
641         freelocale (loc);
642     }
643
644     /*
645      * Restore old settings from the config in file
646      */
647     fputs( p_bigbuffer, file );
648     free( p_bigbuffer );
649
650     fclose( file );
651     vlc_mutex_unlock( &priv->config_lock );
652
653     return 0;
654 }
655
656 int config_AutoSaveConfigFile( vlc_object_t *p_this )
657 {
658     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
659     size_t i_index;
660     bool done;
661
662     assert( p_this );
663
664     /* Check if there's anything to save */
665     vlc_mutex_lock( &priv->config_lock );
666     module_t **list = module_list_get (NULL);
667     for( i_index = 0; list[i_index]; i_index++ )
668     {
669         module_t *p_parser = list[i_index];
670         module_config_t *p_item, *p_end;
671
672         if( !p_parser->i_config_items ) continue;
673
674         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
675              p_item < p_end;
676              p_item++ )
677         {
678             if( p_item->b_autosave && p_item->b_dirty ) break;
679         }
680         if( p_item < p_end ) break;
681     }
682     done = list[i_index] == NULL;
683     module_list_free (list);
684     vlc_mutex_unlock( &priv->config_lock );
685
686     return done ? VLC_SUCCESS : SaveConfigFile( p_this, NULL, true );
687 }
688
689 int __config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
690 {
691     return SaveConfigFile( p_this, psz_module_name, false );
692 }
693
694 int ConfigStringToKey( const char *psz_key )
695 {
696     int i_key = 0;
697     unsigned int i;
698     const char *psz_parser = strchr( psz_key, '-' );
699     while( psz_parser && psz_parser != psz_key )
700     {
701         for( i = 0; i < sizeof(vlc_modifiers) / sizeof(key_descriptor_t); i++ )
702         {
703             if( !strncasecmp( vlc_modifiers[i].psz_key_string, psz_key,
704                               strlen( vlc_modifiers[i].psz_key_string ) ) )
705             {
706                 i_key |= vlc_modifiers[i].i_key_code;
707             }
708         }
709         psz_key = psz_parser + 1;
710         psz_parser = strchr( psz_key, '-' );
711     }
712     for( i = 0; i < sizeof(vlc_keys) / sizeof( key_descriptor_t ); i++ )
713     {
714         if( !strcasecmp( vlc_keys[i].psz_key_string, psz_key ) )
715         {
716             i_key |= vlc_keys[i].i_key_code;
717             break;
718         }
719     }
720     return i_key;
721 }
722
723 char *ConfigKeyToString( int i_key )
724 {
725     char *psz_key = malloc( 100 );
726     char *p;
727     size_t index;
728
729     if ( !psz_key )
730     {
731         return NULL;
732     }
733     *psz_key = '\0';
734     p = psz_key;
735
736     for( index = 0; index < (sizeof(vlc_modifiers) / sizeof(key_descriptor_t));
737          index++ )
738     {
739         if( i_key & vlc_modifiers[index].i_key_code )
740         {
741             p += sprintf( p, "%s-", vlc_modifiers[index].psz_key_string );
742         }
743     }
744     for( index = 0; index < (sizeof(vlc_keys) / sizeof( key_descriptor_t));
745          index++)
746     {
747         if( (int)( i_key & ~KEY_MODIFIER ) == vlc_keys[index].i_key_code )
748         {
749             p += sprintf( p, "%s", vlc_keys[index].psz_key_string );
750             break;
751         }
752     }
753     return psz_key;
754 }
755