Blob


1 %{
3 /*
4 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <ctype.h>
20 #include <errno.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
26 #include "gmid.h"
28 FILE *yyfp;
30 typedef struct {
31 union {
32 char *str;
33 int num;
34 } v;
35 int lineno;
36 int colno;
37 } yystype;
38 #define YYSTYPE yystype
40 /*
41 * #define YYDEBUG 1
42 * int yydebug = 1;
43 */
45 /*
46 * The idea behind this implementation of macros is from rad/parse.y
47 */
48 TAILQ_HEAD(symhead, sym) symhead = TAILQ_HEAD_INITIALIZER(symhead);
49 struct sym {
50 TAILQ_ENTRY(sym) entry;
51 int used;
52 int persist;
53 char *name;
54 char *val;
55 };
57 struct vhost *host;
58 struct location *loc;
60 static int goterror;
62 static struct vhost *new_vhost(void);
63 static struct location *new_location(void);
65 void yyerror(const char*, ...);
66 int kw_cmp(const void *, const void *);
67 static int yylex(void);
68 int parse_portno(const char*);
69 void parse_conf(const char*);
70 char *ensure_absolute_path(char*);
71 int check_block_code(int);
72 char *check_block_fmt(char*);
73 int check_strip_no(int);
74 int check_prefork_num(int);
75 void advance_loc(void);
76 void only_once(const void*, const char*);
77 void only_oncei(int, const char*);
78 int fastcgi_conf(char *, char *, char *);
79 void add_param(char *, char *, int);
80 int symset(const char *, const char *, int);
81 char *symget(const char *);
83 %}
85 /* for bison: */
86 /* %define parse.error verbose */
88 %token TIPV6 TPORT TPROTOCOLS TMIME TDEFAULT TTYPE TCHROOT TUSER TSERVER
89 %token TPREFORK TLOCATION TCERT TKEY TROOT TCGI TENV TLANG TLOG TINDEX TAUTO
90 %token TSTRIP TBLOCK TRETURN TENTRYPOINT TREQUIRE TCLIENT TCA TALIAS TTCP
91 %token TFASTCGI TSPAWN TPARAM TMAP TTOEXT
93 %token TERR
95 %token <v.str> TSTRING
96 %token <v.num> TNUM
97 %token <v.num> TBOOL
99 %type <v.str> string
101 %%
103 conf : /* empty */
104 | conf var
105 | conf option
106 | conf vhost
109 string : string TSTRING {
110 if (asprintf(&$$, "%s%s", $1, $2) == -1) {
111 free($1);
112 free($2);
113 yyerror("string: asprintf: %s", strerror(errno));
114 YYERROR;
116 free($1);
117 free($2);
119 | TSTRING
122 var : TSTRING '=' string {
123 char *s = $1;
124 while (*s++) {
125 if (isspace(*s)) {
126 yyerror("macro name cannot contain "
127 "whitespaces");
128 free($1);
129 free($3);
130 YYERROR;
133 symset($1, $3, 0);
134 free($1);
135 free($3);
139 option : TCHROOT string { conf.chroot = $2; }
140 | TIPV6 TBOOL { conf.ipv6 = $2; }
141 | TMIME TSTRING string {
142 fprintf(stderr, "%s:%d: `mime MIME EXT' is deprecated and "
143 "will be removed in a future version, "
144 "please use the new syntax: `map MIME to-ext EXT'",
145 config_path, yylval.lineno+1);
146 add_mime(&conf.mime, $2, $3);
148 | TMAP string TTOEXT string { add_mime(&conf.mime, $2, $4); }
149 | TPORT TNUM { conf.port = $2; }
150 | TPREFORK TNUM { conf.prefork = check_prefork_num($2); }
151 | TPROTOCOLS string {
152 if (tls_config_parse_protocols(&conf.protos, $2) == -1)
153 yyerror("invalid protocols string \"%s\"", $2);
155 | TUSER string { conf.user = $2; }
158 vhost : TSERVER string {
159 host = new_vhost();
160 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
162 loc = new_location();
163 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
165 loc->match = xstrdup("*");
166 host->domain = $2;
168 if (strstr($2, "xn--") != NULL) {
169 warnx("%s:%d:%d \"%s\" looks like punycode: "
170 "you should use the decoded hostname.",
171 config_path, yylval.lineno+1, yylval.colno,
172 $2);
174 } '{' servopts locations '}' {
176 if (host->cert == NULL || host->key == NULL)
177 yyerror("invalid vhost definition: %s", $2);
179 | error '}' { yyerror("error in server directive"); }
182 servopts : /* empty */
183 | servopts servopt
186 servopt : TALIAS string {
187 struct alist *a;
189 a = xcalloc(1, sizeof(*a));
190 a->alias = $2;
191 if (TAILQ_EMPTY(&host->aliases))
192 TAILQ_INSERT_HEAD(&host->aliases, a, aliases);
193 else
194 TAILQ_INSERT_TAIL(&host->aliases, a, aliases);
196 | TCERT string {
197 only_once(host->cert, "cert");
198 host->cert = ensure_absolute_path($2);
200 | TCGI string {
201 only_once(host->cgi, "cgi");
202 /* drop the starting '/', if any */
203 if (*$2 == '/')
204 memmove($2, $2+1, strlen($2));
205 host->cgi = $2;
207 | TENTRYPOINT string {
208 only_once(host->entrypoint, "entrypoint");
209 while (*$2 == '/')
210 memmove($2, $2+1, strlen($2));
211 host->entrypoint = $2;
213 | TENV string '=' string {
214 add_param($2, $4, 1);
216 | TKEY string {
217 only_once(host->key, "key");
218 host->key = ensure_absolute_path($2);
220 | TPARAM string '=' string {
221 add_param($2, $4, 0);
223 | locopt
226 locations : /* empty */
227 | locations location
230 location : TLOCATION { advance_loc(); } string '{' locopts '}' {
231 /* drop the starting '/' if any */
232 if (*$3 == '/')
233 memmove($3, $3+1, strlen($3));
234 loc->match = $3;
236 | error '}'
239 locopts : /* empty */
240 | locopts locopt
243 locopt : TAUTO TINDEX TBOOL { loc->auto_index = $3 ? 1 : -1; }
244 | TBLOCK TRETURN TNUM string {
245 only_once(loc->block_fmt, "block");
246 loc->block_fmt = check_block_fmt($4);
247 loc->block_code = check_block_code($3);
249 | TBLOCK TRETURN TNUM {
250 only_once(loc->block_fmt, "block");
251 loc->block_fmt = xstrdup("temporary failure");
252 loc->block_code = check_block_code($3);
253 if ($3 >= 30 && $3 < 40)
254 yyerror("missing `meta' for block return %d", $3);
256 | TBLOCK {
257 only_once(loc->block_fmt, "block");
258 loc->block_fmt = xstrdup("temporary failure");
259 loc->block_code = 40;
261 | TDEFAULT TTYPE string {
262 only_once(loc->default_mime, "default type");
263 loc->default_mime = $3;
265 | TFASTCGI fastcgi
266 | TINDEX string {
267 only_once(loc->index, "index");
268 loc->index = $2;
270 | TLANG string {
271 only_once(loc->lang, "lang");
272 loc->lang = $2;
274 | TLOG TBOOL { loc->disable_log = !$2; }
275 | TREQUIRE TCLIENT TCA string {
276 only_once(loc->reqca, "require client ca");
277 ensure_absolute_path($4);
278 if ((loc->reqca = load_ca($4)) == NULL)
279 yyerror("couldn't load ca cert: %s", $4);
280 free($4);
282 | TROOT string {
283 only_once(loc->dir, "root");
284 loc->dir = ensure_absolute_path($2);
286 | TSTRIP TNUM { loc->strip = check_strip_no($2); }
289 fastcgi : TSPAWN string {
290 only_oncei(loc->fcgi, "fastcgi");
291 loc->fcgi = fastcgi_conf(NULL, NULL, $2);
293 | string {
294 only_oncei(loc->fcgi, "fastcgi");
295 loc->fcgi = fastcgi_conf($1, NULL, NULL);
297 | TTCP string TPORT TNUM {
298 char *c;
299 if (asprintf(&c, "%d", $4) == -1)
300 err(1, "asprintf");
301 only_oncei(loc->fcgi, "fastcgi");
302 loc->fcgi = fastcgi_conf($2, c, NULL);
304 | TTCP string {
305 only_oncei(loc->fcgi, "fastcgi");
306 loc->fcgi = fastcgi_conf($2, xstrdup("9000"), NULL);
308 | TTCP string TPORT string {
309 only_oncei(loc->fcgi, "fastcgi");
310 loc->fcgi = fastcgi_conf($2, $4, NULL);
314 %%
316 static struct vhost *
317 new_vhost(void)
319 return xcalloc(1, sizeof(struct vhost));
322 static struct location *
323 new_location(void)
325 struct location *l;
327 l = xcalloc(1, sizeof(*l));
328 l->dirfd = -1;
329 l->fcgi = -1;
330 return l;
333 void
334 yyerror(const char *msg, ...)
336 va_list ap;
338 goterror = 1;
340 va_start(ap, msg);
341 fprintf(stderr, "%s:%d: ", config_path, yylval.lineno);
342 vfprintf(stderr, msg, ap);
343 fprintf(stderr, "\n");
344 va_end(ap);
347 static struct keyword {
348 const char *word;
349 int token;
350 } keywords[] = {
351 /* these MUST be sorted */
352 {"alias", TALIAS},
353 {"auto", TAUTO},
354 {"block", TBLOCK},
355 {"ca", TCA},
356 {"cert", TCERT},
357 {"cgi", TCGI},
358 {"chroot", TCHROOT},
359 {"client", TCLIENT},
360 {"default", TDEFAULT},
361 {"entrypoint", TENTRYPOINT},
362 {"env", TENV},
363 {"fastcgi", TFASTCGI},
364 {"index", TINDEX},
365 {"ipv6", TIPV6},
366 {"key", TKEY},
367 {"lang", TLANG},
368 {"location", TLOCATION},
369 {"log", TLOG},
370 {"map", TMAP},
371 {"mime", TMIME},
372 {"param", TPARAM},
373 {"port", TPORT},
374 {"prefork", TPREFORK},
375 {"protocols", TPROTOCOLS},
376 {"require", TREQUIRE},
377 {"return", TRETURN},
378 {"root", TROOT},
379 {"server", TSERVER},
380 {"spawn", TSPAWN},
381 {"strip", TSTRIP},
382 {"tcp", TTCP},
383 {"to-ext", TTOEXT},
384 {"type", TTYPE},
385 {"user", TUSER},
386 };
388 int
389 kw_cmp(const void *k, const void *e)
391 return strcmp(k, ((struct keyword *)e)->word);
394 /*
395 * Taken an adapted from doas' parse.y
396 */
397 static int
398 yylex(void)
400 struct keyword *kw;
401 char buf[8096], *ebuf, *p, *str, *v, *val;
402 int c, quotes = 0, escape = 0, qpos = -1, nonkw = 0;
403 size_t len;
405 p = buf;
406 ebuf = buf + sizeof(buf);
408 repeat:
409 /* skip whitespace first */
410 for (c = getc(yyfp); isspace(c); c = getc(yyfp)) {
411 yylval.colno++;
412 if (c == '\n') {
413 yylval.lineno++;
414 yylval.colno = 0;
418 /* check for special one-character constructions */
419 switch (c) {
420 case '{':
421 case '}':
422 return c;
423 case '#':
424 /* skip comments; NUL is allowed; no continuation */
425 while ((c = getc(yyfp)) != '\n')
426 if (c == EOF)
427 goto eof;
428 yylval.colno = 0;
429 yylval.lineno++;
430 goto repeat;
431 case '=':
432 return c;
433 case EOF:
434 goto eof;
437 /* parsing next word */
438 for (;; c = getc(yyfp), yylval.colno++) {
439 switch (c) {
440 case '\0':
441 yyerror("unallowed character NULL in column %d",
442 yylval.colno+1);
443 escape = 0;
444 continue;
445 case '\\':
446 escape = !escape;
447 if (escape)
448 continue;
449 break;
451 /* expand macros in-place */
452 case '$':
453 if (!escape && !quotes) {
454 v = p;
455 while (1) {
456 if ((c = getc(yyfp)) == EOF) {
457 yyerror("EOF during macro expansion");
458 return 0;
460 if (p + 1 >= ebuf - 1) {
461 yyerror("string too long");
462 return 0;
464 if (isalnum(c) || c == '_') {
465 *p++ = c;
466 continue;
468 *p = 0;
469 break;
471 p = v;
472 if ((val = symget(p)) == NULL) {
473 yyerror("macro '%s' not defined", v);
474 return TERR;
476 len = strlen(val);
477 if (p + len >= ebuf - 1) {
478 yyerror("after macro-expansion, "
479 "string too long");
480 return TERR;
482 *p = '\0';
483 strlcat(p, val, ebuf - p);
484 p += len;
485 nonkw = 1;
486 goto eow;
488 break;
489 case '\n':
490 if (quotes)
491 yyerror("unterminated quotes in column %d",
492 yylval.colno+1);
493 if (escape) {
494 nonkw = 1;
495 escape = 0;
496 yylval.colno = 0;
497 yylval.lineno++;
499 goto eow;
500 case EOF:
501 if (escape)
502 yyerror("unterminated escape in column %d",
503 yylval.colno);
504 if (quotes)
505 yyerror("unterminated quotes in column %d",
506 qpos+1);
507 goto eow;
508 case '{':
509 case '}':
510 case '#':
511 case ' ':
512 case '\t':
513 if (!escape && !quotes)
514 goto eow;
515 break;
516 case '"':
517 if (!escape) {
518 quotes = !quotes;
519 if (quotes) {
520 nonkw = 1;
521 qpos = yylval.colno;
523 continue;
526 *p++ = c;
527 if (p == ebuf) {
528 yyerror("line too long");
529 p = buf;
531 escape = 0;
534 eow:
535 *p = 0;
536 if (c != EOF)
537 ungetc(c, yyfp);
538 if (p == buf) {
539 /*
540 * There could be a number of reason for empty buffer,
541 * and we handle all of them here, to avoid cluttering
542 * the main loop.
543 */
544 if (c == EOF)
545 goto eof;
546 else if (qpos == -1) /* accept, e.g., empty args: cmd foo args "" */
547 goto repeat;
549 if (!nonkw) {
550 kw = bsearch(buf, keywords, sizeof(keywords)/sizeof(keywords[0]),
551 sizeof(keywords[0]), kw_cmp);
552 if (kw != NULL)
553 return kw->token;
555 c = *buf;
556 if (!nonkw && (c == '-' || isdigit(c))) {
557 yylval.v.num = parse_portno(buf);
558 return TNUM;
560 if (!nonkw && !strcmp(buf, "on")) {
561 yylval.v.num = 1;
562 return TBOOL;
564 if (!nonkw && !strcmp(buf, "off")) {
565 yylval.v.num = 0;
566 return TBOOL;
568 if ((str = strdup(buf)) == NULL)
569 err(1, "%s", __func__);
570 yylval.v.str = str;
571 return TSTRING;
573 eof:
574 if (ferror(yyfp))
575 yyerror("input error reading config");
576 return 0;
579 int
580 parse_portno(const char *p)
582 const char *errstr;
583 int n;
585 n = strtonum(p, 0, UINT16_MAX, &errstr);
586 if (errstr != NULL)
587 yyerror("port number is %s: %s", errstr, p);
588 return n;
591 void
592 parse_conf(const char *path)
594 struct sym *sym, *next;
596 config_path = path;
597 if ((yyfp = fopen(path, "r")) == NULL)
598 err(1, "cannot open config: %s", path);
599 yyparse();
600 fclose(yyfp);
602 if (goterror)
603 exit(1);
605 if (TAILQ_FIRST(&hosts)->domain == NULL)
606 errx(1, "no vhost defined in %s", path);
608 /* free unused macros */
609 TAILQ_FOREACH_SAFE(sym, &symhead, entry, next) {
610 /* TODO: warn if !sym->used */
611 if (!sym->persist) {
612 free(sym->name);
613 free(sym->val);
614 TAILQ_REMOVE(&symhead, sym, entry);
615 free(sym);
620 char *
621 ensure_absolute_path(char *path)
623 if (path == NULL || *path != '/')
624 yyerror("not an absolute path: %s", path);
625 return path;
628 int
629 check_block_code(int n)
631 if (n < 10 || n >= 70 || (n >= 20 && n <= 29))
632 yyerror("invalid block code %d", n);
633 return n;
636 char *
637 check_block_fmt(char *fmt)
639 char *s;
641 for (s = fmt; *s; ++s) {
642 if (*s != '%')
643 continue;
644 switch (*++s) {
645 case '%':
646 case 'p':
647 case 'q':
648 case 'P':
649 case 'N':
650 break;
651 default:
652 yyerror("invalid format specifier %%%c", *s);
656 return fmt;
659 int
660 check_strip_no(int n)
662 if (n <= 0)
663 yyerror("invalid strip number %d", n);
664 return n;
667 int
668 check_prefork_num(int n)
670 if (n <= 0 || n >= PROC_MAX)
671 yyerror("invalid prefork number %d", n);
672 return n;
675 void
676 advance_loc(void)
678 loc = new_location();
679 TAILQ_INSERT_TAIL(&host->locations, loc, locations);
682 void
683 only_once(const void *ptr, const char *name)
685 if (ptr != NULL)
686 yyerror("`%s' specified more than once", name);
689 void
690 only_oncei(int i, const char *name)
692 if (i != -1)
693 yyerror("`%s' specified more than once", name);
696 int
697 fastcgi_conf(char *path, char *port, char *prog)
699 struct fcgi *f;
700 int i;
702 for (i = 0; i < FCGI_MAX; ++i) {
703 f = &fcgi[i];
705 if (f->path == NULL) {
706 f->id = i;
707 f->path = path;
708 f->port = port;
709 f->prog = prog;
710 return i;
713 /* XXX: what to do with prog? */
714 if (!strcmp(f->path, path) &&
715 ((port == NULL && f->port == NULL) ||
716 !strcmp(f->port, port))) {
717 free(path);
718 free(port);
719 return i;
723 yyerror("too much `fastcgi' rules defined.");
724 return -1;
727 void
728 add_param(char *name, char *val, int env)
730 struct envlist *e;
731 struct envhead *h;
733 if (env)
734 h = &host->env;
735 else
736 h = &host->params;
738 e = xcalloc(1, sizeof(*e));
739 e->name = name;
740 e->value = val;
741 if (TAILQ_EMPTY(h))
742 TAILQ_INSERT_HEAD(h, e, envs);
743 else
744 TAILQ_INSERT_TAIL(h, e, envs);
747 int
748 symset(const char *name, const char *val, int persist)
750 struct sym *sym;
752 TAILQ_FOREACH(sym, &symhead, entry) {
753 if (!strcmp(name, sym->name))
754 break;
757 if (sym != NULL) {
758 if (sym->persist)
759 return 0;
760 else {
761 free(sym->name);
762 free(sym->val);
763 TAILQ_REMOVE(&symhead, sym, entry);
764 free(sym);
768 sym = xcalloc(1, sizeof(*sym));
769 sym->name = xstrdup(name);
770 sym->val = xstrdup(val);
771 sym->used = 0;
772 sym->persist = persist;
774 TAILQ_INSERT_TAIL(&symhead, sym, entry);
775 return 0;
778 int
779 cmdline_symset(char *s)
781 char *sym, *val;
782 int ret;
784 if ((val = strrchr(s, '=')) == NULL)
785 return -1;
786 sym = xcalloc(1, val - s + 1);
787 memcpy(sym, s, val - s);
788 ret = symset(sym, val + 1, 1);
789 free(sym);
790 return ret;
793 char *
794 symget(const char *name)
796 struct sym *sym;
798 TAILQ_FOREACH(sym, &symhead, entry) {
799 if (!strcmp(name, sym->name)) {
800 sym->used = 1;
801 return sym->val;
805 return NULL;