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 <vlc_modules.h>
46 #include "configuration.h"
47 #include "modules/modules.h"
49 static inline char *strdupnull (const char *src)
51 return src ? strdup (src) : NULL;
55 * Get the user's configuration file
57 static char *config_GetConfigFile( vlc_object_t *obj )
59 char *psz_file = var_CreateGetNonEmptyString( obj, "config" );
60 var_Destroy( obj, "config" );
61 if( psz_file == NULL )
63 char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
65 if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
72 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
74 char *psz_filename = config_GetConfigFile( p_obj );
75 if( psz_filename == NULL )
78 msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
80 FILE *p_stream = vlc_fopen( psz_filename, "rt" );
81 if( p_stream == NULL && errno != ENOENT )
83 msg_Err( p_obj, "cannot open config file (%s): %m",
87 #if !( defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS) )
88 else if( p_stream == NULL && errno == ENOENT )
90 /* This is the fallback for pre XDG Base Directory
91 * Specification configs */
92 char *home = config_GetUserDir(VLC_HOME_DIR);
96 && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
99 p_stream = vlc_fopen( psz_old, "rt" );
102 /* Old config file found. We want to write it at the
103 * new location now. */
104 msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
105 "VLC will now use %s.", psz_old, psz_filename );
107 if( asprintf(&psz_readme,"%s/.vlc/README",
110 FILE *p_readme = vlc_fopen( psz_readme, "wt" );
113 fprintf( p_readme, "The VLC media player "
114 "configuration folder has moved to comply\n"
115 "with the XDG Base Directory Specification "
116 "version 0.6. Your\nconfiguration has been "
117 "copied to the new location:\n%s\nYou can "
118 "delete this directory and all its contents.",
124 /* Remove the old configuration file so that --reset-config
125 * can work properly. Fortunately, Linux allows removing
126 * open files - with most filesystems. */
134 free( psz_filename );
139 static int64_t strtoi (const char *str)
145 l = strtoll (str, &end, 0);
149 #if (LLONG_MAX > 0x7fffffffffffffffLL)
150 if (l > 0x7fffffffffffffffLL
151 || l < -0x8000000000000000LL)
160 #undef config_LoadConfigFile
161 /*****************************************************************************
162 * config_LoadConfigFile: loads the configuration file.
163 *****************************************************************************
164 * This function is called to load the config options stored in the config
166 *****************************************************************************/
167 int config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
171 file = config_OpenConfigFile (p_this);
175 /* Look for the selected module, if NULL then save everything */
176 module_t **list = module_list_get (NULL);
178 /* Look for UTF-8 Byte Order Mark */
179 char * (*convert) (const char *) = strdupnull;
182 if ((fread (bom, 1, 3, file) != 3)
183 || memcmp (bom, "\xEF\xBB\xBF", 3))
185 convert = FromLocaleDup;
186 rewind (file); /* no BOM, rewind */
189 module_t *module = NULL;
190 char line[1024], section[1022];
193 /* Ensure consistent number formatting... */
194 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
195 locale_t baseloc = uselocale (loc);
197 vlc_rwlock_wrlock (&config_lock);
198 while (fgets (line, 1024, file) != NULL)
200 /* Ignore comments and empty lines */
211 char *ptr = strchr (line, ']');
213 continue; /* syntax error; */
216 /* New section ( = a given module) */
217 strcpy (section, line + 1);
220 if ((psz_module_name == NULL)
221 || (strcmp (psz_module_name, section) == 0))
223 for (int i = 0; list[i]; i++)
225 module_t *m = list[i];
227 if ((strcmp (section, m->psz_object_name) == 0)
228 && (m->i_config_items > 0)) /* ignore config-less modules */
231 if (psz_module_name != NULL)
233 "loading config for module \"%s\"",
244 continue; /* no need to parse if there is no matching module */
246 char *ptr = strchr (line, '\n');
250 /* look for option name */
251 const char *psz_option_name = line;
253 ptr = strchr (line, '=');
255 continue; /* syntax error */
258 const char *psz_option_value = ptr + 1;
260 /* try to match this option with one of the module's options */
261 for (size_t i = 0; i < module->confsize; i++)
263 module_config_t *p_item = module->p_config + i;
265 if ((p_item->i_type & CONFIG_HINT)
266 || strcmp (p_item->psz_name, psz_option_name))
272 switch( p_item->i_type )
274 case CONFIG_ITEM_BOOL:
275 case CONFIG_ITEM_INTEGER:
277 int64_t l = strtoi (psz_option_value);
278 if ((l > p_item->max.i) || (l < p_item->min.i))
281 msg_Warn (p_this, "Integer value (%s) for %s: %m",
282 psz_option_value, psz_option_name);
284 p_item->saved.i = p_item->value.i = l;
288 case CONFIG_ITEM_FLOAT:
289 if( !*psz_option_value )
290 break; /* ignore empty option */
291 p_item->value.f = (float)atof (psz_option_value);
292 p_item->saved.f = p_item->value.f;
295 case CONFIG_ITEM_KEY:
296 if( !*psz_option_value )
297 break; /* ignore empty option */
298 p_item->value.i = ConfigStringToKey(psz_option_value);
299 p_item->saved.i = p_item->value.i;
303 /* free old string */
304 free( (char*) p_item->value.psz );
305 free( (char*) p_item->saved.psz );
307 p_item->value.psz = convert (psz_option_value);
308 p_item->saved.psz = strdupnull (p_item->value.psz);
314 vlc_rwlock_unlock (&config_lock);
318 msg_Err (p_this, "error reading configuration: %m");
323 module_list_free (list);
324 if (loc != (locale_t)0)
332 /*****************************************************************************
333 * config_CreateDir: Create configuration directory if it doesn't exist.
334 *****************************************************************************/
335 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
337 if( !psz_dirname || !*psz_dirname ) return -1;
339 if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
349 /* Let's try to create the parent directory */
350 char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
351 strcpy( psz_parent, psz_dirname );
353 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
354 if( psz_end && psz_end != psz_parent )
357 if( config_CreateDir( p_this, psz_parent ) == 0 )
359 if( !vlc_mkdir( psz_dirname, 0700 ) )
366 msg_Warn( p_this, "could not create %s: %m", psz_dirname );
371 config_Write (FILE *file, const char *desc, const char *type,
372 bool comment, const char *name, const char *fmt, ...)
380 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
381 comment ? "#" : "", name) < 0)
385 ret = vfprintf (file, fmt, ap);
390 if (fputs ("\n\n", file) == EOF)
396 static int config_PrepareDir (vlc_object_t *obj)
398 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
399 if (psz_configdir == NULL)
402 int ret = config_CreateDir (obj, psz_configdir);
403 free (psz_configdir);
407 /*****************************************************************************
408 * config_SaveConfigFile: Save a module's config options.
409 *****************************************************************************
410 * This will save the specified module's config options to the config file.
411 * If psz_module_name is NULL then we save all the modules config options.
412 * It's no use to save the config options that kept their default values, so
413 * we'll try to be a bit clever here.
415 * When we save we mustn't delete the config options of the modules that
416 * haven't been loaded. So we cannot just create a new config file with the
417 * config structures we've got in memory.
418 * I don't really know how to deal with this nicely, so I will use a completly
420 * I will load the config file in memory, but skipping all the sections of the
421 * modules we want to save. Then I will create a brand new file, dump the file
422 * loaded in memory and then append the sections of the modules we want to
425 *****************************************************************************/
426 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
431 char *permanent = NULL, *temporary = NULL;
432 char p_line[1024], *p_index2;
433 unsigned long i_sizebuf = 0;
434 char *p_bigbuffer = NULL, *p_index;
438 if( config_PrepareDir( p_this ) )
440 msg_Err( p_this, "no configuration directory" );
444 file = config_OpenConfigFile( p_this );
449 /* Some users make vlcrc read-only to prevent changes.
450 * The atomic replacement scheme breaks this "feature",
451 * so we check for read-only by hand. */
452 if (fstat (fileno (file), &st)
453 || !(st.st_mode & S_IWUSR))
455 msg_Err (p_this, "configuration file is read-only");
458 i_sizebuf = ( st.st_size < LONG_MAX ) ? st.st_size : 0;
461 p_bigbuffer = p_index = malloc( i_sizebuf+1 );
466 /* List all available modules */
467 module_t **list = module_list_get (NULL);
469 /* backup file into memory, we only need to backup the sections we won't
472 while( file && fgets( p_line, 1024, file ) )
474 if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
477 /* we found a section, check if we need to do a backup */
478 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
480 if( ((p_index2 - &p_line[1])
481 == (int)strlen(p_parser->psz_object_name) )
482 && !memcmp( &p_line[1], p_parser->psz_object_name,
483 strlen(p_parser->psz_object_name) ) )
485 if( !psz_module_name )
487 else if( !strcmp( psz_module_name,
488 p_parser->psz_object_name ) )
493 if( list[i_index] == NULL )
495 /* we don't have this section in our list so we need to back
499 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
512 /* save line if requested and line is valid (doesn't begin with a
513 * space, tab, or eol) */
514 if( b_backup && (p_line[0] != '\n') && (p_line[0] != ' ')
515 && (p_line[0] != '\t') )
517 strcpy( p_index, p_line );
518 p_index += strlen( p_line );
526 * Save module config in file
528 permanent = config_GetConfigFile (p_this);
531 module_list_free (list);
535 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
538 module_list_free (list);
542 /* Configuration lock must be taken before vlcrc serializer below. */
543 vlc_rwlock_rdlock (&config_lock);
545 /* The temporary configuration file is per-PID. Therefore SaveConfigFile()
546 * should be serialized against itself within a given process. */
547 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
548 vlc_mutex_lock (&lock);
550 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
553 vlc_rwlock_unlock (&config_lock);
554 vlc_mutex_unlock (&lock);
555 module_list_free (list);
558 file = fdopen (fd, "wt");
561 msg_Err (p_this, "cannot create configuration file: %m");
562 vlc_rwlock_unlock (&config_lock);
564 vlc_mutex_unlock (&lock);
565 module_list_free (list);
571 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
575 "### lines beginning with a '#' character are comments\n"
579 /* Ensure consistent number formatting... */
580 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
581 locale_t baseloc = uselocale (loc);
583 /* We would take the config lock here. But this would cause a lock
584 * inversion with the serializer above and config_AutoSaveConfigFile().
585 vlc_rwlock_rdlock (&config_lock);*/
587 /* Look for the selected module, if NULL then save everything */
588 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
590 module_config_t *p_item, *p_end;
592 if( psz_module_name && strcmp( psz_module_name,
593 p_parser->psz_object_name ) )
596 if( !p_parser->i_config_items )
599 if( psz_module_name )
600 msg_Dbg( p_this, "saving config for module \"%s\"",
601 p_parser->psz_object_name );
603 fprintf( file, "[%s]", p_parser->psz_object_name );
604 if( p_parser->psz_longname )
605 fprintf( file, " # %s\n\n", p_parser->psz_longname );
607 fprintf( file, "\n\n" );
609 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
613 if ((p_item->i_type & CONFIG_HINT) /* ignore hint */
614 || p_item->b_removed /* ignore deprecated option */
615 || p_item->b_unsaveable) /* ignore volatile option */
618 /* Do not save the new value in the configuration file
619 * if doing an autosave, and the item is not an "autosaved" one. */
620 bool b_retain = b_autosave && !p_item->b_autosave;
622 if (IsConfigIntegerType (p_item->i_type))
624 int64_t val = b_retain ? p_item->saved.i : p_item->value.i;
625 if (p_item->i_type == CONFIG_ITEM_KEY)
627 char *psz_key = ConfigKeyToString (val);
628 config_Write (file, p_item->psz_text, N_("key"),
629 val == p_item->orig.i,
630 p_item->psz_name, "%s",
631 psz_key ? psz_key : "");
635 config_Write (file, p_item->psz_text,
636 (p_item->i_type == CONFIG_ITEM_BOOL)
637 ? N_("boolean") : N_("integer"),
638 val == p_item->orig.i,
639 p_item->psz_name, "%"PRId64, val);
640 p_item->saved.i = val;
643 if (IsConfigFloatType (p_item->i_type))
645 float val = b_retain ? p_item->saved.f : p_item->value.f;
646 config_Write (file, p_item->psz_text, N_("float"),
647 val == p_item->orig.f,
648 p_item->psz_name, "%f", val);
649 p_item->saved.f = val;
653 const char *psz_value = b_retain ? p_item->saved.psz
657 assert (IsConfigStringType (p_item->i_type));
659 if (b_retain && (psz_value == NULL)) /* FIXME: hack */
660 psz_value = p_item->orig.psz;
664 ? ((p_item->orig.psz != NULL)
665 ? (strcmp (psz_value, p_item->orig.psz) != 0)
667 : (p_item->orig.psz != NULL);
669 config_Write (file, p_item->psz_text, N_("string"),
670 !modified, p_item->psz_name, "%s",
671 psz_value ? psz_value : "");
676 free ((char *)p_item->saved.psz);
677 if( (psz_value && p_item->orig.psz &&
678 strcmp( psz_value, p_item->orig.psz )) ||
679 !psz_value || !p_item->orig.psz)
680 p_item->saved.psz = strdupnull (psz_value);
682 p_item->saved.psz = NULL;
687 p_item->b_dirty = false;
690 vlc_rwlock_unlock (&config_lock);
692 module_list_free (list);
693 if (loc != (locale_t)0)
700 * Restore old settings from the config in file
702 fputs( p_bigbuffer, file );
706 * Flush to disk and replace atomically
708 fflush (file); /* Flush from run-time */
711 vlc_unlink (temporary);
712 vlc_mutex_unlock (&lock);
713 msg_Err (p_this, "cannot write configuration file");
719 fsync (fd); /* Flush from OS */
721 fdatasync (fd); /* Flush from OS */
723 /* Atomically replace the file... */
724 if (vlc_rename (temporary, permanent))
725 vlc_unlink (temporary);
726 /* (...then synchronize the directory, err, TODO...) */
727 /* ...and finally close the file */
728 vlc_mutex_unlock (&lock);
732 /* Windows cannot remove open files nor overwrite existing ones */
733 vlc_unlink (permanent);
734 if (vlc_rename (temporary, permanent))
735 vlc_unlink (temporary);
736 vlc_mutex_unlock (&lock);
752 int config_AutoSaveConfigFile( vlc_object_t *p_this )
754 int ret = VLC_SUCCESS;
759 /* Check if there's anything to save */
760 module_t **list = module_list_get (NULL);
761 vlc_rwlock_rdlock (&config_lock);
762 for (size_t i_index = 0; list[i_index] && !save; i_index++)
764 module_t *p_parser = list[i_index];
765 module_config_t *p_item, *p_end;
767 if( !p_parser->i_config_items ) continue;
769 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
770 p_item < p_end && !save;
773 save = p_item->b_autosave && p_item->b_dirty;
778 /* Note: this will get the read lock recursively. Ok. */
779 ret = SaveConfigFile (p_this, NULL, true);
780 vlc_rwlock_unlock (&config_lock);
782 module_list_free (list);
786 #undef config_SaveConfigFile
787 int config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
789 return SaveConfigFile( p_this, psz_module_name, false );