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(__OS2__) )
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 )
171 file = config_OpenConfigFile (p_this);
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 */
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 ((linelen = getline (&line, &bufsize, file)) != -1)
197 line[linelen - 1] = '\0'; /* trim newline */
199 /* Ignore comments, section and empty lines */
200 if (memchr ("#[", line[0], 3) != NULL)
203 /* look for option name */
204 const char *psz_option_name = line;
206 char *ptr = strchr (line, '=');
208 continue; /* syntax error */
211 module_config_t *item = config_FindConfig (p_this, psz_option_name);
215 const char *psz_option_value = ptr + 1;
216 switch (item->i_type)
218 case CONFIG_ITEM_BOOL:
219 case CONFIG_ITEM_INTEGER:
224 l = strtoi (psz_option_value);
225 if ((l > item->max.i) || (l < item->min.i))
228 msg_Warn (p_this, "Integer value (%s) for %s: %m",
229 psz_option_value, psz_option_name);
235 case CONFIG_ITEM_FLOAT:
236 if (!*psz_option_value)
237 break; /* ignore empty option */
238 item->value.f = (float)atof (psz_option_value);
242 free ((char *)item->value.psz);
243 item->value.psz = convert (psz_option_value);
247 vlc_rwlock_unlock (&config_lock);
252 msg_Err (p_this, "error reading configuration: %m");
257 if (loc != (locale_t)0)
265 /*****************************************************************************
266 * config_CreateDir: Create configuration directory if it doesn't exist.
267 *****************************************************************************/
268 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
270 if( !psz_dirname || !*psz_dirname ) return -1;
272 if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
282 /* Let's try to create the parent directory */
283 char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
284 strcpy( psz_parent, psz_dirname );
286 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
287 if( psz_end && psz_end != psz_parent )
290 if( config_CreateDir( p_this, psz_parent ) == 0 )
292 if( !vlc_mkdir( psz_dirname, 0700 ) )
299 msg_Warn( p_this, "could not create %s: %m", psz_dirname );
304 config_Write (FILE *file, const char *desc, const char *type,
305 bool comment, const char *name, const char *fmt, ...)
313 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
314 comment ? "#" : "", name) < 0)
318 ret = vfprintf (file, fmt, ap);
323 if (fputs ("\n\n", file) == EOF)
329 static int config_PrepareDir (vlc_object_t *obj)
331 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
332 if (psz_configdir == NULL)
335 int ret = config_CreateDir (obj, psz_configdir);
336 free (psz_configdir);
340 /*****************************************************************************
341 * config_SaveConfigFile: Save a module's config options.
342 *****************************************************************************
343 * It's no use to save the config options that kept their default values, so
344 * we'll try to be a bit clever here.
346 * When we save we mustn't delete the config options of the modules that
347 * haven't been loaded. So we cannot just create a new config file with the
348 * config structures we've got in memory.
349 * I don't really know how to deal with this nicely, so I will use a completly
351 * I will load the config file in memory, but skipping all the sections of the
352 * modules we want to save. Then I will create a brand new file, dump the file
353 * loaded in memory and then append the sections of the modules we want to
356 *****************************************************************************/
357 static int SaveConfigFile (vlc_object_t *p_this)
360 char *permanent = NULL, *temporary = NULL;
362 if( config_PrepareDir( p_this ) )
364 msg_Err( p_this, "no configuration directory" );
368 /* List all available modules */
369 module_t **list = module_list_get (NULL);
373 FILE *file = config_OpenConfigFile (p_this);
378 /* Some users make vlcrc read-only to prevent changes.
379 * The atomic replacement scheme breaks this "feature",
380 * so we check for read-only by hand. */
381 if (fstat (fileno (file), &st)
382 || !(st.st_mode & S_IWUSR))
384 msg_Err (p_this, "configuration file is read-only");
388 bigsize = (st.st_size < LONG_MAX) ? st.st_size : 0;
389 bigbuf = malloc (bigsize + 1);
393 /* backup file into memory, we only need to backup the sections we
394 * won't save later on */
395 char *p_index = bigbuf;
401 while ((linelen = getline (&line, &bufsize, file)) != -1)
405 if ((line[0] == '[') && (p_index2 = strchr(line,']')))
407 /* we found a new section, check if we need to do a backup */
409 for (int i = 0; (p_parser = list[i]) != NULL; i++)
411 if (!strncmp (line + 1, p_parser->psz_object_name,
412 strlen (p_parser->psz_object_name)))
414 backup = false; /* no, we will rewrite it! */
420 /* save line if requested and line is valid (doesn't begin with a
421 * space, tab, or eol) */
422 if (backup && !memchr ("\n\t ", line[0], 3))
424 memcpy (p_index, line, linelen);
432 bigsize = p_index - bigbuf;
436 * Save module config in file
438 permanent = config_GetConfigFile (p_this);
441 module_list_free (list);
445 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
448 module_list_free (list);
452 /* Configuration lock must be taken before vlcrc serializer below. */
453 vlc_rwlock_rdlock (&config_lock);
455 /* The temporary configuration file is per-PID. Therefore SaveConfigFile()
456 * should be serialized against itself within a given process. */
457 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
458 vlc_mutex_lock (&lock);
460 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
463 vlc_rwlock_unlock (&config_lock);
464 vlc_mutex_unlock (&lock);
465 module_list_free (list);
468 file = fdopen (fd, "wt");
471 msg_Err (p_this, "cannot create configuration file: %m");
472 vlc_rwlock_unlock (&config_lock);
474 vlc_mutex_unlock (&lock);
475 module_list_free (list);
481 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
485 "### lines beginning with a '#' character are comments\n"
489 /* Ensure consistent number formatting... */
490 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
491 locale_t baseloc = uselocale (loc);
493 /* We would take the config lock here. But this would cause a lock
494 * inversion with the serializer above and config_AutoSaveConfigFile().
495 vlc_rwlock_rdlock (&config_lock);*/
497 /* Look for the selected module, if NULL then save everything */
498 for (int i = 0; (p_parser = list[i]) != NULL; i++)
500 module_config_t *p_item, *p_end;
502 if( !p_parser->i_config_items )
505 fprintf( file, "[%s]", p_parser->psz_object_name );
506 if( p_parser->psz_longname )
507 fprintf( file, " # %s\n\n", p_parser->psz_longname );
509 fprintf( file, "\n\n" );
511 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
515 if ((p_item->i_type & CONFIG_HINT) /* ignore hint */
516 || p_item->b_removed /* ignore deprecated option */
517 || p_item->b_unsaveable) /* ignore volatile option */
520 if (IsConfigIntegerType (p_item->i_type))
522 int64_t val = p_item->value.i;
523 config_Write (file, p_item->psz_text,
524 (p_item->i_type == CONFIG_ITEM_BOOL)
525 ? N_("boolean") : N_("integer"),
526 val == p_item->orig.i,
527 p_item->psz_name, "%"PRId64, val);
530 if (IsConfigFloatType (p_item->i_type))
532 float val = p_item->value.f;
533 config_Write (file, p_item->psz_text, N_("float"),
534 val == p_item->orig.f,
535 p_item->psz_name, "%f", val);
539 const char *psz_value = p_item->value.psz;
542 assert (IsConfigStringType (p_item->i_type));
544 modified = !!strcmp (psz_value ? psz_value : "",
545 p_item->orig.psz ? p_item->orig.psz : "");
546 config_Write (file, p_item->psz_text, N_("string"),
547 !modified, p_item->psz_name, "%s",
548 psz_value ? psz_value : "");
550 p_item->b_dirty = false;
553 vlc_rwlock_unlock (&config_lock);
555 module_list_free (list);
556 if (loc != (locale_t)0)
563 * Restore old settings from the config in file
566 fwrite (bigbuf, 1, bigsize, file);
569 * Flush to disk and replace atomically
571 fflush (file); /* Flush from run-time */
574 vlc_unlink (temporary);
575 vlc_mutex_unlock (&lock);
576 msg_Err (p_this, "cannot write configuration file");
580 #if !defined( WIN32 ) && !defined( __OS2__ )
582 fsync (fd); /* Flush from OS */
584 fdatasync (fd); /* Flush from OS */
586 /* Atomically replace the file... */
587 if (vlc_rename (temporary, permanent))
588 vlc_unlink (temporary);
589 /* (...then synchronize the directory, err, TODO...) */
590 /* ...and finally close the file */
591 vlc_mutex_unlock (&lock);
594 #if defined( WIN32 ) || defined( __OS2__ )
595 /* Windows cannot remove open files nor overwrite existing ones */
596 vlc_unlink (permanent);
597 if (vlc_rename (temporary, permanent))
598 vlc_unlink (temporary);
599 vlc_mutex_unlock (&lock);
616 int config_AutoSaveConfigFile( vlc_object_t *p_this )
618 int ret = VLC_SUCCESS;
623 /* Check if there's anything to save */
624 module_t **list = module_list_get (NULL);
625 vlc_rwlock_rdlock (&config_lock);
626 for (size_t i_index = 0; list[i_index] && !save; i_index++)
628 module_t *p_parser = list[i_index];
629 module_config_t *p_item, *p_end;
631 if( !p_parser->i_config_items ) continue;
633 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
634 p_item < p_end && !save;
637 save = p_item->b_dirty;
642 /* Note: this will get the read lock recursively. Ok. */
643 ret = SaveConfigFile (p_this);
644 vlc_rwlock_unlock (&config_lock);
646 module_list_free (list);
650 #undef config_SaveConfigFile
651 int config_SaveConfigFile( vlc_object_t *p_this )
653 return SaveConfigFile (p_this);