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