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/>.
36 static void passdata(int in, int out)
43 len = read(in, buf, 65536);
45 flog(LOG_ERR, "sendfile: could not read input: %s", strerror(errno));
50 for(off = 0; off < len; off += ret) {
51 ret = write(out, buf + off, len - off);
53 flog(LOG_ERR, "sendfile: could not write output: %s", strerror(errno));
61 static int strrcmp(char *str, char *end)
63 return(strcmp(str + strlen(str) - strlen(end), end));
66 static char *getmimetype(char *file, struct stat *sb)
68 /* Rewrite with libmagic. */
69 if(!strrcmp(file, ".html"))
71 if(!strrcmp(file, ".xhtml"))
72 return("application/xhtml+xml");
73 if(!strrcmp(file, ".txt"))
75 if(!strrcmp(file, ".css"))
77 if(!strrcmp(file, ".py"))
79 if(!strrcmp(file, ".c"))
81 return("application/octet-stream");
84 static void checkcache(char *file, struct stat *sb)
88 if((hdr = getenv("REQ_IF_MODIFIED_SINCE")) != NULL) {
89 if(parsehttpdate(hdr) < sb->st_mtime)
91 printf("HTTP/1.1 304 Not Modified\r\n");
92 printf("Date: %s\r\n", fmthttpdate(time(NULL)));
93 printf("Content-Length: 0\r\n");
99 static void usage(void)
101 flog(LOG_ERR, "usage: sendfile [-c CONTENT-TYPE] METHOD URL REST");
104 int main(int argc, char **argv)
113 while((c = getopt(argc, argv, "c:")) >= 0) {
124 if(argc - optind < 3) {
128 if((file = getenv("REQ_X_ASH_FILE")) == NULL) {
129 flog(LOG_ERR, "sendfile: needs to be called with the X-Ash-File header");
132 if(*argv[optind + 2]) {
133 simpleerror(1, 404, "Not Found", "The requested URL has no corresponding resource.");
136 if(stat(file, &sb) || ((fd = open(file, O_RDONLY)) < 0)) {
137 flog(LOG_ERR, "sendfile: could not stat input file %s: %s", file, strerror(errno));
138 simpleerror(1, 500, "Internal Error", "The server could not access its own data.");
142 contype = getmimetype(file, &sb);
144 checkcache(file, &sb);
146 printf("HTTP/1.1 200 OK\r\n");
147 printf("Content-Type: %s\r\n", contype);
148 printf("Content-Length: %ji\r\n", (intmax_t)sb.st_size);
149 printf("Last-Modified: %s\r\n", fmthttpdate(sb.st_mtime));
150 printf("Date: %s\r\n", fmthttpdate(time(NULL)));
153 if(strcasecmp(argv[optind], "head"))