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)
42 #include <vlc_common.h>
43 #include "../libvlc.h"
44 #include <vlc_charset.h>
47 #include <vlc_modules.h>
49 #include "configuration.h"
50 #include "modules/modules.h"
52 static inline char *strdupnull (const char *src)
54 return src ? strdup (src) : NULL;
58 * Get the user's configuration file
60 static char *config_GetConfigFile( vlc_object_t *obj )
62 char *psz_file = var_CreateGetNonEmptyString( obj, "config" );
63 var_Destroy( obj, "config" );
64 if( psz_file == NULL )
66 char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
68 if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
75 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
77 char *psz_filename = config_GetConfigFile( p_obj );
78 if( psz_filename == NULL )
81 msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
83 FILE *p_stream = vlc_fopen( psz_filename, "rt" );
84 if( p_stream == NULL && errno != ENOENT )
86 msg_Err( p_obj, "cannot open config file (%s): %m",
90 #if !( defined(WIN32) || defined(__APPLE__) || defined(__OS2__) )
91 else if( p_stream == NULL && errno == ENOENT )
93 /* This is the fallback for pre XDG Base Directory
94 * Specification configs */
95 char *home = config_GetUserDir(VLC_HOME_DIR);
99 && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
102 p_stream = vlc_fopen( psz_old, "rt" );
105 /* Old config file found. We want to write it at the
106 * new location now. */
107 msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
108 "VLC will now use %s.", psz_old, psz_filename );
110 if( asprintf(&psz_readme,"%s/.vlc/README",
113 FILE *p_readme = vlc_fopen( psz_readme, "wt" );
116 fprintf( p_readme, "The VLC media player "
117 "configuration folder has moved to comply\n"
118 "with the XDG Base Directory Specification "
119 "version 0.6. Your\nconfiguration has been "
120 "copied to the new location:\n%s\nYou can "
121 "delete this directory and all its contents.",
127 /* Remove the old configuration file so that --reset-config
128 * can work properly. Fortunately, Linux allows removing
129 * open files - with most filesystems. */
137 free( psz_filename );
142 static int64_t strtoi (const char *str)
148 l = strtoll (str, &end, 0);
152 #if (LLONG_MAX > 0x7fffffffffffffffLL)
153 if (l > 0x7fffffffffffffffLL
154 || l < -0x8000000000000000LL)
163 #undef config_LoadConfigFile
164 /*****************************************************************************
165 * config_LoadConfigFile: loads the configuration file.
166 *****************************************************************************
167 * This function is called to load the config options stored in the config
169 *****************************************************************************/
170 int config_LoadConfigFile( vlc_object_t *p_this )
174 file = config_OpenConfigFile (p_this);
178 /* Look for UTF-8 Byte Order Mark */
179 char * (*convert) (const char *) = strdupnull;
182 if ((fread (bom, 1, 3, file) != 3)
183 || memcmp (bom, "\xEF\xBB\xBF", 3))
185 convert = FromLocaleDup;
186 rewind (file); /* no BOM, rewind */
193 /* Ensure consistent number formatting... */
194 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
195 locale_t baseloc = uselocale (loc);
197 vlc_rwlock_wrlock (&config_lock);
198 while ((linelen = getline (&line, &bufsize, file)) != -1)
200 line[linelen - 1] = '\0'; /* trim newline */
202 /* Ignore comments, section and empty lines */
203 if (memchr ("#[", line[0], 3) != NULL)
206 /* look for option name */
207 const char *psz_option_name = line;
209 char *ptr = strchr (line, '=');
211 continue; /* syntax error */
214 module_config_t *item = config_FindConfig (p_this, psz_option_name);
218 const char *psz_option_value = ptr + 1;
219 switch (CONFIG_CLASS(item->i_type))
221 case CONFIG_ITEM_BOOL:
222 case CONFIG_ITEM_INTEGER:
227 l = strtoi (psz_option_value);
228 if ((l > item->max.i) || (l < item->min.i))
231 msg_Warn (p_this, "Integer value (%s) for %s: %m",
232 psz_option_value, psz_option_name);
238 case CONFIG_ITEM_FLOAT:
239 if (!*psz_option_value)
240 break; /* ignore empty option */
241 item->value.f = (float)atof (psz_option_value);
245 free ((char *)item->value.psz);
246 item->value.psz = convert (psz_option_value);
250 vlc_rwlock_unlock (&config_lock);
255 msg_Err (p_this, "error reading configuration: %m");
260 if (loc != (locale_t)0)
268 /*****************************************************************************
269 * config_CreateDir: Create configuration directory if it doesn't exist.
270 *****************************************************************************/
271 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
273 if( !psz_dirname || !*psz_dirname ) return -1;
275 if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
285 /* Let's try to create the parent directory */
286 char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
287 strcpy( psz_parent, psz_dirname );
289 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
290 if( psz_end && psz_end != psz_parent )
293 if( config_CreateDir( p_this, psz_parent ) == 0 )
295 if( !vlc_mkdir( psz_dirname, 0700 ) )
302 msg_Warn( p_this, "could not create %s: %m", psz_dirname );
307 config_Write (FILE *file, const char *desc, const char *type,
308 bool comment, const char *name, const char *fmt, ...)
316 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
317 comment ? "#" : "", name) < 0)
321 ret = vfprintf (file, fmt, ap);
326 if (fputs ("\n\n", file) == EOF)
332 static int config_PrepareDir (vlc_object_t *obj)
334 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
335 if (psz_configdir == NULL)
338 int ret = config_CreateDir (obj, psz_configdir);
339 free (psz_configdir);
343 /*****************************************************************************
344 * config_SaveConfigFile: Save a module's config options.
345 *****************************************************************************
346 * It's no use to save the config options that kept their default values, so
347 * we'll try to be a bit clever here.
349 * When we save we mustn't delete the config options of the modules that
350 * haven't been loaded. So we cannot just create a new config file with the
351 * config structures we've got in memory.
352 * I don't really know how to deal with this nicely, so I will use a completly
354 * I will load the config file in memory, but skipping all the sections of the
355 * modules we want to save. Then I will create a brand new file, dump the file
356 * loaded in memory and then append the sections of the modules we want to
359 *****************************************************************************/
360 static int SaveConfigFile (vlc_object_t *p_this)
362 char *permanent = NULL, *temporary = NULL;
364 if( config_PrepareDir( p_this ) )
366 msg_Err( p_this, "no configuration directory" );
370 /* List all available modules */
371 module_t **list = module_list_get (NULL);
375 FILE *file = config_OpenConfigFile (p_this);
380 /* Some users make vlcrc read-only to prevent changes.
381 * The atomic replacement scheme breaks this "feature",
382 * so we check for read-only by hand. */
383 if (fstat (fileno (file), &st)
384 || !(st.st_mode & S_IWUSR))
386 msg_Err (p_this, "configuration file is read-only");
390 bigsize = (st.st_size < LONG_MAX) ? st.st_size : 0;
391 bigbuf = malloc (bigsize + 1);
395 /* backup file into memory, we only need to backup the sections we
396 * won't save later on */
397 char *p_index = bigbuf;
403 while ((linelen = getline (&line, &bufsize, file)) != -1)
407 if ((line[0] == '[') && (p_index2 = strchr(line,']')))
411 /* we found a new section, check if we need to do a backup */
413 for (int i = 0; (module = list[i]) != NULL; i++)
415 const char *objname = module_get_object (module);
417 if (!strncmp (line + 1, objname, strlen (objname)))
419 backup = false; /* no, we will rewrite it! */
425 /* save line if requested and line is valid (doesn't begin with a
426 * space, tab, or eol) */
427 if (backup && !memchr ("\n\t ", line[0], 3))
429 memcpy (p_index, line, linelen);
437 bigsize = p_index - bigbuf;
441 * Save module config in file
443 permanent = config_GetConfigFile (p_this);
446 module_list_free (list);
450 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
453 module_list_free (list);
457 /* Configuration lock must be taken before vlcrc serializer below. */
458 vlc_rwlock_rdlock (&config_lock);
460 /* The temporary configuration file is per-PID. Therefore SaveConfigFile()
461 * should be serialized against itself within a given process. */
462 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
463 vlc_mutex_lock (&lock);
465 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
468 vlc_rwlock_unlock (&config_lock);
469 vlc_mutex_unlock (&lock);
470 module_list_free (list);
473 file = fdopen (fd, "wt");
476 msg_Err (p_this, "cannot create configuration file: %m");
477 vlc_rwlock_unlock (&config_lock);
479 vlc_mutex_unlock (&lock);
480 module_list_free (list);
486 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
490 "### lines beginning with a '#' character are comments\n"
494 /* Ensure consistent number formatting... */
495 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
496 locale_t baseloc = uselocale (loc);
498 /* We would take the config lock here. But this would cause a lock
499 * inversion with the serializer above and config_AutoSaveConfigFile().
500 vlc_rwlock_rdlock (&config_lock);*/
502 /* Look for the selected module, if NULL then save everything */
504 for (int i = 0; (p_parser = list[i]) != NULL; i++)
506 module_config_t *p_item, *p_end;
508 if( !p_parser->i_config_items )
511 fprintf( file, "[%s]", module_get_object (p_parser) );
512 if( p_parser->psz_longname )
513 fprintf( file, " # %s\n\n", p_parser->psz_longname );
515 fprintf( file, "\n\n" );
517 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
521 if (!CONFIG_ITEM(p_item->i_type) /* ignore hint */
522 || p_item->b_removed /* ignore deprecated option */
523 || p_item->b_unsaveable) /* ignore volatile option */
526 if (IsConfigIntegerType (p_item->i_type))
528 int64_t val = p_item->value.i;
529 config_Write (file, p_item->psz_text,
530 (CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL)
531 ? N_("boolean") : N_("integer"),
532 val == p_item->orig.i,
533 p_item->psz_name, "%"PRId64, val);
536 if (IsConfigFloatType (p_item->i_type))
538 float val = p_item->value.f;
539 config_Write (file, p_item->psz_text, N_("float"),
540 val == p_item->orig.f,
541 p_item->psz_name, "%f", val);
545 const char *psz_value = p_item->value.psz;
548 assert (IsConfigStringType (p_item->i_type));
550 modified = !!strcmp (psz_value ? psz_value : "",
551 p_item->orig.psz ? p_item->orig.psz : "");
552 config_Write (file, p_item->psz_text, N_("string"),
553 !modified, p_item->psz_name, "%s",
554 psz_value ? psz_value : "");
556 p_item->b_dirty = false;
559 vlc_rwlock_unlock (&config_lock);
561 module_list_free (list);
562 if (loc != (locale_t)0)
569 * Restore old settings from the config in file
572 fwrite (bigbuf, 1, bigsize, file);
575 * Flush to disk and replace atomically
577 fflush (file); /* Flush from run-time */
580 vlc_unlink (temporary);
581 vlc_mutex_unlock (&lock);
582 msg_Err (p_this, "cannot write configuration file");
586 #if defined(__APPLE__) || defined(__ANDROID__)
587 fsync (fd); /* Flush from OS */
589 fdatasync (fd); /* Flush from OS */
591 #if defined (WIN32) || defined (__OS2__)
592 /* Windows cannot (re)move open files nor overwrite existing ones */
594 vlc_unlink (permanent);
596 /* Atomically replace the file... */
597 if (vlc_rename (temporary, permanent))
598 vlc_unlink (temporary);
599 /* (...then synchronize the directory, err, TODO...) */
600 /* ...and finally close the file */
601 vlc_mutex_unlock (&lock);
602 #if !defined (WIN32) && !defined (__OS2__)
620 int config_AutoSaveConfigFile( vlc_object_t *p_this )
622 int ret = VLC_SUCCESS;
627 /* Check if there's anything to save */
628 module_t **list = module_list_get (NULL);
629 vlc_rwlock_rdlock (&config_lock);
630 for (size_t i_index = 0; list[i_index] && !save; i_index++)
632 module_t *p_parser = list[i_index];
633 module_config_t *p_item, *p_end;
635 if( !p_parser->i_config_items ) continue;
637 for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
638 p_item < p_end && !save;
641 save = p_item->b_dirty;
646 /* Note: this will get the read lock recursively. Ok. */
647 ret = SaveConfigFile (p_this);
648 vlc_rwlock_unlock (&config_lock);
650 module_list_free (list);
654 #undef config_SaveConfigFile
655 int config_SaveConfigFile( vlc_object_t *p_this )
657 return SaveConfigFile (p_this);