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