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