patplex: Replace the `default' handling with arbitrary priorities.
[ashd.git] / src / patplex.c
1 /*
2     ashd - A Sane HTTP Daemon
3     Copyright (C) 2008  Fredrik Tolf <fredrik@dolda2000.com>
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 3 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,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU 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, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <signal.h>
24 #include <errno.h>
25 #include <ctype.h>
26 #include <regex.h>
27 #include <limits.h>
28 #include <sys/wait.h>
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33 #include <utils.h>
34 #include <log.h>
35 #include <req.h>
36 #include <proc.h>
37 #include <resp.h>
38 #include <cf.h>
39
40 #define PAT_REST 0
41 #define PAT_URL 1
42 #define PAT_METHOD 2
43 #define PAT_HEADER 3
44 #define PAT_ALL 4
45
46 #define PATFL_MSS 1
47 #define PATFL_UNQ 2
48
49 struct config {
50     struct child *children;
51     struct pattern *patterns;
52 };
53
54 struct rule {
55     int type;
56     int fl;
57     char *header;
58     regex_t *pattern;
59 };
60
61 struct headmod {
62     struct headmod *next;
63     char *name, *value;
64 };
65
66 struct pattern {
67     struct pattern *next;
68     struct headmod *headers;
69     char *childnm;
70     struct rule **rules;
71     char *restpat;
72     int prio;
73 };
74
75 static struct config *gconfig, *lconfig;
76 static volatile int reload = 0;
77
78 static void freepattern(struct pattern *pat)
79 {
80     struct rule **rule;
81     struct headmod *head;
82     
83     for(rule = pat->rules; *rule; rule++) {
84         if((*rule)->header != NULL)
85             free((*rule)->header);
86         if((*rule)->pattern != NULL) {
87             regfree((*rule)->pattern);
88             free((*rule)->pattern);
89         }
90         free(*rule);
91     }
92     while((head = pat->headers) != NULL) {
93         pat->headers = head->next;
94         free(head->name);
95         free(head->value);
96         free(head);
97     }
98     if(pat->childnm != NULL)
99         free(pat->childnm);
100     free(pat);
101 }
102
103 static void freeconfig(struct config *cf)
104 {
105     struct child *ch, *nch;
106     struct pattern *pat, *npat;
107     
108     for(ch = cf->children; ch != NULL; ch = nch) {
109         nch = ch->next;
110         freechild(ch);
111     }
112     for(pat = cf->patterns; pat != NULL; pat = npat) {
113         npat = pat->next;
114         freepattern(pat);
115     }
116     free(cf);
117 }
118
119 static struct child *getchild(struct config *cf, char *name)
120 {
121     struct child *ch;
122     
123     for(ch = cf->children; ch; ch = ch->next) {
124         if(!strcmp(ch->name, name))
125             break;
126     }
127     return(ch);
128 }
129
130 static struct rule *newrule(struct pattern *pat)
131 {
132     int i;
133     struct rule *rule;
134     
135     for(i = 0; pat->rules[i]; i++);
136     pat->rules = srealloc(pat->rules, sizeof(*pat->rules) * (i + 2));
137     rule = pat->rules[i] = szmalloc(sizeof(*rule));
138     pat->rules[i + 1] = NULL;
139     return(rule);
140 }
141
142 static struct pattern *newpattern(void)
143 {
144     struct pattern *pat;
145     
146     omalloc(pat);
147     pat->rules = szmalloc(sizeof(*pat->rules));
148     return(pat);
149 }
150
151 static regex_t *regalloc(char *regex, int flags)
152 {
153     regex_t *ret;
154     int res;
155     char errbuf[256];
156     
157     omalloc(ret);
158     if((res = regcomp(ret, regex, flags | REG_EXTENDED)) != 0) {
159         regerror(res, ret, errbuf, sizeof(errbuf));
160         flog(LOG_WARNING, "%s: %s", regex, errbuf);
161         free(ret);
162         return(NULL);
163     }
164     return(ret);
165 }
166
167 static struct pattern *parsepattern(struct cfstate *s)
168 {
169     struct pattern *pat;
170     int sl;
171     struct rule *rule;
172     struct headmod *head;
173     regex_t *regex;
174     int rxfl;
175     
176     if(!strcmp(s->argv[0], "match")) {
177         s->expstart = 1;
178         pat = newpattern();
179     } else {
180         return(NULL);
181     }
182     
183     sl = s->lno;
184     while(1) {
185         getcfline(s);
186         if(!strcmp(s->argv[0], "point") ||
187            !strcmp(s->argv[0], "url") ||
188            !strcmp(s->argv[0], "method")) {
189             if(s->argc < 2) {
190                 flog(LOG_WARNING, "%s:%i: missing pattern for `%s' match", s->file, s->lno, s->argv[0]);
191                 continue;
192             }
193             rxfl = 0;
194             if(s->argc >= 3) {
195                 if(strchr(s->argv[2], 'i'))
196                     rxfl |= REG_ICASE;
197             }
198             if((regex = regalloc(s->argv[1], rxfl)) == NULL) {
199                 flog(LOG_WARNING, "%s:%i: invalid regex for `%s' match", s->file, s->lno, s->argv[0]);
200                 continue;
201             }
202             rule = newrule(pat);
203             if(!strcmp(s->argv[0], "point"))
204                 rule->type = PAT_REST;
205             else if(!strcmp(s->argv[0], "url"))
206                 rule->type = PAT_URL;
207             else if(!strcmp(s->argv[0], "method"))
208                 rule->type = PAT_METHOD;
209             rule->pattern = regex;
210             if(s->argc >= 3) {
211                 if(strchr(s->argv[2], 's'))
212                     rule->fl |= PATFL_MSS;
213                 if(strchr(s->argv[2], 'q'))
214                     rule->fl |= PATFL_UNQ;
215             }
216         } else if(!strcmp(s->argv[0], "header")) {
217             if(s->argc < 3) {
218                 flog(LOG_WARNING, "%s:%i: missing header name or pattern for `header' match", s->file, s->lno);
219                 continue;
220             }
221             rxfl = 0;
222             if(s->argc >= 4) {
223                 if(strchr(s->argv[3], 'i'))
224                     rxfl |= REG_ICASE;
225             }
226             if((regex = regalloc(s->argv[2], rxfl)) == NULL) {
227                 flog(LOG_WARNING, "%s:%i: invalid regex for `header' match", s->file, s->lno);
228                 continue;
229             }
230             rule = newrule(pat);
231             rule->type = PAT_HEADER;
232             rule->header = sstrdup(s->argv[1]);
233             rule->pattern = regex;
234             if(s->argc >= 4) {
235                 if(strchr(s->argv[3], 's'))
236                     rule->fl |= PATFL_MSS;
237             }
238         } else if(!strcmp(s->argv[0], "all")) {
239             newrule(pat)->type = PAT_ALL;
240         } else if(!strcmp(s->argv[0], "default")) {
241             newrule(pat)->type = PAT_ALL;
242             pat->prio = -10;
243         } else if(!strcmp(s->argv[0], "order") || !strcmp(s->argv[0], "priority")) {
244             if(s->argc < 2) {
245                 flog(LOG_WARNING, "%s:%i: missing specification for `%s' directive", s->file, s->lno, s->argv[0]);
246                 continue;
247             }
248             pat->prio = atoi(s->argv[1]);
249         } else if(!strcmp(s->argv[0], "handler")) {
250             if(s->argc < 2) {
251                 flog(LOG_WARNING, "%s:%i: missing child name for `handler' directive", s->file, s->lno);
252                 continue;
253             }
254             if(pat->childnm != NULL)
255                 free(pat->childnm);
256             pat->childnm = sstrdup(s->argv[1]);
257         } else if(!strcmp(s->argv[0], "restpat")) {
258             if(s->argc < 2) {
259                 flog(LOG_WARNING, "%s:%i: missing pattern for `restpat' directive", s->file, s->lno);
260                 continue;
261             }
262             if(pat->restpat != NULL)
263                 free(pat->restpat);
264             pat->restpat = sstrdup(s->argv[1]);
265         } else if(!strcmp(s->argv[0], "set") || !strcmp(s->argv[0], "xset")) {
266             if(s->argc < 3) {
267                 flog(LOG_WARNING, "%s:%i: missing header name or pattern for `%s' directive", s->file, s->lno, s->argv[0]);
268                 continue;
269             }
270             omalloc(head);
271             if(!strcmp(s->argv[0], "xset"))
272                 head->name = sprintf2("X-Ash-%s", s->argv[1]);
273             else
274                 head->name = sstrdup(s->argv[1]);
275             head->value = sstrdup(s->argv[2]);
276             head->next = pat->headers;
277             pat->headers = head;
278         } else if(!strcmp(s->argv[0], "end") || !strcmp(s->argv[0], "eof")) {
279             break;
280         } else {
281             flog(LOG_WARNING, "%s:%i: unknown directive `%s' in pattern declaration", s->file, s->lno, s->argv[0]);
282         }
283     }
284     
285     if(pat->rules[0] == NULL) {
286         flog(LOG_WARNING, "%s:%i: missing rules in match declaration", s->file, sl);
287         freepattern(pat);
288         return(NULL);
289     }
290     if(pat->childnm == NULL) {
291         flog(LOG_WARNING, "%s:%i: missing handler in match declaration", s->file, sl);
292         freepattern(pat);
293         return(NULL);
294     }
295     return(pat);
296 }
297
298 static struct config *readconfig(char *filename)
299 {
300     struct cfstate *s;
301     struct config *cf;
302     struct child *ch;
303     struct pattern *pat;
304     FILE *in;
305     
306     if((in = fopen(filename, "r")) == NULL) {
307         flog(LOG_WARNING, "%s: %s", filename, strerror(errno));
308         return(NULL);
309     }
310     s = mkcfparser(in, filename);
311     omalloc(cf);
312     
313     while(1) {
314         getcfline(s);
315         if((ch = parsechild(s)) != NULL) {
316             ch->next = cf->children;
317             cf->children = ch;
318         } else if((pat = parsepattern(s)) != NULL) {
319             pat->next = cf->patterns;
320             cf->patterns = pat;
321         } else if(!strcmp(s->argv[0], "eof")) {
322             break;
323         } else {
324             flog(LOG_WARNING, "%s:%i: unknown directive `%s'", s->file, s->lno, s->argv[0]);
325         }
326     }
327     
328     freecfparser(s);
329     fclose(in);
330     return(cf);
331 }
332
333 static void exprestpat(struct hthead *req, struct pattern *pat, char **mstr)
334 {
335     char *p, *p2, *hdr;
336     int mc;
337     struct charbuf buf;
338     
339     if(mstr == NULL)
340         mc = 0;
341     else
342         for(mc = 0; mstr[mc]; mc++);
343     bufinit(buf);
344     for(p = pat->restpat; *p; ) {
345         if(*p == '$') {
346             p++;
347             if((*p >= '0') && (*p <= '9')) {
348                 if(*p - '0' < mc)
349                     bufcatstr(buf, mstr[*p - '0']);
350                 p++;
351             } else if(*p == '_') {
352                 bufcatstr(buf, req->rest);
353                 p++;
354             } else if(*p == '$') {
355                 bufadd(buf, '$');
356                 p++;
357             } else if(*p == '{') {
358                 if((p2 = strchr(p, '}')) == NULL) {
359                     p++;
360                 } else {
361                     hdr = getheader(req, sprintf3("%.*s", p2 - p - 1, p + 1));
362                     if(hdr)
363                         bufcatstr(buf, hdr);
364                 }
365             } else if(!*p) {
366             }
367         } else {
368             bufadd(buf, *(p++));
369         }
370     }
371     bufadd(buf, 0);
372     replrest(req, buf.b);
373     buffree(buf);
374 }
375
376 static void qoffsets(char *buf, int *obuf, char *pstr, int unquote)
377 {
378     int i, o, d1, d2;
379     
380     if(unquote) {
381         i = o = 0;
382         while(pstr[i]) {
383             obuf[o] = i;
384             if((pstr[i] == '%') && ((d1 = hexdigit(pstr[i + 1])) >= 0) && ((d2 = hexdigit(pstr[i + 2])) >= 0)) {
385                 buf[o] = (d1 << 4) | d2;
386                 i += 3;
387             } else {
388                 buf[o] = pstr[i];
389                 i++;
390             }
391             o++;
392         }
393         buf[o] = 0;
394         obuf[o] = i;
395     } else {
396         for(i = 0; pstr[i]; i++) {
397             buf[i] = pstr[i];
398             obuf[i] = i;
399         }
400         buf[i] = 0;
401         obuf[i] = i;
402     }
403 }
404
405 struct match {
406     struct pattern *pat;
407     char **mstr;
408     int rmo;
409 };
410
411 static void freematch(struct match *match)
412 {
413     freeca(match->mstr);
414     free(match);
415 }
416
417 static struct match *findmatch(struct config *cf, struct hthead *req, struct match *match)
418 {
419     int i, o;
420     struct pattern *pat;
421     struct rule *rule;
422     int rmo;
423     regex_t *rx;
424     char *pstr;
425     char **mstr;
426     regmatch_t gr[10];
427     
428     mstr = NULL;
429     for(pat = cf->patterns; pat != NULL; pat = pat->next) {
430         if(match && (pat->prio <= match->pat->prio))
431             continue;
432         rmo = -1;
433         for(i = 0; (rule = pat->rules[i]) != NULL; i++) {
434             rx = NULL;
435             if(rule->type == PAT_REST) {
436                 rx = rule->pattern;
437                 pstr = req->rest;
438             } else if(rule->type == PAT_URL) {
439                 rx = rule->pattern;
440                 pstr = req->url;
441             } else if(rule->type == PAT_METHOD) {
442                 rx = rule->pattern;
443                 pstr = req->method;
444             } else if(rule->type == PAT_HEADER) {
445                 rx = rule->pattern;
446                 if(!(pstr = getheader(req, rule->header)))
447                     break;
448             }
449             if(rx != NULL) {
450                 char pbuf[strlen(pstr) + 1];
451                 int  obuf[strlen(pstr) + 1];
452                 qoffsets(pbuf, obuf, pstr, !!(rule->fl & PATFL_UNQ));
453                 if(regexec(rx, pbuf, 10, gr, 0))
454                     break;
455                 else if(rule->type == PAT_REST)
456                     rmo = obuf[gr[0].rm_eo];
457                 if(rule->fl & PATFL_MSS) {
458                     if(mstr) {
459                         flog(LOG_WARNING, "two pattern rules marked with `s' flag found (for handler %s)", pat->childnm);
460                         freeca(mstr);
461                     }
462                     for(o = 0; o < 10; o++) {
463                         if(gr[o].rm_so < 0)
464                             break;
465                     }
466                     mstr = szmalloc((o + 1) * sizeof(*mstr));
467                     for(o = 0; o < 10; o++) {
468                         if(gr[o].rm_so < 0)
469                             break;
470                         mstr[o] = smalloc(obuf[gr[o].rm_eo] - obuf[gr[o].rm_so] + 1);
471                         memcpy(mstr[o], pstr + obuf[gr[o].rm_so], obuf[gr[o].rm_eo] - obuf[gr[o].rm_so]);
472                         mstr[o][obuf[gr[o].rm_eo] - obuf[gr[o].rm_so]] = 0;
473                     }
474                 }
475             } else if(rule->type == PAT_ALL) {
476             }
477         }
478         if(!rule) {
479             if(match)
480                 freematch(match);
481             omalloc(match);
482             match->pat = pat;
483             match->mstr = mstr;
484             match->rmo = rmo;
485         }
486     }
487     return(match);
488 }
489
490 static void execmatch(struct hthead *req, struct match *match)
491 {
492     struct headmod *head;
493     
494     if(match->pat->restpat)
495         exprestpat(req, match->pat, match->mstr);
496     else if(match->rmo != -1)
497         replrest(req, req->rest + match->rmo);
498     for(head = match->pat->headers; head != NULL; head = head->next) {
499         headrmheader(req, head->name);
500         headappheader(req, head->name, head->value);
501     }
502 }
503
504 static void childerror(struct hthead *req, int fd)
505 {
506     if(errno == EAGAIN)
507         simpleerror(fd, 500, "Server Error", "The request handler is overloaded.");
508     else
509         simpleerror(fd, 500, "Server Error", "The request handler crashed.");
510 }
511
512 static void serve(struct hthead *req, int fd)
513 {
514     struct match *match;
515     struct child *ch;
516     
517     match = NULL;
518     match = findmatch(lconfig, req, match);
519     if(gconfig != NULL)
520         match = findmatch(gconfig, req, match);
521     if(match == NULL) {
522         simpleerror(fd, 404, "Not Found", "The requested resource could not be found on this server.");
523         return;
524     }
525     ch = NULL;
526     if(ch == NULL)
527         ch = getchild(lconfig, match->pat->childnm);
528     if((ch == NULL) && (gconfig != NULL))
529         ch = getchild(gconfig, match->pat->childnm);
530     if(ch == NULL) {
531         flog(LOG_ERR, "child %s requested, but was not declared", match->pat->childnm);
532         simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", match->pat->childnm);
533         freematch(match);
534         return;
535     }
536     
537     execmatch(req, match);
538     if(childhandle(ch, req, fd, NULL, NULL))
539         childerror(req, fd);
540     freematch(match);
541 }
542
543 static void reloadconf(char *nm)
544 {
545     struct config *cf;
546     
547     if((cf = readconfig(nm)) == NULL) {
548         flog(LOG_WARNING, "could not reload configuration file `%s'", nm);
549         return;
550     }
551     mergechildren(cf->children, lconfig->children);
552     freeconfig(lconfig);
553     lconfig = cf;
554 }
555
556 static void chldhandler(int sig)
557 {
558     pid_t pid;
559     int st;
560     
561     while((pid = waitpid(-1, &st, WNOHANG)) > 0) {
562         if(WCOREDUMP(st))
563             flog(LOG_WARNING, "child process %i dumped core", pid);
564     }
565 }
566
567 static void sighandler(int sig)
568 {
569     if(sig == SIGHUP)
570         reload = 1;
571 }
572
573 static void usage(FILE *out)
574 {
575     fprintf(out, "usage: patplex [-hN] CONFIGFILE\n");
576 }
577
578 int main(int argc, char **argv)
579 {
580     int c;
581     int nodef;
582     char *gcf, *lcf;
583     struct hthead *req;
584     int fd;
585     
586     nodef = 0;
587     while((c = getopt(argc, argv, "hN")) >= 0) {
588         switch(c) {
589         case 'h':
590             usage(stdout);
591             exit(0);
592         case 'N':
593             nodef = 1;
594             break;
595         default:
596             usage(stderr);
597             exit(1);
598         }
599     }
600     if(argc - optind < 1) {
601         usage(stderr);
602         exit(1);
603     }
604     if(!nodef) {
605         if((gcf = findstdconf("ashd/patplex.rc")) != NULL) {
606             gconfig = readconfig(gcf);
607             free(gcf);
608         }
609     }
610     if((strchr(lcf = argv[optind], '/')) == NULL) {
611         if((lcf = findstdconf(sprintf3("ashd/%s", lcf))) == NULL) {
612             flog(LOG_ERR, "could not find requested configuration file `%s'", argv[optind]);
613             exit(1);
614         }
615     }
616     if((lconfig = readconfig(lcf)) == NULL) {
617         flog(LOG_ERR, "could not read `%s'", lcf);
618         exit(1);
619     }
620     signal(SIGCHLD, chldhandler);
621     signal(SIGHUP, sighandler);
622     signal(SIGPIPE, sighandler);
623     while(1) {
624         if(reload) {
625             reloadconf(lcf);
626             reload = 0;
627         }
628         if((fd = recvreq(0, &req)) < 0) {
629             if(errno == EINTR)
630                 continue;
631             if(errno != 0)
632                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
633             break;
634         }
635         serve(req, fd);
636         freehthead(req);
637         close(fd);
638     }
639     return(0);
640 }