1 /*****************************************************************************
2 * file.c: configuration file handling
3 *****************************************************************************
4 * Copyright (C) 2001-2007 the VideoLAN team
7 * Authors: Gildas Bazin <gbazin@videolan.org>
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.
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.
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 *****************************************************************************/
28 #include <errno.h> /* errno */
35 #elif defined(HAVE_USELOCALE)
39 #include <vlc_common.h>
40 #include "../libvlc.h"
41 #include "vlc_charset.h"
44 #include "configuration.h"
45 #include "modules/modules.h"
47 static inline char *strdupnull (const char *src)
49 return src ? strdup (src) : NULL;
53 * Get the user's configuration file
55 static char *config_GetConfigFile( vlc_object_t *obj )
57 char *psz_file = var_CreateGetNonEmptyString( obj, "config" );
58 var_Destroy( obj, "config" );
59 if( psz_file == NULL )
61 char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
63 if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
70 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
72 char *psz_filename = config_GetConfigFile( p_obj );
73 if( psz_filename == NULL )
76 msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
78 FILE *p_stream = utf8_fopen( psz_filename, "rt" );
79 if( p_stream == NULL && errno != ENOENT )
81 msg_Err( p_obj, "cannot open config file (%s): %m",
85 #if !( defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS) )
86 else if( p_stream == NULL && errno == ENOENT )
88 /* This is the fallback for pre XDG Base Directory
89 * Specification configs */
90 char *home = config_GetUserDir(VLC_HOME_DIR);
94 && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
97 p_stream = utf8_fopen( psz_old, "rt" );
100 /* Old config file found. We want to write it at the
101 * new location now. */
102 msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
103 "VLC will now use %s.", psz_old, psz_filename );
105 if( asprintf(&psz_readme,"%s/.vlc/README",
108 FILE *p_readme = utf8_fopen( psz_readme, "wt" );
111 fprintf( p_readme, "The VLC media player "
112 "configuration folder has moved to comply\n"
113 "with the XDG Base Directory Specification "
114 "version 0.6. Your\nconfiguration has been "
115 "copied to the new location:\n%s\nYou can "
116 "delete this directory and all its contents.",
122 /* Remove the old configuration file so that --reset-config
123 * can work properly. Fortunately, Linux allows removing
124 * open files - with most filesystems. */
132 free( psz_filename );
137 static int strtoi (const char *str)
143 l = strtol (str, &end, 0);
147 if ((l > INT_MAX) || (l < INT_MIN))
155 #undef config_LoadConfigFile
156 /*****************************************************************************
157 * config_LoadConfigFile: loads the configuration file.
158 *****************************************************************************
159 * This function is called to load the config options stored in the config
161 *****************************************************************************/
162 int config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
166 file = config_OpenConfigFile (p_this);
170 /* Look for the selected module, if NULL then save everything */
171 module_t **list = module_list_get (NULL);
173 /* Look for UTF-8 Byte Order Mark */
174 char * (*convert) (const char *) = strdupnull;
177 if ((fread (bom, 1, 3, file) != 3)
178 || memcmp (bom, "\xEF\xBB\xBF", 3))
180 convert = FromLocaleDup;
181 rewind (file); /* no BOM, rewind */
184 module_t *module = NULL;
185 char line[1024], section[1022];
188 /* Ensure consistent number formatting... */
189 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
190 locale_t baseloc = uselocale (loc);
192 vlc_rwlock_wrlock (&config_lock);
193 while (fgets (line, 1024, file) != NULL)
195 /* Ignore comments and empty lines */
206 char *ptr = strchr (line, ']');
208 continue; /* syntax error; */
211 /* New section ( = a given module) */
212 strcpy (section, line + 1);
215 if ((psz_module_name == NULL)
216 || (strcmp (psz_module_name, section) == 0))
218 for (int i = 0; list[i]; i++)
220 module_t *m = list[i];
222 if ((strcmp (section, m->psz_object_name) == 0)
223 && (m->i_config_items > 0)) /* ignore config-less modules */
226 if (psz_module_name != NULL)
228 "loading config for module \"%s\"",
239 continue; /* no need to parse if there is no matching module */
241 char *ptr = strchr (line, '\n');
245 /* look for option name */
246 const char *psz_option_name = line;
248 ptr = strchr (line, '=');
250 continue; /* syntax error */
253 const char *psz_option_value = ptr + 1;
255 /* try to match this option with one of the module's options */
256 for (size_t i = 0; i < module->confsize; i++)
258 module_config_t *p_item = module->p_config + i;
260 if ((p_item->i_type & CONFIG_HINT)
261 || strcmp (p_item->psz_name, psz_option_name))
267 switch( p_item->i_type )
269 case CONFIG_ITEM_BOOL:
270 case CONFIG_ITEM_INTEGER:
272 long l = strtoi (psz_option_value);
274 msg_Warn (p_this, "Integer value (%s) for %s: %m",
275 psz_option_value, psz_option_name);
277 p_item->saved.i = p_item->value.i = (int)l;
281 case CONFIG_ITEM_FLOAT:
282 if( !*psz_option_value )
283 break; /* ignore empty option */
284 p_item->value.f = (float)atof (psz_option_value);
285 p_item->saved.f = p_item->value.f;
288 case CONFIG_ITEM_KEY:
289 if( !*psz_option_value )
290 break; /* ignore empty option */
291 p_item->value.i = ConfigStringToKey(psz_option_value);
292 p_item->saved.i = p_item->value.i;
296 /* free old string */
297 free( (char*) p_item->value.psz );
298 free( (char*) p_item->saved.psz );
300 p_item->value.psz = convert (psz_option_value);
301 p_item->saved.psz = strdupnull (p_item->value.psz);
307 vlc_rwlock_unlock (&config_lock);
311 msg_Err (p_this, "error reading configuration: %m");
316 module_list_free (list);
317 if (loc != (locale_t)0)
325 /*****************************************************************************
326 * config_CreateDir: Create configuration directory if it doesn't exist.
327 *****************************************************************************/
328 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
330 if( !psz_dirname || !*psz_dirname ) return -1;
332 if( utf8_mkdir( psz_dirname, 0700 ) == 0 )
342 /* Let's try to create the parent directory */
343 char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
344 strcpy( psz_parent, psz_dirname );
346 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
347 if( psz_end && psz_end != psz_parent )
350 if( config_CreateDir( p_this, psz_parent ) == 0 )
352 if( !utf8_mkdir( psz_dirname, 0700 ) )
359 msg_Warn( p_this, "could not create %s: %m", psz_dirname );
364 config_Write (FILE *file, const char *desc, const char *type,
365 bool comment, const char *name, const char *fmt, ...)
373 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
374 comment ? "#" : "", name) < 0)
378 ret = vfprintf (file, fmt, ap);
383 if (fputs ("\n\n", file) == EOF)
389 static int config_PrepareDir (vlc_object_t *obj)
391 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
392 if (psz_configdir == NULL)
395 int ret = config_CreateDir (obj, psz_configdir);
396 free (psz_configdir);
400 /*****************************************************************************
401 * config_SaveConfigFile: Save a module's config options.
402 *****************************************************************************
403 * This will save the specified module's config options to the config file.
404 * If psz_module_name is NULL then we save all the modules config options.
405 * It's no use to save the config options that kept their default values, so
406 * we'll try to be a bit clever here.
408 * When we save we mustn't delete the config options of the modules that
409 * haven't been loaded. So we cannot just create a new config file with the
410 * config structures we've got in memory.
411 * I don't really know how to deal with this nicely, so I will use a completly
413 * I will load the config file in memory, but skipping all the sections of the
414 * modules we want to save. Then I will create a brand new file, dump the file
415 * loaded in memory and then append the sections of the modules we want to
418 *****************************************************************************/
419 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
424 char *permanent = NULL, *temporary = NULL;
425 char p_line[1024], *p_index2;
426 unsigned long i_sizebuf = 0;
427 char *p_bigbuffer = NULL, *p_index;
431 if( config_PrepareDir( p_this ) )
433 msg_Err( p_this, "no configuration directory" );
437 file = config_OpenConfigFile( p_this );
442 /* Some users make vlcrc read-only to prevent changes.
443 * The atomic replacement scheme breaks this "feature",
444 * so we check for read-only by hand. */
445 if (fstat (fileno (file), &st)
446 || !(st.st_mode & S_IWUSR))
448 msg_Err (p_this, "configuration file is read-only");
451 i_sizebuf = ( st.st_size < LONG_MAX ) ? st.st_size : 0;
454 p_bigbuffer = p_index = malloc( i_sizebuf+1 );
459 /* List all available modules */
460 module_t **list = module_list_get (NULL);
462 /* backup file into memory, we only need to backup the sections we won't
465 while( file && fgets( p_line, 1024, file ) )
467 if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
470 /* we found a section, check if we need to do a backup */
471 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
473 if( ((p_index2 - &p_line[1])
474 == (int)strlen(p_parser->psz_object_name) )
475 && !memcmp( &p_line[1], p_parser->psz_object_name,
476 strlen(p_parser->psz_object_name) ) )
478 if( !psz_module_name )
480 else if( !strcmp( psz_module_name,
481 p_parser->psz_object_name ) )
486 if( list[i_index] == NULL )
488 /* we don't have this section in our list so we need to back
492 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
505 /* save line if requested and line is valid (doesn't begin with a
506 * space, tab, or eol) */
507 if( b_backup && (p_line[0] != '\n') && (p_line[0] != ' ')
508 && (p_line[0] != '\t') )
510 strcpy( p_index, p_line );
511 p_index += strlen( p_line );
519 * Save module config in file
521 permanent = config_GetConfigFile (p_this);
524 module_list_free (list);
528 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
531 module_list_free (list);
535 /* Configuration lock must be taken before vlcrc serializer below. */
536 vlc_rwlock_rdlock (&config_lock);
538 /* The temporary configuration file is per-PID. Therefore SaveConfigFile()
539 * should be serialized against itself within a given process. */
540 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
541 vlc_mutex_lock (&lock);
543 int fd = utf8_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
546 vlc_rwlock_unlock (&config_lock);
547 vlc_mutex_unlock (&lock);
548 module_list_free (list);
551 file = fdopen (fd, "wt");
554 vlc_rwlock_unlock (&config_lock);
556 vlc_mutex_unlock (&lock);
557 module_list_free (list);
561 fprintf( file, "\xEF\xBB\xBF###\n### " COPYRIGHT_MESSAGE "\n###\n\n"
562 "###\n### lines beginning with a '#' character are comments\n###\n\n" );
564 /* Ensure consistent number formatting... */
565 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
566 locale_t baseloc = uselocale (loc);
568 /* We would take the config lock here. But this would cause a lock
569 * inversion with the serializer above and config_AutoSaveConfigFile().
570 vlc_rwlock_rdlock (&config_lock);*/
572 /* Look for the selected module, if NULL then save everything */
573 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
575 module_config_t *p_item, *p_end;
577 if( psz_module_name && strcmp( psz_module_name,
578 p_parser->psz_object_name ) )
581 if( !p_parser->i_config_items )
584 if( psz_module_name )
585 msg_Dbg( p_this, "saving config for module \"%s\"",
586 p_parser->psz_object_name );
588 fprintf( file, "[%s]", p_parser->psz_object_name );
589 if( p_parser->psz_longname )
590 fprintf( file, " # %s\n\n", p_parser->psz_longname );
592 fprintf( file, "\n\n" );
594 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
598 if ((p_item->i_type & CONFIG_HINT) /* ignore hint */
599 || p_item->b_removed /* ignore deprecated option */
600 || p_item->b_unsaveable) /* ignore volatile option */
603 /* Do not save the new value in the configuration file
604 * if doing an autosave, and the item is not an "autosaved" one. */
605 bool b_retain = b_autosave && !p_item->b_autosave;
607 if (IsConfigIntegerType (p_item->i_type))
609 int val = b_retain ? p_item->saved.i : p_item->value.i;
610 if (p_item->i_type == CONFIG_ITEM_KEY)
612 char *psz_key = ConfigKeyToString (val);
613 config_Write (file, p_item->psz_text, N_("key"),
614 val == p_item->orig.i,
615 p_item->psz_name, "%s",
616 psz_key ? psz_key : "");
620 config_Write (file, p_item->psz_text,
621 (p_item->i_type == CONFIG_ITEM_BOOL)
622 ? N_("boolean") : N_("integer"),
623 val == p_item->orig.i,
624 p_item->psz_name, "%d", val);
625 p_item->saved.i = val;
628 if (IsConfigFloatType (p_item->i_type))
630 float val = b_retain ? p_item->saved.f : p_item->value.f;
631 config_Write (file, p_item->psz_text, N_("float"),
632 val == p_item->orig.f,
633 p_item->psz_name, "%f", val);
634 p_item->saved.f = val;
638 const char *psz_value = b_retain ? p_item->saved.psz
642 assert (IsConfigStringType (p_item->i_type));
644 if (b_retain && (psz_value == NULL)) /* FIXME: hack */
645 psz_value = p_item->orig.psz;
649 ? ((p_item->orig.psz != NULL)
650 ? (strcmp (psz_value, p_item->orig.psz) != 0)
652 : (p_item->orig.psz != NULL);
654 config_Write (file, p_item->psz_text, N_("string"),
655 !modified, p_item->psz_name, "%s",
656 psz_value ? psz_value : "");
661 free ((char *)p_item->saved.psz);
662 if( (psz_value && p_item->orig.psz &&
663 strcmp( psz_value, p_item->orig.psz )) ||
664 !psz_value || !p_item->orig.psz)
665 p_item->saved.psz = strdupnull (psz_value);
667 p_item->saved.psz = NULL;
672 p_item->b_dirty = false;
675 vlc_rwlock_unlock (&config_lock);
677 module_list_free (list);
678 if (loc != (locale_t)0)
685 * Restore old settings from the config in file
687 fputs( p_bigbuffer, file );
691 * Flush to disk and replace atomically
693 fflush (file); /* Flush from run-time */
696 fsync (fd); /* Flush from OS */
698 fdatasync (fd); /* Flush from OS */
700 /* Atomically replace the file... */
701 if (utf8_rename (temporary, permanent))
702 utf8_unlink (temporary);
703 /* (...then synchronize the directory, err, TODO...) */
704 /* ...and finally close the file */
705 vlc_mutex_unlock (&lock);
709 /* Windows cannot remove open files nor overwrite existing ones */
710 utf8_unlink (permanent);
711 if (utf8_rename (temporary, permanent))
712 utf8_unlink (temporary);
713 vlc_mutex_unlock (&lock);
729 int config_AutoSaveConfigFile( vlc_object_t *p_this )
731 int ret = VLC_SUCCESS;
736 /* Check if there's anything to save */
737 module_t **list = module_list_get (NULL);
738 vlc_rwlock_rdlock (&config_lock);
739 for (size_t i_index = 0; list[i_index] && !save; i_index++)
741 module_t *p_parser = list[i_index];
742 module_config_t *p_item, *p_end;
744 if( !p_parser->i_config_items ) continue;
746 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
747 p_item < p_end && !save;
750 save = p_item->b_autosave && p_item->b_dirty;
755 /* Note: this will get the read lock recursively. Ok. */
756 ret = SaveConfigFile (p_this, NULL, true);
757 vlc_rwlock_unlock (&config_lock);
759 module_list_free (list);
763 #undef config_SaveConfigFile
764 int config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
766 return SaveConfigFile( p_this, psz_module_name, false );