patplex: Fixed regex compilation bug.
[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     } else {
387         for(i = 0; pstr[i]; i++) {
388             buf[i] = pstr[i];
389             obuf[i] = i;
390         }
391         buf[i] = 0;
392     }
393 }
394
395 static struct pattern *findmatch(struct config *cf, struct hthead *req, int trydefault)
396 {
397     int i, o;
398     struct pattern *pat;
399     struct rule *rule;
400     int rmo;
401     regex_t *rx;
402     char *pstr;
403     char **mstr;
404     regmatch_t gr[10];
405     
406     mstr = NULL;
407     for(pat = cf->patterns; pat != NULL; pat = pat->next) {
408         rmo = -1;
409         for(i = 0; (rule = pat->rules[i]) != NULL; i++) {
410             rx = NULL;
411             if(rule->type == PAT_REST) {
412                 rx = rule->pattern;
413                 pstr = req->rest;
414             } else if(rule->type == PAT_URL) {
415                 rx = rule->pattern;
416                 pstr = req->url;
417             } else if(rule->type == PAT_METHOD) {
418                 rx = rule->pattern;
419                 pstr = req->method;
420             } else if(rule->type == PAT_HEADER) {
421                 rx = rule->pattern;
422                 if(!(pstr = getheader(req, rule->header)))
423                     break;
424             }
425             if(rx != NULL) {
426                 char pbuf[strlen(pstr) + 1];
427                 int  obuf[strlen(pstr) + 1];
428                 qoffsets(pbuf, obuf, pstr, !!(rule->fl & PATFL_UNQ));
429                 if(regexec(rx, pbuf, 10, gr, 0))
430                     break;
431                 else if(rule->type == PAT_REST)
432                     rmo = obuf[gr[0].rm_eo];
433                 if(rule->fl & PATFL_MSS) {
434                     if(mstr) {
435                         flog(LOG_WARNING, "two pattern rules marked with `s' flag found (for handler %s)", pat->childnm);
436                         freeca(mstr);
437                     }
438                     for(o = 0; o < 10; o++) {
439                         if(gr[o].rm_so < 0)
440                             break;
441                     }
442                     mstr = szmalloc((o + 1) * sizeof(*mstr));
443                     for(o = 0; o < 10; o++) {
444                         if(gr[o].rm_so < 0)
445                             break;
446                         mstr[o] = smalloc(obuf[gr[o].rm_eo] - obuf[gr[o].rm_so] + 1);
447                         memcpy(mstr[o], pstr + obuf[gr[o].rm_so], obuf[gr[o].rm_eo] - obuf[gr[o].rm_so]);
448                         mstr[o][obuf[gr[o].rm_eo] - obuf[gr[o].rm_so]] = 0;
449                     }
450                 }
451             } else if(rule->type == PAT_ALL) {
452             } else if(rule->type == PAT_DEFAULT) {
453                 if(!trydefault)
454                     break;
455             }
456         }
457         if(!rule) {
458             if(pat->restpat) {
459                 exprestpat(req, pat, mstr);
460             } else if(rmo != -1) {
461                 replrest(req, req->rest + rmo);
462             }
463             if(mstr)
464                 freeca(mstr);
465             return(pat);
466         }
467         if(mstr) {
468             freeca(mstr);
469             mstr = NULL;
470         }
471     }
472     return(NULL);
473 }
474
475 static void serve(struct hthead *req, int fd)
476 {
477     struct pattern *pat;
478     struct headmod *head;
479     struct child *ch;
480     
481     pat = NULL;
482     if(pat == NULL)
483         pat = findmatch(lconfig, req, 0);
484     if(pat == NULL)
485         pat = findmatch(lconfig, req, 1);
486     if(gconfig != NULL) {
487         if(pat == NULL)
488             pat = findmatch(gconfig, req, 0);
489         if(pat == NULL)
490             pat = findmatch(gconfig, req, 1);
491     }
492     if(pat == NULL) {
493         simpleerror(fd, 404, "Not Found", "The requested resource could not be found on this server.");
494         return;
495     }
496     ch = NULL;
497     if(ch == NULL)
498         ch = getchild(lconfig, pat->childnm);
499     if(gconfig != NULL) {
500         if(ch == NULL)
501             ch = getchild(gconfig, pat->childnm);
502     }
503     if(ch == NULL) {
504         flog(LOG_ERR, "child %s requested, but was not declared", pat->childnm);
505         simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", pat->childnm);
506         return;
507     }
508     
509     for(head = pat->headers; head != NULL; head = head->next) {
510         headrmheader(req, head->name);
511         headappheader(req, head->name, head->value);
512     }
513     if(childhandle(ch, req, fd, NULL, NULL))
514         simpleerror(fd, 500, "Server Error", "The request handler crashed.");
515 }
516
517 static void reloadconf(char *nm)
518 {
519     struct config *cf;
520     
521     if((cf = readconfig(nm)) == NULL) {
522         flog(LOG_WARNING, "could not reload configuration file `%s'", nm);
523         return;
524     }
525     mergechildren(cf->children, lconfig->children);
526     freeconfig(lconfig);
527     lconfig = cf;
528 }
529
530 static void chldhandler(int sig)
531 {
532     pid_t pid;
533     int st;
534     
535     while((pid = waitpid(-1, &st, WNOHANG)) > 0) {
536         if(WCOREDUMP(st))
537             flog(LOG_WARNING, "child process %i dumped core", pid);
538     }
539 }
540
541 static void sighandler(int sig)
542 {
543     if(sig == SIGHUP)
544         reload = 1;
545 }
546
547 static void usage(FILE *out)
548 {
549     fprintf(out, "usage: patplex [-hN] CONFIGFILE\n");
550 }
551
552 int main(int argc, char **argv)
553 {
554     int c;
555     int nodef;
556     char *gcf, *lcf;
557     struct hthead *req;
558     int fd;
559     
560     nodef = 0;
561     while((c = getopt(argc, argv, "hN")) >= 0) {
562         switch(c) {
563         case 'h':
564             usage(stdout);
565             exit(0);
566         case 'N':
567             nodef = 1;
568             break;
569         default:
570             usage(stderr);
571             exit(1);
572         }
573     }
574     if(argc - optind < 1) {
575         usage(stderr);
576         exit(1);
577     }
578     if(!nodef) {
579         if((gcf = findstdconf("ashd/patplex.rc")) != NULL) {
580             gconfig = readconfig(gcf);
581             free(gcf);
582         }
583     }
584     if((strchr(lcf = argv[optind], '/')) == NULL) {
585         if((lcf = findstdconf(sprintf3("ashd/%s", lcf))) == NULL) {
586             flog(LOG_ERR, "could not find requested configuration file `%s'", argv[optind]);
587             exit(1);
588         }
589     }
590     if((lconfig = readconfig(lcf)) == NULL) {
591         flog(LOG_ERR, "could not read `%s'", lcf);
592         exit(1);
593     }
594     signal(SIGCHLD, chldhandler);
595     signal(SIGHUP, sighandler);
596     signal(SIGPIPE, sighandler);
597     while(1) {
598         if(reload) {
599             reloadconf(lcf);
600             reload = 0;
601         }
602         if((fd = recvreq(0, &req)) < 0) {
603             if(errno == EINTR)
604                 continue;
605             if(errno != 0)
606                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
607             break;
608         }
609         serve(req, fd);
610         freehthead(req);
611         close(fd);
612     }
613     return(0);
614 }