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