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 (CONFIG_CLASS(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)
359 char *permanent = NULL, *temporary = NULL;
361 if( config_PrepareDir( p_this ) )
363 msg_Err( p_this, "no configuration directory" );
367 /* List all available modules */
368 module_t **list = module_list_get (NULL);
372 FILE *file = config_OpenConfigFile (p_this);
377 /* Some users make vlcrc read-only to prevent changes.
378 * The atomic replacement scheme breaks this "feature",
379 * so we check for read-only by hand. */
380 if (fstat (fileno (file), &st)
381 || !(st.st_mode & S_IWUSR))
383 msg_Err (p_this, "configuration file is read-only");
387 bigsize = (st.st_size < LONG_MAX) ? st.st_size : 0;
388 bigbuf = malloc (bigsize + 1);
392 /* backup file into memory, we only need to backup the sections we
393 * won't save later on */
394 char *p_index = bigbuf;
400 while ((linelen = getline (&line, &bufsize, file)) != -1)
404 if ((line[0] == '[') && (p_index2 = strchr(line,']')))
408 /* we found a new section, check if we need to do a backup */
410 for (int i = 0; (module = list[i]) != NULL; i++)
412 const char *objname = module_get_object (module);
414 if (!strncmp (line + 1, objname, strlen (objname)))
416 backup = false; /* no, we will rewrite it! */
422 /* save line if requested and line is valid (doesn't begin with a
423 * space, tab, or eol) */
424 if (backup && !memchr ("\n\t ", line[0], 3))
426 memcpy (p_index, line, linelen);
434 bigsize = p_index - bigbuf;
438 * Save module config in file
440 permanent = config_GetConfigFile (p_this);
443 module_list_free (list);
447 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
450 module_list_free (list);
454 /* Configuration lock must be taken before vlcrc serializer below. */
455 vlc_rwlock_rdlock (&config_lock);
457 /* The temporary configuration file is per-PID. Therefore SaveConfigFile()
458 * should be serialized against itself within a given process. */
459 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
460 vlc_mutex_lock (&lock);
462 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
465 vlc_rwlock_unlock (&config_lock);
466 vlc_mutex_unlock (&lock);
467 module_list_free (list);
470 file = fdopen (fd, "wt");
473 msg_Err (p_this, "cannot create configuration file: %m");
474 vlc_rwlock_unlock (&config_lock);
476 vlc_mutex_unlock (&lock);
477 module_list_free (list);
483 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
487 "### lines beginning with a '#' character are comments\n"
491 /* Ensure consistent number formatting... */
492 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
493 locale_t baseloc = uselocale (loc);
495 /* We would take the config lock here. But this would cause a lock
496 * inversion with the serializer above and config_AutoSaveConfigFile().
497 vlc_rwlock_rdlock (&config_lock);*/
499 /* Look for the selected module, if NULL then save everything */
501 for (int i = 0; (p_parser = list[i]) != NULL; i++)
503 module_config_t *p_item, *p_end;
505 if( !p_parser->i_config_items )
508 fprintf( file, "[%s]", module_get_object (p_parser) );
509 if( p_parser->psz_longname )
510 fprintf( file, " # %s\n\n", p_parser->psz_longname );
512 fprintf( file, "\n\n" );
514 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
518 if (!CONFIG_ITEM(p_item->i_type) /* ignore hint */
519 || p_item->b_removed /* ignore deprecated option */
520 || p_item->b_unsaveable) /* ignore volatile option */
523 if (IsConfigIntegerType (p_item->i_type))
525 int64_t val = p_item->value.i;
526 config_Write (file, p_item->psz_text,
527 (CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL)
528 ? N_("boolean") : N_("integer"),
529 val == p_item->orig.i,
530 p_item->psz_name, "%"PRId64, val);
533 if (IsConfigFloatType (p_item->i_type))
535 float val = p_item->value.f;
536 config_Write (file, p_item->psz_text, N_("float"),
537 val == p_item->orig.f,
538 p_item->psz_name, "%f", val);
542 const char *psz_value = p_item->value.psz;
545 assert (IsConfigStringType (p_item->i_type));
547 modified = !!strcmp (psz_value ? psz_value : "",
548 p_item->orig.psz ? p_item->orig.psz : "");
549 config_Write (file, p_item->psz_text, N_("string"),
550 !modified, p_item->psz_name, "%s",
551 psz_value ? psz_value : "");
553 p_item->b_dirty = false;
556 vlc_rwlock_unlock (&config_lock);
558 module_list_free (list);
559 if (loc != (locale_t)0)
566 * Restore old settings from the config in file
569 fwrite (bigbuf, 1, bigsize, file);
572 * Flush to disk and replace atomically
574 fflush (file); /* Flush from run-time */
577 vlc_unlink (temporary);
578 vlc_mutex_unlock (&lock);
579 msg_Err (p_this, "cannot write configuration file");
583 #if defined(__APPLE__) || defined(__ANDROID__)
584 fsync (fd); /* Flush from OS */
586 fdatasync (fd); /* Flush from OS */
588 #if defined (WIN32) || defined (__OS2__)
589 /* Windows cannot (re)move open files nor overwrite existing ones */
591 vlc_unlink (permanent);
593 /* Atomically replace the file... */
594 if (vlc_rename (temporary, permanent))
595 vlc_unlink (temporary);
596 /* (...then synchronize the directory, err, TODO...) */
597 /* ...and finally close the file */
598 vlc_mutex_unlock (&lock);
599 #if !defined (WIN32) && !defined (__OS2__)
617 int config_AutoSaveConfigFile( vlc_object_t *p_this )
619 int ret = VLC_SUCCESS;
624 /* Check if there's anything to save */
625 module_t **list = module_list_get (NULL);
626 vlc_rwlock_rdlock (&config_lock);
627 for (size_t i_index = 0; list[i_index] && !save; i_index++)
629 module_t *p_parser = list[i_index];
630 module_config_t *p_item, *p_end;
632 if( !p_parser->i_config_items ) continue;
634 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
635 p_item < p_end && !save;
638 save = p_item->b_dirty;
643 /* Note: this will get the read lock recursively. Ok. */
644 ret = SaveConfigFile (p_this);
645 vlc_rwlock_unlock (&config_lock);
647 module_list_free (list);
651 #undef config_SaveConfigFile
652 int config_SaveConfigFile( vlc_object_t *p_this )
654 return SaveConfigFile (p_this);