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/>.
20 * XXX: This program is mostly copied from callscgi. It may be
21 * reasonable to unify some of their shared code in a source file.
25 * XXX: All the various ways to start a child process makes this
26 * program quite ugly at the moment. It is unclear whether it is
27 * meaningfully possible to unify them better than they currently are.
36 #include <sys/socket.h>
38 #include <netinet/in.h>
40 #include <sys/signal.h>
52 #define FCGI_BEGIN_REQUEST 1
53 #define FCGI_ABORT_REQUEST 2
54 #define FCGI_END_REQUEST 3
60 static char **progspec;
61 static char *sockid, *unspec, *inspec;
63 static struct sockaddr *curaddr;
64 static size_t caddrlen;
65 static int cafamily, isanon;
68 static struct addrinfo *resolv(int flags)
71 struct addrinfo *ai, h;
74 if((p = strchr(inspec, ':')) != NULL) {
75 name = smalloc(p - inspec + 1);
76 memcpy(name, inspec, p - inspec);
80 name = sstrdup("localhost");
83 memset(&h, 0, sizeof(h));
84 h.ai_family = AF_UNSPEC;
85 h.ai_socktype = SOCK_STREAM;
87 ret = getaddrinfo(name, srv, &h, &ai);
90 flog(LOG_ERR, "could not resolve TCP specification `%s': %s", inspec, gai_strerror(ret));
96 static char *mksockid(char *sockid)
100 home = getenv("HOME");
101 if(home && !access(sprintf3("%s/.ashd/sockets/", home), X_OK))
102 return(sprintf3("%s/.ashd/sockets/fcgi-p-%s", home, sockid));
103 return(sprintf3("/tmp/fcgi-%i-%s", getuid(), sockid));
106 static char *mkanonid(void)
112 home = getenv("HOME");
113 if(home && !access(sprintf3("%s/.ashd/sockets/", home), X_OK))
114 tmpl = sprintf2("%s/.ashd/sockets/fcgi-a-XXXXXX", home);
116 tmpl = sprintf2("/tmp/fcgi-a-%i-XXXXXX", getuid());
117 if((fd = mkstemp(tmpl)) < 0) {
118 flog(LOG_ERR, "could not create anonymous socket `%s': %s", tmpl, strerror(errno));
126 static void startlisten(void)
129 struct addrinfo *ai, *cai;
131 struct sockaddr_un unm;
137 for(cai = ai = resolv(AI_PASSIVE); cai != NULL; cai = cai->ai_next) {
138 if((fd = socket(cai->ai_family, cai->ai_socktype, cai->ai_protocol)) < 0)
140 if(bind(fd, cai->ai_addr, cai->ai_addrlen)) {
145 if(listen(fd, 128)) {
154 flog(LOG_ERR, "could not bind to specified TCP address: %s", strerror(errno));
157 } else if((unspec != NULL) || (sockid != NULL)) {
158 if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
159 flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
165 unpath = mksockid(sockid);
167 unm.sun_family = AF_UNIX;
168 strcpy(unm.sun_path, unpath);
169 if(bind(fd, (struct sockaddr *)&unm, sizeof(unm))) {
170 flog(LOG_ERR, "could not bind Unix socket to `%s': %s", unspec, strerror(errno));
173 if(listen(fd, 128)) {
174 flog(LOG_ERR, "listen: %s", strerror(errno));
178 if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
179 flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
182 memset(&unm, 0, sizeof(unm));
184 unm.sun_family = AF_UNIX;
185 strcpy(unm.sun_path, aname);
187 if(bind(fd, (struct sockaddr *)&unm, sizeof(unm))) {
188 flog(LOG_ERR, "could not bind Unix socket to `%s': %s", unspec, strerror(errno));
191 if(listen(fd, 128)) {
192 flog(LOG_ERR, "listen: %s", strerror(errno));
196 curaddr = smalloc(caddrlen = sizeof(unm));
197 memcpy(curaddr, &unm, sizeof(unm));
201 if((child = fork()) < 0) {
202 flog(LOG_ERR, "could not fork: %s", strerror(errno));
207 for(i = 3; i < FD_SETSIZE; i++)
209 execvp(*progspec, progspec);
210 flog(LOG_ERR, "callfcgi: %s: %s", *progspec, strerror(errno));
216 static void startnolisten(void)
220 if((child = fork()) < 0) {
221 flog(LOG_ERR, "could not fork: %s", strerror(errno));
225 for(i = 3; i < FD_SETSIZE; i++)
227 if((fd = open("/dev/null", O_RDONLY)) < 0) {
228 flog(LOG_ERR, "/dev/null: %s", strerror(errno));
233 execvp(*progspec, progspec);
234 flog(LOG_ERR, "callfcgi: %s: %s", *progspec, strerror(errno));
239 static int sconnect(void)
245 fd = socket(cafamily, SOCK_STREAM, 0);
246 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
248 if(connect(fd, curaddr, caddrlen)) {
249 if(errno == EINPROGRESS) {
250 block(fd, EV_WRITE, 30);
251 errlen = sizeof(err);
252 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) || ((errno = err) != 0)) {
265 static int econnect(void)
268 struct addrinfo *ai, *cai;
271 struct sockaddr_un unm;
277 for(cai = ai = resolv(0); cai != NULL; cai = cai->ai_next) {
278 if((fd = socket(cai->ai_family, cai->ai_socktype, cai->ai_protocol)) < 0)
280 if(connect(fd, cai->ai_addr, cai->ai_addrlen)) {
288 if(tries++ < nolisten) {
292 flog(LOG_ERR, "could not connect to specified TCP address: %s", strerror(errno));
295 curaddr = smalloc(caddrlen = cai->ai_addrlen);
296 memcpy(curaddr, cai->ai_addr, caddrlen);
297 cafamily = cai->ai_family;
301 } else if((unspec != NULL) || (sockid != NULL)) {
302 if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
303 flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
309 unpath = mksockid(sockid);
311 unm.sun_family = AF_UNIX;
312 strcpy(unm.sun_path, unpath);
313 if(connect(fd, (struct sockaddr *)&unm, sizeof(unm))) {
315 if(tries++ < nolisten) {
319 flog(LOG_ERR, "could not connect to Unix socket `%s': %s", unspec, strerror(errno));
322 curaddr = smalloc(caddrlen = sizeof(unm));
323 memcpy(curaddr, &unm, sizeof(unm));
328 flog(LOG_ERR, "callfcgi: cannot use an anonymous socket without a program to start");
333 static int startconn(void)
346 static void killcuraddr(void)
351 unlink(((struct sockaddr_un *)curaddr)->sun_path);
353 kill(child, SIGTERM);
359 static int reconn(void)
363 if(curaddr != NULL) {
364 if((fd = sconnect()) >= 0)
371 static off_t passdata(FILE *in, FILE *out)
379 read = fread(buf, 1, sizeof(buf), in);
382 if(fwrite(buf, 1, read, out) != read)
389 static void bufcatkv(struct charbuf *dst, char *key, char *val)
393 if((kl = strlen(key)) < 128) {
396 bufadd(*dst, ((kl & 0x7f000000) >> 24) | 0x80);
397 bufadd(*dst, (kl & 0x00ff0000) >> 16);
398 bufadd(*dst, (kl & 0x0000ff00) >> 8);
399 bufadd(*dst, kl & 0x000000ff);
401 if((vl = strlen(val)) < 128) {
404 bufadd(*dst, ((vl & 0x7f000000) >> 24) | 0x80);
405 bufadd(*dst, (vl & 0x00ff0000) >> 16);
406 bufadd(*dst, (vl & 0x0000ff00) >> 8);
407 bufadd(*dst, vl & 0x000000ff);
409 bufcat(*dst, key, kl);
410 bufcat(*dst, val, vl);
413 static void bufaddenv(struct charbuf *dst, char *name, char *fmt, ...)
419 val = vsprintf2(fmt, args);
421 bufcatkv(dst, name, val);
425 static char *absolutify(char *file)
427 static int inited = 0;
428 static char cwd[1024];
432 getcwd(cwd, sizeof(cwd));
435 return(sprintf2("%s/%s", cwd, file));
437 return(sstrdup(file));
440 /* Mostly copied from callcgi. */
441 static void mkcgienv(struct hthead *req, struct charbuf *dst)
444 char *url, *unq, *qp, *h, *p;
446 bufaddenv(dst, "SERVER_SOFTWARE", "ashd/%s", VERSION);
447 bufaddenv(dst, "GATEWAY_INTERFACE", "CGI/1.1");
448 bufaddenv(dst, "SERVER_PROTOCOL", "%s", req->ver);
449 bufaddenv(dst, "REQUEST_METHOD", "%s", req->method);
450 bufaddenv(dst, "REQUEST_URI", "%s", req->url);
451 if((unq = unquoteurl(req->rest)) != NULL) {
452 bufaddenv(dst, "PATH_INFO", unq);
455 bufaddenv(dst, "PATH_INFO", req->rest);
457 url = sstrdup(req->url);
458 if((qp = strchr(url, '?')) != NULL)
460 /* XXX: This is an ugly hack (I think), but though I can think of
461 * several alternatives, none seem to be better. */
462 if(*req->rest && (strlen(url) >= strlen(req->rest)) &&
463 !strcmp(req->rest, url + strlen(url) - strlen(req->rest))) {
464 bufaddenv(dst, "SCRIPT_NAME", "%.*s", (int)(strlen(url) - strlen(req->rest)), url);
466 bufaddenv(dst, "SCRIPT_NAME", "%s", url);
469 bufaddenv(dst, "QUERY_STRING", "%s", qp?qp:"");
470 if((h = getheader(req, "Host")) != NULL)
471 bufaddenv(dst, "SERVER_NAME", "%s", h);
472 if((h = getheader(req, "X-Ash-Server-Port")) != NULL)
473 bufaddenv(dst, "SERVER_PORT", "%s", h);
474 if((h = getheader(req, "X-Ash-Remote-User")) != NULL)
475 bufaddenv(dst, "REMOTE_USER", "%s", h);
476 if(((h = getheader(req, "X-Ash-Protocol")) != NULL) && !strcmp(h, "https"))
477 bufaddenv(dst, "HTTPS", "on");
478 if((h = getheader(req, "X-Ash-Address")) != NULL)
479 bufaddenv(dst, "REMOTE_ADDR", "%s", h);
480 if((h = getheader(req, "Content-Type")) != NULL)
481 bufaddenv(dst, "CONTENT_TYPE", "%s", h);
482 if((h = getheader(req, "Content-Length")) != NULL)
483 bufaddenv(dst, "CONTENT_LENGTH", "%s", h);
485 bufaddenv(dst, "CONTENT_LENGTH", "0");
486 if((h = getheader(req, "X-Ash-File")) != NULL) {
488 bufaddenv(dst, "SCRIPT_FILENAME", "%s", h);
491 for(i = 0; i < req->noheaders; i++) {
492 h = sprintf2("HTTP_%s", req->headers[i][0]);
493 for(p = h; *p; p++) {
499 bufcatkv(dst, h, req->headers[i][1]);
504 static char *defstatus(int code)
513 return("No Content");
515 return("Multiple Choices");
517 return("Moved Permanently");
523 return("Not Modified");
525 return("Moved Temporarily");
527 return("Bad Request");
529 return("Unauthorized");
535 return("Internal Server Error");
537 return("Not Implemented");
539 return("Service Unavailable");
541 return("Unknown status");
544 static struct hthead *parseresp(FILE *in)
550 resp->ver = sstrdup("HTTP/1.1");
551 if(parseheaders(resp, in)) {
555 if((st = getheader(resp, "Status")) != NULL) {
556 if((p = strchr(st, ' ')) != NULL) {
558 resp->code = atoi(st);
559 resp->msg = sstrdup(p);
561 resp->code = atoi(st);
562 resp->msg = sstrdup(defstatus(resp->code));
564 headrmheader(resp, "Status");
565 } else if(getheader(resp, "Location")) {
567 resp->msg = sstrdup("See Other");
570 resp->msg = sstrdup("OK");
575 #define fputc2(b, f) if(fputc((b), (f)) == EOF) return(-1);
577 static int sendrec(FILE *out, int type, int rid, char *data, size_t dlen)
585 cl = min(dlen - off, 65535);
586 p = (8 - (cl % 8)) % 8;
589 fputc2((rid & 0xff00) >> 8, out);
590 fputc2(rid & 0x00ff, out);
591 fputc2((cl & 0xff00) >> 8, out);
592 fputc2(cl & 0x00ff, out);
595 if(fwrite(data + off, 1, cl, out) != cl)
599 } while((off += cl) < dlen);
603 #define fgetc2(f) ({int __c__ = fgetc(f); if(__c__ == EOF) return(-1); __c__;})
605 static int recvrec(FILE *in, int *type, int *rid, char **data, size_t *dlen)
614 *rid = (b1 << 8) | b2;
617 *dlen = (b1 << 8) | b2;
621 *data = smalloc(max(*dlen, 1));
622 if(fread(*data, 1, *dlen, in) != *dlen) {
626 for(; pl > 0; pl--) {
627 if(fgetc(in) == EOF) {
635 static int begreq(FILE *out, int rid)
637 char rec[] = {0, 1, 0, 0, 0, 0, 0, 0};
639 return(sendrec(out, FCGI_BEGIN_REQUEST, rid, rec, 8));
642 static void mtiopipe(FILE **read, FILE **write)
647 *read = mtstdopen(fds[0], 0, 600, "r");
648 *write = mtstdopen(fds[1], 0, 600, "w");
651 static void outplex(struct muth *muth, va_list args)
668 while((ch.s = va_arg(args, FILE *)) != NULL) {
669 ch.id = va_arg(args, int);
674 if(recvrec(sk, &type, &rid, &data, &dlen))
678 for(i = 0; i < outs.d; i++) {
679 if(outs.b[i].id == type) {
680 if(outs.b[i].s != NULL) {
685 if(fwrite(data, 1, dlen, outs.b[i].s) != dlen)
699 for(i = 0; i < outs.d; i++) {
700 if(outs.b[i].s != NULL)
707 static void errhandler(struct muth *muth, va_list args)
714 while(fgets(buf, sizeof(buf), in) != NULL) {
715 p = buf + strlen(buf) - 1;
716 while((p >= buf) && (*p == '\n'))
719 flog(LOG_INFO, "child said: %s", buf);
724 static void serve(struct muth *muth, va_list args)
726 vavar(struct hthead *, req);
729 FILE *is, *os, *outi, *outo, *erri, *erro;
736 is = mtstdopen(fd, 1, 60, "r+");
737 os = mtstdopen(sfd, 1, 600, "r+");
740 mtiopipe(&outi, &outo); mtiopipe(&erri, &erro);
741 mustart(outplex, mtstdopen(dup(sfd), 1, 600, "r+"), outo, FCGI_STDOUT, erro, FCGI_STDERR, NULL);
742 mustart(errhandler, erri);
747 mkcgienv(req, &head);
748 if(sendrec(os, FCGI_PARAMS, 1, head.b, head.d))
750 if(sendrec(os, FCGI_PARAMS, 1, NULL, 0))
757 read = fread(buf, 1, sizeof(buf), is);
760 if(sendrec(os, FCGI_STDIN, 1, buf, read))
763 if(sendrec(os, FCGI_STDIN, 1, NULL, 0))
768 if((resp = parseresp(outi)) == NULL)
773 if(passdata(outi, is) < 0)
779 shutdown(sfd, SHUT_RDWR);
786 static void listenloop(struct muth *muth, va_list args)
793 block(0, EV_READ, 0);
794 if((fd = recvreq(lfd, &req)) < 0) {
796 flog(LOG_ERR, "recvreq: %s", strerror(errno));
799 mustart(serve, req, fd);
803 static void sigign(int sig)
807 static void sigexit(int sig)
812 static void usage(FILE *out)
814 fprintf(out, "usage: callfcgi [-h] [-N RETRIES] [-i ID] [-u UNIX-PATH] [-t [HOST:]TCP-PORT] [PROGRAM [ARGS...]]\n");
817 int main(int argc, char **argv)
821 while((c = getopt(argc, argv, "+hN:i:u:t:")) >= 0) {
827 nolisten = atoi(optarg);
843 progspec = argv + optind;
844 if(((sockid != NULL) + (unspec != NULL) + (inspec != NULL)) > 1) {
845 flog(LOG_ERR, "callfcgi: at most one of -i, -u or -t may be given");
848 signal(SIGCHLD, SIG_IGN);
849 signal(SIGPIPE, sigign);
850 signal(SIGINT, sigexit);
851 signal(SIGTERM, sigexit);
852 mustart(listenloop, 0);