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>
53 #define FCGI_BEGIN_REQUEST 1
54 #define FCGI_ABORT_REQUEST 2
55 #define FCGI_END_REQUEST 3
61 static char **progspec;
62 static char *sockid, *unspec, *inspec;
64 static struct sockaddr *curaddr;
65 static size_t caddrlen;
66 static int cafamily, isanon;
69 static struct addrinfo *resolv(int flags)
72 struct addrinfo *ai, h;
75 if((p = strchr(inspec, ':')) != NULL) {
76 name = smalloc(p - inspec + 1);
77 memcpy(name, inspec, p - inspec);
81 name = sstrdup("localhost");
84 memset(&h, 0, sizeof(h));
85 h.ai_family = AF_UNSPEC;
86 h.ai_socktype = SOCK_STREAM;
88 ret = getaddrinfo(name, srv, &h, &ai);
91 flog(LOG_ERR, "could not resolve TCP specification `%s': %s", inspec, gai_strerror(ret));
97 static char *mksockid(char *sockid)
101 home = getenv("HOME");
102 if(home && !access(sprintf3("%s/.ashd/sockets/", home), X_OK))
103 return(sprintf3("%s/.ashd/sockets/fcgi-p-%s", home, sockid));
104 return(sprintf3("/tmp/fcgi-%i-%s", getuid(), sockid));
107 static char *mkanonid(void)
113 home = getenv("HOME");
114 if(home && !access(sprintf3("%s/.ashd/sockets/", home), X_OK))
115 tmpl = sprintf2("%s/.ashd/sockets/fcgi-a-XXXXXX", home);
117 tmpl = sprintf2("/tmp/fcgi-a-%i-XXXXXX", getuid());
118 if((fd = mkstemp(tmpl)) < 0) {
119 flog(LOG_ERR, "could not create anonymous socket `%s': %s", tmpl, strerror(errno));
127 static void setupchild(void)
129 /* PHP appears to not expect to inherit SIGCHLD set to SIG_IGN, so
130 * reset it for it. */
131 signal(SIGCHLD, SIG_DFL);
134 static void startlisten(void)
137 struct addrinfo *ai, *cai;
139 struct sockaddr_un unm;
145 for(cai = ai = resolv(AI_PASSIVE); cai != NULL; cai = cai->ai_next) {
146 if((fd = socket(cai->ai_family, cai->ai_socktype, cai->ai_protocol)) < 0)
148 if(bind(fd, cai->ai_addr, cai->ai_addrlen)) {
153 if(listen(fd, 128)) {
162 flog(LOG_ERR, "could not bind to specified TCP address: %s", strerror(errno));
165 } else if((unspec != NULL) || (sockid != NULL)) {
166 if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
167 flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
173 unpath = mksockid(sockid);
175 unm.sun_family = AF_UNIX;
176 strcpy(unm.sun_path, unpath);
177 if(bind(fd, (struct sockaddr *)&unm, sizeof(unm))) {
178 flog(LOG_ERR, "could not bind Unix socket to `%s': %s", unspec, strerror(errno));
181 if(listen(fd, 128)) {
182 flog(LOG_ERR, "listen: %s", strerror(errno));
186 if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
187 flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
190 memset(&unm, 0, sizeof(unm));
192 unm.sun_family = AF_UNIX;
193 strcpy(unm.sun_path, aname);
195 if(bind(fd, (struct sockaddr *)&unm, sizeof(unm))) {
196 flog(LOG_ERR, "could not bind Unix socket to `%s': %s", unspec, strerror(errno));
199 if(listen(fd, 128)) {
200 flog(LOG_ERR, "listen: %s", strerror(errno));
204 curaddr = smalloc(caddrlen = sizeof(unm));
205 memcpy(curaddr, &unm, sizeof(unm));
209 if((child = fork()) < 0) {
210 flog(LOG_ERR, "could not fork: %s", strerror(errno));
217 execvp(*progspec, progspec);
218 flog(LOG_ERR, "callfcgi: %s: %s", *progspec, strerror(errno));
224 static void startnolisten(void)
228 if((child = fork()) < 0) {
229 flog(LOG_ERR, "could not fork: %s", strerror(errno));
234 if((fd = open("/dev/null", O_RDONLY)) < 0) {
235 flog(LOG_ERR, "/dev/null: %s", strerror(errno));
240 execvp(*progspec, progspec);
241 flog(LOG_ERR, "callfcgi: %s: %s", *progspec, strerror(errno));
246 static int sconnect(void)
252 fd = socket(cafamily, SOCK_STREAM, 0);
253 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
255 if(connect(fd, curaddr, caddrlen)) {
256 if(errno == EINPROGRESS) {
257 block(fd, EV_WRITE, 30);
258 errlen = sizeof(err);
259 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) || ((errno = err) != 0)) {
272 static int econnect(void)
275 struct addrinfo *ai, *cai;
278 struct sockaddr_un unm;
284 for(cai = ai = resolv(0); cai != NULL; cai = cai->ai_next) {
285 if((fd = socket(cai->ai_family, cai->ai_socktype, cai->ai_protocol)) < 0)
287 if(connect(fd, cai->ai_addr, cai->ai_addrlen)) {
295 if(tries++ < nolisten) {
299 flog(LOG_ERR, "could not connect to specified TCP address: %s", strerror(errno));
302 curaddr = smalloc(caddrlen = cai->ai_addrlen);
303 memcpy(curaddr, cai->ai_addr, caddrlen);
304 cafamily = cai->ai_family;
308 } else if((unspec != NULL) || (sockid != NULL)) {
309 if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
310 flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
316 unpath = mksockid(sockid);
318 unm.sun_family = AF_UNIX;
319 strcpy(unm.sun_path, unpath);
320 if(connect(fd, (struct sockaddr *)&unm, sizeof(unm))) {
322 if(tries++ < nolisten) {
326 flog(LOG_ERR, "could not connect to Unix socket `%s': %s", unspec, strerror(errno));
329 curaddr = smalloc(caddrlen = sizeof(unm));
330 memcpy(curaddr, &unm, sizeof(unm));
335 flog(LOG_ERR, "callfcgi: cannot use an anonymous socket without a program to start");
340 static int startconn(void)
353 static void killcuraddr(void)
358 unlink(((struct sockaddr_un *)curaddr)->sun_path);
360 kill(child, SIGTERM);
366 static int reconn(void)
370 if(curaddr != NULL) {
371 if((fd = sconnect()) >= 0)
378 static off_t passdata(FILE *in, FILE *out)
386 read = fread(buf, 1, sizeof(buf), in);
389 if(fwrite(buf, 1, read, out) != read)
396 static void bufcatkv(struct charbuf *dst, char *key, char *val)
400 if((kl = strlen(key)) < 128) {
403 bufadd(*dst, ((kl & 0x7f000000) >> 24) | 0x80);
404 bufadd(*dst, (kl & 0x00ff0000) >> 16);
405 bufadd(*dst, (kl & 0x0000ff00) >> 8);
406 bufadd(*dst, kl & 0x000000ff);
408 if((vl = strlen(val)) < 128) {
411 bufadd(*dst, ((vl & 0x7f000000) >> 24) | 0x80);
412 bufadd(*dst, (vl & 0x00ff0000) >> 16);
413 bufadd(*dst, (vl & 0x0000ff00) >> 8);
414 bufadd(*dst, vl & 0x000000ff);
416 bufcat(*dst, key, kl);
417 bufcat(*dst, val, vl);
420 static void bufaddenv(struct charbuf *dst, char *name, char *fmt, ...)
426 val = vsprintf2(fmt, args);
428 bufcatkv(dst, name, val);
432 static char *absolutify(char *file)
434 static int inited = 0;
435 static char cwd[1024];
439 getcwd(cwd, sizeof(cwd));
442 return(sprintf2("%s/%s", cwd, file));
444 return(sstrdup(file));
447 /* Mostly copied from callcgi. */
448 static void mkcgienv(struct hthead *req, struct charbuf *dst)
451 char *url, *pi, *tmp, *qp, *h, *p;
453 bufaddenv(dst, "SERVER_SOFTWARE", "ashd/%s", VERSION);
454 bufaddenv(dst, "GATEWAY_INTERFACE", "CGI/1.1");
455 bufaddenv(dst, "SERVER_PROTOCOL", "%s", req->ver);
456 bufaddenv(dst, "REQUEST_METHOD", "%s", req->method);
457 bufaddenv(dst, "REQUEST_URI", "%s", req->url);
458 url = sstrdup(req->url);
459 if((qp = strchr(url, '?')) != NULL)
461 /* XXX: This is an ugly hack (I think), but though I can think of
462 * several alternatives, none seem to be better. */
463 if(*req->rest && (strlen(url) >= strlen(req->rest)) &&
464 !strcmp(req->rest, url + strlen(url) - strlen(req->rest))) {
465 url[strlen(url) - strlen(req->rest)] = 0;
467 if((pi = unquoteurl(req->rest)) == NULL)
468 pi = sstrdup(req->rest);
469 if(!strcmp(url, "/")) {
470 /* This seems to be normal CGI behavior, but see callcgi.c for
473 pi = sprintf2("/%s", tmp = pi);
476 bufaddenv(dst, "PATH_INFO", "%s", pi);
477 bufaddenv(dst, "SCRIPT_NAME", "%s", url);
478 bufaddenv(dst, "QUERY_STRING", "%s", qp?qp:"");
481 if((h = getheader(req, "Host")) != NULL)
482 bufaddenv(dst, "SERVER_NAME", "%s", h);
483 if((h = getheader(req, "X-Ash-Server-Address")) != NULL)
484 bufaddenv(dst, "SERVER_ADDR", "%s", h);
485 if((h = getheader(req, "X-Ash-Server-Port")) != NULL)
486 bufaddenv(dst, "SERVER_PORT", "%s", h);
487 if((h = getheader(req, "X-Ash-Remote-User")) != NULL)
488 bufaddenv(dst, "REMOTE_USER", "%s", h);
489 if(((h = getheader(req, "X-Ash-Protocol")) != NULL) && !strcmp(h, "https"))
490 bufaddenv(dst, "HTTPS", "on");
491 if((h = getheader(req, "X-Ash-Address")) != NULL)
492 bufaddenv(dst, "REMOTE_ADDR", "%s", h);
493 if((h = getheader(req, "X-Ash-Port")) != NULL)
494 bufaddenv(dst, "REMOTE_PORT", "%s", h);
495 if((h = getheader(req, "Content-Type")) != NULL)
496 bufaddenv(dst, "CONTENT_TYPE", "%s", h);
497 if((h = getheader(req, "Content-Length")) != NULL)
498 bufaddenv(dst, "CONTENT_LENGTH", "%s", h);
500 bufaddenv(dst, "CONTENT_LENGTH", "0");
501 if((h = getheader(req, "X-Ash-File")) != NULL) {
503 bufaddenv(dst, "SCRIPT_FILENAME", "%s", h);
506 for(i = 0; i < req->noheaders; i++) {
507 h = sprintf2("HTTP_%s", req->headers[i][0]);
508 for(p = h; *p; p++) {
514 bufcatkv(dst, h, req->headers[i][1]);
519 static struct hthead *parseresp(FILE *in)
525 resp->ver = sstrdup("HTTP/1.1");
526 if(parseheaders(resp, in)) {
530 if((st = getheader(resp, "Status")) != NULL) {
531 if((p = strchr(st, ' ')) != NULL) {
533 resp->code = atoi(st);
534 resp->msg = sstrdup(p);
536 resp->code = atoi(st);
537 resp->msg = sstrdup(httpdefstatus(resp->code));
539 headrmheader(resp, "Status");
540 } else if(getheader(resp, "Location")) {
542 resp->msg = sstrdup("See Other");
545 resp->msg = sstrdup("OK");
550 #define fputc2(b, f) if(fputc((b), (f)) == EOF) return(-1);
552 static int sendrec(FILE *out, int type, int rid, char *data, size_t dlen)
560 cl = min(dlen - off, 65535);
561 p = (8 - (cl % 8)) % 8;
564 fputc2((rid & 0xff00) >> 8, out);
565 fputc2(rid & 0x00ff, out);
566 fputc2((cl & 0xff00) >> 8, out);
567 fputc2(cl & 0x00ff, out);
570 if(fwrite(data + off, 1, cl, out) != cl)
574 } while((off += cl) < dlen);
578 static int recvrec(FILE *in, int *type, int *rid, char **data, size_t *dlen)
580 unsigned char header[8];
583 if(fread(header, 1, 8, in) != 8)
588 *rid = (header[2] << 8) | header[3];
589 *dlen = (header[4] << 8) | header[5];
590 tl = *dlen + header[6];
593 *data = smalloc(max(tl, 1));
594 if(fread(*data, 1, tl, in) != tl) {
601 static int begreq(FILE *out, int rid)
603 char rec[] = {0, 1, 0, 0, 0, 0, 0, 0};
605 return(sendrec(out, FCGI_BEGIN_REQUEST, rid, rec, 8));
608 static void outplex(struct muth *muth, va_list args)
625 while((ch.s = va_arg(args, FILE *)) != NULL) {
626 ch.id = va_arg(args, int);
631 if(recvrec(sk, &type, &rid, &data, &dlen))
635 for(i = 0; i < outs.d; i++) {
636 if(outs.b[i].id == type) {
637 if(outs.b[i].s != NULL) {
642 if(fwrite(data, 1, dlen, outs.b[i].s) != dlen)
656 for(i = 0; i < outs.d; i++) {
657 if(outs.b[i].s != NULL)
664 static void errhandler(struct muth *muth, va_list args)
671 while(fgets(buf, sizeof(buf), in) != NULL) {
672 p = buf + strlen(buf) - 1;
673 while((p >= buf) && (*p == '\n'))
676 flog(LOG_INFO, "child said: %s", buf);
681 static void serve(struct muth *muth, va_list args)
683 vavar(struct hthead *, req);
686 FILE *is, *os, *outi, *outo, *erri, *erro;
693 is = mtstdopen(fd, 1, 60, "r+");
694 os = mtstdopen(sfd, 1, 600, "r+");
697 mtiopipe(&outi, &outo); mtiopipe(&erri, &erro);
698 mustart(outplex, mtstdopen(dup(sfd), 1, 600, "r+"), outo, FCGI_STDOUT, erro, FCGI_STDERR, NULL);
699 mustart(errhandler, erri);
704 mkcgienv(req, &head);
705 if(sendrec(os, FCGI_PARAMS, 1, head.b, head.d))
707 if(sendrec(os, FCGI_PARAMS, 1, NULL, 0))
714 read = fread(buf, 1, sizeof(buf), is);
717 if(sendrec(os, FCGI_STDIN, 1, buf, read))
720 if(sendrec(os, FCGI_STDIN, 1, NULL, 0))
725 if((resp = parseresp(outi)) == NULL)
730 if(passdata(outi, is) < 0)
736 shutdown(sfd, SHUT_RDWR);
743 static void listenloop(struct muth *muth, va_list args)
750 block(0, EV_READ, 0);
751 if((fd = recvreq(lfd, &req)) < 0) {
753 flog(LOG_ERR, "recvreq: %s", strerror(errno));
756 mustart(serve, req, fd);
760 static void sigign(int sig)
764 static void sigexit(int sig)
766 shutdown(0, SHUT_RDWR);
769 static void usage(FILE *out)
771 fprintf(out, "usage: callfcgi [-h] [-N RETRIES] [-i ID] [-u UNIX-PATH] [-t [HOST:]TCP-PORT] [PROGRAM [ARGS...]]\n");
774 int main(int argc, char **argv)
778 while((c = getopt(argc, argv, "+hN:i:u:t:")) >= 0) {
784 nolisten = atoi(optarg);
800 progspec = argv + optind;
801 if(((sockid != NULL) + (unspec != NULL) + (inspec != NULL)) > 1) {
802 flog(LOG_ERR, "callfcgi: at most one of -i, -u or -t may be given");
805 signal(SIGCHLD, SIG_IGN);
806 signal(SIGPIPE, sigign);
807 signal(SIGINT, sigexit);
808 signal(SIGTERM, sigexit);
809 mustart(listenloop, 0);