chiark / gitweb /
separate thread to add to heap
[disorder] / lib / configuration.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004, 2005, 2006, 2007 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20
21 #include <config.h>
22 #include "types.h"
23
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include <ctype.h>
32 #include <stddef.h>
33 #include <pwd.h>
34 #include <langinfo.h>
35 #include <pcre.h>
36 #include <signal.h>
37
38 #include "configuration.h"
39 #include "mem.h"
40 #include "log.h"
41 #include "split.h"
42 #include "syscalls.h"
43 #include "table.h"
44 #include "inputline.h"
45 #include "charset.h"
46 #include "defs.h"
47 #include "mixer.h"
48 #include "printf.h"
49 #include "regsub.h"
50 #include "signame.h"
51
52 /** @brief Path to config file 
53  *
54  * set_configfile() sets the deafult if it is null.
55  */
56 char *configfile;
57
58 /** @brief Config file parser state */
59 struct config_state {
60   /** @brief Filename */
61   const char *path;
62   /** @brief Line number */
63   int line;
64   /** @brief Configuration object under construction */
65   struct config *config;
66 };
67
68 /** @brief Current configuration */
69 struct config *config;
70
71 /** @brief One configuration item */
72 struct conf {
73   /** @brief Name as it appears in the config file */
74   const char *name;
75   /** @brief Offset in @ref config structure */
76   size_t offset;
77   /** @brief Pointer to item type */
78   const struct conftype *type;
79   /** @brief Pointer to item-specific validation routine */
80   int (*validate)(const struct config_state *cs,
81                   int nvec, char **vec);
82 };
83
84 /** @brief Type of a configuration item */
85 struct conftype {
86   /** @brief Pointer to function to set item */
87   int (*set)(const struct config_state *cs,
88              const struct conf *whoami,
89              int nvec, char **vec);
90   /** @brief Pointer to function to free item */
91   void (*free)(struct config *c, const struct conf *whoami);
92 };
93
94 /** @brief Compute the address of an item */
95 #define ADDRESS(C, TYPE) ((TYPE *)((char *)(C) + whoami->offset))
96 /** @brief Return the value of an item */
97 #define VALUE(C, TYPE) (*ADDRESS(C, TYPE))
98
99 static int set_signal(const struct config_state *cs,
100                       const struct conf *whoami,
101                       int nvec, char **vec) {
102   int n;
103   
104   if(nvec != 1) {
105     error(0, "%s:%d: '%s' requires one argument",
106           cs->path, cs->line, whoami->name);
107     return -1;
108   }
109   if((n = find_signal(vec[0])) == -1) {
110     error(0, "%s:%d: unknown signal '%s'",
111           cs->path, cs->line, vec[0]);
112     return -1;
113   }
114   VALUE(cs->config, int) = n;
115   return 0;
116 }
117
118 static int set_collections(const struct config_state *cs,
119                            const struct conf *whoami,
120                            int nvec, char **vec) {
121   struct collectionlist *cl;
122   
123   if(nvec != 3) {
124     error(0, "%s:%d: '%s' requires three arguments",
125           cs->path, cs->line, whoami->name);
126     return -1;
127   }
128   if(vec[2][0] != '/') {
129     error(0, "%s:%d: collection root must start with '/'",
130           cs->path, cs->line);
131     return -1;
132   }
133   if(vec[2][1] && vec[2][strlen(vec[2])-1] == '/') {
134     error(0, "%s:%d: collection root must not end with '/'",
135           cs->path, cs->line);
136     return -1;
137   }
138   cl = ADDRESS(cs->config, struct collectionlist);
139   ++cl->n;
140   cl->s = xrealloc(cl->s, cl->n * sizeof (struct collection));
141   cl->s[cl->n - 1].module = xstrdup(vec[0]);
142   cl->s[cl->n - 1].encoding = xstrdup(vec[1]);
143   cl->s[cl->n - 1].root = xstrdup(vec[2]);
144   return 0;
145 }
146
147 static int set_boolean(const struct config_state *cs,
148                        const struct conf *whoami,
149                        int nvec, char **vec) {
150   int state;
151   
152   if(nvec != 1) {
153     error(0, "%s:%d: '%s' takes only one argument",
154           cs->path, cs->line, whoami->name);
155     return -1;
156   }
157   if(!strcmp(vec[0], "yes")) state = 1;
158   else if(!strcmp(vec[0], "no")) state = 0;
159   else {
160     error(0, "%s:%d: argument to '%s' must be 'yes' or 'no'",
161           cs->path, cs->line, whoami->name);
162     return -1;
163   }
164   VALUE(cs->config, int) = state;
165   return 0;
166 }
167
168 static int set_string(const struct config_state *cs,
169                       const struct conf *whoami,
170                       int nvec, char **vec) {
171   if(nvec != 1) {
172     error(0, "%s:%d: '%s' takes only one argument",
173           cs->path, cs->line, whoami->name);
174     return -1;
175   }
176   VALUE(cs->config, char *) = xstrdup(vec[0]);
177   return 0;
178 }
179
180 static int set_stringlist(const struct config_state *cs,
181                           const struct conf *whoami,
182                           int nvec, char **vec) {
183   int n;
184   struct stringlist *sl;
185
186   sl = ADDRESS(cs->config, struct stringlist);
187   sl->n = 0;
188   for(n = 0; n < nvec; ++n) {
189     sl->n++;
190     sl->s = xrealloc(sl->s, (sl->n * sizeof (char *)));
191     sl->s[sl->n - 1] = xstrdup(vec[n]);
192   }
193   return 0;
194 }
195
196 static int set_integer(const struct config_state *cs,
197                        const struct conf *whoami,
198                        int nvec, char **vec) {
199   char *e;
200
201   if(nvec != 1) {
202     error(0, "%s:%d: '%s' takes only one argument",
203           cs->path, cs->line, whoami->name);
204     return -1;
205   }
206   if(xstrtol(ADDRESS(cs->config, long), vec[0], &e, 0)) {
207     error(errno, "%s:%d: converting integer", cs->path, cs->line);
208     return -1;
209   }
210   if(*e) {
211     error(0, "%s:%d: invalid integer syntax", cs->path, cs->line);
212     return -1;
213   }
214   return 0;
215 }
216
217 static int set_stringlist_accum(const struct config_state *cs,
218                                 const struct conf *whoami,
219                                 int nvec, char **vec) {
220   int n;
221   struct stringlist *s;
222   struct stringlistlist *sll;
223
224   sll = ADDRESS(cs->config, struct stringlistlist);
225   sll->n++;
226   sll->s = xrealloc(sll->s, (sll->n * sizeof (struct stringlist)));
227   s = &sll->s[sll->n - 1];
228   s->n = nvec;
229   s->s = xmalloc((nvec + 1) * sizeof (char *));
230   for(n = 0; n < nvec; ++n)
231     s->s[n] = xstrdup(vec[n]);
232   return 0;
233 }
234
235 static int set_string_accum(const struct config_state *cs,
236                             const struct conf *whoami,
237                             int nvec, char **vec) {
238   int n;
239   struct stringlist *sl;
240
241   sl = ADDRESS(cs->config, struct stringlist);
242   for(n = 0; n < nvec; ++n) {
243     sl->n++;
244     sl->s = xrealloc(sl->s, (sl->n * sizeof (char *)));
245     sl->s[sl->n - 1] = xstrdup(vec[n]);
246   }
247   return 0;
248 }
249
250 static int set_restrict(const struct config_state *cs,
251                         const struct conf *whoami,
252                         int nvec, char **vec) {
253   unsigned r = 0;
254   int n, i;
255   
256   static const struct restriction {
257     const char *name;
258     unsigned bit;
259   } restrictions[] = {
260     { "remove", RESTRICT_REMOVE },
261     { "scratch", RESTRICT_SCRATCH },
262     { "move", RESTRICT_MOVE },
263   };
264
265   for(n = 0; n < nvec; ++n) {
266     if((i = TABLE_FIND(restrictions, struct restriction, name, vec[n])) < 0) {
267       error(0, "%s:%d: invalid restriction '%s'",
268             cs->path, cs->line, vec[n]);
269       return -1;
270     }
271     r |= restrictions[i].bit;
272   }
273   VALUE(cs->config, unsigned) = r;
274   return 0;
275 }
276
277 static int parse_sample_format(const struct config_state *cs,
278                                ao_sample_format *ao,
279                                int nvec, char **vec) {
280   char *p = vec[0];
281   long t;
282
283   if (nvec != 1) {
284     error(0, "%s:%d: wrong number of arguments", cs->path, cs->line);
285     return -1;
286   }
287   if (xstrtol(&t, p, &p, 0)) {
288     error(errno, "%s:%d: converting bits-per-sample", cs->path, cs->line);
289     return -1;
290   }
291   if (t != 8 && t != 16) {
292     error(0, "%s:%d: bad bite-per-sample (%ld)", cs->path, cs->line, t);
293     return -1;
294   }
295   if (ao) ao->bits = t;
296   switch (*p) {
297     case 'l': case 'L': t = AO_FMT_LITTLE; p++; break;
298     case 'b': case 'B': t = AO_FMT_BIG; p++; break;
299     default: t = AO_FMT_NATIVE; break;
300   }
301   if (ao) ao->byte_format = t;
302   if (*p != '/') {
303     error(errno, "%s:%d: expected `/' after bits-per-sample",
304           cs->path, cs->line);
305     return -1;
306   }
307   p++;
308   if (xstrtol(&t, p, &p, 0)) {
309     error(errno, "%s:%d: converting sample-rate", cs->path, cs->line);
310     return -1;
311   }
312   if (t < 1 || t > INT_MAX) {
313     error(0, "%s:%d: silly sample-rate (%ld)", cs->path, cs->line, t);
314     return -1;
315   }
316   if (ao) ao->rate = t;
317   if (*p != '/') {
318     error(0, "%s:%d: expected `/' after sample-rate",
319           cs->path, cs->line);
320     return -1;
321   }
322   p++;
323   if (xstrtol(&t, p, &p, 0)) {
324     error(errno, "%s:%d: converting channels", cs->path, cs->line);
325     return -1;
326   }
327   if (t < 1 || t > 8) {
328     error(0, "%s:%d: silly number (%ld) of channels", cs->path, cs->line, t);
329     return -1;
330   }
331   if (ao) ao->channels = t;
332   if (*p) {
333     error(0, "%s:%d: junk after channels", cs->path, cs->line);
334     return -1;
335   }
336   return 0;
337 }
338
339 static int set_sample_format(const struct config_state *cs,
340                              const struct conf *whoami,
341                              int nvec, char **vec) {
342   return parse_sample_format(cs, ADDRESS(cs->config, ao_sample_format),
343                              nvec, vec);
344 }
345
346 static int set_namepart(const struct config_state *cs,
347                         const struct conf *whoami,
348                         int nvec, char **vec) {
349   struct namepartlist *npl = ADDRESS(cs->config, struct namepartlist);
350   unsigned reflags;
351   const char *errstr;
352   int erroffset, n;
353   pcre *re;
354
355   if(nvec < 3) {
356     error(0, "%s:%d: namepart needs at least 3 arguments", cs->path, cs->line);
357     return -1;
358   }
359   if(nvec > 5) {
360     error(0, "%s:%d: namepart needs at most 5 arguments", cs->path, cs->line);
361     return -1;
362   }
363   reflags = nvec >= 5 ? regsub_flags(vec[4]) : 0;
364   if(!(re = pcre_compile(vec[1],
365                          PCRE_UTF8
366                          |regsub_compile_options(reflags),
367                          &errstr, &erroffset, 0))) {
368     error(0, "%s:%d: error compiling regexp /%s/: %s (offset %d)",
369           cs->path, cs->line, vec[1], errstr, erroffset);
370     return -1;
371   }
372   npl->s = xrealloc(npl->s, (npl->n + 1) * sizeof (struct namepart));
373   npl->s[npl->n].part = xstrdup(vec[0]);
374   npl->s[npl->n].re = re;
375   npl->s[npl->n].replace = xstrdup(vec[2]);
376   npl->s[npl->n].context = xstrdup(vec[3]);
377   npl->s[npl->n].reflags = reflags;
378   ++npl->n;
379   /* XXX a bit of a bodge; relies on there being very few parts. */
380   for(n = 0; (n < cs->config->nparts
381               && strcmp(cs->config->parts[n], vec[0])); ++n)
382     ;
383   if(n >= cs->config->nparts) {
384     cs->config->parts = xrealloc(cs->config->parts,
385                                  (cs->config->nparts + 1) * sizeof (char *));
386     cs->config->parts[cs->config->nparts++] = xstrdup(vec[0]);
387   }
388   return 0;
389 }
390
391 static int set_transform(const struct config_state *cs,
392                          const struct conf *whoami,
393                          int nvec, char **vec) {
394   struct transformlist *tl = ADDRESS(cs->config, struct transformlist);
395   pcre *re;
396   unsigned reflags;
397   const char *errstr;
398   int erroffset;
399
400   if(nvec < 3) {
401     error(0, "%s:%d: transform needs at least 3 arguments", cs->path, cs->line);
402     return -1;
403   }
404   if(nvec > 5) {
405     error(0, "%s:%d: transform needs at most 5 arguments", cs->path, cs->line);
406     return -1;
407   }
408   reflags = (nvec >= 5 ? regsub_flags(vec[4]) : 0);
409   if(!(re = pcre_compile(vec[1],
410                          PCRE_UTF8
411                          |regsub_compile_options(reflags),
412                          &errstr, &erroffset, 0))) {
413     error(0, "%s:%d: error compiling regexp /%s/: %s (offset %d)",
414           cs->path, cs->line, vec[1], errstr, erroffset);
415     return -1;
416   }
417   tl->t = xrealloc(tl->t, (tl->n + 1) * sizeof (struct namepart));
418   tl->t[tl->n].type = xstrdup(vec[0]);
419   tl->t[tl->n].context = xstrdup(vec[3] ? vec[3] : "*");
420   tl->t[tl->n].re = re;
421   tl->t[tl->n].replace = xstrdup(vec[2]);
422   tl->t[tl->n].flags = reflags;
423   ++tl->n;
424   return 0;
425 }
426
427 static int set_backend(const struct config_state *cs,
428                        const struct conf *whoami,
429                        int nvec, char **vec) {
430   int *const valuep = ADDRESS(cs->config, int);
431   
432   if(nvec != 1) {
433     error(0, "%s:%d: '%s' requires one argument",
434           cs->path, cs->line, whoami->name);
435     return -1;
436   }
437   if(!strcmp(vec[0], "alsa")) {
438 #if API_ALSA
439     *valuep = BACKEND_ALSA;
440 #else
441     error(0, "%s:%d: ALSA is not available on this platform",
442           cs->path, cs->line);
443     return -1;
444 #endif
445   } else if(!strcmp(vec[0], "command"))
446     *valuep = BACKEND_COMMAND;
447   else if(!strcmp(vec[0], "network"))
448     *valuep = BACKEND_NETWORK;
449   else {
450     error(0, "%s:%d: invalid '%s' value '%s'",
451           cs->path, cs->line, whoami->name, vec[0]);
452     return -1;
453   }
454   return 0;
455 }
456
457 /* free functions */
458
459 static void free_none(struct config attribute((unused)) *c,
460                       const struct conf attribute((unused)) *whoami) {
461 }
462
463 static void free_string(struct config *c,
464                         const struct conf *whoami) {
465   xfree(VALUE(c, char *));
466 }
467
468 static void free_stringlist(struct config *c,
469                             const struct conf *whoami) {
470   int n;
471   struct stringlist *sl = ADDRESS(c, struct stringlist);
472
473   for(n = 0; n < sl->n; ++n)
474     xfree(sl->s[n]);
475   xfree(sl->s);
476 }
477
478 static void free_stringlistlist(struct config *c,
479                                 const struct conf *whoami) {
480   int n, m;
481   struct stringlistlist *sll = ADDRESS(c, struct stringlistlist);
482   struct stringlist *sl;
483
484   for(n = 0; n < sll->n; ++n) {
485     sl = &sll->s[n];
486     for(m = 0; m < sl->n; ++m)
487       xfree(sl->s[m]);
488     xfree(sl->s);
489   }
490   xfree(sll->s);
491 }
492
493 static void free_collectionlist(struct config *c,
494                                 const struct conf *whoami) {
495   struct collectionlist *cll = ADDRESS(c, struct collectionlist);
496   struct collection *cl;
497   int n;
498
499   for(n = 0; n < cll->n; ++n) {
500     cl = &cll->s[n];
501     xfree(cl->module);
502     xfree(cl->encoding);
503     xfree(cl->root);
504   }
505   xfree(cll->s);
506 }
507
508 static void free_namepartlist(struct config *c,
509                               const struct conf *whoami) {
510   struct namepartlist *npl = ADDRESS(c, struct namepartlist);
511   struct namepart *np;
512   int n;
513
514   for(n = 0; n < npl->n; ++n) {
515     np = &npl->s[n];
516     xfree(np->part);
517     pcre_free(np->re);                  /* ...whatever pcre_free is set to. */
518     xfree(np->replace);
519     xfree(np->context);
520   }
521   xfree(npl->s);
522 }
523
524 static void free_transformlist(struct config *c,
525                                const struct conf *whoami) {
526   struct transformlist *tl = ADDRESS(c, struct transformlist);
527   struct transform *t;
528   int n;
529
530   for(n = 0; n < tl->n; ++n) {
531     t = &tl->t[n];
532     xfree(t->type);
533     pcre_free(t->re);                   /* ...whatever pcre_free is set to. */
534     xfree(t->replace);
535     xfree(t->context);
536   }
537   xfree(tl->t);
538 }
539
540 /* configuration types */
541
542 static const struct conftype
543   type_signal = { set_signal, free_none },
544   type_collections = { set_collections, free_collectionlist },
545   type_boolean = { set_boolean, free_none },
546   type_string = { set_string, free_string },
547   type_stringlist = { set_stringlist, free_stringlist },
548   type_integer = { set_integer, free_none },
549   type_stringlist_accum = { set_stringlist_accum, free_stringlistlist },
550   type_string_accum = { set_string_accum, free_stringlist },
551   type_sample_format = { set_sample_format, free_none },
552   type_restrict = { set_restrict, free_none },
553   type_namepart = { set_namepart, free_namepartlist },
554   type_transform = { set_transform, free_transformlist },
555   type_backend = { set_backend, free_none };
556
557 /* specific validation routine */
558
559 #define VALIDATE_FILE(test, what) do {                          \
560   struct stat sb;                                               \
561   int n;                                                        \
562                                                                 \
563   for(n = 0; n < nvec; ++n) {                                   \
564     if(stat(vec[n], &sb) < 0) {                                 \
565       error(errno, "%s:%d: %s", cs->path, cs->line, vec[n]);    \
566       return -1;                                                \
567     }                                                           \
568     if(!test(sb.st_mode)) {                                     \
569       error(0, "%s:%d: %s is not a %s",                         \
570             cs->path, cs->line, vec[n], what);                  \
571       return -1;                                                \
572     }                                                           \
573   }                                                             \
574 } while(0)
575
576 static int validate_isdir(const struct config_state *cs,
577                           int nvec, char **vec) {
578   VALIDATE_FILE(S_ISDIR, "directory");
579   return 0;
580 }
581
582 static int validate_isreg(const struct config_state *cs,
583                           int nvec, char **vec) {
584   VALIDATE_FILE(S_ISREG, "regular file");
585   return 0;
586 }
587
588 static int validate_ischr(const struct config_state *cs,
589                           int nvec, char **vec) {
590   VALIDATE_FILE(S_ISCHR, "character device");
591   return 0;
592 }
593
594 static int validate_player(const struct config_state *cs,
595                            int nvec,
596                            char attribute((unused)) **vec) {
597   if(nvec < 2) {
598     error(0, "%s:%d: should be at least 'player PATTERN MODULE'",
599           cs->path, cs->line);
600     return -1;
601   }
602   return 0;
603 }
604
605 static int validate_allow(const struct config_state *cs,
606                           int nvec,
607                           char attribute((unused)) **vec) {
608   if(nvec != 2) {
609     error(0, "%s:%d: must be 'allow NAME PASS'", cs->path, cs->line);
610     return -1;
611   }
612   return 0;
613 }
614
615 static int validate_non_negative(const struct config_state *cs,
616                                  int nvec, char **vec) {
617   long n;
618
619   if(nvec < 1) {
620     error(0, "%s:%d: missing argument", cs->path, cs->line);
621     return -1;
622   }
623   if(nvec > 1) {
624     error(0, "%s:%d: too many arguments", cs->path, cs->line);
625     return -1;
626   }
627   if(xstrtol(&n, vec[0], 0, 0)) {
628     error(0, "%s:%d: %s", cs->path, cs->line, strerror(errno));
629     return -1;
630   }
631   if(n < 0) {
632     error(0, "%s:%d: must not be negative", cs->path, cs->line);
633     return -1;
634   }
635   return 0;
636 }
637
638 static int validate_positive(const struct config_state *cs,
639                           int nvec, char **vec) {
640   long n;
641
642   if(nvec < 1) {
643     error(0, "%s:%d: missing argument", cs->path, cs->line);
644     return -1;
645   }
646   if(nvec > 1) {
647     error(0, "%s:%d: too many arguments", cs->path, cs->line);
648     return -1;
649   }
650   if(xstrtol(&n, vec[0], 0, 0)) {
651     error(0, "%s:%d: %s", cs->path, cs->line, strerror(errno));
652     return -1;
653   }
654   if(n <= 0) {
655     error(0, "%s:%d: must be positive", cs->path, cs->line);
656     return -1;
657   }
658   return 0;
659 }
660
661 static int validate_isauser(const struct config_state *cs,
662                             int attribute((unused)) nvec,
663                             char **vec) {
664   struct passwd *pw;
665
666   if(!(pw = getpwnam(vec[0]))) {
667     error(0, "%s:%d: no such user as '%s'", cs->path, cs->line, vec[0]);
668     return -1;
669   }
670   return 0;
671 }
672
673 static int validate_sample_format(const struct config_state *cs,
674                                   int attribute((unused)) nvec,
675                                   char **vec) {
676   return parse_sample_format(cs, 0, nvec, vec);
677 }
678
679 static int validate_channel(const struct config_state *cs,
680                             int attribute((unused)) nvec,
681                             char **vec) {
682   if(mixer_channel(vec[0]) == -1) {
683     error(0, "%s:%d: invalid channel '%s'", cs->path, cs->line, vec[0]);
684     return -1;
685   }
686   return 0;
687 }
688
689 static int validate_any(const struct config_state attribute((unused)) *cs,
690                         int attribute((unused)) nvec,
691                         char attribute((unused)) **vec) {
692   return 0;
693 }
694
695 static int validate_url(const struct config_state attribute((unused)) *cs,
696                         int attribute((unused)) nvec,
697                         char **vec) {
698   const char *s;
699   int n;
700   /* absoluteURI   = scheme ":" ( hier_part | opaque_part )
701      scheme        = alpha *( alpha | digit | "+" | "-" | "." ) */
702   s = vec[0];
703   n = strspn(s, ("abcdefghijklmnopqrstuvwxyz"
704                  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
705                  "0123456789"));
706   if(s[n] != ':') {
707     error(0, "%s:%d: invalid url '%s'", cs->path, cs->line, vec[0]);
708     return -1;
709   }
710   if(!strncmp(s, "http:", 5)
711      || !strncmp(s, "https:", 6)) {
712     s += n + 1;
713     /* we only do a rather cursory check */
714     if(strncmp(s, "//", 2)) {
715       error(0, "%s:%d: invalid url '%s'", cs->path, cs->line, vec[0]);
716       return -1;
717     }
718   }
719   return 0;
720 }
721
722 static int validate_alias(const struct config_state *cs,
723                           int nvec,
724                           char **vec) {
725   const char *s;
726   int in_brackets = 0, c;
727
728   if(nvec < 1) {
729     error(0, "%s:%d: missing argument", cs->path, cs->line);
730     return -1;
731   }
732   if(nvec > 1) {
733     error(0, "%s:%d: too many arguments", cs->path, cs->line);
734     return -1;
735   }
736   s = vec[0];
737   while((c = (unsigned char)*s++)) {
738     if(in_brackets) {
739       if(c == '}')
740         in_brackets = 0;
741       else if(!isalnum(c)) {
742         error(0, "%s:%d: invalid part name in alias expansion in '%s'",
743               cs->path, cs->line, vec[0]);
744           return -1;
745       }
746     } else {
747       if(c == '{') {
748         in_brackets = 1;
749         if(*s == '/')
750           ++s;
751       } else if(c == '\\') {
752         if(!(c = (unsigned char)*s++)) {
753           error(0, "%s:%d: unterminated escape in alias expansion in '%s'",
754                 cs->path, cs->line, vec[0]);
755           return -1;
756         } else if(c != '\\' && c != '{') {
757           error(0, "%s:%d: invalid escape in alias expansion in '%s'",
758                 cs->path, cs->line, vec[0]);
759           return -1;
760         }
761       }
762     }
763     ++s;
764   }
765   if(in_brackets) {
766     error(0, "%s:%d: unterminated part name in alias expansion in '%s'",
767           cs->path, cs->line, vec[0]);
768     return -1;
769   }
770   return 0;
771 }
772
773 static int validate_addrport(const struct config_state attribute((unused)) *cs,
774                              int nvec,
775                              char attribute((unused)) **vec) {
776   switch(nvec) {
777   case 0:
778     error(0, "%s:%d: missing address",
779           cs->path, cs->line);
780     return -1;
781   case 1:
782     error(0, "%s:%d: missing port name/number",
783           cs->path, cs->line);
784     return -1;
785   case 2:
786     return 0;
787   default:
788     error(0, "%s:%d: expected ADDRESS PORT",
789           cs->path, cs->line);
790     return -1;
791   }
792 }
793
794 static int validate_address(const struct config_state attribute((unused)) *cs,
795                          int nvec,
796                          char attribute((unused)) **vec) {
797   switch(nvec) {
798   case 0:
799     error(0, "%s:%d: missing address",
800           cs->path, cs->line);
801     return -1;
802   case 1:
803   case 2:
804     return 0;
805   default:
806     error(0, "%s:%d: expected ADDRESS PORT",
807           cs->path, cs->line);
808     return -1;
809   }
810 }
811
812 /** @brief Item name and and offset */
813 #define C(x) #x, offsetof(struct config, x)
814 /** @brief Item name and and offset */
815 #define C2(x,y) #x, offsetof(struct config, y)
816
817 /** @brief All configuration items */
818 static const struct conf conf[] = {
819   { C(alias),            &type_string,           validate_alias },
820   { C(allow),            &type_stringlist_accum, validate_allow },
821   { C(broadcast),        &type_stringlist,       validate_addrport },
822   { C(broadcast_from),   &type_stringlist,       validate_address },
823   { C(channel),          &type_string,           validate_channel },
824   { C(checkpoint_kbyte), &type_integer,          validate_non_negative },
825   { C(checkpoint_min),   &type_integer,          validate_non_negative },
826   { C(collection),       &type_collections,      validate_any },
827   { C(connect),          &type_stringlist,       validate_addrport },
828   { C(device),           &type_string,           validate_any },
829   { C(gap),              &type_integer,          validate_non_negative },
830   { C(history),          &type_integer,          validate_positive },
831   { C(home),             &type_string,           validate_isdir },
832   { C(listen),           &type_stringlist,       validate_addrport },
833   { C(lock),             &type_boolean,          validate_any },
834   { C(mixer),            &type_string,           validate_ischr },
835   { C(namepart),         &type_namepart,         validate_any },
836   { C2(nice, nice_rescan), &type_integer,        validate_non_negative },
837   { C(nice_rescan),      &type_integer,          validate_non_negative },
838   { C(nice_server),      &type_integer,          validate_any },
839   { C(nice_speaker),     &type_integer,          validate_any },
840   { C(password),         &type_string,           validate_any },
841   { C(player),           &type_stringlist_accum, validate_player },
842   { C(plugins),          &type_string_accum,     validate_isdir },
843   { C(prefsync),         &type_integer,          validate_positive },
844   { C(queue_pad),        &type_integer,          validate_positive },
845   { C(refresh),          &type_integer,          validate_positive },
846   { C2(restrict, restrictions),         &type_restrict,         validate_any },
847   { C(sample_format),    &type_sample_format,    validate_sample_format },
848   { C(scratch),          &type_string_accum,     validate_isreg },
849   { C(signal),           &type_signal,           validate_any },
850   { C(sox_generation),   &type_integer,          validate_non_negative },
851   { C(speaker_backend),  &type_backend,          validate_any },
852   { C(speaker_command),  &type_string,           validate_any },
853   { C(stopword),         &type_string_accum,     validate_any },
854   { C(templates),        &type_string_accum,     validate_isdir },
855   { C(transform),        &type_transform,        validate_any },
856   { C(trust),            &type_string_accum,     validate_any },
857   { C(url),              &type_string,           validate_url },
858   { C(user),             &type_string,           validate_isauser },
859   { C(username),         &type_string,           validate_any },
860 };
861
862 /** @brief Find a configuration item's definition by key */
863 static const struct conf *find(const char *key) {
864   int n;
865
866   if((n = TABLE_FIND(conf, struct conf, name, key)) < 0)
867     return 0;
868   return &conf[n];
869 }
870
871 /** @brief Set a new configuration value */
872 static int config_set(const struct config_state *cs,
873                       int nvec, char **vec) {
874   const struct conf *which;
875
876   D(("config_set %s", vec[0]));
877   if(!(which = find(vec[0]))) {
878     error(0, "%s:%d: unknown configuration key '%s'",
879           cs->path, cs->line, vec[0]);
880     return -1;
881   }
882   return (which->validate(cs, nvec - 1, vec + 1)
883           || which->type->set(cs, which, nvec - 1, vec + 1));
884 }
885
886 static void config_error(const char *msg, void *u) {
887   const struct config_state *cs = u;
888
889   error(0, "%s:%d: %s", cs->path, cs->line, msg);
890 }
891
892 /** @brief Include a file by name */
893 static int config_include(struct config *c, const char *path) {
894   FILE *fp;
895   char *buffer, *inputbuffer, **vec;
896   int n, ret = 0;
897   struct config_state cs;
898
899   cs.path = path;
900   cs.line = 0;
901   cs.config = c;
902   D(("%s: reading configuration", path));
903   if(!(fp = fopen(path, "r"))) {
904     error(errno, "error opening %s", path);
905     return -1;
906   }
907   while(!inputline(path, fp, &inputbuffer, '\n')) {
908     ++cs.line;
909     if(!(buffer = mb2utf8(inputbuffer))) {
910       error(errno, "%s:%d: cannot convert to UTF-8", cs.path, cs.line);
911       ret = -1;
912       xfree(inputbuffer);
913       continue;
914     }
915     xfree(inputbuffer);
916     if(!(vec = split(buffer, &n, SPLIT_COMMENTS|SPLIT_QUOTES,
917                      config_error, &cs))) {
918       ret = -1;
919       xfree(buffer);
920       continue;
921     }
922     if(n) {
923       if(!strcmp(vec[0], "include")) {
924         if(n != 2) {
925           error(0, "%s:%d: must be 'include PATH'", cs.path, cs.line);
926           ret = -1;
927         } else
928           config_include(c, vec[1]);
929       } else
930         ret |= config_set(&cs, n, vec);
931     }
932     for(n = 0; vec[n]; ++n) xfree(vec[n]);
933     xfree(vec);
934     xfree(buffer);
935   }
936   if(ferror(fp)) {
937     error(errno, "error reading %s", path);
938     ret = -1;
939   }
940   fclose(fp);
941   return ret;
942 }
943
944 /** @brief Make a new default configuration */
945 static struct config *config_default(void) {
946   struct config *c = xmalloc(sizeof *c);
947   const char *logname;
948   struct passwd *pw;
949
950   /* Strings had better be xstrdup'd as they will get freed at some point. */
951   c->gap = 2;
952   c->history = 60;
953   c->home = xstrdup(pkgstatedir);
954   if(!(pw = getpwuid(getuid())))
955     fatal(0, "cannot determine our username");
956   logname = pw->pw_name;
957   c->username = xstrdup(logname);
958   c->refresh = 15;
959   c->prefsync = 3600;
960   c->signal = SIGKILL;
961   c->alias = xstrdup("{/artist}{/album}{/title}{ext}");
962   c->lock = 1;
963   c->device = xstrdup("default");
964   c->nice_rescan = 10;
965   c->speaker_command = 0;
966   c->sample_format.bits = 16;
967   c->sample_format.rate = 44100;
968   c->sample_format.channels = 2;
969   c->sample_format.byte_format = AO_FMT_NATIVE;
970   c->queue_pad = 10;
971   c->speaker_backend = -1;
972   return c;
973 }
974
975 static char *get_file(struct config *c, const char *name) {
976   char *s;
977
978   byte_xasprintf(&s, "%s/%s", c->home, name);
979   return s;
980 }
981
982 /** @brief Set the default configuration file */
983 static void set_configfile(void) {
984   if(!configfile)
985     byte_xasprintf(&configfile, "%s/config", pkgconfdir);
986 }
987
988 /** @brief Free a configuration object */
989 static void config_free(struct config *c) {
990   int n;
991
992   if(c) {
993     for(n = 0; n < (int)(sizeof conf / sizeof *conf); ++n)
994       conf[n].type->free(c, &conf[n]);
995     for(n = 0; n < c->nparts; ++n)
996       xfree(c->parts[n]);
997     xfree(c->parts);
998     xfree(c);
999   }
1000 }
1001
1002 /** @brief Set post-parse defaults */
1003 static void config_postdefaults(struct config *c) {
1004   struct config_state cs;
1005   const struct conf *whoami;
1006   int n;
1007
1008   static const char *namepart[][4] = {
1009     { "title",  "/([0-9]+:)?([^/]+)\\.[a-zA-Z0-9]+$", "$2", "display" },
1010     { "title",  "/([^/]+)\\.[a-zA-Z0-9]+$",           "$1", "sort" },
1011     { "album",  "/([^/]+)/[^/]+$",                    "$1", "*" },
1012     { "artist", "/([^/]+)/[^/]+/[^/]+$",              "$1", "*" },
1013     { "ext",    "(\\.[a-zA-Z0-9]+)$",                 "$1", "*" },
1014   };
1015 #define NNAMEPART (int)(sizeof namepart / sizeof *namepart)
1016
1017   static const char *transform[][5] = {
1018     { "track", "^.*/([0-9]+:)?([^/]+)\\.[a-zA-Z0-9]+$", "$2", "display", "" },
1019     { "track", "^.*/([^/]+)\\.[a-zA-Z0-9]+$",           "$1", "sort", "" },
1020     { "dir",   "^.*/([^/]+)$",                          "$1", "*", "" },
1021     { "dir",   "^(the) ([^/]*)",                        "$2, $1", "sort", "i", },
1022     { "dir",   "[[:punct:]]",                           "", "sort", "g", }
1023   };
1024 #define NTRANSFORM (int)(sizeof transform / sizeof *transform)
1025
1026   cs.path = "<internal>";
1027   cs.line = 0;
1028   cs.config = c;
1029   if(!c->namepart.n) {
1030     whoami = find("namepart");
1031     for(n = 0; n < NNAMEPART; ++n)
1032       set_namepart(&cs, whoami, 4, (char **)namepart[n]);
1033   }
1034   if(!c->transform.n) {
1035     whoami = find("transform");
1036     for(n = 0; n < NTRANSFORM; ++n)
1037       set_transform(&cs, whoami, 5, (char **)transform[n]);
1038   }
1039   if(c->speaker_backend == -1) {
1040     if(c->speaker_command)
1041       c->speaker_backend = BACKEND_COMMAND;
1042     else if(c->broadcast.n)
1043       c->speaker_backend = BACKEND_NETWORK;
1044     else {
1045 #if API_ALSA
1046       c->speaker_backend = BACKEND_ALSA;
1047 #else
1048       c->speaker_backend = BACKEND_COMMAND;
1049 #endif
1050     }
1051   }
1052   if(c->speaker_backend == BACKEND_COMMAND && !c->speaker_command)
1053     fatal(0, "speaker_backend is command but speaker_command is not set");
1054   if(c->speaker_backend == BACKEND_NETWORK && !c->broadcast.n)
1055     fatal(0, "speaker_backend is network but broadcast is not set");
1056 }
1057
1058 /** @brief (Re-)read the config file */
1059 int config_read() {
1060   struct config *c;
1061   char *privconf;
1062   struct passwd *pw;
1063
1064   set_configfile();
1065   c = config_default();
1066   if(config_include(c, configfile))
1067     return -1;
1068   /* if we can read the private config file, do */
1069   if((privconf = config_private())
1070      && access(privconf, R_OK) == 0
1071      && config_include(c, privconf))
1072     return -1;
1073   xfree(privconf);
1074   /* if there's a per-user system config file for this user, read it */
1075   if(!(pw = getpwuid(getuid())))
1076     fatal(0, "cannot determine our username");
1077   if((privconf = config_usersysconf(pw))
1078      && access(privconf, F_OK) == 0
1079      && config_include(c, privconf))
1080       return -1;
1081   xfree(privconf);
1082   /* if we have a password file, read it */
1083   if((privconf = config_userconf(getenv("HOME"), pw))
1084      && access(privconf, F_OK) == 0
1085      && config_include(c, privconf))
1086     return -1;
1087   xfree(privconf);
1088   /* install default namepart and transform settings */
1089   config_postdefaults(c);
1090   /* everything is good so we shall use the new config */
1091   config_free(config);
1092   config = c;
1093   return 0;
1094 }
1095
1096 /** @brief Return the path to the private configuration file */
1097 char *config_private(void) {
1098   char *s;
1099
1100   set_configfile();
1101   byte_xasprintf(&s, "%s.private", configfile);
1102   return s;
1103 }
1104
1105 /** @brief Return the path to user's personal configuration file */
1106 char *config_userconf(const char *home, const struct passwd *pw) {
1107   char *s;
1108
1109   byte_xasprintf(&s, "%s/.disorder/passwd", home ? home : pw->pw_dir);
1110   return s;
1111 }
1112
1113 /** @brief Return the path to user-specific system configuration */
1114 char *config_usersysconf(const struct passwd *pw) {
1115   char *s;
1116
1117   set_configfile();
1118   if(!strchr(pw->pw_name, '/')) {
1119     byte_xasprintf(&s, "%s.%s", configfile, pw->pw_name);
1120     return s;
1121   } else
1122     return 0;
1123 }
1124
1125 char *config_get_file(const char *name) {
1126   return get_file(config, name);
1127 }
1128
1129 /*
1130 Local Variables:
1131 c-basic-offset:2
1132 comment-column:40
1133 fill-column:79
1134 End:
1135 */