]> git.sesse.net Git - vlc/blob - src/config/file.c
WinCE: guard against inclusion of missing header file
[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_keys.h"
43
44 #include "configuration.h"
45 #include "modules/modules.h"
46
47 static inline char *strdupnull (const char *src)
48 {
49     return src ? strdup (src) : NULL;
50 }
51
52 /**
53  * Get the user's configuration file
54  */
55 static char *config_GetConfigFile( vlc_object_t *obj )
56 {
57     char *psz_file = config_GetPsz( obj, "config" );
58     if( psz_file == NULL )
59     {
60         char *psz_dir = config_GetUserDir( VLC_CONFIG_DIR );
61
62         if( asprintf( &psz_file, "%s" DIR_SEP CONFIG_FILE, psz_dir ) == -1 )
63             psz_file = NULL;
64         free( psz_dir );
65     }
66     return psz_file;
67 }
68
69 static FILE *config_OpenConfigFile( vlc_object_t *p_obj )
70 {
71     char *psz_filename = config_GetConfigFile( p_obj );
72     if( psz_filename == NULL )
73         return NULL;
74
75     msg_Dbg( p_obj, "opening config file (%s)", psz_filename );
76
77     FILE *p_stream = utf8_fopen( psz_filename, "rt" );
78     if( p_stream == NULL && errno != ENOENT )
79     {
80         msg_Err( p_obj, "cannot open config file (%s): %m",
81                  psz_filename );
82
83     }
84 #if !( defined(WIN32) || defined(__APPLE__) || defined(SYS_BEOS) )
85     else if( p_stream == NULL && errno == ENOENT )
86     {
87         /* This is the fallback for pre XDG Base Directory
88          * Specification configs */
89         char *home = config_GetUserDir(VLC_HOME_DIR);
90         char *psz_old;
91
92         if( home != NULL
93          && asprintf( &psz_old, "%s/.vlc/" CONFIG_FILE,
94                       home ) != -1 )
95         {
96             p_stream = utf8_fopen( psz_old, "rt" );
97             if( p_stream )
98             {
99                 /* Old config file found. We want to write it at the
100                  * new location now. */
101                 msg_Info( p_obj->p_libvlc, "Found old config file at %s. "
102                           "VLC will now use %s.", psz_old, psz_filename );
103                 char *psz_readme;
104                 if( asprintf(&psz_readme,"%s/.vlc/README",
105                              home ) != -1 )
106                 {
107                     FILE *p_readme = utf8_fopen( psz_readme, "wt" );
108                     if( p_readme )
109                     {
110                         fprintf( p_readme, "The VLC media player "
111                                  "configuration folder has moved to comply\n"
112                                  "with the XDG Base Directory Specification "
113                                  "version 0.6. Your\nconfiguration has been "
114                                  "copied to the new location:\n%s\nYou can "
115                                  "delete this directory and all its contents.",
116                                   psz_filename);
117                         fclose( p_readme );
118                     }
119                     free( psz_readme );
120                 }
121                 /* Remove the old configuration file so that --reset-config
122                  * can work properly. Fortunately, Linux allows removing
123                  * open files - with most filesystems. */
124                 unlink( psz_old );
125             }
126             free( psz_old );
127         }
128         free( home );
129     }
130 #endif
131     free( psz_filename );
132     return p_stream;
133 }
134
135
136 static int strtoi (const char *str)
137 {
138     char *end;
139     long l;
140
141     errno = 0;
142     l = strtol (str, &end, 0);
143
144     if (!errno)
145     {
146         if ((l > INT_MAX) || (l < INT_MIN))
147             errno = ERANGE;
148         if (*end)
149             errno = EINVAL;
150     }
151     return (int)l;
152 }
153
154
155 /*****************************************************************************
156  * config_LoadConfigFile: loads the configuration file.
157  *****************************************************************************
158  * This function is called to load the config options stored in the config
159  * file.
160  *****************************************************************************/
161 int __config_LoadConfigFile( vlc_object_t *p_this, const char *psz_module_name )
162 {
163     FILE *file;
164
165     file = config_OpenConfigFile (p_this);
166     if (file == NULL)
167         return VLC_EGENERIC;
168
169     /* Look for the selected module, if NULL then save everything */
170     module_t **list = module_list_get (NULL);
171
172     /* Look for UTF-8 Byte Order Mark */
173     char * (*convert) (const char *) = strdupnull;
174     char bom[3];
175
176     if ((fread (bom, 1, 3, file) != 3)
177      || memcmp (bom, "\xEF\xBB\xBF", 3))
178     {
179         convert = FromLocaleDup;
180         rewind (file); /* no BOM, rewind */
181     }
182
183     module_t *module = NULL;
184     char line[1024], section[1022];
185     section[0] = '\0';
186
187     /* Ensure consistent number formatting... */
188     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
189     locale_t baseloc = uselocale (loc);
190
191     while (fgets (line, 1024, file) != NULL)
192     {
193         /* Ignore comments and empty lines */
194         switch (line[0])
195         {
196             case '#':
197             case '\n':
198             case '\0':
199                 continue;
200         }
201
202         if (line[0] == '[')
203         {
204             char *ptr = strchr (line, ']');
205             if (ptr == NULL)
206                 continue; /* syntax error; */
207             *ptr = '\0';
208
209             /* New section ( = a given module) */
210             strcpy (section, line + 1);
211             module = NULL;
212
213             if ((psz_module_name == NULL)
214              || (strcmp (psz_module_name, section) == 0))
215             {
216                 for (int i = 0; list[i]; i++)
217                 {
218                     module_t *m = list[i];
219
220                     if ((strcmp (section, m->psz_object_name) == 0)
221                      && (m->i_config_items > 0)) /* ignore config-less modules */
222                     {
223                         module = m;
224                         if (psz_module_name != NULL)
225                             msg_Dbg (p_this,
226                                      "loading config for module \"%s\"",
227                                      section);
228                         break;
229                     }
230                 }
231             }
232
233             continue;
234         }
235
236         if (module == NULL)
237             continue; /* no need to parse if there is no matching module */
238
239         char *ptr = strchr (line, '\n');
240         if (ptr != NULL)
241             *ptr = '\0';
242
243         /* look for option name */
244         const char *psz_option_name = line;
245
246         ptr = strchr (line, '=');
247         if (ptr == NULL)
248             continue; /* syntax error */
249
250         *ptr = '\0';
251         const char *psz_option_value = ptr + 1;
252
253         /* try to match this option with one of the module's options */
254         for (size_t i = 0; i < module->confsize; i++)
255         {
256             module_config_t *p_item = module->p_config + i;
257
258             if ((p_item->i_type & CONFIG_HINT)
259              || strcmp (p_item->psz_name, psz_option_name))
260                 continue;
261
262             /* We found it */
263             errno = 0;
264
265             vlc_mutex_lock( p_item->p_lock );
266             switch( p_item->i_type )
267             {
268                 case CONFIG_ITEM_BOOL:
269                 case CONFIG_ITEM_INTEGER:
270                 {
271                     long l = strtoi (psz_option_value);
272                     if (errno)
273                         msg_Warn (p_this, "Integer value (%s) for %s: %m",
274                                   psz_option_value, psz_option_name);
275                     else
276                         p_item->saved.i = p_item->value.i = (int)l;
277                     break;
278                 }
279
280                 case CONFIG_ITEM_FLOAT:
281                     if( !*psz_option_value )
282                         break;                    /* ignore empty option */
283                     p_item->value.f = (float)atof (psz_option_value);
284                     p_item->saved.f = p_item->value.f;
285                     break;
286
287                 case CONFIG_ITEM_KEY:
288                     if( !*psz_option_value )
289                         break;                    /* ignore empty option */
290                     p_item->value.i = ConfigStringToKey(psz_option_value);
291                     p_item->saved.i = p_item->value.i;
292                     break;
293
294                 default:
295                     /* free old string */
296                     free( (char*) p_item->value.psz );
297                     free( (char*) p_item->saved.psz );
298
299                     p_item->value.psz = convert (psz_option_value);
300                     p_item->saved.psz = strdupnull (p_item->value.psz);
301                     break;
302             }
303             vlc_mutex_unlock( p_item->p_lock );
304             break;
305         }
306     }
307
308     if (ferror (file))
309     {
310         msg_Err (p_this, "error reading configuration: %m");
311         clearerr (file);
312     }
313     fclose (file);
314
315     module_list_free (list);
316     if (loc != (locale_t)0)
317     {
318         uselocale (baseloc);
319         freelocale (loc);
320     }
321     return 0;
322 }
323
324 /*****************************************************************************
325  * config_CreateDir: Create configuration directory if it doesn't exist.
326  *****************************************************************************/
327 int config_CreateDir( vlc_object_t *p_this, const char *psz_dirname )
328 {
329     if( !psz_dirname || !*psz_dirname ) return -1;
330
331     if( utf8_mkdir( psz_dirname, 0700 ) == 0 )
332         return 0;
333
334     switch( errno )
335     {
336         case EEXIST:
337             return 0;
338
339         case ENOENT:
340         {
341             /* Let's try to create the parent directory */
342             char psz_parent[strlen( psz_dirname ) + 1], *psz_end;
343             strcpy( psz_parent, psz_dirname );
344
345             psz_end = strrchr( psz_parent, DIR_SEP_CHAR );
346             if( psz_end && psz_end != psz_parent )
347             {
348                 *psz_end = '\0';
349                 if( config_CreateDir( p_this, psz_parent ) == 0 )
350                 {
351                     if( !utf8_mkdir( psz_dirname, 0700 ) )
352                         return 0;
353                 }
354             }
355         }
356     }
357
358     msg_Err( p_this, "could not create %s: %m", psz_dirname );
359     return -1;
360 }
361
362 static int
363 config_Write (FILE *file, const char *desc, const char *type,
364               bool comment, const char *name, const char *fmt, ...)
365 {
366     va_list ap;
367     int ret;
368
369     if (desc == NULL)
370         desc = "?";
371
372     if (fprintf (file, "# %s (%s)\n%s%s=", desc, vlc_gettext (type),
373                  comment ? "#" : "", name) < 0)
374         return -1;
375
376     va_start (ap, fmt);
377     ret = vfprintf (file, fmt, ap);
378     va_end (ap);
379     if (ret < 0)
380         return -1;
381
382     if (fputs ("\n\n", file) == EOF)
383         return -1;
384     return 0;
385 }
386
387
388 static int config_PrepareDir (vlc_object_t *obj)
389 {
390     char *psz_configdir = config_GetUserDir (VLC_CONFIG_DIR);
391     if (psz_configdir == NULL)
392         return -1;
393
394     int ret = config_CreateDir (obj, psz_configdir);
395     free (psz_configdir);
396     return ret;
397 }
398
399 /*****************************************************************************
400  * config_SaveConfigFile: Save a module's config options.
401  *****************************************************************************
402  * This will save the specified module's config options to the config file.
403  * If psz_module_name is NULL then we save all the modules config options.
404  * It's no use to save the config options that kept their default values, so
405  * we'll try to be a bit clever here.
406  *
407  * When we save we mustn't delete the config options of the modules that
408  * haven't been loaded. So we cannot just create a new config file with the
409  * config structures we've got in memory.
410  * I don't really know how to deal with this nicely, so I will use a completly
411  * dumb method ;-)
412  * I will load the config file in memory, but skipping all the sections of the
413  * modules we want to save. Then I will create a brand new file, dump the file
414  * loaded in memory and then append the sections of the modules we want to
415  * save.
416  * Really stupid no ?
417  *****************************************************************************/
418 static int SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name,
419                            bool b_autosave )
420 {
421     module_t *p_parser;
422     FILE *file = NULL;
423     char *permanent = NULL, *temporary = NULL;
424     char p_line[1024], *p_index2;
425     unsigned long i_sizebuf = 0;
426     char *p_bigbuffer = NULL, *p_index;
427     bool b_backup;
428     int i_index;
429
430     if( config_PrepareDir( p_this ) )
431     {
432         msg_Err( p_this, "no configuration directory" );
433         goto error;
434     }
435
436     file = config_OpenConfigFile( p_this );
437     if( file != NULL )
438     {
439         struct stat st;
440
441         /* Some users make vlcrc read-only to prevent changes.
442          * The atomic replacement scheme breaks this "feature",
443          * so we check for read-only by hand. */
444         if (fstat (fileno (file), &st)
445          || !(st.st_mode & S_IWUSR))
446         {
447             msg_Err (p_this, "configuration file is read-only");
448             goto error;
449         }
450         i_sizebuf = ( st.st_size < LONG_MAX ) ? st.st_size : 0;
451     }
452
453     p_bigbuffer = p_index = malloc( i_sizebuf+1 );
454     if( !p_bigbuffer )
455         goto error;
456     p_bigbuffer[0] = 0;
457
458     /* List all available modules */
459     module_t **list = module_list_get (NULL);
460
461     /* backup file into memory, we only need to backup the sections we won't
462      * save later on */
463     b_backup = false;
464     while( file && fgets( p_line, 1024, file ) )
465     {
466         if( (p_line[0] == '[') && (p_index2 = strchr(p_line,']')))
467         {
468
469             /* we found a section, check if we need to do a backup */
470             for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
471             {
472                 if( ((p_index2 - &p_line[1])
473                        == (int)strlen(p_parser->psz_object_name) )
474                     && !memcmp( &p_line[1], p_parser->psz_object_name,
475                                 strlen(p_parser->psz_object_name) ) )
476                 {
477                     if( !psz_module_name )
478                         break;
479                     else if( !strcmp( psz_module_name,
480                                       p_parser->psz_object_name ) )
481                         break;
482                 }
483             }
484
485             if( list[i_index] == NULL )
486             {
487                 /* we don't have this section in our list so we need to back
488                  * it up */
489                 *p_index2 = 0;
490 #if 0
491                 msg_Dbg( p_this, "backing up config for unknown module \"%s\"",
492                                  &p_line[1] );
493 #endif
494                 *p_index2 = ']';
495
496                 b_backup = true;
497             }
498             else
499             {
500                 b_backup = false;
501             }
502         }
503
504         /* save line if requested and line is valid (doesn't begin with a
505          * space, tab, or eol) */
506         if( b_backup && (p_line[0] != '\n') && (p_line[0] != ' ')
507             && (p_line[0] != '\t') )
508         {
509             strcpy( p_index, p_line );
510             p_index += strlen( p_line );
511         }
512     }
513     if( file )
514         fclose( file );
515     file = NULL;
516
517     /*
518      * Save module config in file
519      */
520     permanent = config_GetConfigFile (p_this);
521     if (!permanent)
522     {
523         module_list_free (list);
524         goto error;
525     }
526
527     if (asprintf (&temporary, "%s.%u", permanent, getpid ()) == -1)
528     {
529         temporary = NULL;
530         module_list_free (list);
531         goto error;
532     }
533
534     /* The temporary configuration file is per-PID. Therefore SaveConfigFile()
535      * should be serialized against itself within a given process. */
536     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
537     vlc_mutex_lock (&lock);
538
539     int fd = utf8_open (temporary, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
540     if (fd == -1)
541     {
542         vlc_mutex_unlock (&lock);
543         module_list_free (list);
544         goto error;
545     }
546     file = fdopen (fd, "wt");
547     if (file == NULL)
548     {
549         close (fd);
550         vlc_mutex_unlock (&lock);
551         module_list_free (list);
552         goto error;
553     }
554
555     fprintf( file, "\xEF\xBB\xBF###\n###  " COPYRIGHT_MESSAGE "\n###\n\n"
556        "###\n### lines beginning with a '#' character are comments\n###\n\n" );
557
558     /* Ensure consistent number formatting... */
559     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
560     locale_t baseloc = uselocale (loc);
561
562     /* Look for the selected module, if NULL then save everything */
563     for( i_index = 0; (p_parser = list[i_index]) != NULL; i_index++ )
564     {
565         module_config_t *p_item, *p_end;
566
567         if( psz_module_name && strcmp( psz_module_name,
568                                        p_parser->psz_object_name ) )
569             continue;
570
571         if( !p_parser->i_config_items )
572             continue;
573
574         if( psz_module_name )
575             msg_Dbg( p_this, "saving config for module \"%s\"",
576                      p_parser->psz_object_name );
577
578         fprintf( file, "[%s]", p_parser->psz_object_name );
579         if( p_parser->psz_longname )
580             fprintf( file, " # %s\n\n", p_parser->psz_longname );
581         else
582             fprintf( file, "\n\n" );
583
584         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
585              p_item < p_end;
586              p_item++ )
587         {
588             if ((p_item->i_type & CONFIG_HINT) /* ignore hint */
589              || p_item->b_removed              /* ignore deprecated option */
590              || p_item->b_unsaveable)          /* ignore volatile option */
591                 continue;
592
593             vlc_mutex_lock (p_item->p_lock);
594
595             /* Do not save the new value in the configuration file
596              * if doing an autosave, and the item is not an "autosaved" one. */
597             bool b_retain = b_autosave && !p_item->b_autosave;
598
599             if (IsConfigIntegerType (p_item->i_type))
600             {
601                 int val = b_retain ? p_item->saved.i : p_item->value.i;
602                 if (p_item->i_type == CONFIG_ITEM_KEY)
603                 {
604                     char *psz_key = ConfigKeyToString (val);
605                     config_Write (file, p_item->psz_text, N_("key"),
606                                   val == p_item->orig.i,
607                                   p_item->psz_name, "%s",
608                                   psz_key ? psz_key : "");
609                     free (psz_key);
610                 }
611                 else
612                     config_Write (file, p_item->psz_text,
613                                   (p_item->i_type == CONFIG_ITEM_BOOL)
614                                       ? N_("boolean") : N_("integer"),
615                                   val == p_item->orig.i,
616                                   p_item->psz_name, "%d", val);
617                 p_item->saved.i = val;
618             }
619             else
620             if (IsConfigFloatType (p_item->i_type))
621             {
622                 float val = b_retain ? p_item->saved.f : p_item->value.f;
623                 config_Write (file, p_item->psz_text, N_("float"),
624                               val == p_item->orig.f,
625                               p_item->psz_name, "%f", val);
626                 p_item->saved.f = val;
627             }
628             else
629             {
630                 const char *psz_value = b_retain ? p_item->saved.psz
631                                                  : p_item->value.psz;
632                 bool modified;
633
634                 assert (IsConfigStringType (p_item->i_type));
635
636                 if (b_retain && (psz_value == NULL)) /* FIXME: hack */
637                     psz_value = p_item->orig.psz;
638
639                 modified =
640                     (psz_value != NULL)
641                         ? ((p_item->orig.psz != NULL)
642                             ? (strcmp (psz_value, p_item->orig.psz) != 0)
643                             : true)
644                         : (p_item->orig.psz != NULL);
645
646                 config_Write (file, p_item->psz_text, N_("string"),
647                               !modified, p_item->psz_name, "%s",
648                               psz_value ? psz_value : "");
649
650                 if ( !b_retain )
651                 {
652
653                     free ((char *)p_item->saved.psz);
654                     if( (psz_value && p_item->orig.psz &&
655                          strcmp( psz_value, p_item->orig.psz )) ||
656                         !psz_value || !p_item->orig.psz)
657                         p_item->saved.psz = strdupnull (psz_value);
658                     else
659                         p_item->saved.psz = NULL;
660                 }
661             }
662
663             if (!b_retain)
664                 p_item->b_dirty = false;
665             vlc_mutex_unlock (p_item->p_lock);
666         }
667     }
668
669     module_list_free (list);
670     if (loc != (locale_t)0)
671     {
672         uselocale (baseloc);
673         freelocale (loc);
674     }
675
676     /*
677      * Restore old settings from the config in file
678      */
679     fputs( p_bigbuffer, file );
680     free( p_bigbuffer );
681
682     /*
683      * Flush to disk and replace atomically
684      */
685     fflush (file); /* Flush from run-time */
686 #ifndef WIN32
687     fdatasync (fd); /* Flush from OS */
688     /* Atomically replace the file... */
689     if (utf8_rename (temporary, permanent))
690         utf8_unlink (temporary);
691     /* (...then synchronize the directory, err, TODO...) */
692     /* ...and finally close the file */
693     vlc_mutex_unlock (&lock);
694 #endif
695     fclose (file);
696 #ifdef WIN32
697     /* Windows cannot remove open files nor overwrite existing ones */
698     utf8_unlink (permanent);
699     if (utf8_rename (temporary, permanent))
700         utf8_unlink (temporary);
701     vlc_mutex_unlock (&lock);
702 #endif
703
704     free (temporary);
705     free (permanent);
706     return 0;
707
708 error:
709     if( file )
710         fclose( file );
711     free (temporary);
712     free (permanent);
713     free( p_bigbuffer );
714     return -1;
715 }
716
717 int config_AutoSaveConfigFile( vlc_object_t *p_this )
718 {
719     size_t i_index;
720     bool save = false;
721
722     assert( p_this );
723
724     /* Check if there's anything to save */
725     module_t **list = module_list_get (NULL);
726     for( i_index = 0; list[i_index] && !save; i_index++ )
727     {
728         module_t *p_parser = list[i_index];
729         module_config_t *p_item, *p_end;
730
731         if( !p_parser->i_config_items ) continue;
732
733         for( p_item = p_parser->p_config, p_end = p_item + p_parser->confsize;
734              p_item < p_end && !save;
735              p_item++ )
736         {
737             vlc_mutex_lock (p_item->p_lock);
738             save = p_item->b_autosave && p_item->b_dirty;
739             vlc_mutex_unlock (p_item->p_lock);
740         }
741     }
742     module_list_free (list);
743
744     return save ? VLC_SUCCESS : SaveConfigFile( p_this, NULL, true );
745 }
746
747 int __config_SaveConfigFile( vlc_object_t *p_this, const char *psz_module_name )
748 {
749     return SaveConfigFile( p_this, psz_module_name, false );
750 }