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