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