htparser: Implemented resource limits for response headers as well.
[ashd.git] / src / htparser.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 <unistd.h>
21 #include <stdio.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <sys/socket.h>
25 #include <pwd.h>
26 #include <sys/signal.h>
27 #include <errno.h>
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32 #include <utils.h>
33 #include <mt.h>
34 #include <mtio.h>
35 #include <log.h>
36 #include <req.h>
37 #include <proc.h>
38
39 #include "htparser.h"
40
41 static int plex;
42 static char *pidfile = NULL;
43 static int daemonize, usesyslog;
44
45 static void trimx(struct hthead *req)
46 {
47     int i;
48     
49     i = 0;
50     while(i < req->noheaders) {
51         if(!strncasecmp(req->headers[i][0], "x-ash-", 6)) {
52             free(req->headers[i][0]);
53             free(req->headers[i][1]);
54             free(req->headers[i]);
55             memmove(req->headers + i, req->headers + i + 1, sizeof(*req->headers) * (--req->noheaders - i));
56         } else {
57             i++;
58         }
59     }
60 }
61
62 static struct hthead *parsereq(FILE *in)
63 {
64     struct hthead *req;
65     struct charbuf method, url, ver;
66     int c;
67     
68     req = NULL;
69     bufinit(method);
70     bufinit(url);
71     bufinit(ver);
72     while(1) {
73         c = getc(in);
74         if(c == ' ') {
75             break;
76         } else if((c == EOF) || (c < 32) || (c >= 128)) {
77             goto fail;
78         } else {
79             bufadd(method, c);
80             if(method.d >= 128)
81                 goto fail;
82         }
83     }
84     while(1) {
85         c = getc(in);
86         if(c == ' ') {
87             break;
88         } else if((c == EOF) || (c < 32)) {
89             goto fail;
90         } else {
91             bufadd(url, c);
92             if(url.d >= 65536)
93                 goto fail;
94         }
95     }
96     while(1) {
97         c = getc(in);
98         if(c == 10) {
99             break;
100         } else if(c == 13) {
101         } else if((c == EOF) || (c < 32) || (c >= 128)) {
102             goto fail;
103         } else {
104             bufadd(ver, c);
105             if(ver.d >= 128)
106                 goto fail;
107         }
108     }
109     bufadd(method, 0);
110     bufadd(url, 0);
111     bufadd(ver, 0);
112     req = mkreq(method.b, url.b, ver.b);
113     if(parseheaders(req, in))
114         goto fail;
115     trimx(req);
116     goto out;
117     
118 fail:
119     if(req != NULL) {
120         freehthead(req);
121         req = NULL;
122     }
123 out:
124     buffree(method);
125     buffree(url);
126     buffree(ver);
127     return(req);
128 }
129
130 static struct hthead *parseresp(FILE *in)
131 {
132     struct hthead *req;
133     int code;
134     struct charbuf ver, msg;
135     int c;
136     
137     req = NULL;
138     bufinit(ver);
139     bufinit(msg);
140     code = 0;
141     while(1) {
142         c = getc(in);
143         if(c == ' ') {
144             break;
145         } else if((c == EOF) || (c < 32) || (c >= 128)) {
146             goto fail;
147         } else {
148             bufadd(ver, c);
149             if(ver.d >= 128)
150                 goto fail;
151         }
152     }
153     while(1) {
154         c = getc(in);
155         if(c == ' ') {
156             break;
157         } else if((c == EOF) || (c < '0') || (c > '9')) {
158             goto fail;
159         } else {
160             code = (code * 10) + (c - '0');
161             if(code >= 10000)
162                 goto fail;
163         }
164     }
165     while(1) {
166         c = getc(in);
167         if(c == 10) {
168             break;
169         } else if(c == 13) {
170         } else if((c == EOF) || (c < 32)) {
171             goto fail;
172         } else {
173             bufadd(msg, c);
174             if(msg.d >= 512)
175                 goto fail;
176         }
177     }
178     bufadd(msg, 0);
179     bufadd(ver, 0);
180     req = mkresp(code, msg.b, ver.b);
181     if(parseheaders(req, in))
182         goto fail;
183     goto out;
184     
185 fail:
186     if(req != NULL) {
187         freehthead(req);
188         req = NULL;
189     }
190 out:
191     buffree(msg);
192     buffree(ver);
193     return(req);
194 }
195
196 static off_t passdata(FILE *in, FILE *out, off_t max)
197 {
198     size_t read;
199     off_t total;
200     char buf[8192];
201     
202     total = 0;
203     while(!feof(in) && ((max < 0) || (total < max))) {
204         read = sizeof(buf);
205         if(max >= 0)
206             read = min(max - total, read);
207         read = fread(buf, 1, read, in);
208         if(ferror(in))
209             return(-1);
210         if(fwrite(buf, 1, read, out) != read)
211             return(-1);
212         total += read;
213     }
214     return(total);
215 }
216
217 static int passchunks(FILE *in, FILE *out)
218 {
219     char buf[8192];
220     size_t read;
221     
222     do {
223         read = fread(buf, 1, sizeof(buf), in);
224         if(ferror(in))
225             return(-1);
226         fprintf(out, "%zx\r\n", read);
227         if(fwrite(buf, 1, read, out) != read)
228             return(-1);
229         fprintf(out, "\r\n");
230     } while(read > 0);
231     return(0);
232 }
233
234 static int hasheader(struct hthead *head, char *name, char *val)
235 {
236     char *hd;
237     
238     if((hd = getheader(head, name)) == NULL)
239         return(0);
240     return(!strcasecmp(hd, val));
241 }
242
243 void serve(FILE *in, struct conn *conn)
244 {
245     int pfds[2];
246     FILE *out;
247     struct hthead *req, *resp;
248     char *hd, *p;
249     off_t dlen;
250     
251     out = NULL;
252     req = resp = NULL;
253     while(1) {
254         if((req = parsereq(in)) == NULL)
255             break;
256         replrest(req, req->url);
257         if(req->rest[0] == '/')
258             replrest(req, req->rest + 1);
259         if((p = strchr(req->rest, '?')) != NULL)
260             *p = 0;
261         
262         if((conn->initreq != NULL) && conn->initreq(conn, req))
263             break;
264         
265         if(block(plex, EV_WRITE, 60) <= 0)
266             break;
267         if(socketpair(PF_UNIX, SOCK_STREAM, 0, pfds))
268             break;
269         if(sendreq(plex, req, pfds[0]))
270             break;
271         close(pfds[0]);
272         out = mtstdopen(pfds[1], 1, 600, "r+");
273
274         if((hd = getheader(req, "content-length")) != NULL) {
275             dlen = atoo(hd);
276             if(dlen > 0) {
277                 if(passdata(in, out, dlen) != dlen)
278                     break;
279             }
280         }
281         if(fflush(out))
282             break;
283         /* Make sure to send EOF */
284         shutdown(pfds[1], SHUT_WR);
285         
286         if((resp = parseresp(out)) == NULL)
287             break;
288         replstr(&resp->ver, req->ver);
289         
290         if(!getheader(resp, "server"))
291             headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
292
293         if(!strcmp(req->ver, "HTTP/1.0")) {
294             writeresp(in, resp);
295             fprintf(in, "\r\n");
296             if(!strcasecmp(req->method, "head")) {
297                 if(!hasheader(req, "connection", "keep-alive"))
298                     break;
299             } else if((hd = getheader(resp, "content-length")) != NULL) {
300                 dlen = atoo(hd);
301                 if(passdata(out, in, dlen) != dlen)
302                     break;
303                 if(!hasheader(req, "connection", "keep-alive"))
304                     break;
305             } else {
306                 passdata(out, in, -1);
307                 break;
308             }
309             if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
310                 break;
311         } else if(!strcmp(req->ver, "HTTP/1.1")) {
312             if(!strcasecmp(req->method, "head")) {
313                 writeresp(in, resp);
314                 fprintf(in, "\r\n");
315             } else if((hd = getheader(resp, "content-length")) != NULL) {
316                 writeresp(in, resp);
317                 fprintf(in, "\r\n");
318                 dlen = atoo(hd);
319                 if(passdata(out, in, dlen) != dlen)
320                     break;
321             } else if(!getheader(resp, "transfer-encoding")) {
322                 headappheader(resp, "Transfer-Encoding", "chunked");
323                 writeresp(in, resp);
324                 fprintf(in, "\r\n");
325                 if(passchunks(out, in))
326                     break;
327             } else {
328                 writeresp(in, resp);
329                 fprintf(in, "\r\n");
330                 passdata(out, in, -1);
331                 break;
332             }
333             if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
334                 break;
335         } else {
336             break;
337         }
338
339         fclose(out);
340         out = NULL;
341         freehthead(req);
342         freehthead(resp);
343         req = resp = NULL;
344     }
345     
346     if(out != NULL)
347         fclose(out);
348     if(req != NULL)
349         freehthead(req);
350     if(resp != NULL)
351         freehthead(resp);
352     fclose(in);
353 }
354
355 static void plexwatch(struct muth *muth, va_list args)
356 {
357     vavar(int, fd);
358     char *buf;
359     int ret;
360     
361     while(1) {
362         block(fd, EV_READ, 0);
363         buf = smalloc(65536);
364         ret = recv(fd, buf, 65536, 0);
365         if(ret < 0) {
366             flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
367             exit(1);
368         } else if(ret == 0) {
369             exit(0);
370         }
371         /* Maybe I'd like to implement some protocol in this direction
372          * some day... */
373         free(buf);
374     }
375 }
376
377 static void initroot(void *uu)
378 {
379     int fd;
380     
381     if(daemonize) {
382         setsid();
383         chdir("/");
384         if((fd = open("/dev/null", O_RDWR)) >= 0) {
385             dup2(fd, 0);
386             dup2(fd, 1);
387             dup2(fd, 2);
388             close(fd);
389         }
390     }
391     if(usesyslog)
392         putenv("ASHD_USESYSLOG=1");
393     else
394         unsetenv("ASHD_USESYSLOG");
395 }
396
397 static void usage(FILE *out)
398 {
399     fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
400     fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
401     fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
402 }
403
404 static void addport(char *spec)
405 {
406     char *nm, *p, *p2, *n;
407     struct charvbuf pars, vals;
408     
409     bufinit(pars);
410     bufinit(vals);
411     if((p = strchr(spec, ':')) == NULL) {
412         nm = spec;
413     } else {
414         nm = spec;
415         *(p++) = 0;
416         do {
417             if((n = strchr(p, ',')) != NULL)
418                 *(n++) = 0;
419             if((p2 = strchr(p, '=')) != NULL)
420                 *(p2++) = 0;
421             if(!*p) {
422                 usage(stderr);
423                 exit(1);
424             }
425             bufadd(pars, p);
426             if(p2)
427                 bufadd(vals, p2);
428             else
429                 bufadd(vals, "");
430         } while((p = n) != NULL);
431     }
432     
433     /* XXX: It would be nice to decentralize this, but, meh... */
434     if(!strcmp(nm, "plain")) {
435         handleplain(pars.d, pars.b, vals.b);
436 #ifdef HAVE_GNUTLS
437     } else if(!strcmp(nm, "ssl")) {
438         handlegnussl(pars.d, pars.b, vals.b);
439 #endif
440     } else {
441         flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
442         exit(1);
443     }
444     
445     buffree(pars);
446     buffree(vals);
447 }
448
449 int main(int argc, char **argv)
450 {
451     int c;
452     int i, s1;
453     char *root;
454     FILE *pidout;
455     struct passwd *pwent;
456     
457     daemonize = usesyslog = 0;
458     root = NULL;
459     pwent = NULL;
460     while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
461         switch(c) {
462         case 'h':
463             usage(stdout);
464             exit(0);
465         case 'f':
466             daemonize = 1;
467             break;
468         case 'S':
469             usesyslog = 1;
470             break;
471         case 'u':
472             if((pwent = getpwnam(optarg)) == NULL) {
473                 flog(LOG_ERR, "could not find user %s", optarg);
474                 exit(1);
475             }
476             break;
477         case 'r':
478             root = optarg;
479             break;
480         case 'p':
481             pidfile = optarg;
482             break;
483         default:
484             usage(stderr);
485             exit(1);
486         }
487     }
488     s1 = 0;
489     for(i = optind; i < argc; i++) {
490         if(!strcmp(argv[i], "--"))
491             break;
492         s1 = 1;
493         addport(argv[i]);
494     }
495     if(!s1 || (i == argc)) {
496         usage(stderr);
497         exit(1);
498     }
499     if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
500         flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
501         return(1);
502     }
503     mustart(plexwatch, plex);
504     pidout = NULL;
505     if(pidfile != NULL) {
506         if((pidout = fopen(pidfile, "w")) == NULL) {
507             flog(LOG_ERR, "could not open %s for writing: %s", pidfile, strerror(errno));
508             return(1);
509         }
510     }
511     if(usesyslog)
512         opensyslog();
513     if(root) {
514         if(chdir(root) || chroot(root)) {
515             flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
516             exit(1);
517         }
518     }
519     if(pwent) {
520         if(setgid(pwent->pw_gid)) {
521             flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
522             exit(1);
523         }
524         if(setuid(pwent->pw_uid)) {
525             flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
526             exit(1);
527         }
528     }
529     signal(SIGPIPE, SIG_IGN);
530     if(daemonize) {
531         daemon(0, 0);
532     }
533     if(pidout != NULL) {
534         fprintf(pidout, "%i\n", getpid());
535         fclose(pidout);
536     }
537     ioloop();
538     return(0);
539 }