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 (LLONG_MAX > 0x7fffffffffffffffLL)
149 if (l > 0x7fffffffffffffffLL
150 || l < -0x8000000000000000LL)
159 #undef config_LoadConfigFile
160 /*****************************************************************************
161 * config_LoadConfigFile: loads the configuration file.
162 *****************************************************************************
163 * This function is called to load the config options stored in the config
165 *****************************************************************************/
166 int config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
170 file = config_OpenConfigFile (p_this);
174 /* Look for the selected module, if NULL then save everything */
175 module_t **list = module_list_get (NULL);
177 /* Look for UTF-8 Byte Order Mark */
178 char * (*convert) (const char *) = strdupnull;
181 if ((fread (bom, 1, 3, file) != 3)
182 || memcmp (bom, "\xEF\xBB\xBF", 3))
184 convert = FromLocaleDup;
185 rewind (file); /* no BOM, rewind */
188 module_t *module = NULL;
189 char line[1024], section[1022];
192 /* Ensure consistent number formatting... */
193 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
194 locale_t baseloc = uselocale (loc);
196 vlc_rwlock_wrlock (&config_lock);
197 while (fgets (line, 1024, file) != NULL)
199 /* Ignore comments and empty lines */
210 char *ptr = strchr (line, ']');
212 continue; /* syntax error; */
215 /* New section ( = a given module) */
216 strcpy (section, line + 1);
219 if ((psz_module_name == NULL)
220 || (strcmp (psz_module_name, section) == 0))
222 for (int i = 0; list[i]; i++)
224 module_t *m = list[i];
226 if ((strcmp (section, m->psz_object_name) == 0)
227 && (m->i_config_items > 0)) /* ignore config-less modules */
230 if (psz_module_name != NULL)
232 "loading config for module \"%s\"",
243 continue; /* no need to parse if there is no matching module */
245 char *ptr = strchr (line, '\n');
249 /* look for option name */
250 const char *psz_option_name = line;
252 ptr = strchr (line, '=');
254 continue; /* syntax error */
257 const char *psz_option_value = ptr + 1;
259 /* try to match this option with one of the module's options */
260 for (size_t i = 0; i < module->confsize; i++)
262 module_config_t *p_item = module->p_config + i;
264 if ((p_item->i_type & CONFIG_HINT)
265 || strcmp (p_item->psz_name, psz_option_name))
271 switch( p_item->i_type )
273 case CONFIG_ITEM_BOOL:
274 case CONFIG_ITEM_INTEGER:
276 int64_t l = strtoi (psz_option_value);
277 if ((l > p_item->max.i) || (l < p_item->min.i))
280 msg_Warn (p_this, "Integer value (%s) for %s: %m",
281 psz_option_value, psz_option_name);
283 p_item->saved.i = p_item->value.i = l;
287 case CONFIG_ITEM_FLOAT:
288 if( !*psz_option_value )
289 break; /* ignore empty option */
290 p_item->value.f = (float)atof (psz_option_value);
291 p_item->saved.f = p_item->value.f;
294 case CONFIG_ITEM_KEY:
295 if( !*psz_option_value )
296 break; /* ignore empty option */
297 p_item->value.i = ConfigStringToKey(psz_option_value);
298 p_item->saved.i = p_item->value.i;
302 /* free old string */
303 free( (char*) p_item->value.psz );
304 free( (char*) p_item->saved.psz );
306 p_item->value.psz = convert (psz_option_value);
307 p_item->saved.psz = strdupnull (p_item->value.psz);
313 vlc_rwlock_unlock (&config_lock);
317 msg_Err (p_this, "error reading configuration: %m");
322 module_list_free (list);
323 if (loc != (locale_t)0)
331 /*****************************************************************************
332 * config_CreateDir: Create configuration directory if it doesn't exist.
333 *****************************************************************************/
334 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
336 if( !psz_dirname || !*psz_dirname ) return -1;
338 if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
348 /* Let's try to create the parent directory */
349 char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
350 strcpy( psz_parent, psz_dirname );
352 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
353 if( psz_end && psz_end != psz_parent )
356 if( config_CreateDir( p_this, psz_parent ) == 0 )
358 if( !vlc_mkdir( psz_dirname, 0700 ) )
365 msg_Warn( p_this, "could not create %s: %m", psz_dirname );
370 config_Write (FILE *file, const char *desc, const char *type,
371 bool comment, const char *name, const char *fmt, ...)
379 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
380 comment ? "#" : "", name) < 0)
384 ret = vfprintf (file, fmt, ap);
389 if (fputs ("\n\n", file) == EOF)
395 static int config_PrepareDir (vlc_object_t *obj)
397 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
398 if (psz_configdir == NULL)
401 int ret = config_CreateDir (obj, psz_configdir);
402 free (psz_configdir);
406 /*****************************************************************************
407 * config_SaveConfigFile: Save a module's config options.
408 *****************************************************************************
409 * This will save the specified module's config options to the config file.
410 * If psz_module_name is NULL then we save all the modules config options.
411 * It's no use to save the config options that kept their default values, so
412 * we'll try to be a bit clever here.
414 * When we save we mustn't delete the config options of the modules that
415 * haven't been loaded. So we cannot just create a new config file with the
416 * config structures we've got in memory.
417 * I don't really know how to deal with this nicely, so I will use a completly
419 * I will load the config file in memory, but skipping all the sections of the
420 * modules we want to save. Then I will create a brand new file, dump the file
421 * loaded in memory and then append the sections of the modules we want to
424 *****************************************************************************/
425 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
430 char *permanent = NULL, *temporary = NULL;
431 char p_line[1024], *p_index2;
432 unsigned long i_sizebuf = 0;
433 char *p_bigbuffer = NULL, *p_index;
437 if( config_PrepareDir( p_this ) )
439 msg_Err( p_this, "no configuration directory" );
443 file = config_OpenConfigFile( p_this );
448 /* Some users make vlcrc read-only to prevent changes.
449 * The atomic replacement scheme breaks this "feature",
450 * so we check for read-only by hand. */
451 if (fstat (fileno (file), &st)
452 || !(st.st_mode & S_IWUSR))
454 msg_Err (p_this, "configuration file is read-only");
457 i_sizebuf = ( st.st_size < LONG_MAX ) ? st.st_size : 0;
460 p_bigbuffer = p_index = malloc( i_sizebuf+1 );
465 /* List all available modules */
466 module_t **list = module_list_get (NULL);
468 /* backup file into memory, we only need to backup the sections we won't
471 while( file && fgets( p_line, 1024, file ) )
473 if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
476 /* we found a section, check if we need to do a backup */
477 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
479 if( ((p_index2 - &p_line[1])
480 == (int)strlen(p_parser->psz_object_name) )
481 && !memcmp( &p_line[1], p_parser->psz_object_name,
482 strlen(p_parser->psz_object_name) ) )
484 if( !psz_module_name )
486 else if( !strcmp( psz_module_name,
487 p_parser->psz_object_name ) )
492 if( list[i_index] == NULL )
494 /* we don't have this section in our list so we need to back
498 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
511 /* save line if requested and line is valid (doesn't begin with a
512 * space, tab, or eol) */
513 if( b_backup && (p_line[0] != '\n') && (p_line[0] != ' ')
514 && (p_line[0] != '\t') )
516 strcpy( p_index, p_line );
517 p_index += strlen( p_line );
525 * Save module config in file
527 permanent = config_GetConfigFile (p_this);
530 module_list_free (list);
534 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
537 module_list_free (list);
541 /* Configuration lock must be taken before vlcrc serializer below. */
542 vlc_rwlock_rdlock (&config_lock);
544 /* The temporary configuration file is per-PID. Therefore SaveConfigFile()
545 * should be serialized against itself within a given process. */
546 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
547 vlc_mutex_lock (&lock);
549 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
552 vlc_rwlock_unlock (&config_lock);
553 vlc_mutex_unlock (&lock);
554 module_list_free (list);
557 file = fdopen (fd, "wt");
560 msg_Err (p_this, "cannot create configuration file: %m");
561 vlc_rwlock_unlock (&config_lock);
563 vlc_mutex_unlock (&lock);
564 module_list_free (list);
570 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
574 "### lines beginning with a '#' character are comments\n"
578 /* Ensure consistent number formatting... */
579 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
580 locale_t baseloc = uselocale (loc);
582 /* We would take the config lock here. But this would cause a lock
583 * inversion with the serializer above and config_AutoSaveConfigFile().
584 vlc_rwlock_rdlock (&config_lock);*/
586 /* Look for the selected module, if NULL then save everything */
587 for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
589 module_config_t *p_item, *p_end;
591 if( psz_module_name && strcmp( psz_module_name,
592 p_parser->psz_object_name ) )
595 if( !p_parser->i_config_items )
598 if( psz_module_name )
599 msg_Dbg( p_this, "saving config for module \"%s\"",
600 p_parser->psz_object_name );
602 fprintf( file, "[%s]", p_parser->psz_object_name );
603 if( p_parser->psz_longname )
604 fprintf( file, " # %s\n\n", p_parser->psz_longname );
606 fprintf( file, "\n\n" );
608 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
612 if ((p_item->i_type & CONFIG_HINT) /* ignore hint */
613 || p_item->b_removed /* ignore deprecated option */
614 || p_item->b_unsaveable) /* ignore volatile option */
617 /* Do not save the new value in the configuration file
618 * if doing an autosave, and the item is not an "autosaved" one. */
619 bool b_retain = b_autosave && !p_item->b_autosave;
621 if (IsConfigIntegerType (p_item->i_type))
623 int64_t val = b_retain ? p_item->saved.i : p_item->value.i;
624 if (p_item->i_type == CONFIG_ITEM_KEY)
626 char *psz_key = ConfigKeyToString (val);
627 config_Write (file, p_item->psz_text, N_("key"),
628 val == p_item->orig.i,
629 p_item->psz_name, "%s",
630 psz_key ? psz_key : "");
634 config_Write (file, p_item->psz_text,
635 (p_item->i_type == CONFIG_ITEM_BOOL)
636 ? N_("boolean") : N_("integer"),
637 val == p_item->orig.i,
638 p_item->psz_name, "%"PRId64, val);
639 p_item->saved.i = val;
642 if (IsConfigFloatType (p_item->i_type))
644 float val = b_retain ? p_item->saved.f : p_item->value.f;
645 config_Write (file, p_item->psz_text, N_("float"),
646 val == p_item->orig.f,
647 p_item->psz_name, "%f", val);
648 p_item->saved.f = val;
652 const char *psz_value = b_retain ? p_item->saved.psz
656 assert (IsConfigStringType (p_item->i_type));
658 if (b_retain && (psz_value == NULL)) /* FIXME: hack */
659 psz_value = p_item->orig.psz;
663 ? ((p_item->orig.psz != NULL)
664 ? (strcmp (psz_value, p_item->orig.psz) != 0)
666 : (p_item->orig.psz != NULL);
668 config_Write (file, p_item->psz_text, N_("string"),
669 !modified, p_item->psz_name, "%s",
670 psz_value ? psz_value : "");
675 free ((char *)p_item->saved.psz);
676 if( (psz_value && p_item->orig.psz &&
677 strcmp( psz_value, p_item->orig.psz )) ||
678 !psz_value || !p_item->orig.psz)
679 p_item->saved.psz = strdupnull (psz_value);
681 p_item->saved.psz = NULL;
686 p_item->b_dirty = false;
689 vlc_rwlock_unlock (&config_lock);
691 module_list_free (list);
692 if (loc != (locale_t)0)
699 * Restore old settings from the config in file
701 fputs( p_bigbuffer, file );
705 * Flush to disk and replace atomically
707 fflush (file); /* Flush from run-time */
710 vlc_unlink (temporary);
711 vlc_mutex_unlock (&lock);
712 msg_Err (p_this, "cannot write configuration file");
718 fsync (fd); /* Flush from OS */
720 fdatasync (fd); /* Flush from OS */
722 /* Atomically replace the file... */
723 if (vlc_rename (temporary, permanent))
724 vlc_unlink (temporary);
725 /* (...then synchronize the directory, err, TODO...) */
726 /* ...and finally close the file */
727 vlc_mutex_unlock (&lock);
731 /* Windows cannot remove open files nor overwrite existing ones */
732 vlc_unlink (permanent);
733 if (vlc_rename (temporary, permanent))
734 vlc_unlink (temporary);
735 vlc_mutex_unlock (&lock);
751 int config_AutoSaveConfigFile( vlc_object_t *p_this )
753 int ret = VLC_SUCCESS;
758 /* Check if there's anything to save */
759 module_t **list = module_list_get (NULL);
760 vlc_rwlock_rdlock (&config_lock);
761 for (size_t i_index = 0; list[i_index] && !save; i_index++)
763 module_t *p_parser = list[i_index];
764 module_config_t *p_item, *p_end;
766 if( !p_parser->i_config_items ) continue;
768 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
769 p_item < p_end && !save;
772 save = p_item->b_autosave && p_item->b_dirty;
777 /* Note: this will get the read lock recursively. Ok. */
778 ret = SaveConfigFile (p_this, NULL, true);
779 vlc_rwlock_unlock (&config_lock);
781 module_list_free (list);
785 #undef config_SaveConfigFile
786 int config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
788 return SaveConfigFile( p_this, psz_module_name, false );