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