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