]> granicus.if.org Git - apache/blob - modules/cache/mod_cache_disk.c
Fix a corner case where automatic APLOGNO number generation generates invalid code...
[apache] / modules / cache / mod_cache_disk.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_lib.h"
18 #include "apr_file_io.h"
19 #include "apr_strings.h"
20 #include "mod_cache.h"
21 #include "mod_cache_disk.h"
22 #include "http_config.h"
23 #include "http_log.h"
24 #include "http_core.h"
25 #include "ap_provider.h"
26 #include "util_filter.h"
27 #include "util_script.h"
28 #include "util_charset.h"
29
30 /*
31  * mod_cache_disk: Disk Based HTTP 1.1 Cache.
32  *
33  * Flow to Find the .data file:
34  *   Incoming client requests URI /foo/bar/baz
35  *   Generate <hash> off of /foo/bar/baz
36  *   Open <hash>.header
37  *   Read in <hash>.header file (may contain Format #1 or Format #2)
38  *   If format #1 (Contains a list of Vary Headers):
39  *      Use each header name (from .header) with our request values (headers_in) to
40  *      regenerate <hash> using HeaderName+HeaderValue+.../foo/bar/baz
41  *      re-read in <hash>.header (must be format #2)
42  *   read in <hash>.data
43  *
44  * Format #1:
45  *   apr_uint32_t format;
46  *   apr_time_t expire;
47  *   apr_array_t vary_headers (delimited by CRLF)
48  *
49  * Format #2:
50  *   disk_cache_info_t (first sizeof(apr_uint32_t) bytes is the format)
51  *   entity name (dobj->name) [length is in disk_cache_info_t->name_len]
52  *   r->headers_out (delimited by CRLF)
53  *   CRLF
54  *   r->headers_in (delimited by CRLF)
55  *   CRLF
56  */
57
58 module AP_MODULE_DECLARE_DATA cache_disk_module;
59
60 /* Forward declarations */
61 static int remove_entity(cache_handle_t *h);
62 static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *i);
63 static apr_status_t store_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *in,
64                                apr_bucket_brigade *out);
65 static apr_status_t recall_headers(cache_handle_t *h, request_rec *r);
66 static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
67 static apr_status_t read_array(request_rec *r, apr_array_header_t* arr,
68                                apr_file_t *file);
69
70 /*
71  * Local static functions
72  */
73
74 static char *header_file(apr_pool_t *p, disk_cache_conf *conf,
75                          disk_cache_object_t *dobj, const char *name)
76 {
77     if (!dobj->hashfile) {
78         dobj->hashfile = ap_cache_generate_name(p, conf->dirlevels,
79                                                 conf->dirlength, name);
80     }
81
82     if (dobj->prefix) {
83         return apr_pstrcat(p, dobj->prefix, CACHE_VDIR_SUFFIX "/",
84                            dobj->hashfile, CACHE_HEADER_SUFFIX, NULL);
85      }
86      else {
87         return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
88                            CACHE_HEADER_SUFFIX, NULL);
89      }
90 }
91
92 static char *data_file(apr_pool_t *p, disk_cache_conf *conf,
93                        disk_cache_object_t *dobj, const char *name)
94 {
95     if (!dobj->hashfile) {
96         dobj->hashfile = ap_cache_generate_name(p, conf->dirlevels,
97                                                 conf->dirlength, name);
98     }
99
100     if (dobj->prefix) {
101         return apr_pstrcat(p, dobj->prefix, CACHE_VDIR_SUFFIX "/",
102                            dobj->hashfile, CACHE_DATA_SUFFIX, NULL);
103      }
104      else {
105         return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
106                            CACHE_DATA_SUFFIX, NULL);
107      }
108 }
109
110 static apr_status_t mkdir_structure(disk_cache_conf *conf, const char *file, apr_pool_t *pool)
111 {
112     apr_status_t rv;
113     char *p;
114
115     for (p = (char*)file + conf->cache_root_len + 1;;) {
116         p = strchr(p, '/');
117         if (!p)
118             break;
119         *p = '\0';
120
121         rv = apr_dir_make(file,
122                           APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
123         if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
124             return rv;
125         }
126         *p = '/';
127         ++p;
128     }
129     return APR_SUCCESS;
130 }
131
132 /* htcacheclean may remove directories underneath us.
133  * So, we'll try renaming three times at a cost of 0.002 seconds.
134  */
135 static apr_status_t safe_file_rename(disk_cache_conf *conf,
136                                      const char *src, const char *dest,
137                                      apr_pool_t *pool)
138 {
139     apr_status_t rv;
140
141     rv = apr_file_rename(src, dest, pool);
142
143     if (rv != APR_SUCCESS) {
144         int i;
145
146         for (i = 0; i < 2 && rv != APR_SUCCESS; i++) {
147             /* 1000 micro-seconds aka 0.001 seconds. */
148             apr_sleep(1000);
149
150             rv = mkdir_structure(conf, dest, pool);
151             if (rv != APR_SUCCESS)
152                 continue;
153
154             rv = apr_file_rename(src, dest, pool);
155         }
156     }
157
158     return rv;
159 }
160
161 static apr_status_t file_cache_el_final(disk_cache_conf *conf, disk_cache_file_t *file,
162                                         request_rec *r)
163 {
164     apr_status_t rv = APR_SUCCESS;
165
166     /* This assumes that the tempfiles are on the same file system
167      * as the cache_root. If not, then we need a file copy/move
168      * rather than a rename.
169      */
170
171     /* move the file over */
172     if (file->tempfd) {
173
174         rv = safe_file_rename(conf, file->tempfile, file->file, file->pool);
175         if (rv != APR_SUCCESS) {
176             ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00699)
177                     "rename tempfile to file failed:"
178                     " %s -> %s", file->tempfile, file->file);
179             apr_file_remove(file->tempfile, file->pool);
180         }
181
182         file->tempfd = NULL;
183     }
184
185     return rv;
186 }
187
188 static apr_status_t file_cache_temp_cleanup(void *dummy)
189 {
190     disk_cache_file_t *file = (disk_cache_file_t *)dummy;
191
192     /* clean up the temporary file */
193     if (file->tempfd) {
194         apr_file_remove(file->tempfile, file->pool);
195         file->tempfd = NULL;
196     }
197     file->tempfile = NULL;
198     file->pool = NULL;
199
200     return APR_SUCCESS;
201 }
202
203 static apr_status_t file_cache_create(disk_cache_conf *conf, disk_cache_file_t *file,
204                                       apr_pool_t *pool)
205 {
206     file->pool = pool;
207     file->tempfile = apr_pstrcat(pool, conf->cache_root, AP_TEMPFILE, NULL);
208
209     apr_pool_cleanup_register(pool, file, file_cache_temp_cleanup, apr_pool_cleanup_null);
210
211     return APR_SUCCESS;
212 }
213
214 /* These two functions get and put state information into the data
215  * file for an ap_cache_el, this state information will be read
216  * and written transparent to clients of this module
217  */
218 static int file_cache_recall_mydata(apr_file_t *fd, cache_info *info,
219                                     disk_cache_object_t *dobj, request_rec *r)
220 {
221     apr_status_t rv;
222     char *urlbuff;
223     apr_size_t len;
224
225     /* read the data from the cache file */
226     len = sizeof(disk_cache_info_t);
227     rv = apr_file_read_full(fd, &dobj->disk_info, len, &len);
228     if (rv != APR_SUCCESS) {
229         return rv;
230     }
231
232     /* Store it away so we can get it later. */
233     info->status = dobj->disk_info.status;
234     info->date = dobj->disk_info.date;
235     info->expire = dobj->disk_info.expire;
236     info->request_time = dobj->disk_info.request_time;
237     info->response_time = dobj->disk_info.response_time;
238
239     memcpy(&info->control, &dobj->disk_info.control, sizeof(cache_control_t));
240
241     /* Note that we could optimize this by conditionally doing the palloc
242      * depending upon the size. */
243     urlbuff = apr_palloc(r->pool, dobj->disk_info.name_len + 1);
244     len = dobj->disk_info.name_len;
245     rv = apr_file_read_full(fd, urlbuff, len, &len);
246     if (rv != APR_SUCCESS) {
247         return rv;
248     }
249     urlbuff[dobj->disk_info.name_len] = '\0';
250
251     /* check that we have the same URL */
252     /* Would strncmp be correct? */
253     if (strcmp(urlbuff, dobj->name) != 0) {
254         return APR_EGENERAL;
255     }
256
257     return APR_SUCCESS;
258 }
259
260 static const char* regen_key(apr_pool_t *p, apr_table_t *headers,
261                              apr_array_header_t *varray, const char *oldkey)
262 {
263     struct iovec *iov;
264     int i, k;
265     int nvec;
266     const char *header;
267     const char **elts;
268
269     nvec = (varray->nelts * 2) + 1;
270     iov = apr_palloc(p, sizeof(struct iovec) * nvec);
271     elts = (const char **) varray->elts;
272
273     /* TODO:
274      *    - Handle multiple-value headers better. (sort them?)
275      *    - Handle Case in-sensitive Values better.
276      *        This isn't the end of the world, since it just lowers the cache
277      *        hit rate, but it would be nice to fix.
278      *
279      * The majority are case insenstive if they are values (encoding etc).
280      * Most of rfc2616 is case insensitive on header contents.
281      *
282      * So the better solution may be to identify headers which should be
283      * treated case-sensitive?
284      *  HTTP URI's (3.2.3) [host and scheme are insensitive]
285      *  HTTP method (5.1.1)
286      *  HTTP-date values (3.3.1)
287      *  3.7 Media Types [exerpt]
288      *     The type, subtype, and parameter attribute names are case-
289      *     insensitive. Parameter values might or might not be case-sensitive,
290      *     depending on the semantics of the parameter name.
291      *  4.20 Except [exerpt]
292      *     Comparison of expectation values is case-insensitive for unquoted
293      *     tokens (including the 100-continue token), and is case-sensitive for
294      *     quoted-string expectation-extensions.
295      */
296
297     for (i=0, k=0; i < varray->nelts; i++) {
298         header = apr_table_get(headers, elts[i]);
299         if (!header) {
300             header = "";
301         }
302         iov[k].iov_base = (char*) elts[i];
303         iov[k].iov_len = strlen(elts[i]);
304         k++;
305         iov[k].iov_base = (char*) header;
306         iov[k].iov_len = strlen(header);
307         k++;
308     }
309     iov[k].iov_base = (char*) oldkey;
310     iov[k].iov_len = strlen(oldkey);
311     k++;
312
313     return apr_pstrcatv(p, iov, k, NULL);
314 }
315
316 static int array_alphasort(const void *fn1, const void *fn2)
317 {
318     return strcmp(*(char**)fn1, *(char**)fn2);
319 }
320
321 static void tokens_to_array(apr_pool_t *p, const char *data,
322                             apr_array_header_t *arr)
323 {
324     char *token;
325
326     while ((token = ap_get_list_item(p, &data)) != NULL) {
327         *((const char **) apr_array_push(arr)) = token;
328     }
329
330     /* Sort it so that "Vary: A, B" and "Vary: B, A" are stored the same. */
331     qsort((void *) arr->elts, arr->nelts,
332          sizeof(char *), array_alphasort);
333 }
334
335 /*
336  * Hook and mod_cache callback functions
337  */
338 static int create_entity(cache_handle_t *h, request_rec *r, const char *key, apr_off_t len,
339                          apr_bucket_brigade *bb)
340 {
341     disk_cache_dir_conf *dconf = ap_get_module_config(r->per_dir_config, &cache_disk_module);
342     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
343                                                  &cache_disk_module);
344     cache_object_t *obj;
345     disk_cache_object_t *dobj;
346     apr_pool_t *pool;
347
348     if (conf->cache_root == NULL) {
349         return DECLINED;
350     }
351
352     /* we don't support caching of range requests (yet) */
353     if (r->status == HTTP_PARTIAL_CONTENT) {
354         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00700)
355                 "URL %s partial content response not cached",
356                 key);
357         return DECLINED;
358     }
359
360     /* Note, len is -1 if unknown so don't trust it too hard */
361     if (len > dconf->maxfs) {
362         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00701)
363                 "URL %s failed the size check "
364                 "(%" APR_OFF_T_FMT " > %" APR_OFF_T_FMT ")",
365                 key, len, dconf->maxfs);
366         return DECLINED;
367     }
368     if (len >= 0 && len < dconf->minfs) {
369         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00702)
370                 "URL %s failed the size check "
371                 "(%" APR_OFF_T_FMT " < %" APR_OFF_T_FMT ")",
372                 key, len, dconf->minfs);
373         return DECLINED;
374     }
375
376     /* Allocate and initialize cache_object_t and disk_cache_object_t */
377     h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(*obj));
378     obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(*dobj));
379
380     obj->key = apr_pstrdup(r->pool, key);
381
382     dobj->name = obj->key;
383     dobj->prefix = NULL;
384     /* Save the cache root */
385     dobj->root = apr_pstrmemdup(r->pool, conf->cache_root, conf->cache_root_len);
386     dobj->root_len = conf->cache_root_len;
387
388     apr_pool_create(&pool, r->pool);
389     apr_pool_tag(pool, "mod_cache (create_entity)");
390
391     file_cache_create(conf, &dobj->hdrs, pool);
392     file_cache_create(conf, &dobj->vary, pool);
393     file_cache_create(conf, &dobj->data, pool);
394
395     dobj->data.file = data_file(r->pool, conf, dobj, key);
396     dobj->hdrs.file = header_file(r->pool, conf, dobj, key);
397     dobj->vary.file = header_file(r->pool, conf, dobj, key);
398
399     dobj->disk_info.header_only = r->header_only;
400
401     return OK;
402 }
403
404 static int open_entity(cache_handle_t *h, request_rec *r, const char *key)
405 {
406     apr_uint32_t format;
407     apr_size_t len;
408     const char *nkey;
409     apr_status_t rc;
410     static int error_logged = 0;
411     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
412                                                  &cache_disk_module);
413 #ifdef APR_SENDFILE_ENABLED
414     core_dir_config *coreconf = ap_get_core_module_config(r->per_dir_config);
415 #endif
416     apr_finfo_t finfo;
417     cache_object_t *obj;
418     cache_info *info;
419     disk_cache_object_t *dobj;
420     int flags;
421     apr_pool_t *pool;
422
423     h->cache_obj = NULL;
424
425     /* Look up entity keyed to 'url' */
426     if (conf->cache_root == NULL) {
427         if (!error_logged) {
428             error_logged = 1;
429             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00703)
430                     "Cannot cache files to disk without a CacheRoot specified.");
431         }
432         return DECLINED;
433     }
434
435     /* Create and init the cache object */
436     obj = apr_pcalloc(r->pool, sizeof(cache_object_t));
437     dobj = apr_pcalloc(r->pool, sizeof(disk_cache_object_t));
438
439     info = &(obj->info);
440
441     /* Open the headers file */
442     dobj->prefix = NULL;
443
444     /* Save the cache root */
445     dobj->root = apr_pstrmemdup(r->pool, conf->cache_root, conf->cache_root_len);
446     dobj->root_len = conf->cache_root_len;
447
448     dobj->vary.file = header_file(r->pool, conf, dobj, key);
449     flags = APR_READ|APR_BINARY|APR_BUFFERED;
450     rc = apr_file_open(&dobj->vary.fd, dobj->vary.file, flags, 0, r->pool);
451     if (rc != APR_SUCCESS) {
452         return DECLINED;
453     }
454
455     /* read the format from the cache file */
456     len = sizeof(format);
457     apr_file_read_full(dobj->vary.fd, &format, len, &len);
458
459     if (format == VARY_FORMAT_VERSION) {
460         apr_array_header_t* varray;
461         apr_time_t expire;
462
463         len = sizeof(expire);
464         apr_file_read_full(dobj->vary.fd, &expire, len, &len);
465
466         varray = apr_array_make(r->pool, 5, sizeof(char*));
467         rc = read_array(r, varray, dobj->vary.fd);
468         if (rc != APR_SUCCESS) {
469             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(00704)
470                     "Cannot parse vary header file: %s",
471                     dobj->vary.file);
472             apr_file_close(dobj->vary.fd);
473             return DECLINED;
474         }
475         apr_file_close(dobj->vary.fd);
476
477         nkey = regen_key(r->pool, r->headers_in, varray, key);
478
479         dobj->hashfile = NULL;
480         dobj->prefix = dobj->vary.file;
481         dobj->hdrs.file = header_file(r->pool, conf, dobj, nkey);
482
483         flags = APR_READ|APR_BINARY|APR_BUFFERED;
484         rc = apr_file_open(&dobj->hdrs.fd, dobj->hdrs.file, flags, 0, r->pool);
485         if (rc != APR_SUCCESS) {
486             return DECLINED;
487         }
488     }
489     else if (format != DISK_FORMAT_VERSION) {
490         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00705)
491                 "File '%s' has a version mismatch. File had version: %d.",
492                 dobj->vary.file, format);
493         apr_file_close(dobj->vary.fd);
494         return DECLINED;
495     }
496     else {
497         apr_off_t offset = 0;
498
499         /* oops, not vary as it turns out */
500         dobj->hdrs.fd = dobj->vary.fd;
501         dobj->vary.fd = NULL;
502         dobj->hdrs.file = dobj->vary.file;
503
504         /* This wasn't a Vary Format file, so we must seek to the
505          * start of the file again, so that later reads work.
506          */
507         apr_file_seek(dobj->hdrs.fd, APR_SET, &offset);
508         nkey = key;
509     }
510
511     obj->key = nkey;
512     dobj->key = nkey;
513     dobj->name = key;
514
515     apr_pool_create(&pool, r->pool);
516     apr_pool_tag(pool, "mod_cache (open_entity)");
517
518     file_cache_create(conf, &dobj->hdrs, pool);
519     file_cache_create(conf, &dobj->vary, pool);
520     file_cache_create(conf, &dobj->data, pool);
521
522     dobj->data.file = data_file(r->pool, conf, dobj, nkey);
523
524     /* Read the bytes to setup the cache_info fields */
525     rc = file_cache_recall_mydata(dobj->hdrs.fd, info, dobj, r);
526     if (rc != APR_SUCCESS) {
527         ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(00706)
528                 "Cannot read header file %s", dobj->hdrs.file);
529         apr_file_close(dobj->hdrs.fd);
530         return DECLINED;
531     }
532
533
534     /* Is this a cached HEAD request? */
535     if (dobj->disk_info.header_only && !r->header_only) {
536         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, r, APLOGNO(00707)
537                 "HEAD request cached, non-HEAD requested, ignoring: %s",
538                 dobj->hdrs.file);
539         apr_file_close(dobj->hdrs.fd);
540         return DECLINED;
541     }
542
543     /* Open the data file */
544     if (dobj->disk_info.has_body) {
545         flags = APR_READ | APR_BINARY;
546 #ifdef APR_SENDFILE_ENABLED
547         /* When we are in the quick handler we don't have the per-directory
548          * configuration, so this check only takes the global setting of
549          * the EnableSendFile directive into account.
550          */
551         flags |= AP_SENDFILE_ENABLED(coreconf->enable_sendfile);
552 #endif
553         rc = apr_file_open(&dobj->data.fd, dobj->data.file, flags, 0, r->pool);
554         if (rc != APR_SUCCESS) {
555             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(00708)
556                     "Cannot open data file %s", dobj->data.file);
557             apr_file_close(dobj->hdrs.fd);
558             return DECLINED;
559         }
560
561         rc = apr_file_info_get(&finfo, APR_FINFO_SIZE | APR_FINFO_IDENT,
562                 dobj->data.fd);
563         if (rc == APR_SUCCESS) {
564             dobj->file_size = finfo.size;
565         }
566
567         /* Atomic check - does the body file belong to the header file? */
568         if (dobj->disk_info.inode == finfo.inode &&
569                 dobj->disk_info.device == finfo.device) {
570
571             /* Initialize the cache_handle callback functions */
572             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00709)
573                     "Recalled cached URL info header %s", dobj->name);
574
575             /* make the configuration stick */
576             h->cache_obj = obj;
577             obj->vobj = dobj;
578
579             return OK;
580         }
581
582     }
583     else {
584
585         /* make the configuration stick */
586         h->cache_obj = obj;
587         obj->vobj = dobj;
588
589         return OK;
590     }
591
592     /* Oh dear, no luck matching header to the body */
593     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00710)
594             "Cached URL info header '%s' didn't match body, ignoring this entry",
595             dobj->name);
596
597     apr_file_close(dobj->hdrs.fd);
598     return DECLINED;
599 }
600
601 static void close_disk_cache_fd(disk_cache_file_t *file)
602 {
603    if (file->fd != NULL) {
604        apr_file_close(file->fd);
605        file->fd = NULL;
606    }
607    if (file->tempfd != NULL) {
608        apr_file_close(file->tempfd);
609        file->tempfd = NULL;
610    }
611 }
612
613 static int remove_entity(cache_handle_t *h)
614 {
615     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
616
617     close_disk_cache_fd(&(dobj->hdrs));
618     close_disk_cache_fd(&(dobj->vary));
619     close_disk_cache_fd(&(dobj->data));
620
621     /* Null out the cache object pointer so next time we start from scratch  */
622     h->cache_obj = NULL;
623     return OK;
624 }
625
626 static int remove_url(cache_handle_t *h, request_rec *r)
627 {
628     apr_status_t rc;
629     disk_cache_object_t *dobj;
630
631     /* Get disk cache object from cache handle */
632     dobj = (disk_cache_object_t *) h->cache_obj->vobj;
633     if (!dobj) {
634         return DECLINED;
635     }
636
637     /* Delete headers file */
638     if (dobj->hdrs.file) {
639         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00711)
640                 "Deleting %s from cache.", dobj->hdrs.file);
641
642         rc = apr_file_remove(dobj->hdrs.file, r->pool);
643         if ((rc != APR_SUCCESS) && !APR_STATUS_IS_ENOENT(rc)) {
644             /* Will only result in an output if httpd is started with -e debug.
645              * For reason see log_error_core for the case s == NULL.
646              */
647             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rc, r, APLOGNO(00712)
648                     "Failed to delete headers file %s from cache.",
649                     dobj->hdrs.file);
650             return DECLINED;
651         }
652     }
653
654     /* Delete data file */
655     if (dobj->data.file) {
656         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00713)
657                 "Deleting %s from cache.", dobj->data.file);
658
659         rc = apr_file_remove(dobj->data.file, r->pool);
660         if ((rc != APR_SUCCESS) && !APR_STATUS_IS_ENOENT(rc)) {
661             /* Will only result in an output if httpd is started with -e debug.
662              * For reason see log_error_core for the case s == NULL.
663              */
664             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rc, r, APLOGNO(00714)
665                     "Failed to delete data file %s from cache.",
666                     dobj->data.file);
667             return DECLINED;
668         }
669     }
670
671     /* now delete directories as far as possible up to our cache root */
672     if (dobj->root) {
673         const char *str_to_copy;
674
675         str_to_copy = dobj->hdrs.file ? dobj->hdrs.file : dobj->data.file;
676         if (str_to_copy) {
677             char *dir, *slash, *q;
678
679             dir = apr_pstrdup(r->pool, str_to_copy);
680
681             /* remove filename */
682             slash = strrchr(dir, '/');
683             *slash = '\0';
684
685             /*
686              * now walk our way back to the cache root, delete everything
687              * in the way as far as possible
688              *
689              * Note: due to the way we constructed the file names in
690              * header_file and data_file, we are guaranteed that the
691              * cache_root is suffixed by at least one '/' which will be
692              * turned into a terminating null by this loop.  Therefore,
693              * we won't either delete or go above our cache root.
694              */
695             for (q = dir + dobj->root_len; *q ; ) {
696                  ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00715)
697                         "Deleting directory %s from cache", dir);
698
699                  rc = apr_dir_remove(dir, r->pool);
700                  if (rc != APR_SUCCESS && !APR_STATUS_IS_ENOENT(rc)) {
701                     break;
702                  }
703                  slash = strrchr(q, '/');
704                  *slash = '\0';
705             }
706         }
707     }
708
709     return OK;
710 }
711
712 static apr_status_t read_array(request_rec *r, apr_array_header_t* arr,
713                                apr_file_t *file)
714 {
715     char w[MAX_STRING_LEN];
716     int p;
717     apr_status_t rv;
718
719     while (1) {
720         rv = apr_file_gets(w, MAX_STRING_LEN - 1, file);
721         if (rv != APR_SUCCESS) {
722             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00716)
723                           "Premature end of vary array.");
724             return rv;
725         }
726
727         p = strlen(w);
728         if (p > 0 && w[p - 1] == '\n') {
729             if (p > 1 && w[p - 2] == CR) {
730                 w[p - 2] = '\0';
731             }
732             else {
733                 w[p - 1] = '\0';
734             }
735         }
736
737         /* If we've finished reading the array, break out of the loop. */
738         if (w[0] == '\0') {
739             break;
740         }
741
742         *((const char **) apr_array_push(arr)) = apr_pstrdup(r->pool, w);
743     }
744
745     return APR_SUCCESS;
746 }
747
748 static apr_status_t store_array(apr_file_t *fd, apr_array_header_t* arr)
749 {
750     int i;
751     apr_status_t rv;
752     struct iovec iov[2];
753     apr_size_t amt;
754     const char **elts;
755
756     elts = (const char **) arr->elts;
757
758     for (i = 0; i < arr->nelts; i++) {
759         iov[0].iov_base = (char*) elts[i];
760         iov[0].iov_len = strlen(elts[i]);
761         iov[1].iov_base = CRLF;
762         iov[1].iov_len = sizeof(CRLF) - 1;
763
764         rv = apr_file_writev_full(fd, (const struct iovec *) &iov, 2, &amt);
765         if (rv != APR_SUCCESS) {
766             return rv;
767         }
768     }
769
770     iov[0].iov_base = CRLF;
771     iov[0].iov_len = sizeof(CRLF) - 1;
772
773     return apr_file_writev_full(fd, (const struct iovec *) &iov, 1, &amt);
774 }
775
776 static apr_status_t read_table(cache_handle_t *handle, request_rec *r,
777                                apr_table_t *table, apr_file_t *file)
778 {
779     char w[MAX_STRING_LEN];
780     char *l;
781     int p;
782     apr_status_t rv;
783
784     while (1) {
785
786         /* ### What about APR_EOF? */
787         rv = apr_file_gets(w, MAX_STRING_LEN - 1, file);
788         if (rv != APR_SUCCESS) {
789             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00717)
790                           "Premature end of cache headers.");
791             return rv;
792         }
793
794         /* Delete terminal (CR?)LF */
795
796         p = strlen(w);
797         /* Indeed, the host's '\n':
798            '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
799            -- whatever the script generates.
800         */
801         if (p > 0 && w[p - 1] == '\n') {
802             if (p > 1 && w[p - 2] == CR) {
803                 w[p - 2] = '\0';
804             }
805             else {
806                 w[p - 1] = '\0';
807             }
808         }
809
810         /* If we've finished reading the headers, break out of the loop. */
811         if (w[0] == '\0') {
812             break;
813         }
814
815 #if APR_CHARSET_EBCDIC
816         /* Chances are that we received an ASCII header text instead of
817          * the expected EBCDIC header lines. Try to auto-detect:
818          */
819         if (!(l = strchr(w, ':'))) {
820             int maybeASCII = 0, maybeEBCDIC = 0;
821             unsigned char *cp, native;
822             apr_size_t inbytes_left, outbytes_left;
823
824             for (cp = w; *cp != '\0'; ++cp) {
825                 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
826                 if (apr_isprint(*cp) && !apr_isprint(native))
827                     ++maybeEBCDIC;
828                 if (!apr_isprint(*cp) && apr_isprint(native))
829                     ++maybeASCII;
830             }
831             if (maybeASCII > maybeEBCDIC) {
832                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00718)
833                         "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
834                         r->filename);
835                 inbytes_left = outbytes_left = cp - w;
836                 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
837                                       w, &inbytes_left, w, &outbytes_left);
838             }
839         }
840 #endif /*APR_CHARSET_EBCDIC*/
841
842         /* if we see a bogus header don't ignore it. Shout and scream */
843         if (!(l = strchr(w, ':'))) {
844             return APR_EGENERAL;
845         }
846
847         *l++ = '\0';
848         while (apr_isspace(*l)) {
849             ++l;
850         }
851
852         apr_table_add(table, w, l);
853     }
854
855     return APR_SUCCESS;
856 }
857
858 /*
859  * Reads headers from a buffer and returns an array of headers.
860  * Returns NULL on file error
861  * This routine tries to deal with too long lines and continuation lines.
862  * @@@: XXX: FIXME: currently the headers are passed thru un-merged.
863  * Is that okay, or should they be collapsed where possible?
864  */
865 static apr_status_t recall_headers(cache_handle_t *h, request_rec *r)
866 {
867     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
868     apr_status_t rv;
869
870     /* This case should not happen... */
871     if (!dobj->hdrs.fd) {
872         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00719)
873                 "recalling headers; but no header fd for %s", dobj->name);
874         return APR_NOTFOUND;
875     }
876
877     h->req_hdrs = apr_table_make(r->pool, 20);
878     h->resp_hdrs = apr_table_make(r->pool, 20);
879
880     /* Call routine to read the header lines/status line */
881     rv = read_table(h, r, h->resp_hdrs, dobj->hdrs.fd);
882     if (rv != APR_SUCCESS) { 
883         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02987) 
884                       "Error reading response headers from %s for %s",
885                       dobj->hdrs.file, dobj->name);
886     }
887     rv = read_table(h, r, h->req_hdrs, dobj->hdrs.fd);
888     if (rv != APR_SUCCESS) { 
889         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02988) 
890                       "Error reading request headers from %s for %s",
891                       dobj->hdrs.file, dobj->name);
892     }
893
894     apr_file_close(dobj->hdrs.fd);
895
896     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00720)
897             "Recalled headers for URL %s", dobj->name);
898     return APR_SUCCESS;
899 }
900
901 static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb)
902 {
903     disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
904
905     if (dobj->data.fd) {
906         apr_brigade_insert_file(bb, dobj->data.fd, 0, dobj->file_size, p);
907     }
908
909     return APR_SUCCESS;
910 }
911
912 static apr_status_t store_table(apr_file_t *fd, apr_table_t *table)
913 {
914     int i;
915     apr_status_t rv;
916     struct iovec iov[4];
917     apr_size_t amt;
918     apr_table_entry_t *elts;
919
920     elts = (apr_table_entry_t *) apr_table_elts(table)->elts;
921     for (i = 0; i < apr_table_elts(table)->nelts; ++i) {
922         if (elts[i].key != NULL) {
923             iov[0].iov_base = elts[i].key;
924             iov[0].iov_len = strlen(elts[i].key);
925             iov[1].iov_base = ": ";
926             iov[1].iov_len = sizeof(": ") - 1;
927             iov[2].iov_base = elts[i].val;
928             iov[2].iov_len = strlen(elts[i].val);
929             iov[3].iov_base = CRLF;
930             iov[3].iov_len = sizeof(CRLF) - 1;
931
932             rv = apr_file_writev_full(fd, (const struct iovec *) &iov, 4, &amt);
933             if (rv != APR_SUCCESS) {
934                 return rv;
935             }
936         }
937     }
938     iov[0].iov_base = CRLF;
939     iov[0].iov_len = sizeof(CRLF) - 1;
940     rv = apr_file_writev_full(fd, (const struct iovec *) &iov, 1, &amt);
941     return rv;
942 }
943
944 static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *info)
945 {
946     disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
947
948     memcpy(&h->cache_obj->info, info, sizeof(cache_info));
949
950     if (r->headers_out) {
951         dobj->headers_out = ap_cache_cacheable_headers_out(r);
952     }
953
954     if (r->headers_in) {
955         dobj->headers_in = ap_cache_cacheable_headers_in(r);
956     }
957
958     if (r->header_only && r->status != HTTP_NOT_MODIFIED) {
959         dobj->disk_info.header_only = 1;
960     }
961
962     return APR_SUCCESS;
963 }
964
965 static apr_status_t write_headers(cache_handle_t *h, request_rec *r)
966 {
967     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
968                                                  &cache_disk_module);
969     apr_status_t rv;
970     apr_size_t amt;
971     disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
972
973     disk_cache_info_t disk_info;
974     struct iovec iov[2];
975
976     memset(&disk_info, 0, sizeof(disk_cache_info_t));
977
978     if (dobj->headers_out) {
979         const char *tmp;
980
981         tmp = apr_table_get(dobj->headers_out, "Vary");
982
983         if (tmp) {
984             apr_array_header_t* varray;
985             apr_uint32_t format = VARY_FORMAT_VERSION;
986
987             /* If we were initially opened as a vary format, rollback
988              * that internal state for the moment so we can recreate the
989              * vary format hints in the appropriate directory.
990              */
991             if (dobj->prefix) {
992                 dobj->hdrs.file = dobj->prefix;
993                 dobj->prefix = NULL;
994             }
995
996             rv = mkdir_structure(conf, dobj->hdrs.file, r->pool);
997             if (rv == APR_SUCCESS) {
998                 rv = apr_file_mktemp(&dobj->vary.tempfd, dobj->vary.tempfile,
999                                      APR_CREATE | APR_WRITE | APR_BINARY | APR_EXCL,
1000                                      dobj->vary.pool);
1001             }
1002
1003             if (rv != APR_SUCCESS) {
1004                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00721)
1005                         "could not create vary file %s",
1006                         dobj->vary.tempfile);
1007                 return rv;
1008             }
1009
1010             amt = sizeof(format);
1011             rv = apr_file_write_full(dobj->vary.tempfd, &format, amt, NULL);
1012             if (rv != APR_SUCCESS) {
1013                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00722)
1014                         "could not write to vary file %s",
1015                         dobj->vary.tempfile);
1016                 apr_file_close(dobj->vary.tempfd);
1017                 apr_pool_destroy(dobj->vary.pool);
1018                 return rv;
1019             }
1020
1021             amt = sizeof(h->cache_obj->info.expire);
1022             rv = apr_file_write_full(dobj->vary.tempfd,
1023                                      &h->cache_obj->info.expire, amt, NULL);
1024             if (rv != APR_SUCCESS) {
1025                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00723)
1026                         "could not write to vary file %s",
1027                         dobj->vary.tempfile);
1028                 apr_file_close(dobj->vary.tempfd);
1029                 apr_pool_destroy(dobj->vary.pool);
1030                 return rv;
1031             }
1032
1033             varray = apr_array_make(r->pool, 6, sizeof(char*));
1034             tokens_to_array(r->pool, tmp, varray);
1035
1036             store_array(dobj->vary.tempfd, varray);
1037
1038             rv = apr_file_close(dobj->vary.tempfd);
1039             if (rv != APR_SUCCESS) {
1040                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00724)
1041                         "could not close vary file %s",
1042                         dobj->vary.tempfile);
1043                 apr_pool_destroy(dobj->vary.pool);
1044                 return rv;
1045             }
1046
1047             tmp = regen_key(r->pool, dobj->headers_in, varray, dobj->name);
1048             dobj->prefix = dobj->hdrs.file;
1049             dobj->hashfile = NULL;
1050             dobj->data.file = data_file(r->pool, conf, dobj, tmp);
1051             dobj->hdrs.file = header_file(r->pool, conf, dobj, tmp);
1052         }
1053     }
1054
1055
1056     rv = apr_file_mktemp(&dobj->hdrs.tempfd, dobj->hdrs.tempfile,
1057                          APR_CREATE | APR_WRITE | APR_BINARY |
1058                          APR_BUFFERED | APR_EXCL, dobj->hdrs.pool);
1059
1060     if (rv != APR_SUCCESS) {
1061         ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00725)
1062                 "could not create header file %s",
1063                 dobj->hdrs.tempfile);
1064         return rv;
1065     }
1066
1067     disk_info.format = DISK_FORMAT_VERSION;
1068     disk_info.date = h->cache_obj->info.date;
1069     disk_info.expire = h->cache_obj->info.expire;
1070     disk_info.entity_version = dobj->disk_info.entity_version++;
1071     disk_info.request_time = h->cache_obj->info.request_time;
1072     disk_info.response_time = h->cache_obj->info.response_time;
1073     disk_info.status = h->cache_obj->info.status;
1074     disk_info.inode = dobj->disk_info.inode;
1075     disk_info.device = dobj->disk_info.device;
1076     disk_info.has_body = dobj->disk_info.has_body;
1077     disk_info.header_only = dobj->disk_info.header_only;
1078
1079     disk_info.name_len = strlen(dobj->name);
1080
1081     memcpy(&disk_info.control, &h->cache_obj->info.control, sizeof(cache_control_t));
1082
1083     iov[0].iov_base = (void*)&disk_info;
1084     iov[0].iov_len = sizeof(disk_cache_info_t);
1085     iov[1].iov_base = (void*)dobj->name;
1086     iov[1].iov_len = disk_info.name_len;
1087
1088     rv = apr_file_writev_full(dobj->hdrs.tempfd, (const struct iovec *) &iov,
1089                               2, &amt);
1090     if (rv != APR_SUCCESS) {
1091         ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00726)
1092                 "could not write info to header file %s",
1093                 dobj->hdrs.tempfile);
1094         apr_file_close(dobj->hdrs.tempfd);
1095         apr_pool_destroy(dobj->hdrs.pool);
1096         return rv;
1097     }
1098
1099     if (dobj->headers_out) {
1100         rv = store_table(dobj->hdrs.tempfd, dobj->headers_out);
1101         if (rv != APR_SUCCESS) {
1102             ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00727)
1103                     "could not write out-headers to header file %s",
1104                     dobj->hdrs.tempfile);
1105             apr_file_close(dobj->hdrs.tempfd);
1106             apr_pool_destroy(dobj->hdrs.pool);
1107             return rv;
1108         }
1109     }
1110
1111     /* Parse the vary header and dump those fields from the headers_in. */
1112     /* FIXME: Make call to the same thing cache_select calls to crack Vary. */
1113     if (dobj->headers_in) {
1114         rv = store_table(dobj->hdrs.tempfd, dobj->headers_in);
1115         if (rv != APR_SUCCESS) {
1116             ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00728)
1117                     "could not write in-headers to header file %s",
1118                     dobj->hdrs.tempfile);
1119             apr_file_close(dobj->hdrs.tempfd);
1120             apr_pool_destroy(dobj->hdrs.pool);
1121             return rv;
1122         }
1123     }
1124
1125     rv = apr_file_close(dobj->hdrs.tempfd); /* flush and close */
1126     if (rv != APR_SUCCESS) {
1127         ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00729)
1128                 "could not close header file %s",
1129                 dobj->hdrs.tempfile);
1130         apr_pool_destroy(dobj->hdrs.pool);
1131         return rv;
1132     }
1133
1134     return APR_SUCCESS;
1135 }
1136
1137 static apr_status_t store_body(cache_handle_t *h, request_rec *r,
1138                                apr_bucket_brigade *in, apr_bucket_brigade *out)
1139 {
1140     apr_bucket *e;
1141     apr_status_t rv = APR_SUCCESS;
1142     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
1143     disk_cache_dir_conf *dconf = ap_get_module_config(r->per_dir_config, &cache_disk_module);
1144     int seen_eos = 0;
1145
1146     if (!dobj->offset) {
1147         dobj->offset = dconf->readsize;
1148     }
1149     if (!dobj->timeout && dconf->readtime) {
1150         dobj->timeout = apr_time_now() + dconf->readtime;
1151     }
1152
1153     if (dobj->offset) {
1154         apr_brigade_partition(in, dobj->offset, &e);
1155     }
1156
1157     while (APR_SUCCESS == rv && !APR_BRIGADE_EMPTY(in)) {
1158         const char *str;
1159         apr_size_t length, written;
1160
1161         e = APR_BRIGADE_FIRST(in);
1162
1163         /* are we done completely? if so, pass any trailing buckets right through */
1164         if (dobj->done || !dobj->data.pool) {
1165             APR_BUCKET_REMOVE(e);
1166             APR_BRIGADE_INSERT_TAIL(out, e);
1167             continue;
1168         }
1169
1170         /* have we seen eos yet? */
1171         if (APR_BUCKET_IS_EOS(e)) {
1172             seen_eos = 1;
1173             dobj->done = 1;
1174             APR_BUCKET_REMOVE(e);
1175             APR_BRIGADE_INSERT_TAIL(out, e);
1176             break;
1177         }
1178
1179         /* honour flush buckets, we'll get called again */
1180         if (APR_BUCKET_IS_FLUSH(e)) {
1181             APR_BUCKET_REMOVE(e);
1182             APR_BRIGADE_INSERT_TAIL(out, e);
1183             break;
1184         }
1185
1186         /* metadata buckets are preserved as is */
1187         if (APR_BUCKET_IS_METADATA(e)) {
1188             APR_BUCKET_REMOVE(e);
1189             APR_BRIGADE_INSERT_TAIL(out, e);
1190             continue;
1191         }
1192
1193         /* read the bucket, write to the cache */
1194         rv = apr_bucket_read(e, &str, &length, APR_BLOCK_READ);
1195         APR_BUCKET_REMOVE(e);
1196         APR_BRIGADE_INSERT_TAIL(out, e);
1197         if (rv != APR_SUCCESS) {
1198             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00730)
1199                     "Error when reading bucket for URL %s",
1200                     h->cache_obj->key);
1201             /* Remove the intermediate cache file and return non-APR_SUCCESS */
1202             apr_pool_destroy(dobj->data.pool);
1203             return rv;
1204         }
1205
1206         /* don't write empty buckets to the cache */
1207         if (!length) {
1208             continue;
1209         }
1210
1211         if (!dobj->disk_info.header_only) {
1212
1213             /* Attempt to create the data file at the last possible moment, if
1214              * the body is empty, we don't write a file at all, and save an inode.
1215              */
1216             if (!dobj->data.tempfd) {
1217                 apr_finfo_t finfo;
1218                 rv = apr_file_mktemp(&dobj->data.tempfd, dobj->data.tempfile,
1219                         APR_CREATE | APR_WRITE | APR_BINARY | APR_BUFFERED
1220                                 | APR_EXCL, dobj->data.pool);
1221                 if (rv != APR_SUCCESS) {
1222                     apr_pool_destroy(dobj->data.pool);
1223                     return rv;
1224                 }
1225                 dobj->file_size = 0;
1226                 rv = apr_file_info_get(&finfo, APR_FINFO_IDENT,
1227                         dobj->data.tempfd);
1228                 if (rv != APR_SUCCESS) {
1229                     apr_pool_destroy(dobj->data.pool);
1230                     return rv;
1231                 }
1232                 dobj->disk_info.device = finfo.device;
1233                 dobj->disk_info.inode = finfo.inode;
1234                 dobj->disk_info.has_body = 1;
1235             }
1236
1237             /* write to the cache, leave if we fail */
1238             rv = apr_file_write_full(dobj->data.tempfd, str, length, &written);
1239             if (rv != APR_SUCCESS) {
1240                 ap_log_rerror(
1241                         APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00731) "Error when writing cache file for URL %s", h->cache_obj->key);
1242                 /* Remove the intermediate cache file and return non-APR_SUCCESS */
1243                 apr_pool_destroy(dobj->data.pool);
1244                 return rv;
1245             }
1246             dobj->file_size += written;
1247             if (dobj->file_size > dconf->maxfs) {
1248                 ap_log_rerror(
1249                         APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00732) "URL %s failed the size check "
1250                         "(%" APR_OFF_T_FMT ">%" APR_OFF_T_FMT ")", h->cache_obj->key, dobj->file_size, dconf->maxfs);
1251                 /* Remove the intermediate cache file and return non-APR_SUCCESS */
1252                 apr_pool_destroy(dobj->data.pool);
1253                 return APR_EGENERAL;
1254             }
1255
1256         }
1257
1258         /* have we reached the limit of how much we're prepared to write in one
1259          * go? If so, leave, we'll get called again. This prevents us from trying
1260          * to swallow too much data at once, or taking so long to write the data
1261          * the client times out.
1262          */
1263         dobj->offset -= length;
1264         if (dobj->offset <= 0) {
1265             dobj->offset = 0;
1266             break;
1267         }
1268         if ((dconf->readtime && apr_time_now() > dobj->timeout)) {
1269             dobj->timeout = 0;
1270             break;
1271         }
1272
1273     }
1274
1275     /* Was this the final bucket? If yes, close the temp file and perform
1276      * sanity checks.
1277      */
1278     if (seen_eos) {
1279         const char *cl_header = apr_table_get(r->headers_out, "Content-Length");
1280
1281         if (!dobj->disk_info.header_only) {
1282
1283             if (dobj->data.tempfd) {
1284                 rv = apr_file_close(dobj->data.tempfd);
1285                 if (rv != APR_SUCCESS) {
1286                     /* Buffered write failed, abandon attempt to write */
1287                     apr_pool_destroy(dobj->data.pool);
1288                     return rv;
1289                 }
1290             }
1291
1292             if (r->connection->aborted || r->no_cache) {
1293                 ap_log_rerror(
1294                         APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00733) "Discarding body for URL %s "
1295                         "because connection has been aborted.", h->cache_obj->key);
1296                 /* Remove the intermediate cache file and return non-APR_SUCCESS */
1297                 apr_pool_destroy(dobj->data.pool);
1298                 return APR_EGENERAL;
1299             }
1300             if (dobj->file_size < dconf->minfs) {
1301                 ap_log_rerror(
1302                         APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00734) "URL %s failed the size check "
1303                         "(%" APR_OFF_T_FMT "<%" APR_OFF_T_FMT ")", h->cache_obj->key, dobj->file_size, dconf->minfs);
1304                 /* Remove the intermediate cache file and return non-APR_SUCCESS */
1305                 apr_pool_destroy(dobj->data.pool);
1306                 return APR_EGENERAL;
1307             }
1308             if (cl_header) {
1309                 apr_int64_t cl = apr_atoi64(cl_header);
1310                 if ((errno == 0) && (dobj->file_size != cl)) {
1311                     ap_log_rerror(
1312                             APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00735) "URL %s didn't receive complete response, not caching", h->cache_obj->key);
1313                     /* Remove the intermediate cache file and return non-APR_SUCCESS */
1314                     apr_pool_destroy(dobj->data.pool);
1315                     return APR_EGENERAL;
1316                 }
1317             }
1318
1319         }
1320
1321         /* All checks were fine, we're good to go when the commit comes */
1322     }
1323
1324     return APR_SUCCESS;
1325 }
1326
1327 static apr_status_t commit_entity(cache_handle_t *h, request_rec *r)
1328 {
1329     disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
1330                                                  &cache_disk_module);
1331     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
1332     apr_status_t rv;
1333
1334     /* write the headers to disk at the last possible moment */
1335     rv = write_headers(h, r);
1336
1337     /* move header and data tempfiles to the final destination */
1338     if (APR_SUCCESS == rv) {
1339         rv = file_cache_el_final(conf, &dobj->hdrs, r);
1340     }
1341     if (APR_SUCCESS == rv) {
1342         rv = file_cache_el_final(conf, &dobj->vary, r);
1343     }
1344     if (APR_SUCCESS == rv) {
1345         if (!dobj->disk_info.header_only) {
1346             rv = file_cache_el_final(conf, &dobj->data, r);
1347         }
1348         else if (dobj->data.file) {
1349             rv = apr_file_remove(dobj->data.file, dobj->data.pool);
1350         }
1351     }
1352
1353     /* remove the cached items completely on any failure */
1354     if (APR_SUCCESS != rv) {
1355         remove_url(h, r);
1356         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00736)
1357                 "commit_entity: URL '%s' not cached due to earlier disk error.",
1358                 dobj->name);
1359     }
1360     else {
1361         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00737)
1362                 "commit_entity: Headers and body for URL %s cached.",
1363                 dobj->name);
1364     }
1365
1366     apr_pool_destroy(dobj->data.pool);
1367
1368     return APR_SUCCESS;
1369 }
1370
1371 static apr_status_t invalidate_entity(cache_handle_t *h, request_rec *r)
1372 {
1373     apr_status_t rv;
1374
1375     rv = recall_headers(h, r);
1376     if (rv != APR_SUCCESS) {
1377         return rv;
1378     }
1379
1380     /* mark the entity as invalidated */
1381     h->cache_obj->info.control.invalidated = 1;
1382
1383     return commit_entity(h, r);
1384 }
1385
1386 static void *create_dir_config(apr_pool_t *p, char *dummy)
1387 {
1388     disk_cache_dir_conf *dconf = apr_pcalloc(p, sizeof(disk_cache_dir_conf));
1389
1390     dconf->maxfs = DEFAULT_MAX_FILE_SIZE;
1391     dconf->minfs = DEFAULT_MIN_FILE_SIZE;
1392     dconf->readsize = DEFAULT_READSIZE;
1393     dconf->readtime = DEFAULT_READTIME;
1394
1395     return dconf;
1396 }
1397
1398 static void *merge_dir_config(apr_pool_t *p, void *basev, void *addv)
1399 {
1400     disk_cache_dir_conf *new = (disk_cache_dir_conf *) apr_pcalloc(p, sizeof(disk_cache_dir_conf));
1401     disk_cache_dir_conf *add = (disk_cache_dir_conf *) addv;
1402     disk_cache_dir_conf *base = (disk_cache_dir_conf *) basev;
1403
1404     new->maxfs = (add->maxfs_set == 0) ? base->maxfs : add->maxfs;
1405     new->maxfs_set = add->maxfs_set || base->maxfs_set;
1406     new->minfs = (add->minfs_set == 0) ? base->minfs : add->minfs;
1407     new->minfs_set = add->minfs_set || base->minfs_set;
1408     new->readsize = (add->readsize_set == 0) ? base->readsize : add->readsize;
1409     new->readsize_set = add->readsize_set || base->readsize_set;
1410     new->readtime = (add->readtime_set == 0) ? base->readtime : add->readtime;
1411     new->readtime_set = add->readtime_set || base->readtime_set;
1412
1413     return new;
1414 }
1415
1416 static void *create_config(apr_pool_t *p, server_rec *s)
1417 {
1418     disk_cache_conf *conf = apr_pcalloc(p, sizeof(disk_cache_conf));
1419
1420     /* XXX: Set default values */
1421     conf->dirlevels = DEFAULT_DIRLEVELS;
1422     conf->dirlength = DEFAULT_DIRLENGTH;
1423
1424     conf->cache_root = NULL;
1425     conf->cache_root_len = 0;
1426
1427     return conf;
1428 }
1429
1430 /*
1431  * mod_cache_disk configuration directives handlers.
1432  */
1433 static const char
1434 *set_cache_root(cmd_parms *parms, void *in_struct_ptr, const char *arg)
1435 {
1436     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
1437                                                  &cache_disk_module);
1438     conf->cache_root = arg;
1439     conf->cache_root_len = strlen(arg);
1440     /* TODO: canonicalize cache_root and strip off any trailing slashes */
1441
1442     return NULL;
1443 }
1444
1445 /*
1446  * Consider eliminating the next two directives in favor of
1447  * Ian's prime number hash...
1448  * key = hash_fn( r->uri)
1449  * filename = "/key % prime1 /key %prime2/key %prime3"
1450  */
1451 static const char
1452 *set_cache_dirlevels(cmd_parms *parms, void *in_struct_ptr, const char *arg)
1453 {
1454     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
1455                                                  &cache_disk_module);
1456     int val = atoi(arg);
1457     if (val < 1)
1458         return "CacheDirLevels value must be an integer greater than 0";
1459     if (val * conf->dirlength > CACHEFILE_LEN)
1460         return "CacheDirLevels*CacheDirLength value must not be higher than 20";
1461     conf->dirlevels = val;
1462     return NULL;
1463 }
1464 static const char
1465 *set_cache_dirlength(cmd_parms *parms, void *in_struct_ptr, const char *arg)
1466 {
1467     disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
1468                                                  &cache_disk_module);
1469     int val = atoi(arg);
1470     if (val < 1)
1471         return "CacheDirLength value must be an integer greater than 0";
1472     if (val * conf->dirlevels > CACHEFILE_LEN)
1473         return "CacheDirLevels*CacheDirLength value must not be higher than 20";
1474
1475     conf->dirlength = val;
1476     return NULL;
1477 }
1478
1479 static const char
1480 *set_cache_minfs(cmd_parms *parms, void *in_struct_ptr, const char *arg)
1481 {
1482     disk_cache_dir_conf *dconf = (disk_cache_dir_conf *)in_struct_ptr;
1483
1484     if (apr_strtoff(&dconf->minfs, arg, NULL, 10) != APR_SUCCESS ||
1485             dconf->minfs < 0)
1486     {
1487         return "CacheMinFileSize argument must be a non-negative integer representing the min size of a file to cache in bytes.";
1488     }
1489     dconf->minfs_set = 1;
1490     return NULL;
1491 }
1492
1493 static const char
1494 *set_cache_maxfs(cmd_parms *parms, void *in_struct_ptr, const char *arg)
1495 {
1496     disk_cache_dir_conf *dconf = (disk_cache_dir_conf *)in_struct_ptr;
1497
1498     if (apr_strtoff(&dconf->maxfs, arg, NULL, 10) != APR_SUCCESS ||
1499             dconf->maxfs < 0)
1500     {
1501         return "CacheMaxFileSize argument must be a non-negative integer representing the max size of a file to cache in bytes.";
1502     }
1503     dconf->maxfs_set = 1;
1504     return NULL;
1505 }
1506
1507 static const char
1508 *set_cache_readsize(cmd_parms *parms, void *in_struct_ptr, const char *arg)
1509 {
1510     disk_cache_dir_conf *dconf = (disk_cache_dir_conf *)in_struct_ptr;
1511
1512     if (apr_strtoff(&dconf->readsize, arg, NULL, 10) != APR_SUCCESS ||
1513             dconf->readsize < 0)
1514     {
1515         return "CacheReadSize argument must be a non-negative integer representing the max amount of data to cache in go.";
1516     }
1517     dconf->readsize_set = 1;
1518     return NULL;
1519 }
1520
1521 static const char
1522 *set_cache_readtime(cmd_parms *parms, void *in_struct_ptr, const char *arg)
1523 {
1524     disk_cache_dir_conf *dconf = (disk_cache_dir_conf *)in_struct_ptr;
1525     apr_off_t milliseconds;
1526
1527     if (apr_strtoff(&milliseconds, arg, NULL, 10) != APR_SUCCESS ||
1528             milliseconds < 0)
1529     {
1530         return "CacheReadTime argument must be a non-negative integer representing the max amount of time taken to cache in go.";
1531     }
1532     dconf->readtime = apr_time_from_msec(milliseconds);
1533     dconf->readtime_set = 1;
1534     return NULL;
1535 }
1536
1537 static const command_rec disk_cache_cmds[] =
1538 {
1539     AP_INIT_TAKE1("CacheRoot", set_cache_root, NULL, RSRC_CONF,
1540                  "The directory to store cache files"),
1541     AP_INIT_TAKE1("CacheDirLevels", set_cache_dirlevels, NULL, RSRC_CONF,
1542                   "The number of levels of subdirectories in the cache"),
1543     AP_INIT_TAKE1("CacheDirLength", set_cache_dirlength, NULL, RSRC_CONF,
1544                   "The number of characters in subdirectory names"),
1545     AP_INIT_TAKE1("CacheMinFileSize", set_cache_minfs, NULL, RSRC_CONF | ACCESS_CONF,
1546                   "The minimum file size to cache a document"),
1547     AP_INIT_TAKE1("CacheMaxFileSize", set_cache_maxfs, NULL, RSRC_CONF | ACCESS_CONF,
1548                   "The maximum file size to cache a document"),
1549     AP_INIT_TAKE1("CacheReadSize", set_cache_readsize, NULL, RSRC_CONF | ACCESS_CONF,
1550                   "The maximum quantity of data to attempt to read and cache in one go"),
1551     AP_INIT_TAKE1("CacheReadTime", set_cache_readtime, NULL, RSRC_CONF | ACCESS_CONF,
1552                   "The maximum time taken to attempt to read and cache in go"),
1553     {NULL}
1554 };
1555
1556 static const cache_provider cache_disk_provider =
1557 {
1558     &remove_entity,
1559     &store_headers,
1560     &store_body,
1561     &recall_headers,
1562     &recall_body,
1563     &create_entity,
1564     &open_entity,
1565     &remove_url,
1566     &commit_entity,
1567     &invalidate_entity
1568 };
1569
1570 static void disk_cache_register_hook(apr_pool_t *p)
1571 {
1572     /* cache initializer */
1573     ap_register_provider(p, CACHE_PROVIDER_GROUP, "disk", "0",
1574                          &cache_disk_provider);
1575 }
1576
1577 AP_DECLARE_MODULE(cache_disk) = {
1578     STANDARD20_MODULE_STUFF,
1579     create_dir_config,          /* create per-directory config structure */
1580     merge_dir_config,           /* merge per-directory config structures */
1581     create_config,              /* create per-server config structure */
1582     NULL,                       /* merge per-server config structures */
1583     disk_cache_cmds,            /* command apr_table_t */
1584     disk_cache_register_hook    /* register hooks */
1585 };