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