]> git.sesse.net Git - vlc/blob - src/config/file.c
LGPL
[vlc] / src / config / file.c
1 /*****************************************************************************
2  * file.c: configuration file handling
3  *****************************************************************************
4  * Copyright (C) 2001-2007 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
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 Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <errno.h>                                                  /* errno */
29 #include <assert.h>
30 #include <limits.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #ifdef __APPLE__
34 #   include <xlocale.h>
35 #elif defined(HAVE_USELOCALE)
36 #include <locale.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41
42 #include <vlc_common.h>
43 #include "../libvlc.h"
44 #include <vlc_charset.h>
45 #include <vlc_fs.h>
46 #include <vlc_keys.h>
47 #include <vlc_modules.h>
48
49 #include "configuration.h"
50 #include "modules/modules.h"
51
52 static inline char *strdupnull (const char *src)
53 {
54     return src ? strdup (src) : NULL;
55 }
56
57 /**
58  * Get the user's configuration file
59  */
60 static char *config_GetConfigFile( vlc_object_t *obj )
61 {
62     char *psz_file = var_CreateGetNonEmptyString( obj, "config" );
63     var_Destroy( obj, "config" );
64     if( psz_file == NULL )
65     {
66         char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
67
68         if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
69             psz_file = NULL;
70         free( psz_dir );
71     }
72     return psz_file;
73 }
74
75 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
76 {
77     char *psz_filename = config_GetConfigFile( p_obj );
78     if( psz_filename == NULL )
79         return NULL;
80
81     msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
82
83     FILE *p_stream = vlc_fopen( psz_filename, "rt" );
84     if( p_stream == NULL && errno != ENOENT )
85     {
86         msg_Err( p_obj, "cannot open config file (%s): %m",
87                  psz_filename );
88
89     }
90 #if !( defined(WIN32) || defined(__APPLE__) || defined(__OS2__) )
91     else if( p_stream == NULL && errno == ENOENT )
92     {
93         /* This is the fallback for pre XDG Base Directory
94          * Specification configs */
95         char *home = config_GetUserDir(VLC_HOME_DIR);
96         char *psz_old;
97
98         if( home != NULL
99          && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
100                       home ) != -1 )
101         {
102             p_stream = vlc_fopen( psz_old, "rt" );
103             if( p_stream )
104             {
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 );
109                 char *psz_readme;
110                 if( asprintf(&psz_readme,"%s/.vlc/README",
111                              home ) != -1 )
112                 {
113                     FILE *p_readme = vlc_fopen( psz_readme, "wt" );
114                     if( p_readme )
115                     {
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.",
122                                   psz_filename);
123                         fclose( p_readme );
124                     }
125                     free( psz_readme );
126                 }
127                 /* Remove the old configuration file so that --reset-config
128                  * can work properly. Fortunately, Linux allows removing
129                  * open files - with most filesystems. */
130                 unlink( psz_old );
131             }
132             free( psz_old );
133         }
134         free( home );
135     }
136 #endif
137     free( psz_filename );
138     return p_stream;
139 }
140
141
142 static int64_t strtoi (const char *str)
143 {
144     char *end;
145     long long l;
146
147     errno = 0;
148     l = strtoll (str, &end, 0);
149
150     if (!errno)
151     {
152 #if (LLONG_MAX > 0x7fffffffffffffffLL)
153         if (l > 0x7fffffffffffffffLL
154          || l < -0x8000000000000000LL)
155             errno = ERANGE;
156 #endif
157         if (*end)
158             errno = EINVAL;
159     }
160     return l;
161 }
162
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
168  * file.
169  *****************************************************************************/
170 int config_LoadConfigFile( vlc_object_t *p_this )
171 {
172     FILE *file;
173
174     file = config_OpenConfigFile (p_this);
175     if (file == NULL)
176         return VLC_EGENERIC;
177
178     /* Look for UTF-8 Byte Order Mark */
179     char * (*convert) (const char *) = strdupnull;
180     char bom[3];
181
182     if ((fread (bom, 1, 3, file) != 3)
183      || memcmp (bom, "\xEF\xBB\xBF", 3))
184     {
185         convert = FromLocaleDup;
186         rewind (file); /* no BOM, rewind */
187     }
188
189     char *line = NULL;
190     size_t bufsize;
191     ssize_t linelen;
192
193     /* Ensure consistent number formatting... */
194     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
195     locale_t baseloc = uselocale (loc);
196
197     vlc_rwlock_wrlock (&config_lock);
198     while ((linelen = getline (&line, &bufsize, file)) != -1)
199     {
200         line[linelen - 1] = '\0'; /* trim newline */
201
202         /* Ignore comments, section and empty lines */
203         if (memchr ("#[", line[0], 3) != NULL)
204             continue;
205
206         /* look for option name */
207         const char *psz_option_name = line;
208
209         char *ptr = strchr (line, '=');
210         if (ptr == NULL)
211             continue; /* syntax error */
212         *ptr = '\0';
213
214         module_config_t *item = config_FindConfig (p_this, psz_option_name);
215         if (item == NULL)
216             continue;
217
218         const char *psz_option_value = ptr + 1;
219         switch (CONFIG_CLASS(item->i_type))
220         {
221             case CONFIG_ITEM_BOOL:
222             case CONFIG_ITEM_INTEGER:
223             {
224                 int64_t l;
225
226                 errno = 0;
227                 l = strtoi (psz_option_value);
228                 if ((l > item->max.i) || (l < item->min.i))
229                     errno = ERANGE;
230                 if (errno)
231                     msg_Warn (p_this, "Integer value (%s) for %s: %m",
232                               psz_option_value, psz_option_name);
233                 else
234                     item->value.i = l;
235                 break;
236             }
237
238             case CONFIG_ITEM_FLOAT:
239                 if (!*psz_option_value)
240                     break;                    /* ignore empty option */
241                 item->value.f = (float)atof (psz_option_value);
242                 break;
243
244             default:
245                 free ((char *)item->value.psz);
246                 item->value.psz = convert (psz_option_value);
247                 break;
248         }
249     }
250     vlc_rwlock_unlock (&config_lock);
251     free (line);
252
253     if (ferror (file))
254     {
255         msg_Err (p_this, "error reading configuration: %m");
256         clearerr (file);
257     }
258     fclose (file);
259
260     if (loc != (locale_t)0)
261     {
262         uselocale (baseloc);
263         freelocale (loc);
264     }
265     return 0;
266 }
267
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 )
272 {
273     if( !psz_dirname || !*psz_dirname ) return -1;
274
275     if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
276         return 0;
277
278     switch( errno )
279     {
280         case EEXIST:
281             return 0;
282
283         case ENOENT:
284         {
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 );
288
289             psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
290             if( psz_end && psz_end != psz_parent )
291             {
292                 *psz_end = '\0';
293                 if( config_CreateDir( p_this, psz_parent ) == 0 )
294                 {
295                     if( !vlc_mkdir( psz_dirname, 0700 ) )
296                         return 0;
297                 }
298             }
299         }
300     }
301
302     msg_Warn( p_this, "could not create %s: %m", psz_dirname );
303     return -1;
304 }
305
306 static int
307 config_Write (FILE *file, const char *desc, const char *type,
308               bool comment, const char *name, const char *fmt, ...)
309 {
310     va_list ap;
311     int ret;
312
313     if (desc == NULL)
314         desc = "?";
315
316     if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
317                  comment ? "#" : "", name) < 0)
318         return -1;
319
320     va_start (ap, fmt);
321     ret = vfprintf (file, fmt, ap);
322     va_end (ap);
323     if (ret < 0)
324         return -1;
325
326     if (fputs ("\n\n", file) == EOF)
327         return -1;
328     return 0;
329 }
330
331
332 static int config_PrepareDir (vlc_object_t *obj)
333 {
334     char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
335     if (psz_configdir == NULL)
336         return -1;
337
338     int ret = config_CreateDir (obj, psz_configdir);
339     free (psz_configdir);
340     return ret;
341 }
342
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.
348  *
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
353  * dumb method ;-)
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
357  * save.
358  * Really stupid no ?
359  *****************************************************************************/
360 static int SaveConfigFile (vlc_object_t *p_this)
361 {
362     char *permanent = NULL, *temporary = NULL;
363
364     if( config_PrepareDir( p_this ) )
365     {
366         msg_Err( p_this, "no configuration directory" );
367         return -1;
368     }
369
370     /* List all available modules */
371     module_t **list = module_list_get (NULL);
372
373     char *bigbuf = NULL;
374     size_t bigsize = 0;
375     FILE *file = config_OpenConfigFile (p_this);
376     if (file != NULL)
377     {
378         struct stat st;
379
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))
385         {
386             msg_Err (p_this, "configuration file is read-only");
387             goto error;
388         }
389
390         bigsize = (st.st_size < LONG_MAX) ? st.st_size : 0;
391         bigbuf = malloc (bigsize + 1);
392         if (bigbuf == NULL)
393             goto error;
394
395         /* backup file into memory, we only need to backup the sections we
396          * won't save later on */
397         char *p_index = bigbuf;
398         char *line = NULL;
399         size_t bufsize;
400         ssize_t linelen;
401         bool backup = false;
402
403         while ((linelen = getline (&line, &bufsize, file)) != -1)
404         {
405             char *p_index2;
406
407             if ((line[0] == '[') && (p_index2 = strchr(line,']')))
408             {
409                 module_t *module;
410
411                 /* we found a new section, check if we need to do a backup */
412                 backup = true;
413                 for (int i = 0; (module = list[i]) != NULL; i++)
414                 {
415                     const char *objname = module_get_object (module);
416
417                     if (!strncmp (line + 1, objname, strlen (objname)))
418                     {
419                         backup = false; /* no, we will rewrite it! */
420                         break;
421                     }
422                 }
423             }
424
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))
428             {
429                 memcpy (p_index, line, linelen);
430                 p_index += linelen;
431             }
432         }
433         fclose (file);
434         file = NULL;
435         free (line);
436         *p_index = '\0';
437         bigsize = p_index - bigbuf;
438     }
439
440     /*
441      * Save module config in file
442      */
443     permanent = config_GetConfigFile (p_this);
444     if (!permanent)
445     {
446         module_list_free (list);
447         goto error;
448     }
449
450     if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
451     {
452         temporary = NULL;
453         module_list_free (list);
454         goto error;
455     }
456
457     /* Configuration lock must be taken before vlcrc serializer below. */
458     vlc_rwlock_rdlock (&config_lock);
459
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);
464
465     int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
466     if (fd == -1)
467     {
468         vlc_rwlock_unlock (&config_lock);
469         vlc_mutex_unlock (&lock);
470         module_list_free (list);
471         goto error;
472     }
473     file = fdopen (fd, "wt");
474     if (file == NULL)
475     {
476         msg_Err (p_this, "cannot create configuration file: %m");
477         vlc_rwlock_unlock (&config_lock);
478         close (fd);
479         vlc_mutex_unlock (&lock);
480         module_list_free (list);
481         goto error;
482     }
483
484     fprintf( file,
485         "\xEF\xBB\xBF###\n"
486         "###  "PACKAGE_NAME" "PACKAGE_VERSION"\n"
487         "###\n"
488         "\n"
489         "###\n"
490         "### lines beginning with a '#' character are comments\n"
491         "###\n"
492         "\n" );
493
494     /* Ensure consistent number formatting... */
495     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
496     locale_t baseloc = uselocale (loc);
497
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);*/
501
502     /* Look for the selected module, if NULL then save everything */
503     module_t *p_parser;
504     for (int i = 0; (p_parser = list[i]) != NULL; i++)
505     {
506         module_config_t *p_item, *p_end;
507
508         if( !p_parser->i_config_items )
509             continue;
510
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 );
514         else
515             fprintf( file, "\n\n" );
516
517         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
518              p_item < p_end;
519              p_item++ )
520         {
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 */
524                 continue;
525
526             if (IsConfigIntegerType (p_item->i_type))
527             {
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);
534             }
535             else
536             if (IsConfigFloatType (p_item->i_type))
537             {
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);
542             }
543             else
544             {
545                 const char *psz_value = p_item->value.psz;
546                 bool modified;
547
548                 assert (IsConfigStringType (p_item->i_type));
549
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 : "");
555             }
556             p_item->b_dirty = false;
557         }
558     }
559     vlc_rwlock_unlock (&config_lock);
560
561     module_list_free (list);
562     if (loc != (locale_t)0)
563     {
564         uselocale (baseloc);
565         freelocale (loc);
566     }
567
568     /*
569      * Restore old settings from the config in file
570      */
571     if (bigsize)
572         fwrite (bigbuf, 1, bigsize, file);
573
574     /*
575      * Flush to disk and replace atomically
576      */
577     fflush (file); /* Flush from run-time */
578     if (ferror (file))
579     {
580         vlc_unlink (temporary);
581         vlc_mutex_unlock (&lock);
582         msg_Err (p_this, "cannot write configuration file");
583         clearerr (file);
584         goto error;
585     }
586 #if defined(__APPLE__) || defined(__ANDROID__)
587     fsync (fd); /* Flush from OS */
588 #else
589     fdatasync (fd); /* Flush from OS */
590 #endif
591 #if defined (WIN32) || defined (__OS2__)
592     /* Windows cannot (re)move open files nor overwrite existing ones */
593     fclose (file);
594     vlc_unlink (permanent);
595 #endif
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__)
603     fclose (file);
604 #endif
605
606     free (temporary);
607     free (permanent);
608     free (bigbuf);
609     return 0;
610
611 error:
612     if( file )
613         fclose( file );
614     free (temporary);
615     free (permanent);
616     free (bigbuf);
617     return -1;
618 }
619
620 int config_AutoSaveConfigFile( vlc_object_t *p_this )
621 {
622     int ret = VLC_SUCCESS;
623     bool save = false;
624
625     assert( p_this );
626
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++)
631     {
632         module_t *p_parser = list[i_index];
633         module_config_t *p_item, *p_end;
634
635         if( !p_parser->i_config_items ) continue;
636
637         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
638              p_item < p_end && !save;
639              p_item++ )
640         {
641             save = p_item->b_dirty;
642         }
643     }
644
645     if (save)
646         /* Note: this will get the read lock recursively. Ok. */
647         ret = SaveConfigFile (p_this);
648     vlc_rwlock_unlock (&config_lock);
649
650     module_list_free (list);
651     return ret;
652 }
653
654 #undef config_SaveConfigFile
655 int config_SaveConfigFile( vlc_object_t *p_this )
656 {
657     return SaveConfigFile (p_this);
658 }