]> git.sesse.net Git - vlc/blob - src/config/file.c
Use _WIN32 rather than WIN32 (same for WIN64)
[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 #include <vlc_plugin.h>
49
50 #include "configuration.h"
51 #include "modules/modules.h"
52
53 static inline char *strdupnull (const char *src)
54 {
55     return src ? strdup (src) : NULL;
56 }
57
58 /**
59  * Get the user's configuration file
60  */
61 static char *config_GetConfigFile( vlc_object_t *obj )
62 {
63     char *psz_file = var_CreateGetNonEmptyString( obj, "config" );
64     var_Destroy( obj, "config" );
65     if( psz_file == NULL )
66     {
67         char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
68
69         if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
70             psz_file = NULL;
71         free( psz_dir );
72     }
73     return psz_file;
74 }
75
76 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
77 {
78     char *psz_filename = config_GetConfigFile( p_obj );
79     if( psz_filename == NULL )
80         return NULL;
81
82     msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
83
84     FILE *p_stream = vlc_fopen( psz_filename, "rt" );
85     if( p_stream == NULL && errno != ENOENT )
86     {
87         msg_Err( p_obj, "cannot open config file (%s): %m",
88                  psz_filename );
89
90     }
91 #if !( defined(_WIN32) || defined(__APPLE__) || defined(__OS2__) )
92     else if( p_stream == NULL && errno == ENOENT )
93     {
94         /* This is the fallback for pre XDG Base Directory
95          * Specification configs */
96         char *home = config_GetUserDir(VLC_HOME_DIR);
97         char *psz_old;
98
99         if( home != NULL
100          && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
101                       home ) != -1 )
102         {
103             p_stream = vlc_fopen( psz_old, "rt" );
104             if( p_stream )
105             {
106                 /* Old config file found. We want to write it at the
107                  * new location now. */
108                 msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
109                           "VLC will now use %s.", psz_old, psz_filename );
110                 char *psz_readme;
111                 if( asprintf(&psz_readme,"%s/.vlc/README",
112                              home ) != -1 )
113                 {
114                     FILE *p_readme = vlc_fopen( psz_readme, "wt" );
115                     if( p_readme )
116                     {
117                         fprintf( p_readme, "The VLC media player "
118                                  "configuration folder has moved to comply\n"
119                                  "with the XDG Base Directory Specification "
120                                  "version 0.6. Your\nconfiguration has been "
121                                  "copied to the new location:\n%s\nYou can "
122                                  "delete this directory and all its contents.",
123                                   psz_filename);
124                         fclose( p_readme );
125                     }
126                     free( psz_readme );
127                 }
128                 /* Remove the old configuration file so that --reset-config
129                  * can work properly. Fortunately, Linux allows removing
130                  * open files - with most filesystems. */
131                 unlink( psz_old );
132             }
133             free( psz_old );
134         }
135         free( home );
136     }
137 #endif
138     free( psz_filename );
139     return p_stream;
140 }
141
142
143 static int64_t strtoi (const char *str)
144 {
145     char *end;
146     long long l;
147
148     errno = 0;
149     l = strtoll (str, &end, 0);
150
151     if (!errno)
152     {
153 #if (LLONG_MAX > 0x7fffffffffffffffLL)
154         if (l > 0x7fffffffffffffffLL
155          || l < -0x8000000000000000LL)
156             errno = ERANGE;
157 #endif
158         if (*end)
159             errno = EINVAL;
160     }
161     return l;
162 }
163
164 #undef config_LoadConfigFile
165 /*****************************************************************************
166  * config_LoadConfigFile: loads the configuration file.
167  *****************************************************************************
168  * This function is called to load the config options stored in the config
169  * file.
170  *****************************************************************************/
171 int config_LoadConfigFile( vlc_object_t *p_this )
172 {
173     FILE *file;
174
175     file = config_OpenConfigFile (p_this);
176     if (file == NULL)
177         return VLC_EGENERIC;
178
179     /* Look for UTF-8 Byte Order Mark */
180     char * (*convert) (const char *) = strdupnull;
181     char bom[3];
182
183     if ((fread (bom, 1, 3, file) != 3)
184      || memcmp (bom, "\xEF\xBB\xBF", 3))
185     {
186         convert = FromLocaleDup;
187         rewind (file); /* no BOM, rewind */
188     }
189
190     char *line = NULL;
191     size_t bufsize;
192     ssize_t linelen;
193
194     /* Ensure consistent number formatting... */
195     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
196     locale_t baseloc = uselocale (loc);
197
198     vlc_rwlock_wrlock (&config_lock);
199     while ((linelen = getline (&line, &bufsize, file)) != -1)
200     {
201         line[linelen - 1] = '\0'; /* trim newline */
202
203         /* Ignore comments, section and empty lines */
204         if (memchr ("#[", line[0], 3) != NULL)
205             continue;
206
207         /* look for option name */
208         const char *psz_option_name = line;
209
210         char *ptr = strchr (line, '=');
211         if (ptr == NULL)
212             continue; /* syntax error */
213         *ptr = '\0';
214
215         module_config_t *item = config_FindConfig (p_this, psz_option_name);
216         if (item == NULL)
217             continue;
218
219         const char *psz_option_value = ptr + 1;
220         switch (CONFIG_CLASS(item->i_type))
221         {
222             case CONFIG_ITEM_BOOL:
223             case CONFIG_ITEM_INTEGER:
224             {
225                 int64_t l;
226
227                 errno = 0;
228                 l = strtoi (psz_option_value);
229                 if ((l > item->max.i) || (l < item->min.i))
230                     errno = ERANGE;
231                 if (errno)
232                     msg_Warn (p_this, "Integer value (%s) for %s: %m",
233                               psz_option_value, psz_option_name);
234                 else
235                     item->value.i = l;
236                 break;
237             }
238
239             case CONFIG_ITEM_FLOAT:
240                 if (!*psz_option_value)
241                     break;                    /* ignore empty option */
242                 item->value.f = (float)atof (psz_option_value);
243                 break;
244
245             default:
246                 free ((char *)item->value.psz);
247                 item->value.psz = convert (psz_option_value);
248                 break;
249         }
250     }
251     vlc_rwlock_unlock (&config_lock);
252     free (line);
253
254     if (ferror (file))
255     {
256         msg_Err (p_this, "error reading configuration: %m");
257         clearerr (file);
258     }
259     fclose (file);
260
261     if (loc != (locale_t)0)
262     {
263         uselocale (baseloc);
264         freelocale (loc);
265     }
266     return 0;
267 }
268
269 /*****************************************************************************
270  * config_CreateDir: Create configuration directory if it doesn't exist.
271  *****************************************************************************/
272 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
273 {
274     if( !psz_dirname || !*psz_dirname ) return -1;
275
276     if( vlc_mkdir( psz_dirname, 0700 ) == 0 )
277         return 0;
278
279     switch( errno )
280     {
281         case EEXIST:
282             return 0;
283
284         case ENOENT:
285         {
286             /* Let's try to create the parent directory */
287             char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
288             strcpy( psz_parent, psz_dirname );
289
290             psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
291             if( psz_end && psz_end != psz_parent )
292             {
293                 *psz_end = '\0';
294                 if( config_CreateDir( p_this, psz_parent ) == 0 )
295                 {
296                     if( !vlc_mkdir( psz_dirname, 0700 ) )
297                         return 0;
298                 }
299             }
300         }
301     }
302
303     msg_Warn( p_this, "could not create %s: %m", psz_dirname );
304     return -1;
305 }
306
307 static int
308 config_Write (FILE *file, const char *desc, const char *type,
309               bool comment, const char *name, const char *fmt, ...)
310 {
311     va_list ap;
312     int ret;
313
314     if (desc == NULL)
315         desc = "?";
316
317     if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
318                  comment ? "#" : "", name) < 0)
319         return -1;
320
321     va_start (ap, fmt);
322     ret = vfprintf (file, fmt, ap);
323     va_end (ap);
324     if (ret < 0)
325         return -1;
326
327     if (fputs ("\n\n", file) == EOF)
328         return -1;
329     return 0;
330 }
331
332
333 static int config_PrepareDir (vlc_object_t *obj)
334 {
335     char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
336     if (psz_configdir == NULL)
337         return -1;
338
339     int ret = config_CreateDir (obj, psz_configdir);
340     free (psz_configdir);
341     return ret;
342 }
343
344 #undef config_SaveConfigFile
345 /**
346  * Saves the in-memory configuration into a file.
347  * @return 0 on success, -1 on error.
348  */
349 int config_SaveConfigFile (vlc_object_t *p_this)
350 {
351
352     if( config_PrepareDir( p_this ) )
353     {
354         msg_Err( p_this, "no configuration directory" );
355         return -1;
356     }
357
358     /*
359      * Save module config in file
360      */
361     char *temporary;
362     char *permanent = config_GetConfigFile (p_this);
363     if (permanent == NULL)
364         return -1;
365     if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
366     {
367         free (permanent);
368         return -1;
369     }
370     else
371     {
372         struct stat st;
373
374         /* Some users make vlcrc read-only to prevent changes.
375          * The atomic replacement scheme breaks this "feature",
376          * so we check for read-only by hand. */
377         if (stat (permanent, &st) == 0 && !(st.st_mode & S_IWUSR))
378         {
379             msg_Err (p_this, "configuration file is read-only");
380             goto error;
381         }
382     }
383
384     /* Configuration lock must be taken before vlcrc serializer below. */
385     vlc_rwlock_rdlock (&config_lock);
386
387     /* The temporary configuration file is per-PID. Therefore this function
388      * should be serialized against itself within a given process. */
389     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
390     vlc_mutex_lock (&lock);
391
392     int fd = vlc_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
393     if (fd == -1)
394     {
395         vlc_rwlock_unlock (&config_lock);
396         vlc_mutex_unlock (&lock);
397         goto error;
398     }
399     FILE *file = fdopen (fd, "wt");
400     if (file == NULL)
401     {
402         msg_Err (p_this, "cannot create configuration file: %m");
403         vlc_rwlock_unlock (&config_lock);
404         close (fd);
405         vlc_mutex_unlock (&lock);
406         goto error;
407     }
408
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" );
418
419     /* Ensure consistent number formatting... */
420     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
421     locale_t baseloc = uselocale (loc);
422
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);*/
426
427     /* Look for the selected module, if NULL then save everything */
428     size_t count;
429     module_t **list = module_list_get (&count);
430     for (size_t i = 0; i < count; i++)
431     {
432         module_t *p_parser = list[i];
433         module_config_t *p_item, *p_end;
434
435         if( !p_parser->i_config_items )
436             continue;
437
438         fprintf( file, "[%s]", module_get_object (p_parser) );
439         if( p_parser->psz_longname )
440             fprintf( file, " # %s\n\n", p_parser->psz_longname );
441         else
442             fprintf( file, "\n\n" );
443
444         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
445              p_item < p_end;
446              p_item++ )
447         {
448             if (!CONFIG_ITEM(p_item->i_type)   /* ignore hint */
449              || p_item->b_removed              /* ignore deprecated option */
450              || p_item->b_unsaveable)          /* ignore volatile option */
451                 continue;
452
453             if (IsConfigIntegerType (p_item->i_type))
454             {
455                 int64_t val = p_item->value.i;
456                 config_Write (file, p_item->psz_text,
457                              (CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL)
458                                   ? N_("boolean") : N_("integer"),
459                               val == p_item->orig.i,
460                               p_item->psz_name, "%"PRId64, val);
461             }
462             else
463             if (IsConfigFloatType (p_item->i_type))
464             {
465                 float val = p_item->value.f;
466                 config_Write (file, p_item->psz_text, N_("float"),
467                               val == p_item->orig.f,
468                               p_item->psz_name, "%f", val);
469             }
470             else
471             {
472                 const char *psz_value = p_item->value.psz;
473                 bool modified;
474
475                 assert (IsConfigStringType (p_item->i_type));
476
477                 modified = !!strcmp (psz_value ? psz_value : "",
478                                      p_item->orig.psz ? p_item->orig.psz : "");
479                 config_Write (file, p_item->psz_text, N_("string"),
480                               !modified, p_item->psz_name, "%s",
481                               psz_value ? psz_value : "");
482             }
483         }
484     }
485     vlc_rwlock_unlock (&config_lock);
486
487     module_list_free (list);
488     if (loc != (locale_t)0)
489     {
490         uselocale (baseloc);
491         freelocale (loc);
492     }
493
494     /*
495      * Flush to disk and replace atomically
496      */
497     fflush (file); /* Flush from run-time */
498     if (ferror (file))
499     {
500         vlc_unlink (temporary);
501         vlc_mutex_unlock (&lock);
502         msg_Err (p_this, "cannot write configuration file");
503         fclose (file);
504         goto error;
505     }
506 #if defined(__APPLE__) || defined(__ANDROID__)
507     fsync (fd); /* Flush from OS */
508 #else
509     fdatasync (fd); /* Flush from OS */
510 #endif
511 #if defined (_WIN32) || defined (__OS2__)
512     /* Windows cannot (re)move open files nor overwrite existing ones */
513     fclose (file);
514     vlc_unlink (permanent);
515 #endif
516     /* Atomically replace the file... */
517     if (vlc_rename (temporary, permanent))
518         vlc_unlink (temporary);
519     /* (...then synchronize the directory, err, TODO...) */
520     /* ...and finally close the file */
521     vlc_mutex_unlock (&lock);
522 #if !defined (_WIN32) && !defined (__OS2__)
523     fclose (file);
524 #endif
525
526     free (temporary);
527     free (permanent);
528     return 0;
529
530 error:
531     free (temporary);
532     free (permanent);
533     return -1;
534 }
535
536 int config_AutoSaveConfigFile( vlc_object_t *p_this )
537 {
538     int ret = 0;
539
540     assert( p_this );
541
542     vlc_rwlock_rdlock (&config_lock);
543     if (config_dirty)
544     {
545         /* Note: this will get the read lock recursively. Ok. */
546         ret = config_SaveConfigFile (p_this);
547         config_dirty = (ret != 0);
548     }
549     vlc_rwlock_unlock (&config_lock);
550
551     return ret;
552 }