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 char *pidfile = NULL;
44 static int daemonize, usesyslog;
45 struct mtbuf listeners;
47 static void trimx(struct hthead *req)
52 while(i < req->noheaders) {
53 if(!strncasecmp(req->headers[i][0], "x-ash-", 6)) {
54 free(req->headers[i][0]);
55 free(req->headers[i][1]);
56 free(req->headers[i]);
57 memmove(req->headers + i, req->headers + i + 1, sizeof(*req->headers) * (--req->noheaders - i));
64 static struct hthead *parsereq(struct bufio *in)
67 struct charbuf method, url, ver;
78 } else if((c == EOF) || (c < 32) || (c >= 128)) {
90 } else if((c == EOF) || (c < 32)) {
103 } else if((c == EOF) || (c < 32) || (c >= 128)) {
114 req = mkreq(method.b, url.b, ver.b);
115 if(parseheadersb(req, in))
132 static off_t passdata(struct bufio *in, struct bufio *out, off_t max)
138 while(!bioeof(in) && ((max < 0) || (total < max))) {
139 if((read = biordata(in)) > 0) {
141 read = min(max - total, read);
142 if((read = biowritesome(out, in->rbuf.b + in->rh, read)) < 0)
147 if(biorspace(in) && ((max < 0) || (biordata(in) < max - total)) && (biofillsome(in) < 0))
153 static int recvchunks(struct bufio *in, struct bufio *out)
168 } else if((c >= '0') && (c <= '9')) {
169 chlen = (chlen << 4) + (c - '0');
171 } else if((c >= 'A') && (c <= 'F')) {
172 chlen = (chlen << 4) + (c + 10 - 'A');
174 } else if((c >= 'a') && (c <= 'f')) {
175 chlen = (chlen << 4) + (c + 10 - 'a');
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. */
188 if((read = biordata(in)) > 0) {
189 if((read = biowritesome(out, in->rbuf.b + in->rh, min(read, chlen))) < 0)
194 if(biorspace(in) && (biordata(in) < chlen) && (biofillsome(in) <= 0))
197 if((biogetc(in) != 13) || (biogetc(in) != 10))
200 /* XXX: Technically, there may be trailers to be read, but that's
201 * just about as likely as chunk extensions. */
202 if((biogetc(in) != 13) || (biogetc(in) != 10))
207 static int passchunks(struct bufio *in, struct bufio *out)
212 if((read = biordata(in)) > 0) {
213 bioprintf(out, "%zx\r\n", read);
214 if(biowrite(out, in->rbuf.b + in->rh, read) != read)
217 bioprintf(out, "\r\n");
218 if(bioflush(out) < 0)
221 if(biorspace(in) && (biofillsome(in) < 0))
224 bioprintf(out, "0\r\n\r\n");
228 static int hasheader(struct hthead *head, char *name, char *val)
232 if((hd = getheader(head, name)) == NULL)
234 return(!strcasecmp(hd, val));
237 static int canonreq(struct hthead *req)
242 if(req->url[0] == '/') {
243 replrest(req, req->url + 1);
244 if((p = strchr(req->rest, '?')) != NULL)
248 if((p = strstr(req->url, "://")) != NULL) {
250 if(((n == 4) && !strncasecmp(req->url, "http", 4)) ||
251 ((n == 5) && !strncasecmp(req->url, "https", 5))) {
252 if(getheader(req, "host"))
255 if((p2 = strchr(p, '/')) == NULL) {
256 headappheader(req, "Host", p);
258 req->url = sstrdup("/");
262 headappheader(req, "Host", p);
266 replrest(req, req->url + 1);
267 if((p = strchr(req->rest, '?')) != NULL)
275 static int http10keep(struct hthead *req, struct hthead *resp)
279 fc = hasheader(resp, "connection", "close");
280 headrmheader(resp, "connection");
281 if(!fc && hasheader(req, "connection", "keep-alive")) {
282 headappheader(resp, "Connection", "Keep-Alive");
289 static char *connid(void)
291 static struct charbuf cur;
295 for(i = 0; i < cur.d; i++) {
296 if((++cur.b[i]) > 'Z')
303 ret = memcpy(smalloc(cur.d + 1), cur.b, cur.d);
308 static void passduplex(struct bufio *a, int afd, struct bufio *b, int bfd)
310 struct selected pfd[4], sel;
314 while(!bioeof(a) && !bioeof(b)) {
325 pfd[n++] = (struct selected){.fd = afd, .ev = ev};
329 if(!b->eof && biorspace(b))
334 pfd[n++] = (struct selected){.fd = bfd, .ev = ev};
336 if((sel = mblock(600, n, pfd)).ev == 0)
340 else if(sel.fd == bfd)
344 if((sel.ev & EV_READ) && (biofillsome(sio) < 0))
346 if((sel.ev & EV_WRITE) && (bioflushsome(sio) < 0))
351 void serve(struct bufio *in, int infd, struct conn *conn)
354 struct bufio *out, *dout;
355 struct stdiofd *outi;
356 struct hthead *req, *resp;
366 if((req = parsereq(in)) == NULL)
371 headappheader(req, "X-Ash-Connection-ID", id);
372 if((conn->initreq != NULL) && conn->initreq(conn, req))
375 if((plex < 0) || block(plex, EV_WRITE, 60) <= 0)
377 if(socketpair(PF_UNIX, SOCK_STREAM, 0, pfds))
379 if(sendreq(plex, req, pfds[0]))
382 out = mtbioopen(pfds[1], 1, 600, "r+", &outi);
384 if(getheader(req, "content-type") != NULL) {
385 if((hd = getheader(req, "content-length")) != NULL) {
388 if(passdata(in, out, dlen) != dlen)
391 } else if(((hd = getheader(req, "transfer-encoding")) != NULL) && !strcasecmp(hd, "chunked")) {
392 if(recvchunks(in, out))
395 /* Ignore rather than abort, to be kinder to broken clients. */
396 headrmheader(req, "content-type");
401 /* Make sure to send EOF */
402 shutdown(pfds[1], SHUT_WR);
404 if((resp = parseresponseb(out)) == NULL)
406 replstr(&resp->ver, req->ver);
408 if(!getheader(resp, "server"))
409 headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
410 duplex = hasheader(resp, "x-ash-switch", "duplex");
416 writerespb(in, resp);
417 bioprintf(in, "\r\n");
418 dout = mtbioopen(outi->rights, 1, 600, "r+", NULL);
419 passduplex(in, infd, dout, outi->rights);
423 } else if(!strcasecmp(req->ver, "HTTP/1.0")) {
424 if(!strcasecmp(req->method, "head")) {
425 keep = http10keep(req, resp);
426 writerespb(in, resp);
427 bioprintf(in, "\r\n");
428 } else if((hd = getheader(resp, "content-length")) != NULL) {
429 keep = http10keep(req, resp);
431 writerespb(in, resp);
432 bioprintf(in, "\r\n");
433 if(passdata(out, in, dlen) != dlen)
436 headrmheader(resp, "connection");
437 writerespb(in, resp);
438 bioprintf(in, "\r\n");
439 passdata(out, in, -1);
444 } else if(!strcasecmp(req->ver, "HTTP/1.1")) {
445 if(!strcasecmp(req->method, "head")) {
446 writerespb(in, resp);
447 bioprintf(in, "\r\n");
448 } else if((hd = getheader(resp, "content-length")) != NULL) {
449 writerespb(in, resp);
450 bioprintf(in, "\r\n");
452 if(passdata(out, in, dlen) != dlen)
454 } else if(!getheader(resp, "transfer-encoding")) {
455 headappheader(resp, "Transfer-Encoding", "chunked");
456 writerespb(in, resp);
457 bioprintf(in, "\r\n");
458 if(passchunks(out, in))
461 writerespb(in, resp);
462 bioprintf(in, "\r\n");
463 passdata(out, in, -1);
466 if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
489 static void plexwatch(struct muth *muth, va_list args)
497 if(block(fd, EV_READ, 0) == 0)
499 buf = smalloc(65536);
500 ret = recv(fd, buf, 65536, 0);
502 flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
504 } else if(ret == 0) {
509 /* Maybe I'd like to implement some protocol in this direction
513 shutdown(plex, SHUT_RDWR);
514 for(i = 0; i < listeners.d; i++) {
515 if(listeners.b[i] == muth)
516 bufdel(listeners, i);
519 flog(LOG_INFO, "root handler exited, so shutting down listening...");
520 while(listeners.d > 0)
521 resume(listeners.b[0], 0);
525 static void initroot(void *uu)
532 if((fd = open("/dev/null", O_RDWR)) >= 0) {
540 putenv("ASHD_USESYSLOG=1");
542 unsetenv("ASHD_USESYSLOG");
545 static void usage(FILE *out)
547 fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
548 fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
549 fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
552 static void addport(char *spec)
554 char *nm, *p, *p2, *n;
555 struct charvbuf pars, vals;
559 if((p = strchr(spec, ':')) == NULL) {
565 if((n = strchr(p, ',')) != NULL)
567 if((p2 = strchr(p, '=')) != NULL)
578 } while((p = n) != NULL);
581 /* XXX: It would be nice to decentralize this, but, meh... */
582 if(!strcmp(nm, "plain")) {
583 handleplain(pars.d, pars.b, vals.b);
585 } else if(!strcmp(nm, "ssl")) {
586 handlegnussl(pars.d, pars.b, vals.b);
589 flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
597 static void sighandler(int sig)
602 int main(int argc, char **argv)
608 struct passwd *pwent;
610 daemonize = usesyslog = 0;
613 while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
625 if((pwent = getpwnam(optarg)) == NULL) {
626 flog(LOG_ERR, "could not find user %s", optarg);
642 for(i = optind; i < argc; i++) {
643 if(!strcmp(argv[i], "--"))
648 if(!s1 || (i == argc)) {
652 if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
653 flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
656 bufadd(listeners, mustart(plexwatch, plex));
658 if(pidfile != NULL) {
659 if((pidout = fopen(pidfile, "w")) == NULL) {
660 flog(LOG_ERR, "could not open %s for writing: %s", pidfile, strerror(errno));
667 if(chdir(root) || chroot(root)) {
668 flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
673 if(setgid(pwent->pw_gid)) {
674 flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
677 if(setuid(pwent->pw_uid)) {
678 flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
682 signal(SIGPIPE, SIG_IGN);
683 signal(SIGCHLD, SIG_IGN);
684 signal(SIGINT, sighandler);
685 signal(SIGTERM, sighandler);
690 fprintf(pidout, "%i\n", getpid());
700 if(listeners.d > 0) {
701 while(listeners.d > 0)
702 resume(listeners.b[0], 0);
703 flog(LOG_INFO, "no longer listening");