htparser: Support chunked request-bodies.
[ashd.git] / src / htparser.c
... / ...
CommitLineData
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
41static int plex;
42static char *pidfile = NULL;
43static int daemonize, usesyslog;
44
45static 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
62static 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
118fail:
119 if(req != NULL) {
120 freehthead(req);
121 req = NULL;
122 }
123out:
124 buffree(method);
125 buffree(url);
126 buffree(ver);
127 return(req);
128}
129
130static off_t passdata(FILE *in, FILE *out, off_t max)
131{
132 size_t read;
133 off_t total;
134 char buf[8192];
135
136 total = 0;
137 while(!feof(in) && ((max < 0) || (total < max))) {
138 read = sizeof(buf);
139 if(max >= 0)
140 read = min(max - total, read);
141 read = fread(buf, 1, read, in);
142 if(ferror(in))
143 return(-1);
144 if(fwrite(buf, 1, read, out) != read)
145 return(-1);
146 total += read;
147 }
148 return(total);
149}
150
151static int recvchunks(FILE *in, FILE *out)
152{
153 char buf[8192];
154 size_t read, chlen;
155 int c, r;
156
157 while(1) {
158 chlen = 0;
159 r = 0;
160 while(1) {
161 c = getc(in);
162 if(c == 10) {
163 if(!r)
164 return(-1);
165 break;
166 } else if(c == 13) {
167 } else if((c >= '0') && (c <= '9')) {
168 chlen = (chlen << 4) + (c - '0');
169 r = 1;
170 } else if((c >= 'A') && (c <= 'F')) {
171 chlen = (chlen << 4) + (c + 10 - 'A');
172 r = 1;
173 } else if((c >= 'a') && (c <= 'f')) {
174 chlen = (chlen << 4) + (c + 10 - 'a');
175 r = 1;
176 } else {
177 /* XXX: Technically, there may be chunk extensions to
178 * be read, but since that will likely never actually
179 * happen in practice, I can just as well add support
180 * for that if it actually does become relevant. */
181 return(-1);
182 }
183 }
184 if(chlen == 0)
185 break;
186 while(chlen > 0) {
187 read = fread(buf, 1, min(sizeof(buf), chlen), in);
188 if(feof(in) || ferror(in))
189 return(-1);
190 if(fwrite(buf, 1, read, out) != read)
191 return(-1);
192 chlen -= read;
193 }
194 if((getc(in) != 13) || (getc(in) != 10))
195 return(-1);
196 }
197 /* XXX: Technically, there may be trailers to be read, but that's
198 * just about as likely as chunk extensions. */
199 if((getc(in) != 13) || (getc(in) != 10))
200 return(-1);
201 return(0);
202}
203
204static int passchunks(FILE *in, FILE *out)
205{
206 char buf[8192];
207 size_t read;
208
209 do {
210 read = fread(buf, 1, sizeof(buf), in);
211 if(ferror(in))
212 return(-1);
213 fprintf(out, "%zx\r\n", read);
214 if(fwrite(buf, 1, read, out) != read)
215 return(-1);
216 fprintf(out, "\r\n");
217 } while(read > 0);
218 return(0);
219}
220
221static int hasheader(struct hthead *head, char *name, char *val)
222{
223 char *hd;
224
225 if((hd = getheader(head, name)) == NULL)
226 return(0);
227 return(!strcasecmp(hd, val));
228}
229
230static int canonreq(struct hthead *req)
231{
232 char *p, *p2, *r;
233 int n;
234
235 if(req->url[0] == '/') {
236 replrest(req, req->url + 1);
237 if((p = strchr(req->rest, '?')) != NULL)
238 *p = 0;
239 return(1);
240 }
241 if((p = strstr(req->url, "://")) != NULL) {
242 n = p - req->url;
243 if(((n == 4) && !strncasecmp(req->url, "http", 4)) ||
244 ((n == 5) && !strncasecmp(req->url, "https", 5))) {
245 if(getheader(req, "host"))
246 return(0);
247 p += 3;
248 if((p2 = strchr(p, '/')) == NULL) {
249 headappheader(req, "Host", p);
250 free(req->url);
251 req->url = sstrdup("/");
252 } else {
253 r = sstrdup(p2);
254 *(p2++) = 0;
255 headappheader(req, "Host", p);
256 free(req->url);
257 req->url = r;
258 }
259 replrest(req, req->url + 1);
260 if((p = strchr(req->rest, '?')) != NULL)
261 *p = 0;
262 return(1);
263 }
264 }
265 return(0);
266}
267
268static int http10keep(struct hthead *req, struct hthead *resp)
269{
270 int fc;
271
272 fc = hasheader(resp, "connection", "close");
273 headrmheader(resp, "connection");
274 if(!fc && hasheader(req, "connection", "keep-alive")) {
275 headappheader(resp, "Connection", "Keep-Alive");
276 return(1);
277 } else {
278 return(0);
279 }
280}
281
282void serve(FILE *in, struct conn *conn)
283{
284 int pfds[2];
285 FILE *out;
286 struct hthead *req, *resp;
287 char *hd;
288 off_t dlen;
289 int keep;
290
291 out = NULL;
292 req = resp = NULL;
293 while(1) {
294 if((req = parsereq(in)) == NULL)
295 break;
296 if(!canonreq(req))
297 break;
298
299 if((conn->initreq != NULL) && conn->initreq(conn, req))
300 break;
301
302 if(block(plex, EV_WRITE, 60) <= 0)
303 break;
304 if(socketpair(PF_UNIX, SOCK_STREAM, 0, pfds))
305 break;
306 if(sendreq(plex, req, pfds[0]))
307 break;
308 close(pfds[0]);
309 out = mtstdopen(pfds[1], 1, 600, "r+");
310
311 if(getheader(req, "content-type") != NULL) {
312 if((hd = getheader(req, "content-length")) != NULL) {
313 dlen = atoo(hd);
314 if(dlen > 0) {
315 if(passdata(in, out, dlen) != dlen)
316 break;
317 }
318 } else if(((hd = getheader(req, "transfer-encoding")) != NULL) && !strcasecmp(hd, "chunked")) {
319 if(recvchunks(in, out))
320 break;
321 } else {
322 break;
323 }
324 }
325 if(fflush(out))
326 break;
327 /* Make sure to send EOF */
328 shutdown(pfds[1], SHUT_WR);
329
330 if((resp = parseresponse(out)) == NULL)
331 break;
332 replstr(&resp->ver, req->ver);
333
334 if(!getheader(resp, "server"))
335 headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
336
337 if(!strcasecmp(req->ver, "HTTP/1.0")) {
338 if(!strcasecmp(req->method, "head")) {
339 keep = http10keep(req, resp);
340 writeresp(in, resp);
341 fprintf(in, "\r\n");
342 } else if((hd = getheader(resp, "content-length")) != NULL) {
343 keep = http10keep(req, resp);
344 dlen = atoo(hd);
345 writeresp(in, resp);
346 fprintf(in, "\r\n");
347 if(passdata(out, in, dlen) != dlen)
348 break;
349 } else {
350 headrmheader(resp, "connection");
351 writeresp(in, resp);
352 fprintf(in, "\r\n");
353 passdata(out, in, -1);
354 break;
355 }
356 if(!keep)
357 break;
358 } else if(!strcasecmp(req->ver, "HTTP/1.1")) {
359 if(!strcasecmp(req->method, "head")) {
360 writeresp(in, resp);
361 fprintf(in, "\r\n");
362 } else if((hd = getheader(resp, "content-length")) != NULL) {
363 writeresp(in, resp);
364 fprintf(in, "\r\n");
365 dlen = atoo(hd);
366 if(passdata(out, in, dlen) != dlen)
367 break;
368 } else if(!getheader(resp, "transfer-encoding")) {
369 headappheader(resp, "Transfer-Encoding", "chunked");
370 writeresp(in, resp);
371 fprintf(in, "\r\n");
372 if(passchunks(out, in))
373 break;
374 } else {
375 writeresp(in, resp);
376 fprintf(in, "\r\n");
377 passdata(out, in, -1);
378 break;
379 }
380 if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
381 break;
382 } else {
383 break;
384 }
385
386 fclose(out);
387 out = NULL;
388 freehthead(req);
389 freehthead(resp);
390 req = resp = NULL;
391 }
392
393 if(out != NULL)
394 fclose(out);
395 if(req != NULL)
396 freehthead(req);
397 if(resp != NULL)
398 freehthead(resp);
399 fclose(in);
400}
401
402static void plexwatch(struct muth *muth, va_list args)
403{
404 vavar(int, fd);
405 char *buf;
406 int ret;
407
408 while(1) {
409 block(fd, EV_READ, 0);
410 buf = smalloc(65536);
411 ret = recv(fd, buf, 65536, 0);
412 if(ret < 0) {
413 flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
414 exit(1);
415 } else if(ret == 0) {
416 exit(0);
417 }
418 /* Maybe I'd like to implement some protocol in this direction
419 * some day... */
420 free(buf);
421 }
422}
423
424static void initroot(void *uu)
425{
426 int fd;
427
428 if(daemonize) {
429 setsid();
430 chdir("/");
431 if((fd = open("/dev/null", O_RDWR)) >= 0) {
432 dup2(fd, 0);
433 dup2(fd, 1);
434 dup2(fd, 2);
435 close(fd);
436 }
437 }
438 if(usesyslog)
439 putenv("ASHD_USESYSLOG=1");
440 else
441 unsetenv("ASHD_USESYSLOG");
442}
443
444static void usage(FILE *out)
445{
446 fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
447 fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
448 fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
449}
450
451static void addport(char *spec)
452{
453 char *nm, *p, *p2, *n;
454 struct charvbuf pars, vals;
455
456 bufinit(pars);
457 bufinit(vals);
458 if((p = strchr(spec, ':')) == NULL) {
459 nm = spec;
460 } else {
461 nm = spec;
462 *(p++) = 0;
463 do {
464 if((n = strchr(p, ',')) != NULL)
465 *(n++) = 0;
466 if((p2 = strchr(p, '=')) != NULL)
467 *(p2++) = 0;
468 if(!*p) {
469 usage(stderr);
470 exit(1);
471 }
472 bufadd(pars, p);
473 if(p2)
474 bufadd(vals, p2);
475 else
476 bufadd(vals, "");
477 } while((p = n) != NULL);
478 }
479
480 /* XXX: It would be nice to decentralize this, but, meh... */
481 if(!strcmp(nm, "plain")) {
482 handleplain(pars.d, pars.b, vals.b);
483#ifdef HAVE_GNUTLS
484 } else if(!strcmp(nm, "ssl")) {
485 handlegnussl(pars.d, pars.b, vals.b);
486#endif
487 } else {
488 flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
489 exit(1);
490 }
491
492 buffree(pars);
493 buffree(vals);
494}
495
496int main(int argc, char **argv)
497{
498 int c;
499 int i, s1;
500 char *root;
501 FILE *pidout;
502 struct passwd *pwent;
503
504 daemonize = usesyslog = 0;
505 root = NULL;
506 pwent = NULL;
507 while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
508 switch(c) {
509 case 'h':
510 usage(stdout);
511 exit(0);
512 case 'f':
513 daemonize = 1;
514 break;
515 case 'S':
516 usesyslog = 1;
517 break;
518 case 'u':
519 if((pwent = getpwnam(optarg)) == NULL) {
520 flog(LOG_ERR, "could not find user %s", optarg);
521 exit(1);
522 }
523 break;
524 case 'r':
525 root = optarg;
526 break;
527 case 'p':
528 pidfile = optarg;
529 break;
530 default:
531 usage(stderr);
532 exit(1);
533 }
534 }
535 s1 = 0;
536 for(i = optind; i < argc; i++) {
537 if(!strcmp(argv[i], "--"))
538 break;
539 s1 = 1;
540 addport(argv[i]);
541 }
542 if(!s1 || (i == argc)) {
543 usage(stderr);
544 exit(1);
545 }
546 if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
547 flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
548 return(1);
549 }
550 mustart(plexwatch, plex);
551 pidout = NULL;
552 if(pidfile != NULL) {
553 if((pidout = fopen(pidfile, "w")) == NULL) {
554 flog(LOG_ERR, "could not open %s for writing: %s", pidfile, strerror(errno));
555 return(1);
556 }
557 }
558 if(usesyslog)
559 opensyslog();
560 if(root) {
561 if(chdir(root) || chroot(root)) {
562 flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
563 exit(1);
564 }
565 }
566 if(pwent) {
567 if(setgid(pwent->pw_gid)) {
568 flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
569 exit(1);
570 }
571 if(setuid(pwent->pw_uid)) {
572 flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
573 exit(1);
574 }
575 }
576 signal(SIGPIPE, SIG_IGN);
577 if(daemonize) {
578 daemon(0, 0);
579 }
580 if(pidout != NULL) {
581 fprintf(pidout, "%i\n", getpid());
582 fclose(pidout);
583 }
584 ioloop();
585 return(0);
586}