bottleneck testcase based on rubbos
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / modules / experimental / mod_disk_cache.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "apr_file_io.h"
18 #include "apr_strings.h"
19 #include "mod_cache.h"
20 #include "ap_provider.h"
21 #include "util_filter.h"
22 #include "util_script.h"
23
24 #if APR_HAVE_UNISTD_H
25 #include <unistd.h> /* needed for unlink/link */
26 #endif
27
28 /* Our on-disk header format is:
29  *
30  * disk_cache_info_t
31  * entity name (dobj->name) [length is in disk_cache_info_t->name_len]
32  * r->headers_out (delimited by CRLF)
33  * CRLF
34  * r->headers_in (delimited by CRLF)
35  * CRLF
36  */
37 #define DISK_FORMAT_VERSION 0
38 typedef struct {
39     /* Indicates the format of the header struct stored on-disk. */
40     int format;
41     /* The HTTP status code returned for this response.  */
42     int status;
43     /* The size of the entity name that follows. */
44     apr_size_t name_len;
45     /* The number of times we've cached this entity. */
46     apr_size_t entity_version;
47     /* Miscellaneous time values. */
48     apr_time_t date;
49     apr_time_t expire;
50     apr_time_t request_time;
51     apr_time_t response_time;
52 } disk_cache_info_t;
53
54 /*
55  * disk_cache_object_t
56  * Pointed to by cache_object_t::vobj
57  */
58 typedef struct disk_cache_object {
59     const char *root;        /* the location of the cache directory */
60     char *tempfile;          /* temp file tohold the content */
61 #if 0
62     int dirlevels;              /* Number of levels of subdirectories */
63     int dirlength;            /* Length of subdirectory names */
64 #endif
65     char *datafile;          /* name of file where the data will go */
66     char *hdrsfile;          /* name of file where the hdrs will go */
67     char *hashfile;          /* Computed hash key for this URI */
68     char *name;
69     apr_file_t *fd;          /* data file */
70     apr_file_t *hfd;         /* headers file */
71     apr_file_t *tfd;         /* temporary file for data */
72     apr_off_t file_size;     /*  File size of the cached data file  */
73     disk_cache_info_t disk_info; /* Header information. */
74 } disk_cache_object_t;
75
76
77 /*
78  * mod_disk_cache configuration
79  */
80 /* TODO: Make defaults OS specific */
81 #define CACHEFILE_LEN 20        /* must be less than HASH_LEN/2 */
82 #define DEFAULT_DIRLEVELS 3
83 #define DEFAULT_DIRLENGTH 2
84 #define DEFAULT_MIN_FILE_SIZE 1
85 #define DEFAULT_MAX_FILE_SIZE 1000000
86 #define DEFAULT_CACHE_SIZE 1000000
87
88 typedef struct {
89     const char* cache_root;
90     apr_size_t cache_root_len;
91     off_t space;                 /* Maximum cache size (in 1024 bytes) */
92     apr_time_t maxexpire;        /* Maximum time to keep cached files in msecs */
93     apr_time_t defaultexpire;    /* default time to keep cached file in msecs */
94     double lmfactor;             /* factor for estimating expires date */
95     apr_time_t gcinterval;       /* garbage collection interval, in msec */
96     int dirlevels;               /* Number of levels of subdirectories */
97     int dirlength;               /* Length of subdirectory names */
98     int        expirychk;               /* true if expiry time is observed for cached files */
99     apr_size_t minfs;            /* minumum file size for cached files */
100     apr_size_t maxfs;            /* maximum file size for cached files */
101     apr_time_t mintm;            /* minimum time margin for caching files */
102     /* dgc_time_t gcdt;            time of day for daily garbage collection */
103     apr_array_header_t *gcclnun; /* gc_retain_t entries for unused files */
104     apr_array_header_t *gcclean; /* gc_retain_t entries for all files */
105     int maxgcmem;                /* maximum memory used by garbage collection */
106 } disk_cache_conf;
107
108 module AP_MODULE_DECLARE_DATA disk_cache_module;
109
110 /* Forward declarations */
111 static int remove_entity(cache_handle_t *h);
112 static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *i);
113 static apr_status_t store_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b);
114 static apr_status_t recall_headers(cache_handle_t *h, request_rec *r);
115 static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
116
117 /*
118  * Local static functions
119  */
120 #define CACHE_HEADER_SUFFIX ".header"
121 #define CACHE_DATA_SUFFIX   ".data"
122 static char *header_file(apr_pool_t *p, disk_cache_conf *conf,
123                          disk_cache_object_t *dobj, const char *name)
124 {
125     if (!dobj->hashfile) {
126         dobj->hashfile = generate_name(p, conf->dirlevels, conf->dirlength,
127                                        name);
128     }
129     return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
130                        CACHE_HEADER_SUFFIX, NULL);
131 }
132
133 static char *data_file(apr_pool_t *p, disk_cache_conf *conf,
134                        disk_cache_object_t *dobj, const char *name)
135 {
136     if (!dobj->hashfile) {
137         dobj->hashfile = generate_name(p, conf->dirlevels, conf->dirlength,
138                                        name);
139     }
140     return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
141                        CACHE_DATA_SUFFIX, NULL);
142 }
143
144 static void mkdir_structure(disk_cache_conf *conf, char *file, apr_pool_t *pool)
145 {
146     apr_status_t rv;
147     char *p;
148
149     for (p = file + conf->cache_root_len + 1;;) {
150         p = strchr(p, '/');
151         if (!p)
152             break;
153         *p = '\0';
154
155         rv = apr_dir_make(file,
156                           APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
157         if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
158             /* XXX */
159         }
160         *p = '/';
161         ++p;
162     }
163 }
164
165 static apr_status_t file_cache_el_final(disk_cache_object_t *dobj,
166                                         request_rec *r)
167 {
168     /* move the data over */
169     if (dobj->tfd) {
170         apr_status_t rv;
171
172         apr_file_close(dobj->tfd);
173
174         /* This assumes that the tempfile is on the same file system
175          * as the cache_root. If not, then we need a file copy/move
176          * rather than a rename.
177          */
178         rv = apr_file_rename(dobj->tempfile, dobj->datafile, r->pool);
179         if (rv != APR_SUCCESS) {
180             /* XXX log */
181         }
182
183         dobj->tfd = NULL;
184     }
185
186     return APR_SUCCESS;
187 }
188
189 static apr_status_t file_cache_errorcleanup(disk_cache_object_t *dobj, request_rec *r)
190 {
191     /* Remove the header file and the body file. */
192     apr_file_remove(dobj->hdrsfile, r->pool);
193     apr_file_remove(dobj->datafile, r->pool);
194
195     /* If we opened the temporary data file, close and remove it. */
196     if (dobj->tfd) {
197         apr_file_close(dobj->tfd);
198         apr_file_remove(dobj->tempfile, r->pool);
199         dobj->tfd = NULL;
200     }
201
202     return APR_SUCCESS;
203 }
204
205
206 /* These two functions get and put state information into the data
207  * file for an ap_cache_el, this state information will be read
208  * and written transparent to clients of this module
209  */
210 static int file_cache_recall_mydata(apr_file_t *fd, cache_info *info,
211                                     disk_cache_object_t *dobj, request_rec *r)
212 {
213     apr_status_t rv;
214     char *urlbuff;
215     disk_cache_info_t disk_info;
216     apr_size_t len;
217
218     /* read the data from the cache file */
219     len = sizeof(disk_cache_info_t);
220     rv = apr_file_read_full(fd, &disk_info, len, &len);
221     if (rv != APR_SUCCESS) {
222         return rv;
223     }
224
225     if (disk_info.format != DISK_FORMAT_VERSION) {
226         ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
227                      "cache_disk: URL %s had a on-disk version mismatch",
228                      r->uri);
229         return APR_EGENERAL;
230     }
231
232     /* Store it away so we can get it later. */
233     dobj->disk_info = disk_info;
234
235     info->date = disk_info.date;
236     info->expire = disk_info.expire;
237     info->request_time = disk_info.request_time;
238     info->response_time = disk_info.response_time;
239
240     /* Note that we could optimize this by conditionally doing the palloc
241      * depending upon the size. */
242     urlbuff = apr_palloc(r->pool, disk_info.name_len + 1);
243     len = disk_info.name_len;
244     rv = apr_file_read_full(fd, urlbuff, len, &len);
245     if (rv != APR_SUCCESS) {
246         return rv;
247     }
248     urlbuff[disk_info.name_len] = '\0';
249
250     /* check that we have the same URL */
251     /* Would strncmp be correct? */
252     if (strcmp(urlbuff, dobj->name) != 0) {
253         return APR_EGENERAL;
254     }
255
256     return APR_SUCCESS;
257 }
258
259 /*
260  * Hook and mod_cache callback functions
261  */
262 #define AP_TEMPFILE "/aptmpXXXXXX"
263 static int create_entity(cache_handle_t *h, request_rec *r,
264                          const char *key,
265                          apr_off_t len)
266 {
267     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
268                                                  &disk_cache_module);
269     cache_object_t *obj;
270     disk_cache_object_t *dobj;
271
272     if (conf->cache_root == NULL) {
273         return DECLINED;
274     }
275
276     /* If the Content-Length is still unknown, cache anyway */
277     if (len != -1 && (len < conf->minfs || len > conf->maxfs)) {
278         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
279                      "cache_disk: URL %s failed the size check, "
280                      "or is incomplete",
281                      key);
282         return DECLINED;
283     }
284
285     /* Allocate and initialize cache_object_t and disk_cache_object_t */
286     h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(*obj));
287     obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(*dobj));
288
289     obj->key = apr_pstrdup(r->pool, key);
290     /* XXX Bad Temporary Cast - see cache_object_t notes */
291     obj->info.len = (apr_size_t) len;
292     obj->complete = 0;   /* Cache object is not complete */
293
294     dobj->name = obj->key;
295     dobj->datafile = data_file(r->pool, conf, dobj, key);
296     dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
297     dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
298
299     return OK;
300 }
301
302 static int open_entity(cache_handle_t *h, request_rec *r, const char *key)
303 {
304     apr_status_t rc;
305     static int error_logged = 0;
306     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
307                                                  &disk_cache_module);
308     apr_finfo_t finfo;
309     cache_object_t *obj;
310     cache_info *info;
311     disk_cache_object_t *dobj;
312     int flags;
313
314     h->cache_obj = NULL;
315
316     /* Look up entity keyed to 'url' */
317     if (conf->cache_root == NULL) {
318         if (!error_logged) {
319             error_logged = 1;
320             ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
321                          "disk_cache: Cannot cache files to disk without a CacheRoot specified.");
322         }
323         return DECLINED;
324     }
325
326     /* Create and init the cache object */
327     h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(cache_object_t));
328     obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(disk_cache_object_t));
329
330     info = &(obj->info);
331     obj->key = (char *) key;
332     dobj->name = (char *) key;
333     dobj->datafile = data_file(r->pool, conf, dobj, key);
334     dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
335     dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
336
337     /* Open the data file */
338     flags = APR_READ|APR_BINARY;
339 #ifdef APR_SENDFILE_ENABLED
340     flags |= APR_SENDFILE_ENABLED;
341 #endif
342     rc = apr_file_open(&dobj->fd, dobj->datafile, flags, 0, r->pool);
343     if (rc != APR_SUCCESS) {
344         /* XXX: Log message */
345         return DECLINED;
346     }
347
348     /* Open the headers file */
349     flags = APR_READ|APR_BINARY|APR_BUFFERED;
350     rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
351     if (rc != APR_SUCCESS) {
352         /* XXX: Log message */
353         return DECLINED;
354     }
355
356     rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, dobj->fd);
357     if (rc == APR_SUCCESS) {
358         dobj->file_size = finfo.size;
359     }
360
361     /* Read the bytes to setup the cache_info fields */
362     rc = file_cache_recall_mydata(dobj->hfd, info, dobj, r);
363     if (rc != APR_SUCCESS) {
364         /* XXX log message */
365         return DECLINED;
366     }
367
368     /* Initialize the cache_handle callback functions */
369     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
370                  "disk_cache: Recalled cached URL info header %s",  dobj->name);
371     return OK;
372 }
373
374 static int remove_entity(cache_handle_t *h)
375 {
376     /* Null out the cache object pointer so next time we start from scratch  */
377     h->cache_obj = NULL;
378     return OK;
379 }
380
381 static int remove_url(const char *key)
382 {
383     /* XXX: Delete file from cache! */
384     return OK;
385 }
386
387 static apr_status_t read_table(cache_handle_t *handle, request_rec *r,
388                                apr_table_t *table, apr_file_t *file)
389 {
390     char w[MAX_STRING_LEN];
391     char *l;
392     int p;
393     apr_status_t rv;
394
395     while (1) {
396
397         /* ### What about APR_EOF? */
398         rv = apr_file_gets(w, MAX_STRING_LEN - 1, file);
399         if (rv != APR_SUCCESS) {
400             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
401                           "Premature end of cache headers.");
402             return rv;
403         }
404
405         /* Delete terminal (CR?)LF */
406
407         p = strlen(w);
408         /* Indeed, the host's '\n':
409            '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
410            -- whatever the script generates.
411         */
412         if (p > 0 && w[p - 1] == '\n') {
413             if (p > 1 && w[p - 2] == CR) {
414                 w[p - 2] = '\0';
415             }
416             else {
417                 w[p - 1] = '\0';
418             }
419         }
420
421         /* If we've finished reading the headers, break out of the loop. */
422         if (w[0] == '\0') {
423             break;
424         }
425
426 #if APR_CHARSET_EBCDIC
427         /* Chances are that we received an ASCII header text instead of
428          * the expected EBCDIC header lines. Try to auto-detect:
429          */
430         if (!(l = strchr(w, ':'))) {
431             int maybeASCII = 0, maybeEBCDIC = 0;
432             unsigned char *cp, native;
433             apr_size_t inbytes_left, outbytes_left;
434
435             for (cp = w; *cp != '\0'; ++cp) {
436                 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
437                 if (apr_isprint(*cp) && !apr_isprint(native))
438                     ++maybeEBCDIC;
439                 if (!apr_isprint(*cp) && apr_isprint(native))
440                     ++maybeASCII;
441             }
442             if (maybeASCII > maybeEBCDIC) {
443                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
444                              "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
445                              r->filename);
446                 inbytes_left = outbytes_left = cp - w;
447                 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
448                                       w, &inbytes_left, w, &outbytes_left);
449             }
450         }
451 #endif /*APR_CHARSET_EBCDIC*/
452
453         /* if we see a bogus header don't ignore it. Shout and scream */
454         if (!(l = strchr(w, ':'))) {
455             return APR_EGENERAL;
456         }
457
458         *l++ = '\0';
459         while (*l && apr_isspace(*l)) {
460             ++l;
461         }
462
463         apr_table_add(table, w, l);
464     }
465
466     return APR_SUCCESS;
467 }
468
469 /*
470  * Reads headers from a buffer and returns an array of headers.
471  * Returns NULL on file error
472  * This routine tries to deal with too long lines and continuation lines.
473  * @@@: XXX: FIXME: currently the headers are passed thru un-merged.
474  * Is that okay, or should they be collapsed where possible?
475  */
476 static apr_status_t recall_headers(cache_handle_t *h, request_rec *r)
477 {
478     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
479
480     /* This case should not happen... */
481     if (!dobj->hfd) {
482         /* XXX log message */
483         return APR_NOTFOUND;
484     }
485
486     h->req_hdrs = apr_table_make(r->pool, 20);
487     h->resp_hdrs = apr_table_make(r->pool, 20);
488     h->resp_err_hdrs = apr_table_make(r->pool, 20);
489
490     /* Call routine to read the header lines/status line */
491     read_table(h, r, h->resp_hdrs, dobj->hfd);
492     read_table(h, r, h->req_hdrs, dobj->hfd);
493
494     apr_file_close(dobj->hfd);
495
496     h->status = dobj->disk_info.status;
497     h->content_type = apr_table_get(h->resp_hdrs, "Content-Type");
498
499     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
500                  "disk_cache: Recalled headers for URL %s",  dobj->name);
501     return APR_SUCCESS;
502 }
503
504 static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb)
505 {
506     apr_bucket *e;
507     disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
508
509     e = apr_bucket_file_create(dobj->fd, 0, (apr_size_t) dobj->file_size, p,
510                                bb->bucket_alloc);
511     APR_BRIGADE_INSERT_HEAD(bb, e);
512     e = apr_bucket_eos_create(bb->bucket_alloc);
513     APR_BRIGADE_INSERT_TAIL(bb, e);
514
515     return APR_SUCCESS;
516 }
517
518 static apr_status_t store_table(apr_file_t *fd, apr_table_t *table)
519 {
520     int i;
521     apr_status_t rv;
522     struct iovec iov[4];
523     apr_size_t amt;
524     apr_table_entry_t *elts;
525
526     elts = (apr_table_entry_t *) apr_table_elts(table)->elts;
527     for (i = 0; i < apr_table_elts(table)->nelts; ++i) {
528         if (elts[i].key != NULL) {
529             iov[0].iov_base = elts[i].key;
530             iov[0].iov_len = strlen(elts[i].key);
531             iov[1].iov_base = ": ";
532             iov[1].iov_len = sizeof(": ") - 1;
533             iov[2].iov_base = elts[i].val;
534             iov[2].iov_len = strlen(elts[i].val);
535             iov[3].iov_base = CRLF;
536             iov[3].iov_len = sizeof(CRLF) - 1;
537
538             rv = apr_file_writev(fd, (const struct iovec *) &iov, 4,
539                                  &amt);
540             if (rv != APR_SUCCESS) {
541                 return rv;
542             }
543         }
544     }
545     iov[0].iov_base = CRLF;
546     iov[0].iov_len = sizeof(CRLF) - 1;
547     rv = apr_file_writev(fd, (const struct iovec *) &iov, 1,
548                          &amt);
549     return rv;
550 }
551
552 static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *info)
553 {
554     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
555                                                  &disk_cache_module);
556     apr_status_t rv;
557     apr_size_t amt;
558     disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
559
560     if (!dobj->hfd)  {
561         disk_cache_info_t disk_info;
562         struct iovec iov[2];
563
564         /* This is flaky... we need to manage the cache_info differently */
565         h->cache_obj->info = *info;
566
567         /* Remove old file with the same name. If remove fails, then
568          * perhaps we need to create the directory tree where we are
569          * about to write the new headers file.
570          */
571         rv = apr_file_remove(dobj->hdrsfile, r->pool);
572         if (rv != APR_SUCCESS) {
573             mkdir_structure(conf, dobj->hdrsfile, r->pool);
574         }
575
576         rv = apr_file_open(&dobj->hfd, dobj->hdrsfile,
577                            APR_WRITE | APR_CREATE | APR_EXCL,
578                            APR_OS_DEFAULT, r->pool);
579         if (rv != APR_SUCCESS) {
580             return rv;
581         }
582         dobj->name = h->cache_obj->key;
583
584         disk_info.format = DISK_FORMAT_VERSION;
585         disk_info.date = info->date;
586         disk_info.expire = info->expire;
587         disk_info.entity_version = dobj->disk_info.entity_version++;
588         disk_info.request_time = info->request_time;
589         disk_info.response_time = info->response_time;
590         disk_info.status = info->status;
591
592         disk_info.name_len = strlen(dobj->name);
593
594         iov[0].iov_base = (void*)&disk_info;
595         iov[0].iov_len = sizeof(disk_cache_info_t);
596         iov[1].iov_base = dobj->name;
597         iov[1].iov_len = disk_info.name_len;
598
599         rv = apr_file_writev(dobj->hfd, (const struct iovec *) &iov, 2, &amt);
600         if (rv != APR_SUCCESS) {
601             return rv;
602         }
603
604         if (r->headers_out) {
605             apr_table_t *headers_out;
606
607             headers_out = ap_cache_cacheable_hdrs_out(r->pool, r->headers_out,
608                                                       r->server);
609
610             if (!apr_table_get(headers_out, "Content-Type") &&
611                 r->content_type) {
612                 apr_table_setn(headers_out, "Content-Type",
613                                ap_make_content_type(r, r->content_type));
614             }
615
616             rv = store_table(dobj->hfd, headers_out);
617             if (rv != APR_SUCCESS) {
618                 return rv;
619             }
620
621         }
622
623         /* Parse the vary header and dump those fields from the headers_in. */
624         /* Make call to the same thing cache_select_url calls to crack Vary. */
625         /* @@@ Some day, not today. */
626         if (r->headers_in) {
627             apr_table_t *headers_in;
628
629             headers_in = ap_cache_cacheable_hdrs_out(r->pool, r->headers_in,
630                                                      r->server);
631             rv = store_table(dobj->hfd, headers_in);
632             if (rv != APR_SUCCESS) {
633                 return rv;
634             }
635         }
636         apr_file_close(dobj->hfd); /* flush and close */
637     }
638     else {
639         /* XXX log message */
640     }
641
642     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
643                  "disk_cache: Stored headers for URL %s",  dobj->name);
644     return APR_SUCCESS;
645 }
646
647 static apr_status_t store_body(cache_handle_t *h, request_rec *r,
648                                apr_bucket_brigade *bb)
649 {
650     apr_bucket *e;
651     apr_status_t rv;
652     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
653     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
654                                                  &disk_cache_module);
655
656     /* We write to a temp file and then atomically rename the file over
657      * in file_cache_el_final().
658      */
659     if (!dobj->tfd) {
660         rv = apr_file_mktemp(&dobj->tfd, dobj->tempfile,
661                              APR_CREATE | APR_WRITE | APR_BINARY |
662                              APR_BUFFERED | APR_EXCL, r->pool);
663         if (rv != APR_SUCCESS) {
664             return rv;
665         }
666         dobj->file_size = 0;
667     }
668
669     for (e = APR_BRIGADE_FIRST(bb);
670          e != APR_BRIGADE_SENTINEL(bb);
671          e = APR_BUCKET_NEXT(e))
672     {
673         const char *str;
674         apr_size_t length, written;
675         apr_bucket_read(e, &str, &length, APR_BLOCK_READ);
676         rv = apr_file_write_full(dobj->tfd, str, length, &written);
677         if (rv != APR_SUCCESS) {
678             ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
679                          "cache_disk: Error when writing cache file for URL %s",
680                          h->cache_obj->key);
681             /* Remove the intermediate cache file and return non-APR_SUCCESS */
682             file_cache_errorcleanup(dobj, r);
683             return APR_EGENERAL;
684         }
685         dobj->file_size += written;
686         if (dobj->file_size > conf->maxfs) {
687             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
688                          "cache_disk: URL %s failed the size check (%lu>%lu)",
689                          h->cache_obj->key, (unsigned long)dobj->file_size,
690                          (unsigned long)conf->maxfs);
691             /* Remove the intermediate cache file and return non-APR_SUCCESS */
692             file_cache_errorcleanup(dobj, r);
693             return APR_EGENERAL;
694         }
695     }
696
697     /* Was this the final bucket? If yes, close the temp file and perform
698      * sanity checks.
699      */
700     if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
701         if (h->cache_obj->info.len <= 0) {
702           /* If the target value of the content length is unknown
703            * (h->cache_obj->info.len <= 0), check if connection has been
704            * aborted by client to avoid caching incomplete request bodies.
705            *
706            * This can happen with large responses from slow backends like
707            * Tomcat via mod_jk.
708            */
709           if (r->connection->aborted) {
710             ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
711                          "disk_cache: Discarding body for URL %s "
712                          "because connection has been aborted.",
713                          h->cache_obj->key);
714             /* Remove the intermediate cache file and return non-APR_SUCCESS */
715             file_cache_errorcleanup(dobj, r);
716             return APR_EGENERAL;
717           }
718           /* XXX Fixme: file_size isn't constrained by size_t. */
719           h->cache_obj->info.len = dobj->file_size;
720         }
721         else if (h->cache_obj->info.len != dobj->file_size) {
722           /* "Content-Length" and actual content disagree in size. Log that. */
723           ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
724                        "disk_cache: URL %s failed the size check (%lu != %lu)",
725                        h->cache_obj->key,
726                        (unsigned long)h->cache_obj->info.len,
727                        (unsigned long)dobj->file_size);
728           /* Remove the intermediate cache file and return non-APR_SUCCESS */
729           file_cache_errorcleanup(dobj, r);
730           return APR_EGENERAL;
731         }
732         if (dobj->file_size < conf->minfs) {
733           ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
734                      "cache_disk: URL %s failed the size check (%lu<%lu)",
735                      h->cache_obj->key, (unsigned long)dobj->file_size, (unsigned long)conf->minfs);
736           /* Remove the intermediate cache file and return non-APR_SUCCESS */
737           file_cache_errorcleanup(dobj, r);
738           return APR_EGENERAL;
739         }
740
741         /* All checks were fine. Move tempfile to final destination */
742         /* Link to the perm file, and close the descriptor */
743         file_cache_el_final(dobj, r);
744         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
745                      "disk_cache: Body for URL %s cached.",  dobj->name);
746     }
747
748     return APR_SUCCESS;
749 }
750
751 static void *create_config(apr_pool_t *p, server_rec *s)
752 {
753     disk_cache_conf *conf = apr_pcalloc(p, sizeof(disk_cache_conf));
754
755     /* XXX: Set default values */
756     conf->dirlevels = DEFAULT_DIRLEVELS;
757     conf->dirlength = DEFAULT_DIRLENGTH;
758     conf->space = DEFAULT_CACHE_SIZE;
759     conf->maxfs = DEFAULT_MAX_FILE_SIZE;
760     conf->minfs = DEFAULT_MIN_FILE_SIZE;
761     conf->expirychk = 1;
762
763     conf->cache_root = NULL;
764     conf->cache_root_len = 0;
765
766     return conf;
767 }
768
769 /*
770  * mod_disk_cache configuration directives handlers.
771  */
772 static const char
773 *set_cache_root(cmd_parms *parms, void *in_struct_ptr, const char *arg)
774 {
775     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
776                                                  &disk_cache_module);
777     conf->cache_root = arg;
778     conf->cache_root_len = strlen(arg);
779     /* TODO: canonicalize cache_root and strip off any trailing slashes */
780
781     return NULL;
782 }
783 static const char
784 *set_cache_size(cmd_parms *parms, void *in_struct_ptr, const char *arg)
785 {
786     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
787                                                  &disk_cache_module);
788     conf->space = atoi(arg);
789     return NULL;
790 }
791 static const char
792 *set_cache_gcint(cmd_parms *parms, void *in_struct_ptr, const char *arg)
793 {
794 /*
795     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
796                                                  &disk_cache_module);
797 */
798     /* XXX */
799     return NULL;
800 }
801 /*
802  * Consider eliminating the next two directives in favor of
803  * Ian's prime number hash...
804  * key = hash_fn( r->uri)
805  * filename = "/key % prime1 /key %prime2/key %prime3"
806  */
807 static const char
808 *set_cache_dirlevels(cmd_parms *parms, void *in_struct_ptr, const char *arg)
809 {
810     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
811                                                  &disk_cache_module);
812     int val = atoi(arg);
813     if (val < 1)
814         return "CacheDirLevels value must be an integer greater than 0";
815     if (val * conf->dirlength > CACHEFILE_LEN)
816         return "CacheDirLevels*CacheDirLength value must not be higher than 20";
817     conf->dirlevels = val;
818     return NULL;
819 }
820 static const char
821 *set_cache_dirlength(cmd_parms *parms, void *in_struct_ptr, const char *arg)
822 {
823     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
824                                                  &disk_cache_module);
825     int val = atoi(arg);
826     if (val < 1)
827         return "CacheDirLength value must be an integer greater than 0";
828     if (val * conf->dirlevels > CACHEFILE_LEN)
829         return "CacheDirLevels*CacheDirLength value must not be higher than 20";
830
831     conf->dirlength = val;
832     return NULL;
833 }
834 static const char
835 *set_cache_exchk(cmd_parms *parms, void *in_struct_ptr, int flag)
836 {
837     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
838                                                  &disk_cache_module);
839     conf->expirychk = flag;
840
841     return NULL;
842 }
843 static const char
844 *set_cache_minfs(cmd_parms *parms, void *in_struct_ptr, const char *arg)
845 {
846     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
847                                                  &disk_cache_module);
848     conf->minfs = atoi(arg);
849     return NULL;
850 }
851 static const char
852 *set_cache_maxfs(cmd_parms *parms, void *in_struct_ptr, const char *arg)
853 {
854     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
855                                                  &disk_cache_module);
856     conf->maxfs = atoi(arg);
857     return NULL;
858 }
859 static const char
860 *set_cache_minetm(cmd_parms *parms, void *in_struct_ptr, const char *arg)
861 {
862     /* XXX
863     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
864                                                  &disk_cache_module);
865     */
866     return NULL;
867 }
868 static const char
869 *set_cache_gctime(cmd_parms *parms, void *in_struct_ptr, const char *arg)
870 {
871     /* XXX
872     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
873                                                  &disk_cache_module);
874     */
875     return NULL;
876 }
877 static const char
878 *add_cache_gcclean(cmd_parms *parms, void *in_struct_ptr, const char *arg, const char *arg1)
879 {
880     /* XXX
881     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
882                                                  &disk_cache_module);
883     */
884     return NULL;
885 }
886 static const char
887 *add_cache_gcclnun(cmd_parms *parms, void *in_struct_ptr, const char *arg, const char *arg1)
888 {
889     /* XXX
890     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
891                                                  &disk_cache_module);
892     */
893     return NULL;
894 }
895 static const char
896 *set_cache_maxgcmem(cmd_parms *parms, void *in_struct_ptr, const char *arg)
897 {
898     /* XXX
899     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
900                                                  &disk_cache_module);
901     */
902     return NULL;
903 }
904
905 static const command_rec disk_cache_cmds[] =
906 {
907     AP_INIT_TAKE1("CacheRoot", set_cache_root, NULL, RSRC_CONF,
908                  "The directory to store cache files"),
909     AP_INIT_TAKE1("CacheSize", set_cache_size, NULL, RSRC_CONF,
910                   "The maximum disk space used by the cache in KB"),
911     AP_INIT_TAKE1("CacheGcInterval", set_cache_gcint, NULL, RSRC_CONF,
912                   "The interval between garbage collections, in hours"),
913     AP_INIT_TAKE1("CacheDirLevels", set_cache_dirlevels, NULL, RSRC_CONF,
914                   "The number of levels of subdirectories in the cache"),
915     AP_INIT_TAKE1("CacheDirLength", set_cache_dirlength, NULL, RSRC_CONF,
916                   "The number of characters in subdirectory names"),
917     AP_INIT_FLAG("CacheExpiryCheck", set_cache_exchk, NULL, RSRC_CONF,
918                  "on if cache observes Expires date when seeking files"),
919     AP_INIT_TAKE1("CacheMinFileSize", set_cache_minfs, NULL, RSRC_CONF,
920                   "The minimum file size to cache a document"),
921     AP_INIT_TAKE1("CacheMaxFileSize", set_cache_maxfs, NULL, RSRC_CONF,
922                   "The maximum file size to cache a document"),
923     AP_INIT_TAKE1("CacheTimeMargin", set_cache_minetm, NULL, RSRC_CONF,
924                   "The minimum time margin to cache a document"),
925     AP_INIT_TAKE1("CacheGcDaily", set_cache_gctime, NULL, RSRC_CONF,
926                   "The time of day for garbage collection (24 hour clock)"),
927     AP_INIT_TAKE2("CacheGcUnused", add_cache_gcclnun, NULL, RSRC_CONF,
928                   "The time in hours to retain unused file that match a url"),
929     AP_INIT_TAKE2("CacheGcClean", add_cache_gcclean, NULL, RSRC_CONF,
930                   "The time in hours to retain unchanged files that match a url"),
931     AP_INIT_TAKE1("CacheGcMemUsage", set_cache_maxgcmem, NULL, RSRC_CONF,
932                   "The maximum kilobytes of memory used for garbage collection"),
933     {NULL}
934 };
935
936 static const cache_provider cache_disk_provider =
937 {
938     &remove_entity,
939     &store_headers,
940     &store_body,
941     &recall_headers,
942     &recall_body,
943     &create_entity,
944     &open_entity,
945     &remove_url,
946 };
947
948 static void disk_cache_register_hook(apr_pool_t *p)
949 {
950     /* cache initializer */
951     ap_register_provider(p, CACHE_PROVIDER_GROUP, "disk", "0",
952                          &cache_disk_provider);
953 }
954
955 module AP_MODULE_DECLARE_DATA disk_cache_module = {
956     STANDARD20_MODULE_STUFF,
957     NULL,                       /* create per-directory config structure */
958     NULL,                       /* merge per-directory config structures */
959     create_config,              /* create per-server config structure */
960     NULL,                       /* merge per-server config structures */
961     disk_cache_cmds,            /* command apr_table_t */
962     disk_cache_register_hook    /* register hooks */
963 };