lib: Allow reception of mtstdopen info structure.
[ashd.git] / src / htparser.c
CommitLineData
f0bbedf7
FT
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>
d341283f 22#include <fcntl.h>
f4cdf919 23#include <string.h>
f4cdf919 24#include <sys/socket.h>
f0cbd8d7 25#include <pwd.h>
15fa3fe8 26#include <sys/signal.h>
f4cdf919 27#include <errno.h>
f0bbedf7
FT
28
29#ifdef HAVE_CONFIG_H
30#include <config.h>
31#endif
32#include <utils.h>
f4cdf919 33#include <mt.h>
83723896 34#include <mtio.h>
f4cdf919 35#include <log.h>
66987955 36#include <req.h>
9d87a119 37#include <proc.h>
f4cdf919 38
8774c31b 39#include "htparser.h"
f4cdf919 40
8774c31b 41static int plex;
43c58ba2 42static char *pidfile = NULL;
d341283f 43static int daemonize, usesyslog;
cac13158 44struct mtbuf listeners;
f4cdf919 45
df431d1d
FT
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
5fc1bf9f 63static struct hthead *parsereq(FILE *in)
66987955 64{
5fc1bf9f
FT
65 struct hthead *req;
66 struct charbuf method, url, ver;
67 int c;
66987955 68
5fc1bf9f
FT
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);
90b0ba0f
FT
81 if(method.d >= 128)
82 goto fail;
66987955 83 }
c9955b14 84 }
c9955b14 85 while(1) {
5fc1bf9f
FT
86 c = getc(in);
87 if(c == ' ') {
c9955b14 88 break;
5fc1bf9f
FT
89 } else if((c == EOF) || (c < 32)) {
90 goto fail;
91 } else {
92 bufadd(url, c);
90b0ba0f
FT
93 if(url.d >= 65536)
94 goto fail;
66987955
FT
95 }
96 }
66987955 97 while(1) {
5fc1bf9f
FT
98 c = getc(in);
99 if(c == 10) {
66987955 100 break;
5fc1bf9f
FT
101 } else if(c == 13) {
102 } else if((c == EOF) || (c < 32) || (c >= 128)) {
c9955b14 103 goto fail;
5fc1bf9f
FT
104 } else {
105 bufadd(ver, c);
90b0ba0f
FT
106 if(ver.d >= 128)
107 goto fail;
5fc1bf9f 108 }
66987955 109 }
5fc1bf9f
FT
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;
df431d1d 116 trimx(req);
5fc1bf9f 117 goto out;
c9955b14
FT
118
119fail:
5fc1bf9f
FT
120 if(req != NULL) {
121 freehthead(req);
122 req = NULL;
123 }
124out:
125 buffree(method);
126 buffree(url);
127 buffree(ver);
128 return(req);
66987955
FT
129}
130
5fc1bf9f 131static off_t passdata(FILE *in, FILE *out, off_t max)
9d87a119 132{
5fc1bf9f
FT
133 size_t read;
134 off_t total;
135 char buf[8192];
136
137 total = 0;
f9255ddd 138 while(!feof(in) && ((max < 0) || (total < max))) {
5fc1bf9f
FT
139 read = sizeof(buf);
140 if(max >= 0)
a701d7b7 141 read = min(max - total, read);
5fc1bf9f
FT
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;
9d87a119 148 }
5fc1bf9f
FT
149 return(total);
150}
151
8d19a9ec
FT
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
5fc1bf9f
FT
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);
f9255ddd 214 fprintf(out, "%zx\r\n", read);
5fc1bf9f
FT
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));
9d87a119
FT
229}
230
64a9096a
FT
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
75bb20c8
FT
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
43066106
FT
283static char *connid(void)
284{
285 static struct charbuf cur;
286 int i;
287 char *ret;
288
289 for(i = 0; i < cur.d; i++) {
290 if((++cur.b[i]) > 'Z')
291 cur.b[i] = 'A';
292 else
293 goto done;
294 }
295 bufadd(cur, 'A');
296done:
297 ret = memcpy(smalloc(cur.d + 1), cur.b, cur.d);
298 ret[cur.d] = 0;
299 return(ret);
300}
301
8774c31b 302void serve(FILE *in, struct conn *conn)
66987955 303{
af34331c 304 int pfds[2];
8774c31b 305 FILE *out;
9d87a119 306 struct hthead *req, *resp;
43066106 307 char *hd, *id;
5fc1bf9f 308 off_t dlen;
75bb20c8 309 int keep;
66987955 310
43066106 311 id = connid();
5fc1bf9f 312 out = NULL;
3c296bd4 313 req = resp = NULL;
cac13158 314 while(plex >= 0) {
5fc1bf9f
FT
315 if((req = parsereq(in)) == NULL)
316 break;
64a9096a
FT
317 if(!canonreq(req))
318 break;
9d87a119 319
43066106 320 headappheader(req, "X-Ash-Connection-ID", id);
8774c31b
FT
321 if((conn->initreq != NULL) && conn->initreq(conn, req))
322 break;
323
cac13158 324 if((plex < 0) || block(plex, EV_WRITE, 60) <= 0)
5fc1bf9f 325 break;
af34331c 326 if(socketpair(PF_UNIX, SOCK_STREAM, 0, pfds))
5fc1bf9f 327 break;
af34331c 328 if(sendreq(plex, req, pfds[0]))
5fc1bf9f 329 break;
af34331c 330 close(pfds[0]);
b71ad67f 331 out = mtstdopen(pfds[1], 1, 600, "r+", NULL);
a0327573 332
8d19a9ec
FT
333 if(getheader(req, "content-type") != NULL) {
334 if((hd = getheader(req, "content-length")) != NULL) {
335 dlen = atoo(hd);
336 if(dlen > 0) {
337 if(passdata(in, out, dlen) != dlen)
338 break;
339 }
340 } else if(((hd = getheader(req, "transfer-encoding")) != NULL) && !strcasecmp(hd, "chunked")) {
341 if(recvchunks(in, out))
5fc1bf9f 342 break;
8d19a9ec 343 } else {
2dbb9937
FT
344 /* Ignore rather than abort, to be kinder to broken clients. */
345 headrmheader(req, "content-type");
a06a2fbd 346 }
a0327573 347 }
5fc1bf9f
FT
348 if(fflush(out))
349 break;
d93d9a05 350 /* Make sure to send EOF */
5fc1bf9f 351 shutdown(pfds[1], SHUT_WR);
9d87a119 352
3ef78895 353 if((resp = parseresponse(out)) == NULL)
f9255ddd 354 break;
5fc1bf9f 355 replstr(&resp->ver, req->ver);
1c3e0167
FT
356
357 if(!getheader(resp, "server"))
358 headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
5fc1bf9f 359
cefb0f7a 360 if(!strcasecmp(req->ver, "HTTP/1.0")) {
18fb436d 361 if(!strcasecmp(req->method, "head")) {
75bb20c8
FT
362 keep = http10keep(req, resp);
363 writeresp(in, resp);
364 fprintf(in, "\r\n");
18fb436d 365 } else if((hd = getheader(resp, "content-length")) != NULL) {
75bb20c8 366 keep = http10keep(req, resp);
5226f7c5 367 dlen = atoo(hd);
75bb20c8
FT
368 writeresp(in, resp);
369 fprintf(in, "\r\n");
5226f7c5 370 if(passdata(out, in, dlen) != dlen)
5fc1bf9f 371 break;
5fc1bf9f 372 } else {
75bb20c8
FT
373 headrmheader(resp, "connection");
374 writeresp(in, resp);
375 fprintf(in, "\r\n");
5fc1bf9f
FT
376 passdata(out, in, -1);
377 break;
9d87a119 378 }
75bb20c8 379 if(!keep)
5fc1bf9f 380 break;
cefb0f7a 381 } else if(!strcasecmp(req->ver, "HTTP/1.1")) {
18fb436d
FT
382 if(!strcasecmp(req->method, "head")) {
383 writeresp(in, resp);
384 fprintf(in, "\r\n");
385 } else if((hd = getheader(resp, "content-length")) != NULL) {
5fc1bf9f
FT
386 writeresp(in, resp);
387 fprintf(in, "\r\n");
5226f7c5
FT
388 dlen = atoo(hd);
389 if(passdata(out, in, dlen) != dlen)
5fc1bf9f
FT
390 break;
391 } else if(!getheader(resp, "transfer-encoding")) {
392 headappheader(resp, "Transfer-Encoding", "chunked");
393 writeresp(in, resp);
394 fprintf(in, "\r\n");
395 if(passchunks(out, in))
396 break;
397 } else {
398 writeresp(in, resp);
399 fprintf(in, "\r\n");
400 passdata(out, in, -1);
9d87a119 401 break;
5fc1bf9f
FT
402 }
403 if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
9d87a119 404 break;
5fc1bf9f
FT
405 } else {
406 break;
9d87a119 407 }
5fc1bf9f
FT
408
409 fclose(out);
410 out = NULL;
9d87a119 411 freehthead(req);
9d87a119 412 freehthead(resp);
5fc1bf9f 413 req = resp = NULL;
66987955
FT
414 }
415
5fc1bf9f
FT
416 if(out != NULL)
417 fclose(out);
9d87a119
FT
418 if(req != NULL)
419 freehthead(req);
420 if(resp != NULL)
421 freehthead(resp);
5fc1bf9f 422 fclose(in);
43066106 423 free(id);
66987955
FT
424}
425
32e24c19
FT
426static void plexwatch(struct muth *muth, va_list args)
427{
428 vavar(int, fd);
429 char *buf;
4139016c 430 int i, s, ret;
32e24c19 431
4139016c 432 s = 0;
32e24c19 433 while(1) {
cac13158
FT
434 if(block(fd, EV_READ, 0) == 0)
435 break;
32e24c19
FT
436 buf = smalloc(65536);
437 ret = recv(fd, buf, 65536, 0);
438 if(ret < 0) {
439 flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
440 exit(1);
441 } else if(ret == 0) {
4139016c 442 s = 1;
8e9ec020
FT
443 free(buf);
444 break;
32e24c19
FT
445 }
446 /* Maybe I'd like to implement some protocol in this direction
447 * some day... */
448 free(buf);
449 }
ecd4208b 450 shutdown(plex, SHUT_RDWR);
8e9ec020
FT
451 for(i = 0; i < listeners.d; i++) {
452 if(listeners.b[i] == muth)
453 bufdel(listeners, i);
454 }
4139016c
FT
455 if(s) {
456 flog(LOG_INFO, "root handler exited, so shutting down listening...");
457 while(listeners.d > 0)
458 resume(listeners.b[0], 0);
459 }
32e24c19
FT
460}
461
d341283f
FT
462static void initroot(void *uu)
463{
464 int fd;
465
cf91aa53 466 setsid();
d341283f 467 if(daemonize) {
d341283f
FT
468 chdir("/");
469 if((fd = open("/dev/null", O_RDWR)) >= 0) {
470 dup2(fd, 0);
471 dup2(fd, 1);
472 dup2(fd, 2);
473 close(fd);
474 }
475 }
476 if(usesyslog)
477 putenv("ASHD_USESYSLOG=1");
478 else
479 unsetenv("ASHD_USESYSLOG");
480}
481
8774c31b
FT
482static void usage(FILE *out)
483{
43c58ba2 484 fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
8774c31b 485 fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
6ca53b2e 486 fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
8774c31b
FT
487}
488
489static void addport(char *spec)
490{
491 char *nm, *p, *p2, *n;
492 struct charvbuf pars, vals;
493
494 bufinit(pars);
495 bufinit(vals);
496 if((p = strchr(spec, ':')) == NULL) {
497 nm = spec;
498 } else {
499 nm = spec;
500 *(p++) = 0;
501 do {
502 if((n = strchr(p, ',')) != NULL)
503 *(n++) = 0;
504 if((p2 = strchr(p, '=')) != NULL)
505 *(p2++) = 0;
506 if(!*p) {
507 usage(stderr);
508 exit(1);
509 }
510 bufadd(pars, p);
511 if(p2)
512 bufadd(vals, p2);
513 else
514 bufadd(vals, "");
515 } while((p = n) != NULL);
516 }
517
518 /* XXX: It would be nice to decentralize this, but, meh... */
519 if(!strcmp(nm, "plain")) {
520 handleplain(pars.d, pars.b, vals.b);
6ca53b2e
FT
521#ifdef HAVE_GNUTLS
522 } else if(!strcmp(nm, "ssl")) {
523 handlegnussl(pars.d, pars.b, vals.b);
524#endif
8774c31b
FT
525 } else {
526 flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
527 exit(1);
528 }
529
530 buffree(pars);
531 buffree(vals);
532}
533
cac13158
FT
534static void sighandler(int sig)
535{
536 exitioloop(1);
537}
538
f0bbedf7
FT
539int main(int argc, char **argv)
540{
cac13158 541 int c, d;
8774c31b 542 int i, s1;
f0cbd8d7 543 char *root;
43c58ba2 544 FILE *pidout;
f0cbd8d7 545 struct passwd *pwent;
f4cdf919 546
d341283f 547 daemonize = usesyslog = 0;
f0cbd8d7
FT
548 root = NULL;
549 pwent = NULL;
43c58ba2 550 while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
8774c31b
FT
551 switch(c) {
552 case 'h':
553 usage(stdout);
554 exit(0);
f0cbd8d7
FT
555 case 'f':
556 daemonize = 1;
557 break;
558 case 'S':
d341283f 559 usesyslog = 1;
f0cbd8d7
FT
560 break;
561 case 'u':
562 if((pwent = getpwnam(optarg)) == NULL) {
563 flog(LOG_ERR, "could not find user %s", optarg);
564 exit(1);
565 }
566 break;
567 case 'r':
568 root = optarg;
569 break;
43c58ba2
FT
570 case 'p':
571 pidfile = optarg;
572 break;
8774c31b
FT
573 default:
574 usage(stderr);
575 exit(1);
576 }
577 }
8774c31b
FT
578 s1 = 0;
579 for(i = optind; i < argc; i++) {
580 if(!strcmp(argv[i], "--"))
581 break;
582 s1 = 1;
583 addport(argv[i]);
9d87a119 584 }
8774c31b
FT
585 if(!s1 || (i == argc)) {
586 usage(stderr);
587 exit(1);
f4cdf919 588 }
d341283f 589 if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
8774c31b
FT
590 flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
591 return(1);
f4cdf919 592 }
cac13158 593 bufadd(listeners, mustart(plexwatch, plex));
43c58ba2
FT
594 pidout = NULL;
595 if(pidfile != NULL) {
596 if((pidout = fopen(pidfile, "w")) == NULL) {
597 flog(LOG_ERR, "could not open %s for writing: %s", pidfile, strerror(errno));
598 return(1);
599 }
600 }
d341283f 601 if(usesyslog)
f0cbd8d7
FT
602 opensyslog();
603 if(root) {
0370bd82 604 if(chdir(root) || chroot(root)) {
f0cbd8d7
FT
605 flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
606 exit(1);
607 }
608 }
609 if(pwent) {
610 if(setgid(pwent->pw_gid)) {
611 flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
612 exit(1);
613 }
614 if(setuid(pwent->pw_uid)) {
615 flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
616 exit(1);
617 }
618 }
15fa3fe8 619 signal(SIGPIPE, SIG_IGN);
cac13158
FT
620 signal(SIGCHLD, SIG_IGN);
621 signal(SIGINT, sighandler);
622 signal(SIGTERM, sighandler);
f0cbd8d7
FT
623 if(daemonize) {
624 daemon(0, 0);
625 }
ee036f74 626 if(pidout != NULL) {
43c58ba2 627 fprintf(pidout, "%i\n", getpid());
ee036f74
FT
628 fclose(pidout);
629 }
cac13158
FT
630 d = 0;
631 while(!d) {
632 switch(ioloop()) {
633 case 0:
634 d = 1;
635 break;
636 case 1:
637 if(listeners.d > 0) {
8e9ec020
FT
638 while(listeners.d > 0)
639 resume(listeners.b[0], 0);
cac13158
FT
640 flog(LOG_INFO, "no longer listening");
641 } else {
642 d = 1;
643 }
644 break;
645 }
646 }
f4cdf919 647 return(0);
f0bbedf7 648}