]> git.sesse.net Git - vlc/blob - src/config/file.c
httpd_UrlNew*(): write warning to correct VLC object
[vlc] / src / config / file.c
1 /*****************************************************************************
2  * file.c: configuration file handling
3  *****************************************************************************
4  * Copyright (C) 2001-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
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.
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 General Public License for more details.
18  *
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  *****************************************************************************/
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
39 #include <vlc_common.h>
40 #include "../libvlc.h"
41 #include <vlc_charset.h>
42 #include <vlc_fs.h>
43 #include <vlc_keys.h>
44 #include <vlc_modules.h>
45
46 #include "configuration.h"
47 #include "modules/modules.h"
48
49 static inline char *strdupnull (const char *src)
50 {
51     return src ? strdup (src) : NULL;
52 }
53
54 /**
55  * Get the user's configuration file
56  */
57 static char *config_GetConfigFile( vlc_object_t *obj )
58 {
59     char *psz_file = var_CreateGetNonEmptyString( obj, "config" );
60     var_Destroy( obj, "config" );
61     if( psz_file == NULL )
62     {
63         char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
64
65         if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
66             psz_file = NULL;
67         free( psz_dir );
68     }
69     return psz_file;
70 }
71
72 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
73 {
74     char *psz_filename = config_GetConfigFile( p_obj );
75     if( psz_filename == NULL )
76         return NULL;
77
78     msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
79
80     FILE *p_stream = vlc_fopen( psz_filename, "rt" );
81     if( p_stream == NULL && errno != ENOENT )
82     {
83         msg_Err( p_obj, "cannot open config file (%s): %m",
84                  psz_filename );
85
86     }
87 #if !( defined(WIN32) || defined(__APPLE__) || defined(__OS2__) )
88     else if( p_stream == NULL && errno == ENOENT )
89     {
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;
94
95         if( home != NULL
96          && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
97                       home ) != -1 )
98         {
99             p_stream = vlc_fopen( psz_old, "rt" );
100             if( p_stream )
101             {
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 );
106                 char *psz_readme;
107                 if( asprintf(&psz_readme,"%s/.vlc/README",
108                              home ) != -1 )
109                 {
110                     FILE *p_readme = vlc_fopen( psz_readme, "wt" );
111                     if( p_readme )
112                     {
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 );
121                     }
122                     free( psz_readme );
123                 }
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 );
128             }
129             free( psz_old );
130         }
131         free( home );
132     }
133 #endif
134     free( psz_filename );
135     return p_stream;
136 }
137
138
139 static int64_t strtoi (const char *str)
140 {
141     char *end;
142     long long l;
143
144     errno = 0;
145     l = strtoll (str, &end, 0);
146
147     if (!errno)
148     {
149 #if (LLONG_MAX > 0x7fffffffffffffffLL)
150         if (l > 0x7fffffffffffffffLL
151          || l < -0x8000000000000000LL)
152             errno = ERANGE;
153 #endif
154         if (*end)
155             errno = EINVAL;
156     }
157     return l;
158 }
159
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
165  * file.
166  *****************************************************************************/
167 int config_LoadConfigFile( vlc_object_t *p_this )
168 {
169     FILE *file;
170
171     file = config_OpenConfigFile (p_this);
172     if (file == NULL)
173         return VLC_EGENERIC;
174
175     /* Look for UTF-8 Byte Order Mark */
176     char * (*convert) (const char *) = strdupnull;
177     char bom[3];
178
179     if ((fread (bom, 1, 3, file) != 3)
180      || memcmp (bom, "\xEF\xBB\xBF", 3))
181     {
182         convert = FromLocaleDup;
183         rewind (file); /* no BOM, rewind */
184     }
185
186     char *line = NULL;
187     size_t bufsize;
188     ssize_t linelen;
189
190     /* Ensure consistent number formatting... */
191     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
192     locale_t baseloc = uselocale (loc);
193
194     vlc_rwlock_wrlock (&config_lock);
195     while ((linelen = getline (&line, &bufsize, file)) != -1)
196     {
197         line[linelen - 1] = '\0'; /* trim newline */
198
199         /* Ignore comments, section and empty lines */
200         if (memchr ("#[", line[0], 3) != NULL)
201             continue;
202
203         /* look for option name */
204         const char *psz_option_name = line;
205
206         char *ptr = strchr (line, '=');
207         if (ptr == NULL)
208             continue; /* syntax error */
209         *ptr = '\0';
210
211         module_config_t *item = config_FindConfig (p_this, psz_option_name);
212         if (item == NULL)
213             continue;
214
215         const char *psz_option_value = ptr + 1;
216         switch (CONFIG_CLASS(item->i_type))
217         {
218             case CONFIG_ITEM_BOOL:
219             case CONFIG_ITEM_INTEGER:
220             {
221                 int64_t l;
222
223                 errno = 0;
224                 l = 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: %m",
229                               psz_option_value, psz_option_name);
230                 else
231                     item->value.i = l;
232                 break;
233             }
234
235             case CONFIG_ITEM_FLOAT:
236                 if (!*psz_option_value)
237                     break;                    /* ignore empty option */
238                 item->value.f = (float)atof (psz_option_value);
239                 break;
240
241             default:
242                 free ((char *)item->value.psz);
243                 item->value.psz = convert (psz_option_value);
244                 break;
245         }
246     }
247     vlc_rwlock_unlock (&config_lock);
248     free (line);
249
250     if (ferror (file))
251     {
252         msg_Err (p_this, "error reading configuration: %m");
253         clearerr (file);
254     }
255     fclose (file);
256
257     if (loc != (locale_t)0)
258     {
259         uselocale (baseloc);
260         freelocale (loc);
261     }
262     return 0;
263 }
264
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 )
269 {
270     if( !psz_dirname || !*psz_dirname ) return -1;
271
272     if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
273         return 0;
274
275     switch( errno )
276     {
277         case EEXIST:
278             return 0;
279
280         case ENOENT:
281         {
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 );
285
286             psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
287             if( psz_end && psz_end != psz_parent )
288             {
289                 *psz_end = '\0';
290                 if( config_CreateDir( p_this, psz_parent ) == 0 )
291                 {
292                     if( !vlc_mkdir( psz_dirname, 0700 ) )
293                         return 0;
294                 }
295             }
296         }
297     }
298
299     msg_Warn( p_this, "could not create %s: %m", psz_dirname );
300     return -1;
301 }
302
303 static int
304 config_Write (FILE *file, const char *desc, const char *type,
305               bool comment, const char *name, const char *fmt, ...)
306 {
307     va_list ap;
308     int ret;
309
310     if (desc == NULL)
311         desc = "?";
312
313     if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
314                  comment ? "#" : "", name) < 0)
315         return -1;
316
317     va_start (ap, fmt);
318     ret = vfprintf (file, fmt, ap);
319     va_end (ap);
320     if (ret < 0)
321         return -1;
322
323     if (fputs ("\n\n", file) == EOF)
324         return -1;
325     return 0;
326 }
327
328
329 static int config_PrepareDir (vlc_object_t *obj)
330 {
331     char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
332     if (psz_configdir == NULL)
333         return -1;
334
335     int ret = config_CreateDir (obj, psz_configdir);
336     free (psz_configdir);
337     return ret;
338 }
339
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.
345  *
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
350  * dumb method ;-)
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
354  * save.
355  * Really stupid no ?
356  *****************************************************************************/
357 static int SaveConfigFile (vlc_object_t *p_this)
358 {
359     char *permanent = NULL, *temporary = NULL;
360
361     if( config_PrepareDir( p_this ) )
362     {
363         msg_Err( p_this, "no configuration directory" );
364         return -1;
365     }
366
367     /* List all available modules */
368     module_t **list = module_list_get (NULL);
369
370     char *bigbuf = NULL;
371     size_t bigsize = 0;
372     FILE *file = config_OpenConfigFile (p_this);
373     if (file != NULL)
374     {
375         struct stat st;
376
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))
382         {
383             msg_Err (p_this, "configuration file is read-only");
384             goto error;
385         }
386
387         bigsize = (st.st_size < LONG_MAX) ? st.st_size : 0;
388         bigbuf = malloc (bigsize + 1);
389         if (bigbuf == NULL)
390             goto error;
391
392         /* backup file into memory, we only need to backup the sections we
393          * won't save later on */
394         char *p_index = bigbuf;
395         char *line = NULL;
396         size_t bufsize;
397         ssize_t linelen;
398         bool backup = false;
399
400         while ((linelen = getline (&line, &bufsize, file)) != -1)
401         {
402             char *p_index2;
403
404             if ((line[0] == '[') && (p_index2 = strchr(line,']')))
405             {
406                 module_t *module;
407
408                 /* we found a new section, check if we need to do a backup */
409                 backup = true;
410                 for (int i = 0; (module = list[i]) != NULL; i++)
411                 {
412                     const char *objname = module_get_object (module);
413
414                     if (!strncmp (line + 1, objname, strlen (objname)))
415                     {
416                         backup = false; /* no, we will rewrite it! */
417                         break;
418                     }
419                 }
420             }
421
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))
425             {
426                 memcpy (p_index, line, linelen);
427                 p_index += linelen;
428             }
429         }
430         fclose (file);
431         file = NULL;
432         free (line);
433         *p_index = '\0';
434         bigsize = p_index - bigbuf;
435     }
436
437     /*
438      * Save module config in file
439      */
440     permanent = config_GetConfigFile (p_this);
441     if (!permanent)
442     {
443         module_list_free (list);
444         goto error;
445     }
446
447     if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
448     {
449         temporary = NULL;
450         module_list_free (list);
451         goto error;
452     }
453
454     /* Configuration lock must be taken before vlcrc serializer below. */
455     vlc_rwlock_rdlock (&config_lock);
456
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);
461
462     int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
463     if (fd == -1)
464     {
465         vlc_rwlock_unlock (&config_lock);
466         vlc_mutex_unlock (&lock);
467         module_list_free (list);
468         goto error;
469     }
470     file = fdopen (fd, "wt");
471     if (file == NULL)
472     {
473         msg_Err (p_this, "cannot create configuration file: %m");
474         vlc_rwlock_unlock (&config_lock);
475         close (fd);
476         vlc_mutex_unlock (&lock);
477         module_list_free (list);
478         goto error;
479     }
480
481     fprintf( file,
482         "\xEF\xBB\xBF###\n"
483         "###  "PACKAGE_NAME" "PACKAGE_VERSION"\n"
484         "###\n"
485         "\n"
486         "###\n"
487         "### lines beginning with a '#' character are comments\n"
488         "###\n"
489         "\n" );
490
491     /* Ensure consistent number formatting... */
492     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
493     locale_t baseloc = uselocale (loc);
494
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);*/
498
499     /* Look for the selected module, if NULL then save everything */
500     module_t *p_parser;
501     for (int i = 0; (p_parser = list[i]) != NULL; i++)
502     {
503         module_config_t *p_item, *p_end;
504
505         if( !p_parser->i_config_items )
506             continue;
507
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 );
511         else
512             fprintf( file, "\n\n" );
513
514         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
515              p_item < p_end;
516              p_item++ )
517         {
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 */
521                 continue;
522
523             if (IsConfigIntegerType (p_item->i_type))
524             {
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);
531             }
532             else
533             if (IsConfigFloatType (p_item->i_type))
534             {
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);
539             }
540             else
541             {
542                 const char *psz_value = p_item->value.psz;
543                 bool modified;
544
545                 assert (IsConfigStringType (p_item->i_type));
546
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 : "");
552             }
553             p_item->b_dirty = false;
554         }
555     }
556     vlc_rwlock_unlock (&config_lock);
557
558     module_list_free (list);
559     if (loc != (locale_t)0)
560     {
561         uselocale (baseloc);
562         freelocale (loc);
563     }
564
565     /*
566      * Restore old settings from the config in file
567      */
568     if (bigsize)
569         fwrite (bigbuf, 1, bigsize, file);
570
571     /*
572      * Flush to disk and replace atomically
573      */
574     fflush (file); /* Flush from run-time */
575     if (ferror (file))
576     {
577         vlc_unlink (temporary);
578         vlc_mutex_unlock (&lock);
579         msg_Err (p_this, "cannot write configuration file");
580         clearerr (file);
581         goto error;
582     }
583 #if defined(__APPLE__) || defined(__ANDROID__)
584     fsync (fd); /* Flush from OS */
585 #else
586     fdatasync (fd); /* Flush from OS */
587 #endif
588 #if defined (WIN32) || defined (__OS2__)
589     /* Windows cannot (re)move open files nor overwrite existing ones */
590     fclose (file);
591     vlc_unlink (permanent);
592 #endif
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__)
600     fclose (file);
601 #endif
602
603     free (temporary);
604     free (permanent);
605     free (bigbuf);
606     return 0;
607
608 error:
609     if( file )
610         fclose( file );
611     free (temporary);
612     free (permanent);
613     free (bigbuf);
614     return -1;
615 }
616
617 int config_AutoSaveConfigFile( vlc_object_t *p_this )
618 {
619     int ret = VLC_SUCCESS;
620     bool save = false;
621
622     assert( p_this );
623
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++)
628     {
629         module_t *p_parser = list[i_index];
630         module_config_t *p_item, *p_end;
631
632         if( !p_parser->i_config_items ) continue;
633
634         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
635              p_item < p_end && !save;
636              p_item++ )
637         {
638             save = p_item->b_dirty;
639         }
640     }
641
642     if (save)
643         /* Note: this will get the read lock recursively. Ok. */
644         ret = SaveConfigFile (p_this);
645     vlc_rwlock_unlock (&config_lock);
646
647     module_list_free (list);
648     return ret;
649 }
650
651 #undef config_SaveConfigFile
652 int config_SaveConfigFile( vlc_object_t *p_this )
653 {
654     return SaveConfigFile (p_this);
655 }