input: resource: move vouts handling from array to list
[vlc.git] / src / config / file.c
blobae6e8b9ce5887b5d91a1a2691e1b0ee92e873ff5
1 /*****************************************************************************
2 * file.c: configuration file handling
3 *****************************************************************************
4 * Copyright (C) 2001-2007 VLC authors and VideoLAN
6 * Authors: Gildas Bazin <gbazin@videolan.org>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation; either version 2.1 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21 *****************************************************************************/
23 #ifdef HAVE_CONFIG_H
24 # include "config.h"
25 #endif
27 #include <errno.h> /* errno */
28 #include <assert.h>
29 #include <limits.h>
30 #include <fcntl.h>
31 #include <sys/stat.h>
32 #ifdef __APPLE__
33 # include <xlocale.h>
34 #elif defined(HAVE_USELOCALE)
35 #include <locale.h>
36 #endif
37 #include <unistd.h>
39 #include <vlc_common.h>
40 #include "../libvlc.h"
41 #include <vlc_charset.h>
42 #include <vlc_fs.h>
43 #include <vlc_actions.h>
44 #include <vlc_modules.h>
45 #include <vlc_plugin.h>
47 #include "configuration.h"
48 #include "modules/modules.h"
50 static inline char *strdupnull (const char *src)
52 return src ? strdup (src) : NULL;
55 /**
56 * Get the user's configuration file
58 static char *config_GetConfigFile( vlc_object_t *obj )
60 char *psz_file = var_InheritString( 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 )
66 psz_file = NULL;
67 free( psz_dir );
69 return psz_file;
72 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
74 char *psz_filename = config_GetConfigFile( p_obj );
75 if( psz_filename == NULL )
76 return 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): %s",
84 psz_filename, vlc_strerror_c(errno) );
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);
93 char *psz_old;
95 if( home != NULL
96 && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
97 home ) != -1 )
99 p_stream = vlc_fopen( psz_old, "rt" );
100 if( p_stream )
102 /* Old config file found. We want to write it at the
103 * new location now. */
104 msg_Info( p_obj, "Found old config file at %s. "
105 "now using %s.", psz_old, psz_filename );
106 char *psz_readme;
107 if( asprintf(&psz_readme,"%s/.vlc/README",
108 home ) != -1 )
110 FILE *p_readme = vlc_fopen( psz_readme, "wt" );
111 if( p_readme )
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.",
119 psz_filename);
120 fclose( p_readme );
122 free( psz_readme );
124 /* Remove the old configuration file so that --reset-config
125 * can work properly. Fortunately, Linux allows removing
126 * open files - with most filesystems. */
127 unlink( psz_old );
129 free( psz_old );
131 free( home );
133 #endif
134 free( psz_filename );
135 return p_stream;
138 static int64_t vlc_strtoi (const char *str)
140 char *end;
141 long long l;
143 errno = 0;
144 l = strtoll (str, &end, 0);
146 if (!errno)
148 #if (LLONG_MAX > 0x7fffffffffffffffLL)
149 if (l > 0x7fffffffffffffffLL
150 || l < -0x8000000000000000LL)
151 errno = ERANGE;
152 #endif
153 if (*end)
154 errno = EINVAL;
156 return l;
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
164 * file.
165 *****************************************************************************/
166 int config_LoadConfigFile( vlc_object_t *p_this )
168 FILE *file;
170 file = config_OpenConfigFile (p_this);
171 if (file == NULL)
172 return VLC_EGENERIC;
174 /* Skip UTF-8 Byte Order Mark if present */
175 char bom[3];
176 if (fread (bom, 1, 3, file) != 3 || memcmp (bom, "\xEF\xBB\xBF", 3))
177 rewind (file); /* no BOM, rewind */
179 char *line = NULL;
180 size_t bufsize;
181 ssize_t linelen;
183 /* Ensure consistent number formatting... */
184 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
185 locale_t baseloc = uselocale (loc);
187 vlc_rwlock_wrlock (&config_lock);
188 while ((linelen = getline (&line, &bufsize, file)) != -1)
190 line[linelen - 1] = '\0'; /* trim newline */
192 /* Ignore comments, section and empty lines */
193 if (memchr ("#[", line[0], 3) != NULL)
194 continue;
196 /* look for option name */
197 const char *psz_option_name = line;
199 char *ptr = strchr (line, '=');
200 if (ptr == NULL)
201 continue; /* syntax error */
202 *ptr = '\0';
204 module_config_t *item = config_FindConfig(psz_option_name);
205 if (item == NULL)
206 continue;
208 /* Reject values of options that are unsaveable */
209 if (item->b_unsaveable)
210 continue;
211 /* Ignore options that are obsolete */
212 if (item->b_removed)
213 continue;
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:
221 int64_t l;
223 errno = 0;
224 l = vlc_strtoi (psz_option_value);
225 if ((l > item->max.i) || (l < item->min.i))
226 errno = ERANGE;
227 if (errno)
228 msg_Warn (p_this, "Integer value (%s) for %s: %s",
229 psz_option_value, psz_option_name,
230 vlc_strerror_c(errno));
231 else
232 item->value.i = l;
233 break;
236 case CONFIG_ITEM_FLOAT:
237 if (!*psz_option_value)
238 break; /* ignore empty option */
239 item->value.f = (float)atof (psz_option_value);
240 break;
242 default:
243 free (item->value.psz);
244 item->value.psz = strdupnull (psz_option_value);
245 break;
248 vlc_rwlock_unlock (&config_lock);
249 free (line);
251 if (ferror (file))
253 msg_Err (p_this, "error reading configuration: %s",
254 vlc_strerror_c(errno));
255 clearerr (file);
257 fclose (file);
259 if (loc != (locale_t)0)
261 uselocale (baseloc);
262 freelocale (loc);
264 return 0;
267 /*****************************************************************************
268 * config_CreateDir: Create configuration directory if it doesn't exist.
269 *****************************************************************************/
270 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
272 if( !psz_dirname || !*psz_dirname ) return -1;
274 if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
275 return 0;
277 switch( errno )
279 case EEXIST:
280 return 0;
282 case ENOENT:
284 /* Let's try to create the parent directory */
285 char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
286 strcpy( psz_parent, psz_dirname );
288 psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
289 if( psz_end && psz_end != psz_parent )
291 *psz_end = '\0';
292 if( config_CreateDir( p_this, psz_parent ) == 0 )
294 if( !vlc_mkdir( psz_dirname, 0700 ) )
295 return 0;
301 msg_Warn( p_this, "could not create %s: %s", psz_dirname,
302 vlc_strerror_c(errno) );
303 return -1;
306 VLC_FORMAT(6, 7) static int
307 config_Write (FILE *file, const char *desc, const char *type,
308 bool comment, const char *name, const char *fmt, ...)
310 va_list ap;
311 int ret;
313 if (desc == NULL)
314 desc = "?";
316 if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
317 comment ? "#" : "", name) < 0)
318 return -1;
320 va_start (ap, fmt);
321 ret = vfprintf (file, fmt, ap);
322 va_end (ap);
323 if (ret < 0)
324 return -1;
326 if (fputs ("\n\n", file) == EOF)
327 return -1;
328 return 0;
332 static int config_PrepareDir (vlc_object_t *obj)
334 char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
335 if (psz_configdir == NULL)
336 return -1;
338 int ret = config_CreateDir (obj, psz_configdir);
339 free (psz_configdir);
340 return ret;
343 #undef config_SaveConfigFile
345 * Saves the in-memory configuration into a file.
346 * @return 0 on success, -1 on error.
348 int config_SaveConfigFile (vlc_object_t *p_this)
351 if( config_PrepareDir( p_this ) )
353 msg_Err( p_this, "no configuration directory" );
354 return -1;
358 * Save module config in file
360 char *temporary;
361 char *permanent = config_GetConfigFile (p_this);
362 if (permanent == NULL)
363 return -1;
364 if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
366 free (permanent);
367 return -1;
369 else
371 struct stat st;
373 /* Some users make vlcrc read-only to prevent changes.
374 * The atomic replacement scheme breaks this "feature",
375 * so we check for read-only by hand. */
376 if (stat (permanent, &st) == 0 && !(st.st_mode & S_IWUSR))
378 msg_Err (p_this, "configuration file is read-only");
379 goto error;
383 /* Configuration lock must be taken before vlcrc serializer below. */
384 vlc_rwlock_rdlock (&config_lock);
386 /* The temporary configuration file is per-PID. Therefore this function
387 * should be serialized against itself within a given process. */
388 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
389 vlc_mutex_lock (&lock);
391 int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
392 if (fd == -1)
394 vlc_rwlock_unlock (&config_lock);
395 vlc_mutex_unlock (&lock);
396 goto error;
398 FILE *file = fdopen (fd, "wt");
399 if (file == NULL)
401 msg_Err (p_this, "cannot create configuration file: %s",
402 vlc_strerror_c(errno));
403 vlc_rwlock_unlock (&config_lock);
404 vlc_close (fd);
405 vlc_mutex_unlock (&lock);
406 goto error;
409 fprintf( file,
410 "\xEF\xBB\xBF###\n"
411 "### "PACKAGE_NAME" "PACKAGE_VERSION"\n"
412 "###\n"
413 "\n"
414 "###\n"
415 "### lines beginning with a '#' character are comments\n"
416 "###\n"
417 "\n" );
419 /* Ensure consistent number formatting... */
420 locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
421 locale_t baseloc = uselocale (loc);
423 /* We would take the config lock here. But this would cause a lock
424 * inversion with the serializer above and config_AutoSaveConfigFile().
425 vlc_rwlock_rdlock (&config_lock);*/
427 /* Look for the selected module, if NULL then save everything */
428 for (vlc_plugin_t *p = vlc_plugins; p != NULL; p = p->next)
430 module_t *p_parser = p->module;
431 module_config_t *p_item, *p_end;
433 if (p->conf.count == 0)
434 continue;
436 fprintf( file, "[%s]", module_get_object (p_parser) );
437 if( p_parser->psz_longname )
438 fprintf( file, " # %s\n\n", p_parser->psz_longname );
439 else
440 fprintf( file, "\n\n" );
442 for (p_item = p->conf.items, p_end = p_item + p->conf.size;
443 p_item < p_end;
444 p_item++)
446 if (!CONFIG_ITEM(p_item->i_type) /* ignore hint */
447 || p_item->b_removed /* ignore deprecated option */
448 || p_item->b_unsaveable) /* ignore volatile option */
449 continue;
451 if (IsConfigIntegerType (p_item->i_type))
453 int64_t val = p_item->value.i;
454 config_Write (file, p_item->psz_text,
455 (CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL)
456 ? N_("boolean") : N_("integer"),
457 val == p_item->orig.i,
458 p_item->psz_name, "%"PRId64, val);
460 else
461 if (IsConfigFloatType (p_item->i_type))
463 float val = p_item->value.f;
464 config_Write (file, p_item->psz_text, N_("float"),
465 val == p_item->orig.f,
466 p_item->psz_name, "%f", val);
468 else
470 const char *psz_value = p_item->value.psz;
471 bool modified;
473 assert (IsConfigStringType (p_item->i_type));
475 modified = !!strcmp (psz_value ? psz_value : "",
476 p_item->orig.psz ? p_item->orig.psz : "");
477 config_Write (file, p_item->psz_text, N_("string"),
478 !modified, p_item->psz_name, "%s",
479 psz_value ? psz_value : "");
483 vlc_rwlock_unlock (&config_lock);
485 if (loc != (locale_t)0)
487 uselocale (baseloc);
488 freelocale (loc);
492 * Flush to disk and replace atomically
494 fflush (file); /* Flush from run-time */
495 if (ferror (file))
497 vlc_unlink (temporary);
498 vlc_mutex_unlock (&lock);
499 msg_Err (p_this, "cannot write configuration file");
500 fclose (file);
501 goto error;
503 fdatasync (fd); /* Flush from OS */
504 #if defined (_WIN32) || defined (__OS2__)
505 /* Windows cannot (re)move open files nor overwrite existing ones */
506 fclose (file);
507 vlc_unlink (permanent);
508 #endif
509 /* Atomically replace the file... */
510 if (vlc_rename (temporary, permanent))
511 vlc_unlink (temporary);
512 /* (...then synchronize the directory, err, TODO...) */
513 /* ...and finally close the file */
514 vlc_mutex_unlock (&lock);
515 #if !defined (_WIN32) && !defined (__OS2__)
516 fclose (file);
517 #endif
519 free (temporary);
520 free (permanent);
521 return 0;
523 error:
524 free (temporary);
525 free (permanent);
526 return -1;
529 int config_AutoSaveConfigFile( vlc_object_t *p_this )
531 int ret = 0;
533 assert( p_this );
535 vlc_rwlock_rdlock (&config_lock);
536 if (config_dirty)
538 /* Note: this will get the read lock recursively. Ok. */
539 ret = config_SaveConfigFile (p_this);
540 config_dirty = (ret != 0);
542 vlc_rwlock_unlock (&config_lock);
544 return ret;