Blob


1 %{
3 /*
4 * Copyright (c) 2021, 2022, 2023 Omar Polo <op@omarpolo.com>
5 * Copyright (c) 2018 Florian Obser <florian@openbsd.org>
6 * Copyright (c) 2004, 2005 Esben Norby <norby@openbsd.org>
7 * Copyright (c) 2004 Ryan McBride <mcbride@openbsd.org>
8 * Copyright (c) 2002, 2003, 2004 Henning Brauer <henning@openbsd.org>
9 * Copyright (c) 2001 Markus Friedl. All rights reserved.
10 * Copyright (c) 2001 Daniel Hartmeier. All rights reserved.
11 * Copyright (c) 2001 Theo de Raadt. All rights reserved.
12 *
13 * Permission to use, copy, modify, and distribute this software for any
14 * purpose with or without fee is hereby granted, provided that the above
15 * copyright notice and this permission notice appear in all copies.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
18 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
20 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
21 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
22 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
23 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 */
26 #include "gmid.h"
28 #include <ctype.h>
29 #include <errno.h>
30 #include <netdb.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <syslog.h>
37 #include "log.h"
39 struct conf *conf;
41 static const char *default_host = "*";
42 static uint16_t default_port = 1965;
44 TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files);
45 static struct file {
46 TAILQ_ENTRY(file) entry;
47 FILE *stream;
48 char *name;
49 size_t ungetpos;
50 size_t ungetsize;
51 u_char *ungetbuf;
52 int eof_reached;
53 int lineno;
54 int errors;
55 } *file, *topfile;
57 struct file *pushfile(const char *, int);
58 int popfile(void);
59 int yyparse(void);
60 int yylex(void);
61 void yyerror(const char *, ...)
62 __attribute__((__format__ (printf, 1, 2)))
63 __attribute__((__nonnull__ (1)));
64 void yywarn(const char *, ...)
65 __attribute__((__format__ (printf, 1, 2)))
66 __attribute__((__nonnull__ (1)));
67 int kw_cmp(const void *, const void *);
68 int lookup(char *);
69 int igetc(void);
70 int lgetc(int);
71 void lungetc(int);
72 int findeol(void);
74 /*
75 * #define YYDEBUG 1
76 * int yydebug = 1;
77 */
79 TAILQ_HEAD(symhead, sym) symhead = TAILQ_HEAD_INITIALIZER(symhead);
80 struct sym {
81 TAILQ_ENTRY(sym) entry;
82 int used;
83 int persist;
84 char *name;
85 char *val;
86 };
88 int symset(const char *, const char *, int);
89 char *symget(const char *);
91 char *ensure_absolute_path(char*);
92 int check_block_code(int);
93 char *check_block_fmt(char*);
94 int check_strip_no(int);
95 int check_port_num(int);
96 int check_prefork_num(int);
97 void advance_loc(void);
98 void advance_proxy(void);
99 void parsehp(char *, char **, const char **, const char *);
100 int fastcgi_conf(const char *, const char *);
101 void add_param(char *, char *);
102 int getservice(const char *);
103 void listen_on(const char *, const char *);
105 static struct vhost *host;
106 static struct location *loc;
107 static struct proxy *proxy;
108 static char *current_media;
109 static int errors;
111 typedef struct {
112 union {
113 char *string;
114 int number;
115 } v;
116 int lineno;
117 } YYSTYPE;
119 #define YYSTYPE YYSTYPE
121 %}
123 /* for bison: */
124 /* %define parse.error verbose */
126 %token ACCESS ALIAS AUTO
127 %token BLOCK
128 %token CA CERT CHROOT CLIENT COMBINED COMMON CONDENSED
129 %token DEFAULT
130 %token FACILITY FASTCGI FOR_HOST
131 %token INCLUDE INDEX IPV6
132 %token KEY
133 %token LANG LEGACY LISTEN LOCATION LOG
134 %token OCSP OFF ON
135 %token PARAM PORT PREFORK PROTO PROTOCOLS PROXY
136 %token RELAY_TO REQUIRE RETURN ROOT
137 %token SERVER SNI SOCKET STRIP STYLE SYSLOG
138 %token TCP TOEXT TYPE TYPES
139 %token USE_TLS USER
140 %token VERIFYNAME
142 %token ERROR
144 %token <v.string> STRING
145 %token <v.number> NUM
147 %type <v.number> bool proxy_port
148 %type <v.string> string numberstring listen_addr
150 %%
152 conf : /* empty */
153 | conf include '\n'
154 | conf '\n'
155 | conf varset '\n'
156 | conf option '\n'
157 | conf vhost '\n'
158 | conf types '\n'
159 | conf error '\n' { file->errors++; }
162 include : INCLUDE STRING {
163 struct file *nfile;
165 if ((nfile = pushfile($2, 0)) == NULL) {
166 yyerror("failed to include file %s", $2);
167 free($2);
168 YYERROR;
170 free($2);
172 file = nfile;
173 lungetc('\n');
177 bool : ON { $$ = 1; }
178 | OFF { $$ = 0; }
181 string : string STRING {
182 if (asprintf(&$$, "%s%s", $1, $2) == -1) {
183 free($1);
184 free($2);
185 yyerror("string: asprintf: %s", strerror(errno));
186 YYERROR;
188 free($1);
189 free($2);
191 | STRING
194 numberstring : NUM {
195 char *s;
196 if (asprintf(&s, "%d", $1) == -1) {
197 yyerror("asprintf: number");
198 YYERROR;
200 $$ = s;
202 | STRING
205 varset : STRING '=' string {
206 char *s = $1;
207 while (*s++) {
208 if (isspace((unsigned char)*s)) {
209 yyerror("macro name cannot contain "
210 "whitespaces");
211 free($1);
212 free($3);
213 YYERROR;
216 symset($1, $3, 0);
217 free($1);
218 free($3);
222 option : CHROOT string {
223 if (strlcpy(conf->chroot, $2, sizeof(conf->chroot)) >=
224 sizeof(conf->chroot))
225 yyerror("chroot path too long");
226 free($2);
228 | IPV6 bool {
229 yywarn("option `ipv6' is deprecated,"
230 " please use `listen on'");
231 if ($2)
232 default_host = "*";
233 else
234 default_host = "0.0.0.0";
236 | log
237 | PORT NUM {
238 yywarn("option `port' is deprecated,"
239 " please use `listen on'");
240 default_port = $2;
242 | PREFORK NUM { conf->prefork = check_prefork_num($2); }
243 | PROTOCOLS string {
244 if (tls_config_parse_protocols(&conf->protos, $2) == -1)
245 yyerror("invalid protocols string \"%s\"", $2);
246 free($2);
248 | USER string {
249 if (strlcpy(conf->user, $2, sizeof(conf->user)) >=
250 sizeof(conf->user))
251 yyerror("user name too long");
252 free($2);
256 log : LOG '{' optnl logopts '}'
257 | LOG logopt
260 logopts : /* empty */
261 | logopts logopt optnl
264 logopt : ACCESS string {
265 free(conf->log_access);
266 conf->log_access = $2;
268 | STYLE COMMON {
269 conf->log_format = LOG_FORMAT_COMMON;
271 | STYLE COMBINED {
272 conf->log_format = LOG_FORMAT_COMBINED;
274 | STYLE CONDENSED {
275 conf->log_format = LOG_FORMAT_CONDENSED;
277 | STYLE LEGACY {
278 conf->log_format = LOG_FORMAT_LEGACY;
280 | SYSLOG FACILITY string {
281 const char *str = $3;
283 conf->log_syslog = 1;
285 if (!strncasecmp(str, "LOG_", 4))
286 str += 4;
288 if (!strcasecmp(str, "daemon"))
289 conf->log_facility = LOG_DAEMON;
290 #ifdef LOG_FTP
291 else if (!strcasecmp(str, "ftp"))
292 conf->log_facility = LOG_FTP;
293 #endif
294 else if (!strcasecmp(str, "local1"))
295 conf->log_facility = LOG_LOCAL1;
296 else if (!strcasecmp(str, "local2"))
297 conf->log_facility = LOG_LOCAL2;
298 else if (!strcasecmp(str, "local3"))
299 conf->log_facility = LOG_LOCAL3;
300 else if (!strcasecmp(str, "local4"))
301 conf->log_facility = LOG_LOCAL4;
302 else if (!strcasecmp(str, "local5"))
303 conf->log_facility = LOG_LOCAL5;
304 else if (!strcasecmp(str, "local6"))
305 conf->log_facility = LOG_LOCAL6;
306 else if (!strcasecmp(str, "local7"))
307 conf->log_facility = LOG_LOCAL7;
308 else if (!strcasecmp(str, "user"))
309 conf->log_facility = LOG_USER;
310 else
311 yywarn("unknown syslog facility `%s'",
312 $3);
314 free($3);
316 | SYSLOG OFF {
317 conf->log_syslog = 0;
319 | SYSLOG {
320 conf->log_syslog = 1;
324 vhost : SERVER string {
325 host = new_vhost();
326 TAILQ_INSERT_HEAD(&conf->hosts, host, vhosts);
328 loc = new_location();
329 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
331 TAILQ_INIT(&host->proxies);
333 (void) strlcpy(loc->match, "*", sizeof(loc->match));
334 (void) strlcpy(host->domain, $2, sizeof(host->domain));
336 if (strstr($2, "xn--") != NULL) {
337 yywarn("\"%s\" looks like punycode: you "
338 "should use the decoded hostname", $2);
341 free($2);
342 } '{' optnl servbody '}' {
343 if (host->cert_path == NULL ||
344 host->key_path == NULL)
345 yyerror("invalid vhost definition: %s",
346 host->domain);
347 if (TAILQ_EMPTY(&host->addrs)) {
348 char portno[32];
349 int r;
351 r = snprintf(portno, sizeof(portno), "%d",
352 default_port);
353 if (r < 0 || (size_t)r >= sizeof(portno))
354 fatal("snprintf");
356 yywarn("missing `listen on' in server %s,"
357 " assuming %s port %d", $2, default_host,
358 default_port);
359 listen_on(default_host, portno);
362 | error '}' { yyerror("bad server directive"); }
365 servbody : /* empty */
366 | servbody servopt optnl
367 | servbody location optnl
368 | servbody proxy optnl
371 listen_addr : '*' { $$ = NULL; }
372 | STRING
375 servopt : ALIAS string {
376 struct alist *a;
378 a = xcalloc(1, sizeof(*a));
379 (void) strlcpy(a->alias, $2, sizeof(a->alias));
380 free($2);
381 TAILQ_INSERT_TAIL(&host->aliases, a, aliases);
383 | CERT string {
384 ensure_absolute_path($2);
385 free(host->cert_path);
386 host->cert_path = $2;
388 | KEY string {
389 ensure_absolute_path($2);
390 free(host->key_path);
391 host->key_path = $2;
393 | OCSP string {
394 ensure_absolute_path($2);
395 free(host->ocsp_path);
396 host->ocsp_path = $2;
398 | PARAM string '=' string {
399 yywarn("the top-level `param' directive is deprecated."
400 " Please use `fastcgi { param ... }`");
401 add_param($2, $4);
403 | LISTEN ON listen_addr {
404 listen_on($3, "1965");
406 | LISTEN ON listen_addr PORT STRING {
407 listen_on($3, $5);
408 free($3);
409 free($5);
411 | LISTEN ON listen_addr PORT NUM {
412 char portno[32];
413 int r;
415 r = snprintf(portno, sizeof(portno), "%d", $5);
416 if (r < 0 || (size_t)r >= sizeof(portno))
417 fatal("snprintf");
419 listen_on($3, portno);
420 free($3);
422 | locopt
425 proxy : PROXY { advance_proxy(); }
426 proxy_matches '{' optnl proxy_opts '}' {
427 if (*proxy->host == '\0')
428 yyerror("invalid proxy block: missing `relay-to' option");
430 if ((proxy->cert_path == NULL && proxy->key_path != NULL) ||
431 (proxy->cert_path != NULL && proxy->key_path == NULL))
432 yyerror("invalid proxy block: missing cert or key");
436 proxy_matches : /* empty */
437 | proxy_matches proxy_match
440 proxy_port : /* empty */ { $$ = 1965; }
441 | PORT STRING {
442 if (($$ = getservice($2)) == -1)
443 yyerror("invalid port number %s", $2);
444 free($2);
446 | PORT NUM { $$ = $2; }
449 proxy_match : PROTO string {
450 (void) strlcpy(proxy->match_proto, $2, sizeof(proxy->match_proto));
451 free($2);
453 | FOR_HOST string proxy_port {
454 (void) strlcpy(proxy->match_host, $2, sizeof(proxy->match_host));
455 (void) snprintf(proxy->match_port, sizeof(proxy->match_port),
456 "%d", $3);
457 free($2);
461 proxy_opts : /* empty */
462 | proxy_opts proxy_opt optnl
465 proxy_opt : CERT string {
466 free(proxy->cert);
467 ensure_absolute_path($2);
468 proxy->cert_path = $2;
470 | KEY string {
471 free(proxy->key);
472 ensure_absolute_path($2);
473 proxy->key_path = $2;
475 | PROTOCOLS string {
476 if (tls_config_parse_protocols(&proxy->protocols, $2) == -1)
477 yyerror("invalid protocols string \"%s\"", $2);
478 free($2);
480 | RELAY_TO string proxy_port {
481 (void) strlcpy(proxy->host, $2, sizeof(proxy->host));
482 (void) snprintf(proxy->port, sizeof(proxy->port),
483 "%d", $3);
484 free($2);
486 | REQUIRE CLIENT CA string {
487 ensure_absolute_path($4);
488 proxy->reqca_path = $4;
490 | SNI string {
491 (void) strlcpy(proxy->sni, $2, sizeof(proxy->sni));
492 free($2);
494 | USE_TLS bool {
495 proxy->notls = !$2;
497 | VERIFYNAME bool {
498 proxy->noverifyname = !$2;
502 location : LOCATION { advance_loc(); } string '{' optnl locopts '}' {
503 /* drop the starting '/' if any */
504 if (*$3 == '/')
505 memmove($3, $3+1, strlen($3));
506 (void) strlcpy(loc->match, $3, sizeof(loc->match));
507 free($3);
509 | error '}'
512 locopts : /* empty */
513 | locopts locopt optnl
516 locopt : AUTO INDEX bool { loc->auto_index = $3 ? 1 : -1; }
517 | BLOCK RETURN NUM string {
518 check_block_fmt($4);
519 (void) strlcpy(loc->block_fmt, $4, sizeof(loc->block_fmt));
520 loc->block_code = check_block_code($3);
521 free($4);
523 | BLOCK RETURN NUM {
524 (void) strlcpy(loc->block_fmt, "temporary failure",
525 sizeof(loc->block_fmt));
526 loc->block_code = check_block_code($3);
527 if ($3 >= 30 && $3 < 40)
528 yyerror("missing `meta' for block return %d", $3);
530 | BLOCK {
531 (void) strlcpy(loc->block_fmt, "temporary failure",
532 sizeof(loc->block_fmt));
533 loc->block_code = 40;
535 | DEFAULT TYPE string {
536 (void) strlcpy(loc->default_mime, $3,
537 sizeof(loc->default_mime));
538 free($3);
540 | fastcgi
541 | INDEX string {
542 (void) strlcpy(loc->index, $2, sizeof(loc->index));
543 free($2);
545 | LANG string {
546 (void) strlcpy(loc->lang, $2,
547 sizeof(loc->lang));
548 free($2);
550 | LOG bool { loc->disable_log = !$2; }
551 | REQUIRE CLIENT CA string {
552 ensure_absolute_path($4);
553 loc->reqca_path = $4;
555 | ROOT string {
556 (void) strlcpy(loc->dir, $2, sizeof(loc->dir));
557 free($2);
559 | STRIP NUM { loc->strip = check_strip_no($2); }
562 fastcgi : FASTCGI '{' optnl fastcgiopts '}'
563 | FASTCGI fastcgiopt
564 | FASTCGI OFF {
565 loc->fcgi = -1;
566 loc->nofcgi = 1;
568 | FASTCGI string {
569 yywarn("`fastcgi path' is deprecated. "
570 "Please use `fastcgi socket path' instead.");
571 loc->fcgi = fastcgi_conf($2, NULL);
572 free($2);
576 fastcgiopts : /* empty */
577 | fastcgiopts fastcgiopt optnl
580 fastcgiopt : PARAM string '=' string {
581 add_param($2, $4);
583 | SOCKET string {
584 loc->fcgi = fastcgi_conf($2, NULL);
585 free($2);
587 | SOCKET TCP string PORT NUM {
588 char *c;
590 if (asprintf(&c, "%d", $5) == -1)
591 fatal("asprintf");
592 loc->fcgi = fastcgi_conf($3, c);
593 free($3);
594 free(c);
596 | SOCKET TCP string {
597 loc->fcgi = fastcgi_conf($3, "9000");
599 | SOCKET TCP string PORT string {
600 loc->fcgi = fastcgi_conf($3, $5);
601 free($3);
602 free($5);
604 | STRIP NUM {
605 loc->fcgi_strip = $2;
609 types : TYPES '{' optnl mediaopts_l '}' ;
611 mediaopts_l : mediaopts_l mediaoptsl nl
612 | mediaoptsl nl
615 mediaoptsl : STRING {
616 free(current_media);
617 current_media = $1;
618 } medianames_l optsemicolon
619 | include
622 medianames_l : medianames_l medianamesl
623 | medianamesl
626 medianamesl : numberstring {
627 if (add_mime(&conf->mime, current_media, $1) == -1)
628 fatal("add_mime");
629 free($1);
633 nl : '\n' optnl
636 optnl : '\n' optnl /* zero or more newlines */
637 | ';' optnl /* semicolons too */
638 | /*empty*/
641 optsemicolon : ';'
645 %%
647 static const struct keyword {
648 const char *word;
649 int token;
650 } keywords[] = {
651 /* these MUST be sorted */
652 {"access", ACCESS},
653 {"alias", ALIAS},
654 {"auto", AUTO},
655 {"block", BLOCK},
656 {"ca", CA},
657 {"cert", CERT},
658 {"chroot", CHROOT},
659 {"client", CLIENT},
660 {"combined", COMBINED},
661 {"common", COMMON},
662 {"condensed", CONDENSED},
663 {"default", DEFAULT},
664 {"facility", FACILITY},
665 {"fastcgi", FASTCGI},
666 {"for-host", FOR_HOST},
667 {"include", INCLUDE},
668 {"index", INDEX},
669 {"ipv6", IPV6},
670 {"key", KEY},
671 {"lang", LANG},
672 {"legacy", LEGACY},
673 {"listen", LISTEN},
674 {"location", LOCATION},
675 {"log", LOG},
676 {"ocsp", OCSP},
677 {"off", OFF},
678 {"on", ON},
679 {"param", PARAM},
680 {"port", PORT},
681 {"prefork", PREFORK},
682 {"proto", PROTO},
683 {"protocols", PROTOCOLS},
684 {"proxy", PROXY},
685 {"relay-to", RELAY_TO},
686 {"require", REQUIRE},
687 {"return", RETURN},
688 {"root", ROOT},
689 {"server", SERVER},
690 {"sni", SNI},
691 {"socket", SOCKET},
692 {"strip", STRIP},
693 {"style", STYLE},
694 {"syslog", SYSLOG},
695 {"tcp", TCP},
696 {"to-ext", TOEXT},
697 {"type", TYPE},
698 {"types", TYPES},
699 {"use-tls", USE_TLS},
700 {"user", USER},
701 {"verifyname", VERIFYNAME},
702 };
704 void
705 yyerror(const char *msg, ...)
707 va_list ap;
709 file->errors++;
711 va_start(ap, msg);
712 fprintf(stderr, "%s:%d error: ", config_path, yylval.lineno);
713 vfprintf(stderr, msg, ap);
714 fprintf(stderr, "\n");
715 va_end(ap);
718 void
719 yywarn(const char *msg, ...)
721 va_list ap;
723 va_start(ap, msg);
724 fprintf(stderr, "%s:%d warning: ", config_path, yylval.lineno);
725 vfprintf(stderr, msg, ap);
726 fprintf(stderr, "\n");
727 va_end(ap);
730 int
731 kw_cmp(const void *k, const void *e)
733 return strcmp(k, ((struct keyword *)e)->word);
736 int
737 lookup(char *s)
739 const struct keyword *p;
741 p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
742 sizeof(keywords[0]), kw_cmp);
744 if (p)
745 return p->token;
746 else
747 return STRING;
750 #define START_EXPAND 1
751 #define DONE_EXPAND 2
753 static int expanding;
755 int
756 igetc(void)
758 int c;
760 while (1) {
761 if (file->ungetpos > 0)
762 c = file->ungetbuf[--file->ungetpos];
763 else
764 c = getc(file->stream);
766 if (c == START_EXPAND)
767 expanding = 1;
768 else if (c == DONE_EXPAND)
769 expanding = 0;
770 else
771 break;
773 return c;
776 int
777 lgetc(int quotec)
779 int c, next;
781 if (quotec) {
782 if ((c = igetc()) == EOF) {
783 yyerror("reached end of file while parsing "
784 "quoted string");
785 if (file == topfile || popfile() == EOF)
786 return EOF;
787 return quotec;
789 return c;
792 while ((c = igetc()) == '\\') {
793 next = igetc();
794 if (next != '\n') {
795 c = next;
796 break;
798 yylval.lineno = file->lineno;
799 file->lineno++;
802 if (c == EOF) {
803 /*
804 * Fake EOL when hit EOF for the first time. This gets line
805 * count right if last line in included file is syntactically
806 * invalid and has no newline.
807 */
808 if (file->eof_reached == 0) {
809 file->eof_reached = 1;
810 return '\n';
812 while (c == EOF) {
813 if (file == topfile || popfile() == EOF)
814 return EOF;
815 c = igetc();
818 return c;
821 void
822 lungetc(int c)
824 if (c == EOF)
825 return;
827 if (file->ungetpos >= file->ungetsize) {
828 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
829 if (p == NULL)
830 fatal("lungetc");
831 file->ungetbuf = p;
832 file->ungetsize *= 2;
834 file->ungetbuf[file->ungetpos++] = c;
837 int
838 findeol(void)
840 int c;
842 /* Skip to either EOF or the first real EOL. */
843 while (1) {
844 c = lgetc(0);
845 if (c == '\n') {
846 file->lineno++;
847 break;
849 if (c == EOF)
850 break;
852 return ERROR;
855 int
856 yylex(void)
858 char buf[8096];
859 char *p, *val;
860 int quotec, next, c;
861 int token;
863 top:
864 p = buf;
865 while ((c = lgetc(0)) == ' ' || c == '\t')
866 ; /* nothing */
868 yylval.lineno = file->lineno;
869 if (c == '#')
870 while ((c = lgetc(0)) != '\n' && c != EOF)
871 ; /* nothing */
872 if (c == '$' && !expanding) {
873 while (1) {
874 if ((c = lgetc(0)) == EOF)
875 return 0;
876 if (p + 1 >= buf + sizeof(buf) -1) {
877 yyerror("string too long");
878 return findeol();
880 if (isalnum(c) || c == '_') {
881 *p++ = c;
882 continue;
884 *p = '\0';
885 lungetc(c);
886 break;
888 val = symget(buf);
889 if (val == NULL) {
890 yyerror("macro `%s' not defined", buf);
891 return findeol();
893 yylval.v.string = xstrdup(val);
894 return STRING;
896 if (c == '@' && !expanding) {
897 while (1) {
898 if ((c = lgetc(0)) == EOF)
899 return 0;
901 if (p + 1 >= buf + sizeof(buf) - 1) {
902 yyerror("string too long");
903 return findeol();
905 if (isalnum(c) || c == '_') {
906 *p++ = c;
907 continue;
909 *p = '\0';
910 lungetc(c);
911 break;
913 val = symget(buf);
914 if (val == NULL) {
915 yyerror("macro '%s' not defined", buf);
916 return findeol();
918 p = val + strlen(val) - 1;
919 lungetc(DONE_EXPAND);
920 while (p >= val) {
921 lungetc(*p);
922 p--;
924 lungetc(START_EXPAND);
925 goto top;
928 switch (c) {
929 case '\'':
930 case '"':
931 quotec = c;
932 while (1) {
933 if ((c = lgetc(quotec)) == EOF)
934 return 0;
935 if (c == '\n') {
936 file->lineno++;
937 continue;
938 } else if (c == '\\') {
939 if ((next = lgetc(quotec)) == EOF)
940 return (0);
941 if (next == quotec || next == ' ' ||
942 next == '\t')
943 c = next;
944 else if (next == '\n') {
945 file->lineno++;
946 continue;
947 } else
948 lungetc(next);
949 } else if (c == quotec) {
950 *p = '\0';
951 break;
952 } else if (c == '\0') {
953 yyerror("invalid syntax");
954 return findeol();
956 if (p + 1 >= buf + sizeof(buf) - 1) {
957 yyerror("string too long");
958 return findeol();
960 *p++ = c;
962 yylval.v.string = strdup(buf);
963 if (yylval.v.string == NULL)
964 fatal("yylex: strdup");
965 return STRING;
968 #define allowed_to_end_number(x) \
969 (isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=')
971 if (c == '-' || isdigit(c)) {
972 do {
973 *p++ = c;
974 if ((size_t)(p-buf) >= sizeof(buf)) {
975 yyerror("string too long");
976 return findeol();
978 } while ((c = lgetc(0)) != EOF && isdigit(c));
979 lungetc(c);
980 if (p == buf + 1 && buf[0] == '-')
981 goto nodigits;
982 if (c == EOF || allowed_to_end_number(c)) {
983 const char *errstr = NULL;
985 *p = '\0';
986 yylval.v.number = strtonum(buf, LLONG_MIN,
987 LLONG_MAX, &errstr);
988 if (errstr) {
989 yyerror("\"%s\" invalid number: %s",
990 buf, errstr);
991 return findeol();
993 return NUM;
994 } else {
995 nodigits:
996 while (p > buf + 1)
997 lungetc(*--p);
998 c = *--p;
999 if (c == '-')
1000 return c;
1004 #define allowed_in_string(x) \
1005 (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
1006 x != '{' && x != '}' && \
1007 x != '!' && x != '=' && x != '#' && \
1008 x != ',' && x != ';'))
1010 if (isalnum(c) || c == ':' || c == '_') {
1011 do {
1012 *p++ = c;
1013 if ((size_t)(p-buf) >= sizeof(buf)) {
1014 yyerror("string too long");
1015 return findeol();
1017 } while ((c = lgetc(0)) != EOF && (allowed_in_string(c)));
1018 lungetc(c);
1019 *p = '\0';
1020 if ((token = lookup(buf)) == STRING)
1021 yylval.v.string = xstrdup(buf);
1022 return token;
1024 if (c == '\n') {
1025 yylval.lineno = file->lineno;
1026 file->lineno++;
1028 if (c == EOF)
1029 return 0;
1030 return c;
1033 struct file *
1034 pushfile(const char *name, int secret)
1036 struct file *nfile;
1038 nfile = xcalloc(1, sizeof(*nfile));
1039 nfile->name = xstrdup(name);
1040 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
1041 log_warn("can't open %s", nfile->name);
1042 free(nfile->name);
1043 free(nfile);
1044 return NULL;
1046 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
1047 nfile->ungetsize = 16;
1048 nfile->ungetbuf = xcalloc(1, nfile->ungetsize);
1049 TAILQ_INSERT_TAIL(&files, nfile, entry);
1050 return nfile;
1053 int
1054 popfile(void)
1056 struct file *prev;
1058 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
1059 prev->errors += file->errors;
1061 TAILQ_REMOVE(&files, file, entry);
1062 fclose(file->stream);
1063 free(file->name);
1064 free(file->ungetbuf);
1065 free(file);
1066 file = prev;
1067 return file ? 0 : EOF;
1070 int
1071 parse_conf(struct conf *c, const char *filename)
1073 struct sym *sym, *next;
1075 default_host = "*";
1076 default_port = 1965;
1078 conf = c;
1080 file = pushfile(filename, 0);
1081 if (file == NULL)
1082 return -1;
1083 topfile = file;
1085 yyparse();
1086 errors = file->errors;
1087 popfile();
1089 /* Free macros and check which have not been used. */
1090 TAILQ_FOREACH_SAFE(sym, &symhead, entry, next) {
1091 /* TODO: warn if !sym->used */
1092 if (!sym->persist) {
1093 free(sym->name);
1094 free(sym->val);
1095 TAILQ_REMOVE(&symhead, sym, entry);
1096 free(sym);
1100 if (errors)
1101 return -1;
1102 return 0;
1105 int
1106 symset(const char *name, const char *val, int persist)
1108 struct sym *sym;
1110 TAILQ_FOREACH(sym, &symhead, entry) {
1111 if (!strcmp(name, sym->name))
1112 break;
1115 if (sym != NULL) {
1116 if (sym->persist)
1117 return 0;
1118 else {
1119 free(sym->name);
1120 free(sym->val);
1121 TAILQ_REMOVE(&symhead, sym, entry);
1122 free(sym);
1126 sym = xcalloc(1, sizeof(*sym));
1127 sym->name = xstrdup(name);
1128 sym->val = xstrdup(val);
1129 sym->used = 0;
1130 sym->persist = persist;
1132 TAILQ_INSERT_TAIL(&symhead, sym, entry);
1133 return 0;
1136 int
1137 cmdline_symset(char *s)
1139 char *sym, *val;
1140 int ret;
1142 if ((val = strrchr(s, '=')) == NULL)
1143 return -1;
1144 sym = xcalloc(1, val - s + 1);
1145 memcpy(sym, s, val - s);
1146 ret = symset(sym, val + 1, 1);
1147 free(sym);
1148 return ret;
1151 char *
1152 symget(const char *nam)
1154 struct sym *sym;
1156 TAILQ_FOREACH(sym, &symhead, entry) {
1157 if (strcmp(nam, sym->name) == 0) {
1158 sym->used = 1;
1159 return sym->val;
1162 return NULL;
1165 char *
1166 ensure_absolute_path(char *path)
1168 if (path == NULL || *path != '/')
1169 yyerror("not an absolute path: %s", path);
1170 return path;
1173 int
1174 check_block_code(int n)
1176 if (n < 10 || n >= 70 || (n >= 20 && n <= 29))
1177 yyerror("invalid block code %d", n);
1178 return n;
1181 char *
1182 check_block_fmt(char *fmt)
1184 char *s;
1186 for (s = fmt; *s; ++s) {
1187 if (*s != '%')
1188 continue;
1189 switch (*++s) {
1190 case '%':
1191 case 'p':
1192 case 'q':
1193 case 'P':
1194 case 'N':
1195 break;
1196 default:
1197 yyerror("invalid format specifier %%%c", *s);
1201 return fmt;
1204 int
1205 check_strip_no(int n)
1207 if (n <= 0)
1208 yyerror("invalid strip number %d", n);
1209 return n;
1212 int
1213 check_port_num(int n)
1215 if (n <= 0 || n >= UINT16_MAX)
1216 yyerror("port number is %s: %d",
1217 n <= 0 ? "too small" : "too large",
1218 n);
1219 return n;
1222 int
1223 check_prefork_num(int n)
1225 if (n <= 0 || n >= PROC_MAX_INSTANCES)
1226 yyerror("invalid prefork number %d", n);
1227 return n;
1230 void
1231 advance_loc(void)
1233 loc = new_location();
1234 TAILQ_INSERT_TAIL(&host->locations, loc, locations);
1237 void
1238 advance_proxy(void)
1240 proxy = new_proxy();
1241 TAILQ_INSERT_TAIL(&host->proxies, proxy, proxies);
1244 void
1245 parsehp(char *str, char **host, const char **port, const char *def)
1247 char *at;
1248 const char *errstr;
1250 *host = str;
1252 if ((at = strchr(str, ':')) != NULL) {
1253 *at++ = '\0';
1254 *port = at;
1255 } else
1256 *port = def;
1258 strtonum(*port, 1, UINT16_MAX, &errstr);
1259 if (errstr != NULL)
1260 yyerror("port is %s: %s", errstr, *port);
1263 int
1264 fastcgi_conf(const char *path, const char *port)
1266 struct fcgi *f;
1267 int i = 0;
1269 TAILQ_FOREACH(f, &conf->fcgi, fcgi) {
1270 if (!strcmp(f->path, path) &&
1271 ((port == NULL && *f->port == '\0') ||
1272 !strcmp(f->port, port)))
1273 return i;
1274 ++i;
1277 f = xcalloc(1, sizeof(*f));
1278 f->id = i;
1279 (void)strlcpy(f->path, path, sizeof(f->path));
1280 if (port != NULL)
1281 (void)strlcpy(f->port, port, sizeof(f->port));
1282 TAILQ_INSERT_TAIL(&conf->fcgi, f, fcgi);
1284 return f->id;
1287 void
1288 add_param(char *name, char *val)
1290 struct envlist *e;
1291 struct envhead *h = &loc->params;
1293 e = xcalloc(1, sizeof(*e));
1294 (void) strlcpy(e->name, name, sizeof(e->name));
1295 (void) strlcpy(e->value, val, sizeof(e->value));
1296 TAILQ_INSERT_TAIL(h, e, envs);
1299 int
1300 getservice(const char *n)
1302 struct servent *s;
1303 const char *errstr;
1304 long long llval;
1306 llval = strtonum(n, 0, UINT16_MAX, &errstr);
1307 if (errstr) {
1308 s = getservbyname(n, "tcp");
1309 if (s == NULL)
1310 s = getservbyname(n, "udp");
1311 if (s == NULL)
1312 return (-1);
1313 return (ntohs(s->s_port));
1316 return ((unsigned short)llval);
1319 static void
1320 add_to_addr_queue(struct addrhead *a, struct addrinfo *ai)
1322 struct address *addr;
1323 struct sockaddr_in *sin;
1324 struct sockaddr_in6 *sin6;
1326 if (ai->ai_addrlen > sizeof(addr->ss))
1327 fatalx("ai_addrlen larger than a sockaddr_storage");
1329 TAILQ_FOREACH(addr, a, addrs) {
1330 if (addr->ai_flags == ai->ai_flags &&
1331 addr->ai_family == ai->ai_family &&
1332 addr->ai_socktype == ai->ai_socktype &&
1333 addr->ai_protocol == ai->ai_protocol &&
1334 addr->slen == ai->ai_addrlen &&
1335 !memcmp(&addr->ss, ai->ai_addr, addr->slen))
1336 return;
1339 addr = xcalloc(1, sizeof(*addr));
1340 addr->ai_flags = ai->ai_flags;
1341 addr->ai_family = ai->ai_family;
1342 addr->ai_socktype = ai->ai_socktype;
1343 addr->ai_protocol = ai->ai_protocol;
1344 addr->slen = ai->ai_addrlen;
1345 memcpy(&addr->ss, ai->ai_addr, ai->ai_addrlen);
1347 /* for commodity */
1348 switch (addr->ai_family) {
1349 case AF_INET:
1350 sin = (struct sockaddr_in *)&addr->ss;
1351 addr->port = ntohs(sin->sin_port);
1352 break;
1353 case AF_INET6:
1354 sin6 = (struct sockaddr_in6 *)&addr->ss;
1355 addr->port = ntohs(sin6->sin6_port);
1356 break;
1357 default:
1358 fatalx("unknown socket family %d", addr->ai_family);
1361 addr->sock = -1;
1363 TAILQ_INSERT_HEAD(a, addr, addrs);
1366 void
1367 listen_on(const char *hostname, const char *servname)
1369 struct addrinfo hints, *res, *res0;
1370 int error;
1372 memset(&hints, 0, sizeof(hints));
1373 hints.ai_family = AF_UNSPEC;
1374 hints.ai_socktype = SOCK_STREAM;
1375 hints.ai_flags = AI_PASSIVE;
1376 error = getaddrinfo(hostname, servname, &hints, &res0);
1377 if (error) {
1378 yyerror("listen on \"%s\" port %s: %s", hostname, servname,
1379 gai_strerror(errno));
1380 return;
1383 for (res = res0; res; res = res->ai_next) {
1384 add_to_addr_queue(&host->addrs, res);
1385 add_to_addr_queue(&conf->addrs, res);
1388 freeaddrinfo(res0);