/* Copyright (C) 2011 Jeff Epler * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #include #include #include #include #include #include #include #define streq(a,b) (strcmp((a),(b)) == 0) char *read_file(char *name, char **end, time_t *mtime) { int f = open(name, O_RDONLY); int sz; struct stat st; if(f == -1) { perror(name); return 0; } fstat(f, &st); char *result = malloc(st.st_size+1); size_t bytes_read = read(f, result, st.st_size); if(bytes_read != st.st_size) { free(result); return 0; } result[bytes_read] = 0; *end = result + bytes_read; *mtime = st.st_mtime; fprintf(stderr, "read=%zd mtime=%ld\n", bytes_read, (long)st.st_mtime); return result; } char *strip(char *s, int ch) { if(!s) return NULL; while(*s == ch) s++; char *t = s + strlen(s) - 1; while(t > s && *t == ch) *t = 0; return s; } int cache_valid(char **dptr, time_t deptime) { char *REQUEST_METHOD = getenv("REQUEST_METHOD"); char *QUERY_STRING = getenv("QUERY_STRING"); if(QUERY_STRING && strlen(QUERY_STRING)) return 0; if(!REQUEST_METHOD) return 0; if(strcmp(REQUEST_METHOD, "GET") && strcmp(REQUEST_METHOD, "HEAD")) return 0; struct stat st; if(!*dptr) return 0; char *dep = *dptr; while(*dep) { if(stat(dep, &st) != 0) { fprintf(stderr, "stat %s -> %s\n", dep, strerror(errno)); return 0; } if(st.st_mtime > deptime) { fprintf(stderr, "mtime %s %ld > %ld\n", dep, (long)st.st_mtime, (long)deptime); return 0; } dep = dep + strlen(dep) + 1; } *dptr = dep + 1; return 1; } int main(int argc, char **argv) { char *PATH_INFO = getenv("PATH_INFO"); char *REQUEST_METHOD = getenv("REQUEST_METHOD"); char *real_script = getenv("REAL_SCRIPT"); char *cache; if(!PATH_INFO) PATH_INFO = strdup(""); PATH_INFO = strip(PATH_INFO, '/'); asprintf(&cache, "%s-cache/%s/_cache", real_script, PATH_INFO); time_t mtime; char *end; char *data = read_file(cache, &end, &mtime); if(cache_valid(&data, mtime)) { fprintf(stderr, "Using cache %s\n", cache); if(streq(REQUEST_METHOD, "HEAD")) { end = strstr(data, "\n\n"); } while(end != data) { ssize_t r = write(1, data, end-data); if(r < 0) { perror("write"); break; } data += r; } } else { // unlink(cache); argv[0] = real_script; execv(real_script, argv); } }