2 ashd - A Sane HTTP Daemon
3 Copyright (C) 2008 Fredrik Tolf <fredrik@dolda2000.com>
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.
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.
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/>.
24 #include <sys/socket.h>
26 #include <sys/signal.h>
43 static int daemonize, usesyslog;
44 struct mtbuf listeners;
46 static void trimx(struct hthead *req)
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));
63 static struct hthead *parsereq(struct bufio *in)
66 struct charbuf method, url, ver;
77 } else if((c == EOF) || (c < 32) || (c >= 128)) {
89 } else if((c == EOF) || (c < 32)) {
102 } else if((c == EOF) || (c < 32) || (c >= 128)) {
113 req = mkreq(method.b, url.b, ver.b);
114 if(parseheadersb(req, in))
131 static off_t passdata(struct bufio *in, struct bufio *out, off_t max)
137 while(!bioeof(in) && ((max < 0) || (total < max))) {
138 if((read = biordata(in)) > 0) {
140 read = min(max - total, read);
141 if((read = biowritesome(out, in->rbuf.b + in->rh, read)) < 0)
146 if(biorspace(in) && ((max < 0) || (biordata(in) < max - total)) && (biofillsome(in) < 0))
152 static int recvchunks(struct bufio *in, struct bufio *out)
167 } else if((c >= '0') && (c <= '9')) {
168 chlen = (chlen << 4) + (c - '0');
170 } else if((c >= 'A') && (c <= 'F')) {
171 chlen = (chlen << 4) + (c + 10 - 'A');
173 } else if((c >= 'a') && (c <= 'f')) {
174 chlen = (chlen << 4) + (c + 10 - 'a');
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. */
187 if((read = biordata(in)) > 0) {
188 if((read = biowritesome(out, in->rbuf.b + in->rh, min(read, chlen))) < 0)
193 if(biorspace(in) && (biordata(in) < chlen) && (biofillsome(in) <= 0))
196 if((biogetc(in) != 13) || (biogetc(in) != 10))
199 /* XXX: Technically, there may be trailers to be read, but that's
200 * just about as likely as chunk extensions. */
201 if((biogetc(in) != 13) || (biogetc(in) != 10))
206 static int passchunks(struct bufio *in, struct bufio *out)
211 if((read = biordata(in)) > 0) {
212 bioprintf(out, "%zx\r\n", read);
213 if(biowrite(out, in->rbuf.b + in->rh, read) != read)
216 bioprintf(out, "\r\n");
217 if(bioflush(out) < 0)
220 if(biorspace(in) && (biofillsome(in) < 0))
223 bioprintf(out, "0\r\n\r\n");
227 static int hasheader(struct hthead *head, char *name, char *val)
231 if((hd = getheader(head, name)) == NULL)
233 return(!strcasecmp(hd, val));
236 static int canonreq(struct hthead *req)
241 if(req->url[0] == '/') {
242 replrest(req, req->url + 1);
243 if((p = strchr(req->rest, '?')) != NULL)
247 if((p = strstr(req->url, "://")) != NULL) {
249 if(((n == 4) && !strncasecmp(req->url, "http", 4)) ||
250 ((n == 5) && !strncasecmp(req->url, "https", 5))) {
251 if(getheader(req, "host"))
254 if((p2 = strchr(p, '/')) == NULL) {
255 headappheader(req, "Host", p);
257 req->url = sstrdup("/");
261 headappheader(req, "Host", p);
265 replrest(req, req->url + 1);
266 if((p = strchr(req->rest, '?')) != NULL)
274 static int http10keep(struct hthead *req, struct hthead *resp)
278 fc = hasheader(resp, "connection", "close");
279 headrmheader(resp, "connection");
280 if(!fc && hasheader(req, "connection", "keep-alive")) {
281 headappheader(resp, "Connection", "Keep-Alive");
288 static char *connid(void)
290 static struct charbuf cur;
294 for(i = 0; i < cur.d; i++) {
295 if((++cur.b[i]) > 'Z')
302 ret = memcpy(smalloc(cur.d + 1), cur.b, cur.d);
307 static void passduplex(struct bufio *a, int afd, struct bufio *b, int bfd)
309 struct selected pfd[4], sel;
313 while(!bioeof(a) && !bioeof(b)) {
324 pfd[n++] = (struct selected){.fd = afd, .ev = ev};
328 if(!b->eof && biorspace(b))
333 pfd[n++] = (struct selected){.fd = bfd, .ev = ev};
335 if((sel = mblock(600, n, pfd)).ev == 0)
339 else if(sel.fd == bfd)
343 if((sel.ev & EV_READ) && (biofillsome(sio) < 0))
345 if((sel.ev & EV_WRITE) && (bioflushsome(sio) < 0))
350 void serve(struct bufio *in, int infd, struct conn *conn)
353 struct bufio *out, *dout;
354 struct stdiofd *outi;
355 struct hthead *req, *resp;
365 if((req = parsereq(in)) == NULL)
370 headappheader(req, "X-Ash-Connection-ID", id);
371 if((conn->initreq != NULL) && conn->initreq(conn, req))
374 if((plex < 0) || block(plex, EV_WRITE, 60) <= 0)
376 if(socketpair(PF_UNIX, SOCK_STREAM, 0, pfds))
378 if(sendreq(plex, req, pfds[0]))
381 out = mtbioopen(pfds[1], 1, 600, "r+", &outi);
383 if(getheader(req, "content-type") != NULL) {
384 if((hd = getheader(req, "content-length")) != NULL) {
387 if(passdata(in, out, dlen) != dlen)
390 } else if(((hd = getheader(req, "transfer-encoding")) != NULL) && !strcasecmp(hd, "chunked")) {
391 if(recvchunks(in, out))
394 /* Ignore rather than abort, to be kinder to broken clients. */
395 headrmheader(req, "content-type");
400 /* Make sure to send EOF */
401 shutdown(pfds[1], SHUT_WR);
403 if((resp = parseresponseb(out)) == NULL)
405 replstr(&resp->ver, req->ver);
407 if(!getheader(resp, "server"))
408 headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
409 duplex = hasheader(resp, "x-ash-switch", "duplex");
415 writerespb(in, resp);
416 bioprintf(in, "\r\n");
417 dout = mtbioopen(outi->rights, 1, 600, "r+", NULL);
418 passduplex(in, infd, dout, outi->rights);
422 } else if(!strcasecmp(req->ver, "HTTP/1.0")) {
423 if(!strcasecmp(req->method, "head")) {
424 keep = http10keep(req, resp);
425 writerespb(in, resp);
426 bioprintf(in, "\r\n");
427 } else if((hd = getheader(resp, "content-length")) != NULL) {
428 keep = http10keep(req, resp);
430 writerespb(in, resp);
431 bioprintf(in, "\r\n");
432 if(passdata(out, in, dlen) != dlen)
435 headrmheader(resp, "connection");
436 writerespb(in, resp);
437 bioprintf(in, "\r\n");
438 passdata(out, in, -1);
443 } else if(!strcasecmp(req->ver, "HTTP/1.1")) {
444 if(!strcasecmp(req->method, "head")) {
445 writerespb(in, resp);
446 bioprintf(in, "\r\n");
447 } else if((hd = getheader(resp, "content-length")) != NULL) {
448 writerespb(in, resp);
449 bioprintf(in, "\r\n");
451 if(passdata(out, in, dlen) != dlen)
453 } else if(!getheader(resp, "transfer-encoding")) {
454 headappheader(resp, "Transfer-Encoding", "chunked");
455 writerespb(in, resp);
456 bioprintf(in, "\r\n");
457 if(passchunks(out, in))
460 writerespb(in, resp);
461 bioprintf(in, "\r\n");
462 passdata(out, in, -1);
465 if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
488 static void plexwatch(struct muth *muth, va_list args)
496 if(block(fd, EV_READ, 0) == 0)
498 buf = smalloc(65536);
499 ret = recv(fd, buf, 65536, 0);
501 flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
503 } else if(ret == 0) {
508 /* Maybe I'd like to implement some protocol in this direction
512 shutdown(plex, SHUT_RDWR);
513 for(i = 0; i < listeners.d; i++) {
514 if(listeners.b[i] == muth)
515 bufdel(listeners, i);
518 flog(LOG_INFO, "root handler exited, so shutting down listening...");
519 while(listeners.d > 0)
520 resume(listeners.b[0], 0);
524 static void initroot(void *uu)
531 if((fd = open("/dev/null", O_RDWR)) >= 0) {
539 putenv("ASHD_USESYSLOG=1");
541 unsetenv("ASHD_USESYSLOG");
544 static void usage(FILE *out)
546 fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
547 fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
548 fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
551 static void addport(char *spec)
553 char *nm, *p, *p2, *n;
554 struct charvbuf pars, vals;
558 if((p = strchr(spec, ':')) == NULL) {
564 if((n = strchr(p, ',')) != NULL)
566 if((p2 = strchr(p, '=')) != NULL)
577 } while((p = n) != NULL);
580 /* XXX: It would be nice to decentralize this, but, meh... */
581 if(!strcmp(nm, "plain")) {
582 handleplain(pars.d, pars.b, vals.b);
584 } else if(!strcmp(nm, "ssl")) {
585 handlegnussl(pars.d, pars.b, vals.b);
588 flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
596 static void sighandler(int sig)
601 int main(int argc, char **argv)
605 char *root, *pidfile, *pidtmp;
607 struct passwd *pwent;
609 daemonize = usesyslog = 0;
610 root = pidfile = NULL;
612 while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
624 if(optarg[0] && ((pwent = getpwnam(optarg)) == NULL)) {
625 flog(LOG_ERR, "could not find user %s", optarg);
630 root = optarg[0] ? optarg : NULL;
633 pidfile = optarg[0] ? optarg : NULL;
641 for(i = optind; i < argc; i++) {
642 if(!strcmp(argv[i], "--"))
647 if(!s1 || (i == argc)) {
651 if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
652 flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
655 bufadd(listeners, mustart(plexwatch, plex));
657 if(pidfile != NULL) {
658 pidtmp = sprintf3("%s.new", pidfile);
659 if((pidout = fopen(pidtmp, "w")) == NULL) {
660 flog(LOG_ERR, "could not open %s for writing: %s", pidtmp, strerror(errno));
663 if(rename(pidtmp, pidfile)) {
664 flog(LOG_ERR, "could not overwrite %s: %s", pidfile, strerror(errno));
672 if(chdir(root) || chroot(root)) {
673 flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
678 if(setgid(pwent->pw_gid)) {
679 flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
682 if(setuid(pwent->pw_uid)) {
683 flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
687 signal(SIGPIPE, SIG_IGN);
688 signal(SIGCHLD, SIG_IGN);
689 signal(SIGINT, sighandler);
690 signal(SIGTERM, sighandler);
695 fprintf(pidout, "%i\n", getpid());
705 if(listeners.d > 0) {
706 while(listeners.d > 0)
707 resume(listeners.b[0], 0);
708 flog(LOG_INFO, "no longer listening");
720 ftruncate(fileno(pidout), 0);