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 int strtoi (const char *str)
144 l = strtol (str, &end, 0);
148 if ((l > INT_MAX) || (l < INT_MIN))
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
162 *****************************************************************************/
163 int config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
167 file = config_OpenConfigFile (p_this);
171 /* Look for the selected module, if NULL then save everything */
172 module_t **list = module_list_get (NULL);
174 /* Look for UTF-8 Byte Order Mark */
175 char * (*convert) (const char *) = strdupnull;
178 if ((fread (bom, 1, 3, file) != 3)
179 || memcmp (bom, "\xEF\xBB\xBF", 3))
181 convert = FromLocaleDup;
182 rewind (file); /* no BOM, rewind */
185 module_t *module = NULL;
186 char line[1024], section[1022];
189 /* Ensure consistent number formatting... */
190 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
191 locale_t baseloc = uselocale (loc);
193 vlc_rwlock_wrlock (&config_lock);
194 while (fgets (line, 1024, file) != NULL)
196 /* Ignore comments and empty lines */
207 char *ptr = strchr (line, ']');
209 continue; /* syntax error; */
212 /* New section ( = a given module) */
213 strcpy (section, line + 1);
216 if ((psz_module_name == NULL)
217 || (strcmp (psz_module_name, section) == 0))
219 for (int i = 0; list[i]; i++)
221 module_t *m = list[i];
223 if ((strcmp (section, m->psz_object_name) == 0)
224 && (m->i_config_items > 0)) /* ignore config-less modules */
227 if (psz_module_name != NULL)
229 "loading config for module \"%s\"",
240 continue; /* no need to parse if there is no matching module */
242 char *ptr = strchr (line, '\n');
246 /* look for option name */
247 const char *psz_option_name = line;
249 ptr = strchr (line, '=');
251 continue; /* syntax error */
254 const char *psz_option_value = ptr + 1;
256 /* try to match this option with one of the module's options */
257 for (size_t i = 0; i < module->confsize; i++)
259 module_config_t *p_item = module->p_config + i;
261 if ((p_item->i_type & CONFIG_HINT)
262 || strcmp (p_item->psz_name, psz_option_name))
268 switch( p_item->i_type )
270 case CONFIG_ITEM_BOOL:
271 case CONFIG_ITEM_INTEGER:
273 long l = strtoi (psz_option_value);
275 msg_Warn (p_this, "Integer value (%s) for %s: %m",
276 psz_option_value, psz_option_name);
278 p_item->saved.i = p_item->value.i = (int)l;
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;
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;
297 /* free old string */
298 free( (char*) p_item->value.psz );
299 free( (char*) p_item->saved.psz );
301 p_item->value.psz = convert (psz_option_value);
302 p_item->saved.psz = strdupnull (p_item->value.psz);
308 vlc_rwlock_unlock (&config_lock);
312 msg_Err (p_this, "error reading configuration: %m");
317 module_list_free (list);
318 if (loc != (locale_t)0)
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 )
331 if( !psz_dirname || !*psz_dirname ) return -1;
333 if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
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 );
347 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
348 if( psz_end && psz_end != psz_parent )
351 if( config_CreateDir( p_this, psz_parent ) == 0 )
353 if( !vlc_mkdir( psz_dirname, 0700 ) )
360 msg_Warn( p_this, "could not create %s: %m", psz_dirname );
365 config_Write (FILE *file, const char *desc, const char *type,
366 bool comment, const char *name, const char *fmt, ...)
374 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
375 comment ? "#" : "", name) < 0)
379 ret = vfprintf (file, fmt, ap);
384 if (fputs ("\n\n", file) == EOF)
390 static int config_PrepareDir (vlc_object_t *obj)
392 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
393 if (psz_configdir == NULL)
396 int ret = config_CreateDir (obj, psz_configdir);
397 free (psz_configdir);
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.
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
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
419 *****************************************************************************/
420 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
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;
432 if( config_PrepareDir( p_this ) )
434 msg_Err( p_this, "no configuration directory" );
438 file = config_OpenConfigFile( p_this );
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))
449 msg_Err (p_this, "configuration file is read-only");
452 i_sizebuf = ( st.st_size < LONG_MAX ) ? st.st_size : 0;
455 p_bigbuffer = p_index = malloc( i_sizebuf+1 );
460 /* List all available modules */
461 module_t **list = module_list_get (NULL);
463 /* backup file into memory, we only need to backup the sections we won't
466 while( file && fgets( p_line, 1024, file ) )
468 if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
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++ )
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) ) )
479 if( !psz_module_name )
481 else if( !strcmp( psz_module_name,
482 p_parser->psz_object_name ) )
487 if( list[i_index] == NULL )
489 /* we don't have this section in our list so we need to back
493 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
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') )
511 strcpy( p_index, p_line );
512 p_index += strlen( p_line );
520 * Save module config in file
522 permanent = config_GetConfigFile (p_this);
525 module_list_free (list);
529 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
532 module_list_free (list);
536 /* Configuration lock must be taken before vlcrc serializer below. */
537 vlc_rwlock_rdlock (&config_lock);
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);
544 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
547 vlc_rwlock_unlock (&config_lock);
548 vlc_mutex_unlock (&lock);
549 module_list_free (list);
552 file = fdopen (fd, "wt");
555 vlc_rwlock_unlock (&config_lock);
557 vlc_mutex_unlock (&lock);
558 module_list_free (list);
564 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
568 "### lines beginning with a '#' character are comments\n"
572 /* Ensure consistent number formatting... */
573 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
574 locale_t baseloc = uselocale (loc);
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);*/
580 /* Look for the selected module, if NULL then save everything */
581 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
583 module_config_t *p_item, *p_end;
585 if( psz_module_name && strcmp( psz_module_name,
586 p_parser->psz_object_name ) )
589 if( !p_parser->i_config_items )
592 if( psz_module_name )
593 msg_Dbg( p_this, "saving config for module \"%s\"",
594 p_parser->psz_object_name );
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 );
600 fprintf( file, "\n\n" );
602 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
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 */
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;
615 if (IsConfigIntegerType (p_item->i_type))
617 int val = b_retain ? p_item->saved.i : p_item->value.i;
618 if (p_item->i_type == CONFIG_ITEM_KEY)
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 : "");
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;
636 if (IsConfigFloatType (p_item->i_type))
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;
646 const char *psz_value = b_retain ? p_item->saved.psz
650 assert (IsConfigStringType (p_item->i_type));
652 if (b_retain && (psz_value == NULL)) /* FIXME: hack */
653 psz_value = p_item->orig.psz;
657 ? ((p_item->orig.psz != NULL)
658 ? (strcmp (psz_value, p_item->orig.psz) != 0)
660 : (p_item->orig.psz != NULL);
662 config_Write (file, p_item->psz_text, N_("string"),
663 !modified, p_item->psz_name, "%s",
664 psz_value ? psz_value : "");
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);
675 p_item->saved.psz = NULL;
680 p_item->b_dirty = false;
683 vlc_rwlock_unlock (&config_lock);
685 module_list_free (list);
686 if (loc != (locale_t)0)
693 * Restore old settings from the config in file
695 fputs( p_bigbuffer, file );
699 * Flush to disk and replace atomically
701 fflush (file); /* Flush from run-time */
704 fsync (fd); /* Flush from OS */
706 fdatasync (fd); /* Flush from OS */
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);
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);
737 int config_AutoSaveConfigFile( vlc_object_t *p_this )
739 int ret = VLC_SUCCESS;
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++)
749 module_t *p_parser = list[i_index];
750 module_config_t *p_item, *p_end;
752 if( !p_parser->i_config_items ) continue;
754 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
755 p_item < p_end && !save;
758 save = p_item->b_autosave && p_item->b_dirty;
763 /* Note: this will get the read lock recursively. Ok. */
764 ret = SaveConfigFile (p_this, NULL, true);
765 vlc_rwlock_unlock (&config_lock);
767 module_list_free (list);
771 #undef config_SaveConfigFile
772 int config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
774 return SaveConfigFile( p_this, psz_module_name, false );