chiark / gitweb /
updated version
[userv.git] / parser.c
1 /*
2  * userv - parser.c
3  * configuration file parser; this file is actually #included from
4  * lexer.c, which is generated using flex from lexer.l, in turn from
5  * lexer.l.m4.  It's in a separate file so that we don't have to worry
6  * about m4 quoting &c., but we have to #include it so that the C
7  * objects from the lexer are available.
8  *
9  * Copyright (C)1996-1999,2001 Ian Jackson
10  *
11  * This is free software; you can redistribute it and/or modify it
12  * under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with userv; if not, write to the Free Software
23  * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24  */
25
26 static int parse_file(const char *string, int *didexist);
27 static int parser(int allowce);
28 int parse_string(const char *string, const char *descrip, int isinternal);
29
30 /*
31  * Error-handling routines
32  */
33
34 static void closeerrorfile(void) {
35   if (eh.file && !eh.filekeep) {
36     if (fclose(eh.file)) {
37       eh.handling= tokv_word_errorstostderr;
38       parseerrprint("error writing to error log file `%s': %s",
39                     eh.filename,strerror(errno));
40     }
41     free(eh.filename);
42   }
43   eh.handling= 0;
44   eh.file= 0; eh.filename= 0; eh.filekeep= 0;
45 }
46
47 static void senderrmsg(const char *errmsg, int useehandling) {
48   char suberrmsg[MAX_ERRMSG_LEN];
49   int e;
50   time_t now;
51   struct tm *lt;
52
53   switch (useehandling) {
54   case tokv_word_errorstostderr:
55     senderrmsgstderr(errmsg);
56     break;
57   case tokv_word_errorstosyslog:
58     ensurelogopen(eh.logfacility);
59     syslog(eh.loglevel,"%s",errmsg);
60     break;
61   case tokv_word_errorstofile:
62     if (time(&now)==-1) syscallerror("get current time");
63     lt= localtime(&now); if (!lt) syscallerror("convert current time");
64     if (fprintf(eh.file,"%d-%02d-%02d %02d:%02d:%02d: uservd: %s\n",
65                 lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday,
66                 lt->tm_hour, lt->tm_min, lt->tm_sec,
67                 errmsg) == EOF) {
68       e= errno;
69       closeerrorfile(); eh.handling= tokv_word_errorstofile;
70       snyprintf(suberrmsg,sizeof(suberrmsg),
71                 "error writing to error log file `%.*s': %s;"
72                 " reverting to errors-to-stderr",
73                 (int)(sizeof(suberrmsg)>>1),eh.filename,strerror(e));
74       senderrmsg(suberrmsg,eh.handling);
75       senderrmsg(errmsg,eh.handling);
76     }
77     break;
78   default:
79     abort();
80   }
81 }
82
83 static void errwhere(struct parser_state *tstate, char *bufput, int bufputlen) {
84   static const char suffix[]= "references ...";
85   char errmsg[MAX_ERRMSG_LEN];
86   
87   if (!tstate) {
88     strnycpy(bufput,"<initialisation>: ",bufputlen);
89     return;
90   }
91   if (!tstate->notedreferer && tstate->upstate && !tstate->upstate->isinternal) {
92     errwhere(tstate->upstate,errmsg,sizeof(errmsg)-sizeof(suffix));
93     strcat(errmsg,suffix);
94     senderrmsg(errmsg,eh.handling);
95     tstate->notedreferer= 1;
96   }
97   snyprintf(bufput,bufputlen,"%.*s:%d: ",bufputlen-10,
98             tstate->filename,tstate->reportlineno);
99 }
100
101 int parseerrprint(const char *fmt, ...) {
102   va_list al;
103   char errmsg[MAX_ERRMSG_LEN];
104
105   va_start(al,fmt);
106   errwhere(cstate,errmsg,sizeof(errmsg)>>1);
107   vsnytprintfcat(errmsg,sizeof(errmsg),fmt,al);
108   senderrmsg(errmsg,eh.handling);
109   va_end(al);
110
111   return tokv_error;
112 }
113
114 static int unexpected(int found, int wanted, const char *wantedstr) {
115   /* pass wanted==-1 if you know it's not what you wanted;
116    * otherwise this function will check it for you.
117    */
118   if (found == wanted) return 0;
119   if (found == tokv_error) return found;
120   return parseerrprint("found %s, expected %s",printtoken(found),wantedstr);
121 }
122
123 static int stringoverflow(const char *where) {
124   return parseerrprint("string buffer became far too large building %s",where);
125 }
126
127 /*
128  * General assistance functions
129  */
130
131 static void freecharparray(char **array) {
132   char **pp;
133
134   if (!array) return;
135   for (pp=array; *pp; pp++) free(*pp);
136   free(array);
137 }
138
139 static void countnewlines(void) {
140   char *p;
141   for (p=yytext; *p; p++)
142     if (*p == '\n')
143       cstate->lineno++;
144 }
145
146 static int dequote(char *inplace) {
147   char *p, *q, buf[4], *bep;
148   int v;
149
150   p=q=inplace;
151   assert(*p=='"');  p++;
152   while (*p && *p != '"') {
153     if (*p != '\\') { *q++= *p++; continue; }
154     switch (*++p) {
155     case 'n': *q++= '\n'; p++; continue;
156     case 'r': *q++= '\r'; p++; continue;
157     case 't': *q++= '\t'; p++; continue;
158     case 'x':
159       p++;
160       if (!((buf[0]= *p++) && (buf[1]= *p++)))
161         return parseerrprint("quoted string ends inside \\x<hex> sequence");
162       buf[2]= 0;
163       v= strtoul(buf,&bep,16);
164       if (bep != buf+2)
165         return parseerrprint("invalid \\<hex> sequence \\x%s in quoted string",buf);
166       assert(!(v & ~0xff));
167       *q++= v;
168       continue;
169     default:
170       if (ISCHAR(isalpha,*p))
171         return parseerrprint("unknown \\<letter> sequence \\%c in quoted string",*p);
172       if (ISCHAR(isdigit,*p)) {
173         if (!((buf[0]= *p++) && (buf[1]= *p++) && (buf[2]= *p++))) abort();
174         buf[3]= 0; v= strtoul(buf,&bep,8);
175         if (bep != buf+3 || (v & ~0xff))
176           return parseerrprint("invalid \\<octal> sequence \\%s in quoted string",buf);
177         *q++= v; continue;
178       } else if (ISCHAR(ispunct,*p)) {
179         *q++= *p++; continue;
180       } else {
181         while (*p==' ' || *p=='\t') p++;
182         v= *p++; assert(v=='\n');
183       }
184     }
185   }
186   assert(*p); p++; assert(!*p);
187   *q++= 0;
188   return tokv_quotedstring;
189 }
190
191 const char *printtoken(int token) {
192   /* Returns pointer to static buffer, overwritten by next call. */
193   static const char keywordfmt[]= "keyword `%s'";
194   static const char operatorfmt[]= "operator `%s'";
195   
196   static char buf[250];
197   
198   char *q;
199   const char *p;
200   int i, c, l;
201   
202   if ((token & tokm_repres) == tokr_word) {
203     assert(strlen(yytext)+sizeof(keywordfmt)<sizeof(buf));
204     snyprintf(buf,sizeof(buf),keywordfmt,yytext);
205     return buf;
206   } else if (token & tokt_number) {
207     snyprintf(buf,sizeof(buf),"number %d",lr_min); return buf;
208   } else if (token & tokt_fdrange && lr_max==-1) {
209     snyprintf(buf,sizeof(buf),"fdrange %d-",lr_min); return buf;
210   } else if (token & tokt_fdrange) {
211     snyprintf(buf,sizeof(buf),"fdrange %d-%d",lr_min,lr_max); return buf;
212   } else if ((token & tokm_repres) == tokr_punct) {
213     assert(strlen(yytext)+sizeof(operatorfmt)<sizeof(buf));
214     snyprintf(buf,sizeof(buf),operatorfmt,yytext);
215     return buf;
216   } else if (token & tokt_string) {
217     switch (token) {
218     case tokv_barestring: strcpy(buf,"unquoted string (bare word)"); break;
219     case tokv_quotedstring: strcpy(buf,"quoted string"); break;
220     default: abort();
221     }
222     strcat(buf," `");
223     l= strlen(buf); i= sizeof(buf)-l-2; p= yytext; q= buf+l;
224     while ((c= *p++)) {
225       if (i-- <= 0) { q--; strcpy(q-3,"..."); break; }
226       if (ISCHAR(isspace,c)) c= ' ';
227       else if (!ISCHAR(isprint,c) || ISCHAR(iscntrl,c)) c= '?';
228       else *q++= c;
229     }
230     strcpy(q,"'");
231     return buf;
232   } else {
233     switch (token) {
234     case tokv_lwsp:    return "linear whitespace";
235     case tokv_newline: return "newline (or comment followed by newline)";
236     case tokv_eof:     return "end of input file";
237     case tokv_error:   return "syntax error token";
238     default:
239       sprintf(buf,"token#0%o",token); return buf;
240     }
241   }
242 }
243
244 static const char *string2path(const char *in) {
245   /* Returned pointers become invalid on next call.
246    * May return 0, having printed an error message.
247    */
248   static char *p;
249   static int pl;
250   
251   if (strncmp(in,"~/",2)) return in;
252   if (makeroom(&p,&pl,strlen(serviceuser_dir)+1+strlen(in+2)+1)) {
253     stringoverflow("pathname");
254     return 0;
255   }
256   snyprintf(p,pl,"%s/%s",serviceuser_dir,in+2);
257   return p;
258 }
259
260 /*
261  * Parser component functions for parsing parameters to directives
262  *
263  * Functions pa_... parse just one parameter,
264  *  and return tokv_error or 0, having scanned exactly what they were expecting
265  * Functions paa_... parse complete parameter lists, including the leading lwsp,
266  *  and return tokv_error or 0, having scanned up to and including the newline
267  *
268  * For any function which takes `const char **rv' the
269  * value returned in *rv is overwritten by repeated calls to
270  * any of those functions (whether the same or another).
271  */
272
273 static int pa_mnl(void) {
274   return unexpected(yylex(),tokv_newline,"newline");
275 }
276 static int pa_mwsp(void) {
277   return unexpected(yylex(),tokv_lwsp,"linear whitespace");
278 }
279
280 static int pa_string(const char **rv) {
281   static char *p= 0;
282   static int pl= 0;
283
284   int r, l;
285
286   r= pa_mwsp(); if (r) return r;
287   r= yylex(); if (r == tokv_error) return r;
288   if ((r & tokm_repres) == tokr_nonstring) return unexpected(r,-1,"string");
289   l= strlen(yytext)+1;
290   if (makeroom(&p,&pl,l)) return stringoverflow("string argument");
291   strcpy(p,yytext); *rv= p;
292
293   return 0;
294 }  
295
296 static int pa_numberdollar(int *value_r) {
297   /* Also parses the whitespace beforehand. */
298   int r;
299
300   r= pa_mwsp(); if (r) return r;
301   r= yylex(); if (r == tokv_error || r == tokv_dollar) return r;
302   if (unexpected(r,tokv_ordinal,"expected number or dollar")) return tokv_error;
303   *value_r= lr_min;
304   return r;
305 }
306
307 static int paa_1string(const char **rv) {
308   int r;
309
310   r= pa_string(rv); if (r) return r;
311   return pa_mnl();
312 }  
313
314 static int paa_1path(const char **rv) {
315   const char *cp;
316   int r;
317   
318   r= paa_1string(&cp); if (r) return r;
319   *rv= string2path(cp); if (!*rv) return tokv_error;
320   return 0;
321 }
322
323 static int paa_pathargs(const char **path_r, char ***newargs_r) {
324   /* Repeated calls do _not_ overwrite newargs_r; caller must free.
325    * Repeated calls _do_ overwrite string returned in path_r.
326    * Any call to this function invalidates previous returns in *rv.
327    */
328   char **newargs;
329   const char *string;
330   int used, size, r;
331
332   r= pa_string(&string); if (r == tokv_error) return r;
333   *path_r= string2path(string); if (!*path_r) return tokv_error;
334   
335   used=0; size=0;
336   newargs= xmalloc(sizeof(char*)*(size+1));
337
338   for (;;) {
339     r= yylex(); if (r == tokv_error) goto error;
340     if (r==tokv_newline) break;
341     if (unexpected(r,tokv_lwsp,"newline after or whitespace between arguments")) {
342       r= tokv_error; goto error;
343     }
344     r= yylex(); if (r==tokv_error) goto error;
345     if ((r & tokm_repres) == tokr_nonstring) {
346       r= unexpected(r,-1,"string for command argument");
347       goto error;
348     }
349     if (used>=size) {
350       if (used >= MAX_ARGSDEFVAR) {
351         r= parseerrprint("far too many arguments to service program");
352         goto error;
353       }
354       size= (used+5)<<1;
355       newargs= xrealloc(newargs,sizeof(char*)*(size+1));
356     }
357     newargs[used++]= xstrsave(yytext);
358   }
359   newargs[used]= 0;
360   *newargs_r= newargs;
361   return 0;
362   
363 error:
364   newargs[used]=0;
365   freecharparray(newargs);
366   return r;
367 }
368
369 static int paa_message(const char **message_r) {
370   /* Returned value is invalidated by repeated calls. */
371   static char *buildbuf;
372   static int buildbuflen;
373   const char *usetext;
374
375   int r, tl;
376
377   r= pa_mwsp(); if (r) return r;
378   tl= 1;
379   if (makeroom(&buildbuf,&buildbuflen,50)) return stringoverflow("start of message");
380   buildbuf[0]= 0;
381   for (;;) {
382     r= yylex(); if (r == tokv_error) return r;
383     if (r == tokv_eof)
384       return parseerrprint("unexpected end of file in message text");
385     if (r == tokv_newline) break;
386     usetext= r == tokv_lwsp ? " " : yytext;
387     tl+= strlen(usetext);
388     if (makeroom(&buildbuf,&buildbuflen,tl)) return stringoverflow("message");
389     strcat(buildbuf,usetext);
390   }
391   *message_r= buildbuf;
392   return 0;
393 }
394
395 /*
396  * Skipping routines (used by e.g. the `if' code).
397  */
398
399 static int skiptoeol(void) {
400   /* Returns 0 if OK, having just parsed the newline
401    * or tokv_error if an error occurs, leaving the position at the error
402    * (which may be EOF or a syntax error token).
403    */
404   int token;
405
406   do { token= yylex(); }
407   while (token != tokv_newline && !(token & tokt_exception));
408   if (token == tokv_newline) return 0;
409   if (token == tokv_error) return token;
410   assert(token == tokv_eof);
411   return parseerrprint("unexpected end of file while looking for end of line");
412 }
413
414 static int skip(int allowce) {
415   /* Scans a piece of config without executing it.  Returns
416    * tokv_error (leaving the parsing state at the error),
417    * or the tokt_controlend token with type allowce if one
418    * was found (in which case rest of line, including any whitespace
419    * after tokt_controlend, has not been parsed), or tokv_eof.
420    */
421   int token, r;
422
423   for (;;) { /* loop over lines */
424     cstate->reportlineno= cstate->lineno;
425     do { token= yylex(); } while (token == tokv_lwsp);
426     if (token & tokt_exception) {
427       return token;
428     } else if (token & tokt_controlend) {
429       if (allowce == lr_controlend) return token;
430       else return unexpected(token,-1,"control structure end of a different kind");
431     } else if (token & tokt_controlstart) {
432       r= token;
433       while (r & tokt_controlstart) {
434         r= skiptoeol(); if (r) return r;
435         cstate->reportlineno= cstate->lineno;
436         r= skip(token); if (r & tokt_exception) return r;
437       }
438     } else if (!(token & tokt_directive) && !(token & tokt_condop)) {
439       return parseerrprint("not a directive (or conditional operator) "
440                            "while looking for control structure end");
441     }
442     r= skiptoeol(); if (r) return r;
443   }
444 }
445
446 /*
447  * Routines for parsing and getting the values of parameters
448  */
449
450 static void parm_1string(char ***rvalues, const char *tocopy) {
451   char **a;
452   a= xmalloc(sizeof(char*)*2);
453   a[0]= xstrsave(tocopy);
454   a[1]= 0;
455   *rvalues= a;
456 }
457
458 static char *parm_ulong(unsigned long ul) {
459   char *p;
460   int l;
461
462   l= CHAR_BIT*sizeof(unsigned long)/3+4;
463   p= xmalloc(l);
464   snyprintf(p,l,"%lu",ul);
465   return p;
466 }
467
468 static int parm_usernameuid(char ***rvalues, const char *name, uid_t id) {
469   char **a;
470   
471   a= xmalloc(sizeof(char*)*3);
472   a[0]= xstrsave(name);
473   a[1]= parm_ulong(id);
474   a[2]= 0;
475   *rvalues= a;
476   return 0;
477 }
478
479 static int parm_groups(char ***rvalues, int size,
480                        gid_t *gids, const char *const *groups) {
481   char **a;
482   int i;
483   
484   if (size >= 2 && gids[0] == gids[1]) { size--; gids++; groups++; }
485   a= xmalloc(sizeof(char*)*(size+1)*2);
486   for (i=0; i<size; i++) {
487     a[i]= xstrsave(groups[i]);
488     a[size+i]= parm_ulong(gids[i]);
489   }
490   a[size*2]= 0;
491   *rvalues= a;
492   return 0;
493 }  
494
495 static int pf_service(int ptoken, char ***rvalues) {
496   parm_1string(rvalues,service); return 0;
497 }
498
499 static int pf_callinguser(int ptoken, char ***rvalues) {
500   return parm_usernameuid(rvalues,loginname,request_mbuf.callinguid);
501 }
502
503 static int pf_serviceuser(int ptoken, char ***rvalues) {
504   return parm_usernameuid(rvalues,serviceuser,serviceuser_uid);
505 }
506
507 static int pf_callinggroup(int ptoken, char ***rvalues) {
508   return parm_groups(rvalues,request_mbuf.ngids,calling_gids,calling_groups);
509 }
510
511 static int pf_servicegroup(int ptoken, char ***rvalues) {
512   return parm_groups(rvalues,service_ngids,service_gids,service_groups);
513 }
514
515 static int pf_callingusershell(int ptoken, char ***rvalues) {
516   parm_1string(rvalues,callinguser_shell); return 0;
517 }
518
519 static int pf_serviceusershell(int ptoken, char ***rvalues) {
520   parm_1string(rvalues,serviceuser_shell); return 0;
521 }
522
523 static int pa_parameter(char ***rvalues, char **rname) {
524   /* Scans a single parameter token and calls the appropriate parameter
525    * function, returning tokv_error (leaving the parser state wherever),
526    * or 0 on success (having just parsed the parameter name).
527    * If rname is non-null then the name of the parameter (malloc'd) will
528    * be stored in it.
529    *
530    * Caller must free *rvalues using freecharparray.
531    */
532   int token, r, i;
533   char *name;
534
535   token= yylex(); if (token == tokv_error) return token;
536   name= xstrsave(yytext);
537   if ((token & tokm_repres) != tokr_nonstring &&
538       !memcmp(yytext,"u-",2) && strlen(yytext)>=3) {
539     for (i=0;
540          i<request_mbuf.nvars && strcmp(yytext+2,defvararray[i].key);
541          i++);
542     if (i>=request_mbuf.nvars) {
543       *rvalues= xmalloc(sizeof(char*));
544       **rvalues= 0;
545     } else {
546       parm_1string(rvalues,defvararray[i].value);
547     }
548   } else if (token & tokt_parameter) {
549     r= (lr_parameter)(token,rvalues);
550     if (r) { free(name); return r; }
551   } else {
552     free(name);
553     return unexpected(token,-1,"parameter name");
554   }
555   debug_dumpparameter(name,*rvalues);
556   if (rname) *rname= name;
557   else free(name);
558   return 0;
559 }
560
561 /*
562  * Routines for parsing conditions, including
563  * parameter-based conditional functions (parmcondition's).
564  */
565
566 int pcf_glob(int ctoken, char *const *pv, int *rtrue) {
567   int token, actrue, r;
568   char *const *pp;
569
570   actrue= 0;
571   r= pa_mwsp(); if (r) return r;
572   for (;;) {
573     token= yylex();
574     if ((token & tokm_repres) == tokr_nonstring)
575       return unexpected(token,-1,"glob pattern");
576     for (pp= pv; !actrue && *pp; pp++) if (!fnmatch(yytext,*pp,0)) actrue= 1;
577     token= yylex(); 
578     if (token == tokv_newline) break;
579     if (unexpected(token,tokv_lwsp,"newline after or whitespace between glob patterns"))
580       return tokv_error;
581   }
582   *rtrue= actrue;
583   return 0;
584 }
585
586 int pcf_range(int ctoken, char *const *pv, int *rtrue) {
587   int mintoken, min, maxtoken, max, r;
588   char *const *pp;
589   char *ep;
590   unsigned long v;
591
592   r= pa_mwsp(); if (r) return r;
593   mintoken= pa_numberdollar(&min); if (mintoken == tokv_error) return mintoken;
594   r= pa_mwsp(); if (r) return r;
595   maxtoken= pa_numberdollar(&max); if (maxtoken == tokv_error) return maxtoken;
596   r= pa_mnl(); if (r) return r;
597   for (pp= pv; *pp; pp++) {
598     v= strtoul(*pp,&ep,10); if (*ep) continue;
599     if (mintoken != tokv_dollar && v < min) continue;
600     if (maxtoken != tokv_dollar && v > max) continue;
601     *rtrue= 1; return 0;
602   }
603   *rtrue= 0; return 0;
604 }
605
606 int pcf_grep(int ctoken, char *const *pv, int *rtrue) {
607   FILE *file;
608   const char *cp;
609   char *const *pp;
610   char *buf, *p;
611   int r, maxlen, l, c, actrue, posstrue;
612   
613   r= paa_1path(&cp); if (r) return r;
614   file= fopen(cp,"r");
615   if (!file)
616     return parseerrprint("unable to open file `%s' for grep: %s",cp,strerror(errno));
617   maxlen= 0;
618   for (pp= pv; *pp; pp++) { l= strlen(*pp); if (l > maxlen) maxlen= l; }
619   buf= xmalloc(maxlen+2); actrue= 0; c= 0;
620   while (!actrue && c!=EOF) {
621     c= getc(file); if (c==EOF) break;
622     if (ISCHAR(isspace,c)) continue;
623     l= maxlen+1; p= buf;
624     while (l>0 && c!='\n' && c!=EOF) { *p++= c; l--; c= getc(file); } 
625     if (c=='\n' || c==EOF || ISCHAR(isspace,c)) {
626       while (p>buf && ISCHAR(isspace,p[-1])) --p;
627       *p= 0; posstrue= 0;
628       for (pp= pv; !posstrue && *pp; pp++)
629         if (!strcmp(*pp,buf)) posstrue= 1;
630     } else {
631       posstrue= 0;
632     }
633     if (c!='\n' && c!=EOF) {
634       for (;;) {
635         c= getc(file);
636         if (c==EOF || c=='\n') break;
637         if (!ISCHAR(isspace,c)) posstrue= 0;
638       }
639     }
640     if (posstrue) actrue= 1;
641   }
642   if (ferror(file)) {
643     parseerrprint("error while reading `%s' for grep: %s",cp,strerror(errno));
644     fclose(file); free(buf); return tokv_error;
645   }
646   assert(actrue || feof(file));
647   fclose(file); free(buf); *rtrue= actrue;
648   return 0;
649
650
651 static int pa_condition(int *rtrue) {
652   /* Scans up to and including the newline following the condition;
653    * may scan more than one line if the condition is a multi-line
654    * one.  Returns 0 (setting *rtrue, and parsing up to and including
655    * the last newline) or tokv_error.
656    * Expects to scan the whitespace before its condition.
657    */
658   int r, token, andor, ctrue, actrue;
659   char **parmvalues;
660
661   r= pa_mwsp(); if (r) return r;
662   token= yylex();
663   if (token == tokv_error) {
664     return token;
665   } else if (token == tokv_not) {
666     r= pa_condition(&ctrue); if (r) return r;
667     *rtrue= !ctrue; return 0;
668   } else if (token == tokv_openparen) {
669     andor= 0; actrue= -1;
670     for (;;) {
671       cstate->reportlineno= cstate->lineno;
672       r= pa_condition(&ctrue); if (r) return r;
673       switch (andor) {
674       case 0:         assert(actrue==-1); actrue= ctrue;           break;
675       case tokv_and:  assert(actrue>=0); actrue= actrue && ctrue;  break;
676       case tokv_or:   assert(actrue>=0); actrue= actrue || ctrue;  break;
677       default:        abort();
678       }
679       do { token= yylex(); } while (token == tokv_lwsp);
680       if (token == tokv_error) return token;
681       if (token == tokv_closeparen) break;
682       if (andor) {
683         r= unexpected(token,andor,"same conjunction as before"); if (r) return r;
684       } else {
685         if (token != tokv_and && token != tokv_or)
686           return unexpected(token,-1,"first conjunction inside connective");
687         andor= token;
688       }
689     }
690     r= pa_mnl(); if (r) return r;
691     *rtrue= actrue; return 0;
692   } else if (token & tokt_parmcondition) {
693     r= pa_mwsp(); if (r) return r;
694     r= pa_parameter(&parmvalues,0); if (r) return r;
695     r= (lr_parmcond)(token,parmvalues,rtrue); freecharparray(parmvalues);
696     return r;
697   } else {
698     return unexpected(token,-1,"condition");
699   }
700 }
701
702 /*
703  * Directive functions and associated `common code' functions
704  */
705
706 /* Directives specifying the service program (execute-... and reset) */
707
708 static void execreset(void) {
709   execute= 0;
710   execbuiltin= 0;
711   free(execpath); execpath= 0;
712   freecharparray(execargs); execargs= 0;
713 }
714
715 int df_reject(int dtoken) {
716   int r;
717   
718   r= pa_mnl(); if (r) return r;
719   execreset();
720   execute= tokv_word_reject;
721   return 0;
722 }
723
724 int df_executefrompath(int dtoken) {
725   int r;
726   
727   r= pa_mnl(); if (r) return r;
728   execreset();
729   execute= tokv_word_executefrompath;
730   return 0;
731 }
732
733 int df_execute(int dtoken) {
734   const char *rv;
735   char **newargs;
736   int r;
737
738   r= paa_pathargs(&rv,&newargs); if (r) return r;
739   execreset();
740   execute= tokv_word_execute;
741   execargs= newargs;
742   execpath= xstrsave(rv);
743   return 0;
744 }
745
746 int df_executefromdirectory(int dtoken) {
747   const char *p, *q, *rv;
748   struct stat stab;
749   char *fn, **newargs;
750   int l, r;
751
752   r= paa_pathargs(&rv,&newargs); if (r) return r;
753   p= strrchr(service,'/'); if (p) p++; else p= service;
754   if (!*p || !ISCHAR(isalnum,*p)) {
755     parseerrprint("execute-from-directory requires initial char of service "
756                   "portion to be alphanumeric (service portion was `%s')",
757                   p);
758     freecharparray(newargs);
759     return tokv_error;
760   }
761   for (q=p+1; *q; q++) {
762     if (!ISCHAR(isalnum,*q) && *q != '-') {
763       parseerrprint("execute-from-directory requires service portion to "
764                     "contain only alphanumerics and hyphens (was `%s')",
765                     p);
766       freecharparray(newargs);
767       return tokv_error;
768     }
769   }
770   l= strlen(rv)+1+strlen(p)+1;
771   fn= xmalloc(l);
772   snyprintf(fn,l,"%s/%s",rv,p);
773   if (stat(fn,&stab)) {
774     if (errno == ENOENT) { free(fn); freecharparray(newargs); return 0; }
775     parseerrprint("failed to stat `%s' for execute-from-directory: %s",
776                   fn,strerror(errno));
777     free(fn); freecharparray(newargs); return tokv_error;
778   }
779   if (!S_ISREG(stab.st_mode)) {
780     parseerrprint("file `%s' in execute-from-directory is not an ordinary file"
781                   " or link to one (mode=0%lo)",fn,(unsigned long)stab.st_mode);
782     free(fn); freecharparray(newargs); return tokv_error;
783   }
784   execreset();
785   execute= tokv_word_executefromdirectory;
786   execargs= newargs;
787   execpath= fn;
788   return 0;
789 }
790
791 /* Parsing builtin service requests (execute-builtin) */
792
793 static int bispa_none(char ***rnewargs) {
794   return pa_mnl();
795 }
796
797 static int bispa_parameter(char ***rnewargs) {
798   int r, i;
799   char **parmvalues, *name, **newargs;
800   
801   r= pa_mwsp(); if (r) return r;
802   r= pa_parameter(&parmvalues,&name); if (r) return r;
803   for (i=0; parmvalues[i]; i++);
804   newargs= xmalloc(sizeof(char*)*(i+2));
805   newargs[0]= name;
806   memcpy(newargs+1,parmvalues,sizeof(char*)*(i+1));
807   free(parmvalues);
808   r= pa_mnl(); if (r) { free(newargs); return r; }
809   *rnewargs= newargs;
810   return 0;
811 }
812
813 int df_executebuiltin(int dtoken) {
814   int r;
815   builtinserviceexec_fnt *bisexec;
816   char *newpath, **newargs;
817
818   r= pa_mwsp(); if (r) return r;
819   r= yylex(); if (r == tokv_error) return r;
820   if (!(r & tokt_builtinservice)) return unexpected(r,-1,"builtin service name");
821   bisexec= lr_bisexec;
822   newpath= xstrsave(yytext);
823   newargs= 0;
824   r= lr_bispa(&newargs); if (r) { free(newpath); return r; }
825
826   execreset();
827   execute= tokv_word_executebuiltin;
828   execbuiltin= bisexec;
829   execpath= newpath;
830   execargs= newargs;
831   return 0;
832 }
833
834 /* Directives for changing other execution parameters */
835
836 int dfg_setflag(int dtoken) {
837   int r;
838
839   r= pa_mnl(); if (r) return r;
840   *lr_flag= lr_flagval;
841   return 0;
842 }
843
844 int df_reset(int dtoken) {
845   int r;
846
847   r= pa_mnl(); if (r) return r;
848   r= parse_string(RESET_CONFIGURATION,"<builtin reset configuration>",1);
849   return r;
850 }
851
852 int dfg_fdwant(int dtoken) {
853   int fdmin, fdmax, r, needreadwrite, havereadwrite, fd;
854
855   needreadwrite= lr_fdwant_readwrite;
856   r= pa_mwsp(); if (r) return r;
857   r= yylex(); if (r == tokv_error) return r;
858   if (!(r & tokt_fdrange)) return unexpected(r,-1,"file descriptor range");
859   fdmin= lr_min; fdmax= lr_max;
860   if (fdmin<0 || fdmin>MAX_ALLOW_FD ||
861       (fdmax != -1 && fdmax<0) || fdmax>MAX_ALLOW_FD)
862     return parseerrprint("file descriptor in range is negative or far too large");
863   r= yylex(); if (r == tokv_error) return r;
864   if (r == tokv_newline) {
865     if (needreadwrite > 0)
866       return parseerrprint("read or write is required");
867     havereadwrite= 0;
868   } else if (r == tokv_lwsp) {
869     if (needreadwrite < 0)
870       return parseerrprint("read or write not allowed");
871     r= yylex(); if (r == tokv_error) return r;
872     if (!(r & tokt_readwrite))
873       return unexpected(r,-1,"read or write (or perhaps newline)");
874     havereadwrite= r;
875     r= pa_mnl(); if (r) return r;
876   } else {
877     return unexpected(r,-1,"whitespace before read or write or newline");
878   }
879   ensurefdarray(fdmin);
880   if (fdmax == -1) {
881     if (!(dtoken == tokv_word_rejectfd || dtoken == tokv_word_ignorefd))
882       return parseerrprint("unspecified maximum only allowed"
883                            " with reject-fd and ignore-fd");
884     fdmax= fdarrayused-1;
885     restfdwantstate= dtoken;
886     restfdwantrw= havereadwrite;
887   }
888   ensurefdarray(fdmax);
889   for (fd=fdmin; fd<=fdmax; fd++) {
890     fdarray[fd].wantstate= dtoken;
891     fdarray[fd].wantrw= havereadwrite;
892   }
893   return 0;
894 }
895
896 /* Directives for changing error handling */
897
898 int df_errorstostderr(int dtoken) {
899   int r;
900   
901   r= pa_mnl(); if (r) return r;
902   closeerrorfile(); eh.handling= dtoken;
903   return 0;
904 }
905
906 int df_errorstosyslog(int dtoken) {
907   int token, level, facility;
908
909   facility= DEFUSERLOGFACILITY;
910   level= DEFUSERLOGLEVEL;
911   token= yylex();
912   if (token == tokv_lwsp) {
913     token= yylex(); if (token == tokv_error) return token;
914     if (!(token & tokt_logfacility))
915       return unexpected(token,-1,"syslog facility (or end of line)");
916     facility= lr_logfacility;
917     token= yylex();
918   }    
919   if (token == tokv_lwsp) {
920     token= yylex(); if (token == tokv_error) return token;
921     if (!(token & tokt_loglevel))
922       return unexpected(token,-1,"syslog level (or end of line) after facility");
923     level= lr_loglevel;
924     token= yylex();
925   }
926   if (unexpected(token,tokv_newline,"end of line after errors-to-syslog"))
927     return tokv_error;
928   closeerrorfile(); eh.handling= tokv_word_errorstosyslog;
929   eh.logfacility= facility; eh.loglevel= level;
930   return 0;
931 }
932
933 int df_errorstofile(int dtoken) {
934   const char *cp;
935   FILE *file;
936   int r;
937   
938   r= paa_1path(&cp); if (r) return r;
939   file= fopen(cp,"a");
940   if (!file)
941     return parseerrprint("unable to open error log file `%s': %s",cp,strerror(errno));
942   if (setvbuf(file,0,_IOLBF,MAX_ERRMSG_LEN)) {
943     parseerrprint("unable to set line buffering on errors file: %s",strerror(errno));
944     fclose(file); return tokv_error;
945   }
946   closeerrorfile(); eh.handling= tokv_word_errorstofile;
947   eh.file= file; eh.filename= xstrsave(cp);
948   return 0;
949 }
950
951 /* Directives for including other files or configuration data */
952
953 int dfi_includeuserrcfile(int dtoken) {
954   int r;
955
956   r= pa_mnl(); if (r) return r;
957   assert(userrcfile);
958   return parse_file(userrcfile,0);
959 }
960
961 int dfi_includeclientconfig(int dtoken) {
962   int r;
963
964   r= pa_mnl(); if (r) return r;
965   assert(overridedata);
966   return parse_string(overridedata,"<configuration override data>",0);
967 }
968
969 int df_include(int dtoken) {
970   const char *cp;
971   int r, found;
972
973   r= paa_1path(&cp); if (r) return r;
974   r= parse_file(cp,&found); if (r) return r;
975   if (found || dtoken == tokv_word_includeifexist) return 0;
976   return parseerrprint(dtoken == tokv_word_includesysconfig ?
977                        "system configuration file `%s' does not exist" :
978                        "included file `%s' does not exist",
979                        cp);
980 }
981
982 int df_includedirectory(int dtoken) {
983   static char *buildbuf=0;
984   static int buildbuflen=0;
985   
986   int r, cpl, tel, c, found;
987   DIR *d;
988   struct dirent *de;
989   const char *p, *cpget;
990   char *cp;
991   
992   r= paa_1path(&cpget); if (r) return r;
993   d= opendir(cpget);
994   if (!d)
995     return parseerrprint("unable to open directory `%s': %s",cpget,strerror(errno));
996   cp= xstrsave(cpget);
997   cpl= strlen(cp);
998   while ((de= readdir(d))) {
999     tel= strlen(de->d_name);
1000     if (!tel) continue;
1001     p= de->d_name;
1002     if (!*p || !ISCHAR(isalnum,*p)) continue;
1003     while ((c= *++p)) if (!(ISCHAR(isalnum,c) || c=='-')) break;
1004     if (c) continue;
1005     if (makeroom(&buildbuf,&buildbuflen,cpl+1+tel+1)) {
1006       stringoverflow("pathname in directory");
1007       r= tokv_error; goto x_err;
1008     }
1009     snyprintf(buildbuf,buildbuflen,"%s/%s",cp,de->d_name);
1010     r= parse_file(buildbuf,&found); if (r) goto x_err;
1011     if (!found) {
1012       r= parseerrprint("unable to open file `%s' in included directory `%s': %s",
1013                        de->d_name,cp,strerror(errno));
1014       goto x_err;
1015     }
1016   }
1017   if (closedir(d)) {
1018     parseerrprint("error closing directory `%s': %s",cp,strerror(errno));
1019     free(cp);
1020     return tokv_error;
1021   }
1022   free(cp);
1023   return 0;
1024
1025 x_err:
1026   closedir(d);
1027   free(cp);
1028   return r;
1029 }
1030
1031 int df_includelookup(int dtoken) {
1032   static char *buildbuf=0;
1033   int buildbuflen=0;
1034   
1035   char **parmvalues, **pp, *p, *q, *cp;
1036   const char *cpget;
1037   struct stat stab;
1038   int r, done, thisdone, cpl, c;
1039
1040   r= pa_mwsp(); if (r) return r;
1041   r= pa_parameter(&parmvalues,0); if (r) return r;
1042   r= paa_1path(&cpget); if (r) { freecharparray(parmvalues); return r; }
1043   if (stat(cpget,&stab)) {
1044     parseerrprint("unable to access directory `%s': %s",cpget,strerror(errno));
1045     freecharparray(parmvalues); return tokv_error;
1046   }
1047   if (!S_ISDIR(stab.st_mode)) {
1048     parseerrprint("object `%s' is not a directory or link to one",cpget);
1049     freecharparray(parmvalues); return tokv_error;
1050   }
1051   done= 0;
1052   cp= xstrsave(cpget);
1053   cpl= strlen(cp);
1054   if (!parmvalues[0]) {
1055     if (makeroom(&buildbuf,&buildbuflen,cpl+1+sizeof(NONEINCLUDELOOKUP))) {
1056       stringoverflow("pathname in directory for lookup of undefined parameter");
1057       r= tokv_error; goto x_err;
1058     }
1059     snyprintf(buildbuf,buildbuflen,"%s/" NONEINCLUDELOOKUP,cp);
1060     r= parse_file(buildbuf,&thisdone); if (r) goto x_err;
1061     if (thisdone) done= 1;
1062   } else {
1063     for (pp=parmvalues;
1064          *pp && (!done || dtoken == tokv_word_includelookupall);
1065          pp++) {
1066       if (makeroom(&buildbuf,&buildbuflen,
1067                    cpl+1+strlen(*pp)*2+3+sizeof(EMPTYINCLUDELOOKUP)+1)) {
1068         stringoverflow("pathname in directory for lookup");
1069         r= tokv_error; goto x_err;
1070       }
1071       strcpy(buildbuf,cp);
1072       p= *pp; q= buildbuf+cpl;
1073       *q++= '/';
1074       if (!*p) {
1075         strcpy(q,EMPTYINCLUDELOOKUP);
1076       } else {
1077         if (*p=='.') *q++= ':';
1078         while ((c= *p++)) {
1079           if (c=='/') {
1080             *q++= ':';
1081             c= '-';
1082           } else if (!((c >= '0' && c <= '9') ||
1083                        (c >= 'a' && c <= 'z') ||
1084                        c == '-' || c == '_')) {
1085             *q++= ':';
1086           }
1087           *q++= c;
1088         }
1089         *q++= 0;
1090       }
1091       r= parse_file(buildbuf,&thisdone);
1092       if (r) goto x_err;
1093       if (thisdone) done= 1;
1094     }
1095   }
1096   if (!done) {
1097     if (makeroom(&buildbuf,&buildbuflen,
1098                  cpl+1+sizeof(DEFAULTINCLUDELOOKUP))) {
1099       stringoverflow("pathname in directory for lookup of default");
1100       r= tokv_error; goto x_err;
1101     }
1102     snyprintf(buildbuf,buildbuflen,"%s/" DEFAULTINCLUDELOOKUP,cp);
1103     r= parse_file(buildbuf,0); if (r) goto x_err;
1104   }
1105   r= 0;
1106   
1107 x_err:
1108   freecharparray(parmvalues);
1109   free(cp);
1110   return r;
1111 }
1112
1113 /* Control constructs */
1114
1115 int df_catchquit(int dtoken) {
1116   int r;
1117
1118   r= pa_mnl(); if (r) return r;
1119   r= parser(tokv_word_catchquit);
1120   if (r == tokv_quit || r == tokv_error) {
1121     if (r == tokv_error) {
1122       r= parse_string(RESET_CONFIGURATION,
1123                       "<builtin reset configuration (caught error)>",1);
1124       assert(!r);
1125     }
1126     r= skip(tokv_word_catchquit);
1127   }
1128   if (r & tokt_controlend) {
1129     assert(r == tokv_word_hctac);
1130     r= pa_mnl();
1131   }
1132   return r;
1133 }
1134
1135 int df_if(int dtoken) {
1136   int r, true, done;
1137   
1138   done= 0;
1139   do {
1140     r= pa_condition(&true); if (r) return r;
1141     if (!done && true) { r= parser(tokv_word_if); done= 1; }
1142     else { r= skip(tokv_word_if); }
1143     if (!(r & tokt_controlend)) return r;
1144   } while (r == tokv_word_elif);
1145   if (r == tokv_word_else) {
1146     r= pa_mnl(); if (r) return r;
1147     cstate->reportlineno= cstate->lineno;
1148     if (done) r= skip(tokv_word_if);
1149     else r= parser(tokv_word_if);
1150     if (!(r & tokt_controlend)) return r;
1151   }
1152   if (unexpected(r,tokv_word_fi,"`fi' to end `if'")) return tokv_error;
1153   return pa_mnl();
1154 }
1155
1156 int df_errorspush(int dt) {
1157   struct error_handling save;
1158   int r;
1159
1160   r= pa_mnl(); if (r) return r;
1161
1162   save= eh;
1163   eh.filekeep= 1;
1164
1165   r= parser(tokv_word_errorspush);
1166
1167   closeerrorfile();
1168   eh= save;
1169
1170   if (r & tokt_controlend) {
1171     assert(r == tokv_word_srorre);
1172     r= pa_mnl();
1173   }
1174   return r;
1175 }
1176
1177 /* Miscelleanous directives */
1178
1179 int df_cd(int dtoken) {
1180   const char *cp;
1181   int r;
1182
1183   r= paa_1path(&cp); if (r) return r;
1184   if (!chdir(cp)) return 0;
1185   return parseerrprint("unable to change directory to `%s': %s",cp,strerror(errno));
1186 }
1187
1188 int df_userrcfile(int dtoken) {
1189   const char *cp;
1190   int r;
1191
1192   r= paa_1path(&cp); if (r) return r;
1193   free(userrcfile); userrcfile= xstrsave(cp);
1194   return 0;
1195 }
1196
1197 int df_message(int dtoken) {
1198   const char *mp;
1199   int r;
1200
1201   r= paa_message(&mp); if (r) return r;
1202   parseerrprint("`message' directive: %s",mp);
1203   return 0;
1204 }
1205
1206 int df_error(int dtoken) {
1207   const char *mp;
1208   int r;
1209
1210   r= paa_message(&mp); if (r) return r;
1211   return parseerrprint("`error' directive: %s",mp);
1212 }
1213
1214 int df_eof(int dtoken) {
1215   int r;
1216
1217   r= pa_mnl(); if (r) return r;
1218   return tokv_eof;
1219 }
1220
1221 int df_quit(int dtoken) {
1222   int r;
1223
1224   r= pa_mnl(); if (r) return r;
1225   return tokv_quit;
1226 }
1227
1228 /*
1229  * Main parser routines
1230  */
1231       
1232 static void parser_push(struct parser_state *usestate,
1233                         const char *newfile,
1234                         const struct stat *newfilestab,
1235                         YY_BUFFER_STATE ybuf,
1236                         int isinternal) {
1237   usestate->lineno= 1;
1238   usestate->reportlineno= 1;
1239   usestate->filename= newfile;
1240   usestate->filestab= *newfilestab;
1241   usestate->notedreferer= 0;
1242   usestate->isinternal= isinternal;
1243   usestate->ybuf= ybuf;
1244   usestate->upstate= cstate;
1245
1246   cstate= usestate;
1247   yy_switch_to_buffer(ybuf);
1248 }
1249
1250 static void parser_pop(void) {
1251   struct parser_state *oldstate;
1252
1253   oldstate= cstate;
1254   cstate= cstate->upstate;
1255   if (cstate) yy_switch_to_buffer(cstate->ybuf);
1256   yy_delete_buffer(oldstate->ybuf);
1257 }
1258
1259 int parse_string(const char *string, const char *descrip, int isinternal) {
1260   /* Returns the same things as parser, except that tokv_eof is turned
1261    * into 0.  *string must be statically allocated or copied, so that
1262    * it is not overwritten while the parsing takes place (unlike with
1263    * parse_file).
1264    */
1265   static const struct stat blankstab;
1266   
1267   struct parser_state usestate;
1268   YY_BUFFER_STATE ybuf;
1269   int r;
1270
1271   ybuf= yy_scan_string(string);
1272   if (!ybuf) syscallerror("unable to create flex buffer for internal string");
1273   parser_push(&usestate,descrip,&blankstab,ybuf,isinternal);
1274   
1275   r= parser(0);
1276
1277   parser_pop();
1278   if (r == tokv_eof) r= 0;
1279   return r;
1280 }
1281
1282 static int parse_file(const char *string, int *didexist) {
1283   /* Returns the same things as parser, except that tokv_eof is turned
1284    * into 0.  If *didexist is 0 then errno will have been set.
1285    * *string will be copied by parse_file so it may be be overwritten
1286    * during the parsing (so, for example, yytext need not be copied).
1287    */
1288   static int fileparselevel= 0;
1289   
1290   struct parser_state usestate, *checkrecurse;
1291   YY_BUFFER_STATE ybuf;
1292   int r;
1293   FILE *file;
1294   char *filename;
1295   struct stat newstab;
1296
1297   if (fileparselevel >= MAX_INCLUDE_NEST)
1298     return parseerrprint("too many nested levels of included files");
1299   file= fopen(string,"r");
1300   if (!file) {
1301     if (errno == ENOENT) {
1302       if (didexist) *didexist= 0;
1303       return 0;
1304     }
1305     return parseerrprint("unable to open config file `%s': %s",string,strerror(errno));
1306   }
1307   r= fstat(fileno(file),&newstab); if (r) syscallerror("unable to fstat new file");
1308   for (checkrecurse= cstate; checkrecurse; checkrecurse= checkrecurse->upstate) {
1309     if (!checkrecurse->filestab.st_mode) continue;
1310     if (newstab.st_dev==checkrecurse->filestab.st_dev &&
1311         newstab.st_ino==checkrecurse->filestab.st_ino) {
1312       fclose(file);
1313       return parseerrprint("recursion detected - config file `%s' calls itself",string);
1314     }
1315   }
1316   
1317   if (didexist) *didexist= 1;
1318
1319   ybuf= yy_create_buffer(file,YY_BUF_SIZE);
1320   if (!ybuf) syscallerror("unable to create flex buffer for file");
1321   filename= xstrsave(string);
1322   parser_push(&usestate,filename,&newstab,ybuf,0);
1323   fileparselevel++;
1324   
1325   r= parser(0);
1326   if (ferror(file))
1327     r= parseerrprint("error reading configuration file `%s'",string);
1328
1329   fileparselevel--;
1330   parser_pop();
1331   free(filename);
1332   fclose(file);
1333   if (r == tokv_eof) r= 0;
1334   return r;
1335 }
1336
1337 static int parser(int allowce) {
1338   /* Returns:
1339    *  an exception (error, eof or quit)
1340    *   then rest of `file' is uninteresting
1341    * or
1342    *  token if allowce was !0 and equal to token's controlend
1343    *   then rest of `file' (including rest of line with the
1344    *   controlend - even the whitespace) not scanned yet
1345    */
1346   int token, r;
1347
1348   for (;;) { /* loop over lines */
1349     cstate->reportlineno= cstate->lineno;
1350     do { token= yylex(); } while (token == tokv_lwsp);
1351     if (token & tokt_exception) {
1352       return token;
1353     } else if (token & tokt_controlend) {
1354       if (lr_controlend == allowce) return token;
1355       else return unexpected(token,-1,"directive (not this kind of"
1356                              " control structure end)");
1357     } else if (token & tokt_directive) {
1358       if ((token & tokt_internal) && !cstate->isinternal)
1359         return unexpected(token,-1,"published directive, not internal-use-only one");
1360       r= (lr_dir)(token); if (r) { assert(r & tokt_exception); return r; }
1361     } else if (token == tokv_newline) {
1362       /* ignore blank lines (and comment-only lines) */
1363     } else {
1364       return unexpected(token,-1,"directive");
1365     }
1366   }
1367 }