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