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>
45 #include "configuration.h"
46 #include "modules/modules.h"
48 static inline char *strdupnull (const char *src)
50 return src ? strdup (src) : NULL;
54 * Get the user's configuration file
56 static char *config_GetConfigFile( vlc_object_t *obj )
58 char *psz_file = var_CreateGetNonEmptyString( obj, "config" );
59 var_Destroy( obj, "config" );
60 if( psz_file == NULL )
62 char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
64 if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
71 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
73 char *psz_filename = config_GetConfigFile( p_obj );
74 if( psz_filename == NULL )
77 msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
79 FILE *p_stream = vlc_fopen( psz_filename, "rt" );
80 if( p_stream == NULL && errno != ENOENT )
82 msg_Err( p_obj, "cannot open config file (%s): %m",
86 #if !( defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS) )
87 else if( p_stream == NULL && errno == ENOENT )
89 /* This is the fallback for pre XDG Base Directory
90 * Specification configs */
91 char *home = config_GetUserDir(VLC_HOME_DIR);
95 && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
98 p_stream = vlc_fopen( psz_old, "rt" );
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 );
106 if( asprintf(&psz_readme,"%s/.vlc/README",
109 FILE *p_readme = vlc_fopen( psz_readme, "wt" );
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.",
123 /* Remove the old configuration file so that --reset-config
124 * can work properly. Fortunately, Linux allows removing
125 * open files - with most filesystems. */
133 free( psz_filename );
138 static int64_t strtoi (const char *str)
144 l = strtoll (str, &end, 0);
148 if ((l > INT64_C(0x7fffffffffffffff))
149 || (l < INT64_C(-0x8000000000000000)))
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
163 *****************************************************************************/
164 int config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
168 file = config_OpenConfigFile (p_this);
172 /* Look for the selected module, if NULL then save everything */
173 module_t **list = module_list_get (NULL);
175 /* Look for UTF-8 Byte Order Mark */
176 char * (*convert) (const char *) = strdupnull;
179 if ((fread (bom, 1, 3, file) != 3)
180 || memcmp (bom, "\xEF\xBB\xBF", 3))
182 convert = FromLocaleDup;
183 rewind (file); /* no BOM, rewind */
186 module_t *module = NULL;
187 char line[1024], section[1022];
190 /* Ensure consistent number formatting... */
191 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
192 locale_t baseloc = uselocale (loc);
194 vlc_rwlock_wrlock (&config_lock);
195 while (fgets (line, 1024, file) != NULL)
197 /* Ignore comments and empty lines */
208 char *ptr = strchr (line, ']');
210 continue; /* syntax error; */
213 /* New section ( = a given module) */
214 strcpy (section, line + 1);
217 if ((psz_module_name == NULL)
218 || (strcmp (psz_module_name, section) == 0))
220 for (int i = 0; list[i]; i++)
222 module_t *m = list[i];
224 if ((strcmp (section, m->psz_object_name) == 0)
225 && (m->i_config_items > 0)) /* ignore config-less modules */
228 if (psz_module_name != NULL)
230 "loading config for module \"%s\"",
241 continue; /* no need to parse if there is no matching module */
243 char *ptr = strchr (line, '\n');
247 /* look for option name */
248 const char *psz_option_name = line;
250 ptr = strchr (line, '=');
252 continue; /* syntax error */
255 const char *psz_option_value = ptr + 1;
257 /* try to match this option with one of the module's options */
258 for (size_t i = 0; i < module->confsize; i++)
260 module_config_t *p_item = module->p_config + i;
262 if ((p_item->i_type & CONFIG_HINT)
263 || strcmp (p_item->psz_name, psz_option_name))
269 switch( p_item->i_type )
271 case CONFIG_ITEM_BOOL:
272 case CONFIG_ITEM_INTEGER:
274 int64_t l = strtoi (psz_option_value);
276 msg_Warn (p_this, "Integer value (%s) for %s: %m",
277 psz_option_value, psz_option_name);
279 p_item->saved.i = p_item->value.i = l;
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;
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;
298 /* free old string */
299 free( (char*) p_item->value.psz );
300 free( (char*) p_item->saved.psz );
302 p_item->value.psz = convert (psz_option_value);
303 p_item->saved.psz = strdupnull (p_item->value.psz);
309 vlc_rwlock_unlock (&config_lock);
313 msg_Err (p_this, "error reading configuration: %m");
318 module_list_free (list);
319 if (loc != (locale_t)0)
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 )
332 if( !psz_dirname || !*psz_dirname ) return -1;
334 if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
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 );
348 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
349 if( psz_end && psz_end != psz_parent )
352 if( config_CreateDir( p_this, psz_parent ) == 0 )
354 if( !vlc_mkdir( psz_dirname, 0700 ) )
361 msg_Warn( p_this, "could not create %s: %m", psz_dirname );
366 config_Write (FILE *file, const char *desc, const char *type,
367 bool comment, const char *name, const char *fmt, ...)
375 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
376 comment ? "#" : "", name) < 0)
380 ret = vfprintf (file, fmt, ap);
385 if (fputs ("\n\n", file) == EOF)
391 static int config_PrepareDir (vlc_object_t *obj)
393 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
394 if (psz_configdir == NULL)
397 int ret = config_CreateDir (obj, psz_configdir);
398 free (psz_configdir);
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.
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
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
420 *****************************************************************************/
421 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
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;
433 if( config_PrepareDir( p_this ) )
435 msg_Err( p_this, "no configuration directory" );
439 file = config_OpenConfigFile( p_this );
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))
450 msg_Err (p_this, "configuration file is read-only");
453 i_sizebuf = ( st.st_size < LONG_MAX ) ? st.st_size : 0;
456 p_bigbuffer = p_index = malloc( i_sizebuf+1 );
461 /* List all available modules */
462 module_t **list = module_list_get (NULL);
464 /* backup file into memory, we only need to backup the sections we won't
467 while( file && fgets( p_line, 1024, file ) )
469 if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
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++ )
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) ) )
480 if( !psz_module_name )
482 else if( !strcmp( psz_module_name,
483 p_parser->psz_object_name ) )
488 if( list[i_index] == NULL )
490 /* we don't have this section in our list so we need to back
494 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
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') )
512 strcpy( p_index, p_line );
513 p_index += strlen( p_line );
521 * Save module config in file
523 permanent = config_GetConfigFile (p_this);
526 module_list_free (list);
530 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
533 module_list_free (list);
537 /* Configuration lock must be taken before vlcrc serializer below. */
538 vlc_rwlock_rdlock (&config_lock);
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);
545 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
548 vlc_rwlock_unlock (&config_lock);
549 vlc_mutex_unlock (&lock);
550 module_list_free (list);
553 file = fdopen (fd, "wt");
556 vlc_rwlock_unlock (&config_lock);
558 vlc_mutex_unlock (&lock);
559 module_list_free (list);
565 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
569 "### lines beginning with a '#' character are comments\n"
573 /* Ensure consistent number formatting... */
574 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
575 locale_t baseloc = uselocale (loc);
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);*/
581 /* Look for the selected module, if NULL then save everything */
582 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
584 module_config_t *p_item, *p_end;
586 if( psz_module_name && strcmp( psz_module_name,
587 p_parser->psz_object_name ) )
590 if( !p_parser->i_config_items )
593 if( psz_module_name )
594 msg_Dbg( p_this, "saving config for module \"%s\"",
595 p_parser->psz_object_name );
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 );
601 fprintf( file, "\n\n" );
603 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
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 */
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;
616 if (IsConfigIntegerType (p_item->i_type))
618 int64_t val = b_retain ? p_item->saved.i : p_item->value.i;
619 if (p_item->i_type == CONFIG_ITEM_KEY)
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 : "");
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;
637 if (IsConfigFloatType (p_item->i_type))
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;
647 const char *psz_value = b_retain ? p_item->saved.psz
651 assert (IsConfigStringType (p_item->i_type));
653 if (b_retain && (psz_value == NULL)) /* FIXME: hack */
654 psz_value = p_item->orig.psz;
658 ? ((p_item->orig.psz != NULL)
659 ? (strcmp (psz_value, p_item->orig.psz) != 0)
661 : (p_item->orig.psz != NULL);
663 config_Write (file, p_item->psz_text, N_("string"),
664 !modified, p_item->psz_name, "%s",
665 psz_value ? psz_value : "");
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);
676 p_item->saved.psz = NULL;
681 p_item->b_dirty = false;
684 vlc_rwlock_unlock (&config_lock);
686 module_list_free (list);
687 if (loc != (locale_t)0)
694 * Restore old settings from the config in file
696 fputs( p_bigbuffer, file );
700 * Flush to disk and replace atomically
702 fflush (file); /* Flush from run-time */
705 fsync (fd); /* Flush from OS */
707 fdatasync (fd); /* Flush from OS */
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);
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);
738 int config_AutoSaveConfigFile( vlc_object_t *p_this )
740 int ret = VLC_SUCCESS;
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++)
750 module_t *p_parser = list[i_index];
751 module_config_t *p_item, *p_end;
753 if( !p_parser->i_config_items ) continue;
755 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
756 p_item < p_end && !save;
759 save = p_item->b_autosave && p_item->b_dirty;
764 /* Note: this will get the read lock recursively. Ok. */
765 ret = SaveConfigFile (p_this, NULL, true);
766 vlc_rwlock_unlock (&config_lock);
768 module_list_free (list);
772 #undef config_SaveConfigFile
773 int config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
775 return SaveConfigFile( p_this, psz_module_name, false );