refactor more of the mod_disk_cache code into cache folder
[httpd-crcsyncproxy.git] / crccache / cache / cache.c
blob26665c6c08530daf5f7755ddc5d9a9f212990d7d
1 /*
2 * cache.c
4 * Created on: 30/10/2009
5 * Author: tcollett
6 */
8 #include <cache/cache.h>
9 #include <mod_crccache_client.h>
11 #include <apr-1.0/apr_file_io.h>
12 #include <apr-1.0/apr_strings.h>
13 #include <apr-1.0/apr_base64.h>
14 #include <apr-1.0/apr_lib.h>
15 #include <apr-1.0/apr_date.h>
17 #include <http_log.h>
18 #include <http_protocol.h>
21 * mod_disk_cache: Disk Based HTTP 1.1 Cache.
23 * Flow to Find the .data file:
24 * Incoming client requests URI /foo/bar/baz
25 * Generate <hash> off of /foo/bar/baz
26 * Open <hash>.header
27 * Read in <hash>.header file (may contain Format #1 or Format #2)
28 * If format #1 (Contains a list of Vary Headers):
29 * Use each header name (from .header) with our request values (headers_in) to
30 * regenerate <hash> using HeaderName+HeaderValue+.../foo/bar/baz
31 * re-read in <hash>.header (must be format #2)
32 * read in <hash>.data
34 * Format #1:
35 * apr_uint32_t format;
36 * apr_time_t expire;
37 * apr_array_t vary_headers (delimited by CRLF)
39 * Format #2:
40 * disk_cache_info_t (first sizeof(apr_uint32_t) bytes is the format)
41 * entity name (dobj->name) [length is in disk_cache_info_t->name_len]
42 * r->headers_out (delimited by CRLF)
43 * CRLF
44 * r->headers_in (delimited by CRLF)
45 * CRLF
50 * Local static functions
53 static char *header_file(apr_pool_t *p, crccache_client_conf *conf,
54 disk_cache_object_t *dobj, const char *name) {
55 if (!dobj->hashfile) {
56 dobj->hashfile = ap_cache_generate_name(p, conf->dirlevels,
57 conf->dirlength, name);
60 if (dobj->prefix) {
61 return apr_pstrcat(p, dobj->prefix, CACHE_VDIR_SUFFIX, "/",
62 dobj->hashfile, CACHE_HEADER_SUFFIX, NULL);
63 } else {
64 return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
65 CACHE_HEADER_SUFFIX, NULL);
69 static char *data_file(apr_pool_t *p, crccache_client_conf *conf,
70 disk_cache_object_t *dobj, const char *name) {
71 if (!dobj->hashfile) {
72 dobj->hashfile = ap_cache_generate_name(p, conf->dirlevels,
73 conf->dirlength, name);
76 if (dobj->prefix) {
77 return apr_pstrcat(p, dobj->prefix, CACHE_VDIR_SUFFIX, "/",
78 dobj->hashfile, CACHE_DATA_SUFFIX, NULL);
79 } else {
80 return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
81 CACHE_DATA_SUFFIX, NULL);
85 static void mkdir_structure(crccache_client_conf *conf, const char *file,
86 apr_pool_t *pool) {
87 apr_status_t rv;
88 char *p;
90 for (p = (char*) file + conf->cache_root_len + 1;;) {
91 p = strchr(p, '/');
92 if (!p)
93 break;
94 *p = '\0';
96 rv = apr_dir_make(file, APR_UREAD | APR_UWRITE | APR_UEXECUTE, pool);
97 if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
98 /* XXX */
100 *p = '/';
101 ++p;
105 /* htcacheclean may remove directories underneath us.
106 * So, we'll try renaming three times at a cost of 0.002 seconds.
108 static apr_status_t safe_file_rename(crccache_client_conf *conf, const char *src,
109 const char *dest, apr_pool_t *pool) {
110 apr_status_t rv;
112 rv = apr_file_rename(src, dest, pool);
114 if (rv != APR_SUCCESS) {
115 int i;
117 for (i = 0; i < 2 && rv != APR_SUCCESS; i++) {
118 /* 1000 micro-seconds aka 0.001 seconds. */
119 apr_sleep(1000);
121 mkdir_structure(conf, dest, pool);
123 rv = apr_file_rename(src, dest, pool);
127 return rv;
130 static apr_status_t file_cache_el_final(disk_cache_object_t *dobj,
131 request_rec *r) {
132 /* move the data over */
133 if (dobj->tfd) {
134 apr_status_t rv;
136 apr_file_close(dobj->tfd);
138 /* This assumes that the tempfile is on the same file system
139 * as the cache_root. If not, then we need a file copy/move
140 * rather than a rename.
142 rv = apr_file_rename(dobj->tempfile, dobj->datafile, r->pool);
143 if (rv != APR_SUCCESS) {
144 ap_log_error(APLOG_MARK, APLOG_WARNING, rv,r->server, "disk_cache: rename tempfile to datafile failed:"
145 " %s -> %s", dobj->tempfile, dobj->datafile);
146 apr_file_remove(dobj->tempfile, r->pool);
149 dobj->tfd = NULL;
152 return APR_SUCCESS;
155 static apr_status_t file_cache_errorcleanup(disk_cache_object_t *dobj,
156 request_rec *r) {
157 /* Remove the header file and the body file. */
158 apr_file_remove(dobj->hdrsfile, r->pool);
159 apr_file_remove(dobj->datafile, r->pool);
161 /* If we opened the temporary data file, close and remove it. */
162 if (dobj->tfd) {
163 apr_file_close(dobj->tfd);
164 apr_file_remove(dobj->tempfile, r->pool);
165 dobj->tfd = NULL;
168 return APR_SUCCESS;
171 /* These two functions get and put state information into the data
172 * file for an ap_cache_el, this state information will be read
173 * and written transparent to clients of this module
175 static int file_cache_recall_mydata(apr_file_t *fd, cache_info *info,
176 disk_cache_object_t *dobj, request_rec *r) {
177 apr_status_t rv;
178 char *urlbuff;
179 disk_cache_info_t disk_info;
180 apr_size_t len;
182 /* read the data from the cache file */
183 len = sizeof(disk_cache_info_t);
184 rv = apr_file_read_full(fd, &disk_info, len, &len);
185 if (rv != APR_SUCCESS) {
186 return rv;
189 /* Store it away so we can get it later. */
190 dobj->disk_info = disk_info;
192 info->status = disk_info.status;
193 info->date = disk_info.date;
194 info->expire = disk_info.expire;
195 info->request_time = disk_info.request_time;
196 info->response_time = disk_info.response_time;
198 /* Note that we could optimize this by conditionally doing the palloc
199 * depending upon the size. */
200 urlbuff = apr_palloc(r->pool, disk_info.name_len + 1);
201 len = disk_info.name_len;
202 rv = apr_file_read_full(fd, urlbuff, len, &len);
203 if (rv != APR_SUCCESS) {
204 return rv;
206 urlbuff[disk_info.name_len] = '\0';
208 /* check that we have the same URL */
209 /* Would strncmp be correct? */
210 if (strcmp(urlbuff, dobj->name) != 0) {
211 return APR_EGENERAL;
214 return APR_SUCCESS;
217 static const char* regen_key(apr_pool_t *p, apr_table_t *headers,
218 apr_array_header_t *varray, const char *oldkey) {
219 struct iovec *iov;
220 int i, k;
221 int nvec;
222 const char *header;
223 const char **elts;
225 nvec = (varray->nelts * 2) + 1;
226 iov = apr_palloc(p, sizeof(struct iovec) * nvec);
227 elts = (const char **) varray->elts;
229 /* TODO:
230 * - Handle multiple-value headers better. (sort them?)
231 * - Handle Case in-sensitive Values better.
232 * This isn't the end of the world, since it just lowers the cache
233 * hit rate, but it would be nice to fix.
235 * The majority are case insenstive if they are values (encoding etc).
236 * Most of rfc2616 is case insensitive on header contents.
238 * So the better solution may be to identify headers which should be
239 * treated case-sensitive?
240 * HTTP URI's (3.2.3) [host and scheme are insensitive]
241 * HTTP method (5.1.1)
242 * HTTP-date values (3.3.1)
243 * 3.7 Media Types [exerpt]
244 * The type, subtype, and parameter attribute names are case-
245 * insensitive. Parameter values might or might not be case-sensitive,
246 * depending on the semantics of the parameter name.
247 * 4.20 Except [exerpt]
248 * Comparison of expectation values is case-insensitive for unquoted
249 * tokens (including the 100-continue token), and is case-sensitive for
250 * quoted-string expectation-extensions.
253 for (i = 0, k = 0; i < varray->nelts; i++) {
254 header = apr_table_get(headers, elts[i]);
255 if (!header) {
256 header = "";
258 iov[k].iov_base = (char*) elts[i];
259 iov[k].iov_len = strlen(elts[i]);
260 k++;
261 iov[k].iov_base = (char*) header;
262 iov[k].iov_len = strlen(header);
263 k++;
265 iov[k].iov_base = (char*) oldkey;
266 iov[k].iov_len = strlen(oldkey);
267 k++;
269 return apr_pstrcatv(p, iov, k, NULL);
272 static int array_alphasort(const void *fn1, const void *fn2) {
273 return strcmp(*(char**) fn1, *(char**) fn2);
276 static void tokens_to_array(apr_pool_t *p, const char *data,
277 apr_array_header_t *arr) {
278 char *token;
280 while ((token = ap_get_list_item(p, &data)) != NULL) {
281 *((const char **) apr_array_push(arr)) = token;
284 /* Sort it so that "Vary: A, B" and "Vary: B, A" are stored the same. */
285 qsort((void *) arr->elts, arr->nelts, sizeof(char *), array_alphasort);
289 * Hook and mod_cache callback functions
291 int create_entity(cache_handle_t *h, request_rec *r, const char *key,
292 apr_off_t len) {
293 crccache_client_conf *conf = ap_get_module_config(r->server->module_config,
294 &crccache_client_module);
295 cache_object_t *obj;
296 disk_cache_object_t *dobj;
298 if (conf->cache_root == NULL) {
299 return DECLINED;
302 /* Allocate and initialize cache_object_t and disk_cache_object_t */
303 h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(*obj));
304 obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(*dobj));
306 obj->key = apr_pstrdup(r->pool, key);
308 dobj->name = obj->key;
309 dobj->prefix = NULL;
310 /* Save the cache root */
311 dobj->root = apr_pstrndup(r->pool, conf->cache_root, conf->cache_root_len);
312 dobj->root_len = conf->cache_root_len;
313 dobj->datafile = data_file(r->pool, conf, dobj, key);
314 dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
315 dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
317 return OK;
320 int open_entity(cache_handle_t *h, request_rec *r, const char *key) {
321 apr_uint32_t format;
322 apr_size_t len;
323 const char *nkey;
324 apr_status_t rc;
325 static int error_logged = 0;
326 crccache_client_conf *conf = ap_get_module_config(r->server->module_config,
327 &crccache_client_module);
328 apr_finfo_t finfo;
329 cache_object_t *obj;
330 cache_info *info;
331 disk_cache_object_t *dobj;
332 int flags;
333 h->cache_obj = NULL;
335 /* Look up entity keyed to 'url' */
336 if (conf->cache_root == NULL) {
337 if (!error_logged) {
338 error_logged = 1;
339 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
340 "disk_cache: Cannot cache files to disk without a CacheRootClient specified.");
342 return DECLINED;
345 /* Create and init the cache object */
346 h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(cache_object_t));
347 obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(disk_cache_object_t));
349 info = &(obj->info);
351 /* Open the headers file */
352 dobj->prefix = NULL;
354 /* Save the cache root */
355 dobj->root = apr_pstrndup(r->pool, conf->cache_root, conf->cache_root_len);
356 dobj->root_len = conf->cache_root_len;
358 dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
359 flags = APR_READ|APR_BINARY|APR_BUFFERED;
360 rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
361 if (rc != APR_SUCCESS) {
362 return DECLINED;
365 /* read the format from the cache file */
366 len = sizeof(format);
367 apr_file_read_full(dobj->hfd, &format, len, &len);
369 if (format == VARY_FORMAT_VERSION) {
370 apr_array_header_t* varray;
371 apr_time_t expire;
373 len = sizeof(expire);
374 apr_file_read_full(dobj->hfd, &expire, len, &len);
376 varray = apr_array_make(r->pool, 5, sizeof(char*));
377 rc = read_array(r, varray, dobj->hfd);
378 if (rc != APR_SUCCESS) {
379 ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server,
380 "disk_cache: Cannot parse vary header file: %s",
381 dobj->hdrsfile);
382 return DECLINED;
384 apr_file_close(dobj->hfd);
386 nkey = regen_key(r->pool, r->headers_in, varray, key);
388 dobj->hashfile = NULL;
389 dobj->prefix = dobj->hdrsfile;
390 dobj->hdrsfile = header_file(r->pool, conf, dobj, nkey);
392 flags = APR_READ|APR_BINARY|APR_BUFFERED;
393 rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
394 if (rc != APR_SUCCESS) {
395 return DECLINED;
398 else if (format != DISK_FORMAT_VERSION) {
399 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
400 "cache_disk: File '%s' has a version mismatch. File had version: %d.",
401 dobj->hdrsfile, format);
402 return DECLINED;
404 else {
405 apr_off_t offset = 0;
406 /* This wasn't a Vary Format file, so we must seek to the
407 * start of the file again, so that later reads work.
409 apr_file_seek(dobj->hfd, APR_SET, &offset);
410 nkey = key;
413 obj->key = nkey;
414 dobj->key = nkey;
415 dobj->name = key;
416 dobj->datafile = data_file(r->pool, conf, dobj, nkey);
417 dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
419 /* Open the data file */
420 flags = APR_READ|APR_BINARY;
421 #ifdef APR_SENDFILE_ENABLED
422 flags |= APR_SENDFILE_ENABLED;
423 #endif
424 rc = apr_file_open(&dobj->fd, dobj->datafile, flags, 0, r->pool);
425 if (rc != APR_SUCCESS) {
426 /* XXX: Log message */
427 return DECLINED;
430 rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, dobj->fd);
431 if (rc == APR_SUCCESS) {
432 dobj->file_size = finfo.size;
435 /* Read the bytes to setup the cache_info fields */
436 rc = file_cache_recall_mydata(dobj->hfd, info, dobj, r);
437 if (rc != APR_SUCCESS) {
438 /* XXX log message */
439 return DECLINED;
442 /* Initialize the cache_handle callback functions */
443 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
444 "disk_cache: Recalled cached URL info header %s", dobj->name);
445 return OK;
448 int remove_entity(cache_handle_t *h) {
449 /* Null out the cache object pointer so next time we start from scratch */
450 h->cache_obj = NULL;
452 return OK;
455 int remove_url(cache_handle_t *h, apr_pool_t *p) {
456 apr_status_t rc;
457 disk_cache_object_t *dobj;
459 /* Get disk cache object from cache handle */
460 dobj = (disk_cache_object_t *) h->cache_obj->vobj;
461 if (!dobj) {
462 return DECLINED;
465 /* Delete headers file */
466 if (dobj->hdrsfile) {
467 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
468 "disk_cache: Deleting %s from cache.", dobj->hdrsfile);
470 rc = apr_file_remove(dobj->hdrsfile, p);
471 if ((rc != APR_SUCCESS) && !APR_STATUS_IS_ENOENT(rc)) {
472 /* Will only result in an output if httpd is started with -e debug.
473 * For reason see log_error_core for the case s == NULL.
475 ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, NULL,
476 "disk_cache: Failed to delete headers file %s from cache.",
477 dobj->hdrsfile);
478 return DECLINED;
482 /* Delete data file */
483 if (dobj->datafile) {
484 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
485 "disk_cache: Deleting %s from cache.", dobj->datafile);
487 rc = apr_file_remove(dobj->datafile, p);
488 if ((rc != APR_SUCCESS) && !APR_STATUS_IS_ENOENT(rc)) {
489 /* Will only result in an output if httpd is started with -e debug.
490 * For reason see log_error_core for the case s == NULL.
492 ap_log_error(APLOG_MARK, APLOG_DEBUG, rc, NULL,
493 "disk_cache: Failed to delete data file %s from cache.",
494 dobj->datafile);
495 return DECLINED;
499 /* now delete directories as far as possible up to our cache root */
500 if (dobj->root) {
501 const char *str_to_copy;
503 str_to_copy = dobj->hdrsfile ? dobj->hdrsfile : dobj->datafile;
504 if (str_to_copy) {
505 char *dir, *slash, *q;
507 dir = apr_pstrdup(p, str_to_copy);
509 /* remove filename */
510 slash = strrchr(dir, '/');
511 *slash = '\0';
514 * now walk our way back to the cache root, delete everything
515 * in the way as far as possible
517 * Note: due to the way we constructed the file names in
518 * header_file and data_file, we are guaranteed that the
519 * cache_root is suffixed by at least one '/' which will be
520 * turned into a terminating null by this loop. Therefore,
521 * we won't either delete or go above our cache root.
523 for (q = dir + dobj->root_len; *q; ) {
524 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
525 "disk_cache: Deleting directory %s from cache",
526 dir);
528 rc = apr_dir_remove(dir, p);
529 if (rc != APR_SUCCESS && !APR_STATUS_IS_ENOENT(rc)) {
530 break;
532 slash = strrchr(q, '/');
533 *slash = '\0';
538 return OK;
541 apr_status_t read_array(request_rec *r, apr_array_header_t* arr,
542 apr_file_t *file) {
543 char w[MAX_STRING_LEN];
544 int p;
545 apr_status_t rv;
547 while (1) {
548 rv = apr_file_gets(w, MAX_STRING_LEN - 1, file);
549 if (rv != APR_SUCCESS) {
550 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
551 "Premature end of vary array.");
552 return rv;
555 p = strlen(w);
556 if (p> 0 && w[p - 1] == '\n') {
557 if (p> 1 && w[p - 2] == CR) {
558 w[p - 2] = '\0';
560 else {
561 w[p - 1] = '\0';
565 /* If we've finished reading the array, break out of the loop. */
566 if (w[0] == '\0') {
567 break;
570 *((const char **) apr_array_push(arr)) = apr_pstrdup(r->pool, w);
573 return APR_SUCCESS;
576 static apr_status_t store_array(apr_file_t *fd, apr_array_header_t* arr) {
577 int i;
578 apr_status_t rv;
579 struct iovec iov[2];
580 apr_size_t amt;
581 const char **elts;
583 elts = (const char **) arr->elts;
585 for (i = 0; i < arr->nelts; i++) {
586 iov[0].iov_base = (char*) elts[i];
587 iov[0].iov_len = strlen(elts[i]);
588 iov[1].iov_base = CRLF;
589 iov[1].iov_len = sizeof(CRLF) - 1;
591 rv = apr_file_writev(fd, (const struct iovec *) &iov, 2,
592 &amt);
593 if (rv != APR_SUCCESS) {
594 return rv;
598 iov[0].iov_base = CRLF;
599 iov[0].iov_len = sizeof(CRLF) - 1;
601 return apr_file_writev(fd, (const struct iovec *) &iov, 1,
602 &amt);
605 apr_status_t read_table(cache_handle_t *handle, request_rec *r,
606 apr_table_t *table, apr_file_t *file) {
607 char w[MAX_STRING_LEN];
608 char *l;
609 int p;
610 apr_status_t rv;
612 while (1) {
614 /* ### What about APR_EOF? */
615 rv = apr_file_gets(w, MAX_STRING_LEN - 1, file);
616 if (rv != APR_SUCCESS) {
617 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
618 "Premature end of cache headers.");
619 return rv;
622 /* Delete terminal (CR?)LF */
624 p = strlen(w);
625 /* Indeed, the host's '\n':
626 '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
627 -- whatever the script generates.
629 if (p> 0 && w[p - 1] == '\n') {
630 if (p> 1 && w[p - 2] == CR) {
631 w[p - 2] = '\0';
633 else {
634 w[p - 1] = '\0';
638 /* If we've finished reading the headers, break out of the loop. */
639 if (w[0] == '\0') {
640 break;
643 #if APR_CHARSET_EBCDIC
644 /* Chances are that we received an ASCII header text instead of
645 * the expected EBCDIC header lines. Try to auto-detect:
647 if (!(l = strchr(w, ':'))) {
648 int maybeASCII = 0, maybeEBCDIC = 0;
649 unsigned char *cp, native;
650 apr_size_t inbytes_left, outbytes_left;
652 for (cp = w; *cp != '\0'; ++cp) {
653 native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
654 if (apr_isprint(*cp) && !apr_isprint(native))
655 ++maybeEBCDIC;
656 if (!apr_isprint(*cp) && apr_isprint(native))
657 ++maybeASCII;
659 if (maybeASCII> maybeEBCDIC) {
660 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
661 "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
662 r->filename);
663 inbytes_left = outbytes_left = cp - w;
664 apr_xlate_conv_buffer(ap_hdrs_from_ascii,
665 w, &inbytes_left, w, &outbytes_left);
668 #endif /*APR_CHARSET_EBCDIC*/
670 /* if we see a bogus header don't ignore it. Shout and scream */
671 if (!(l = strchr(w, ':'))) {
672 return APR_EGENERAL;
675 *l++ = '\0';
676 while (*l && apr_isspace(*l)) {
677 ++l;
680 apr_table_add(table, w, l);
683 return APR_SUCCESS;
687 apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p,
688 apr_bucket_brigade *bb) {
689 apr_bucket *e;
690 disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
692 e = apr_bucket_file_create(dobj->fd, 0, (apr_size_t) dobj->file_size, p,
693 bb->bucket_alloc);
695 APR_BRIGADE_INSERT_HEAD(bb, e);
696 e = apr_bucket_eos_create(bb->bucket_alloc);
697 APR_BRIGADE_INSERT_TAIL(bb, e);
699 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, "crccache_client: Recalled body for URL %s", dobj->name);
700 return APR_SUCCESS;
703 apr_status_t store_table(apr_file_t *fd, apr_table_t *table) {
704 int i;
705 apr_status_t rv;
706 struct iovec iov[4];
707 apr_size_t amt;
708 apr_table_entry_t *elts;
710 elts = (apr_table_entry_t *) apr_table_elts(table)->elts;
711 for (i = 0; i < apr_table_elts(table)->nelts; ++i) {
712 if (elts[i].key != NULL) {
713 iov[0].iov_base = elts[i].key;
714 iov[0].iov_len = strlen(elts[i].key);
715 iov[1].iov_base = ": ";
716 iov[1].iov_len = sizeof(": ") - 1;
717 iov[2].iov_base = elts[i].val;
718 iov[2].iov_len = strlen(elts[i].val);
719 iov[3].iov_base = CRLF;
720 iov[3].iov_len = sizeof(CRLF) - 1;
722 rv = apr_file_writev(fd, (const struct iovec *) &iov, 4,
723 &amt);
724 if (rv != APR_SUCCESS) {
725 return rv;
729 iov[0].iov_base = CRLF;
730 iov[0].iov_len = sizeof(CRLF) - 1;
731 rv = apr_file_writev(fd, (const struct iovec *) &iov, 1,
732 &amt);
733 return rv;
736 apr_status_t store_headers(cache_handle_t *h, request_rec *r,
737 cache_info *info) {
738 crccache_client_conf *conf = ap_get_module_config(r->server->module_config,
739 &crccache_client_module);
741 apr_status_t rv;
742 apr_size_t amt;
743 disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
745 disk_cache_info_t disk_info;
746 struct iovec iov[2];
748 /* This is flaky... we need to manage the cache_info differently */
749 h->cache_obj->info = *info;
751 if (r->headers_out) {
752 const char *tmp;
754 tmp = apr_table_get(r->headers_out, "Vary");
756 if (tmp) {
757 apr_array_header_t* varray;
758 apr_uint32_t format = VARY_FORMAT_VERSION;
760 /* If we were initially opened as a vary format, rollback
761 * that internal state for the moment so we can recreate the
762 * vary format hints in the appropriate directory.
764 if (dobj->prefix) {
765 dobj->hdrsfile = dobj->prefix;
766 dobj->prefix = NULL;
769 mkdir_structure(conf, dobj->hdrsfile, r->pool);
771 rv = apr_file_mktemp(&dobj->tfd, dobj->tempfile,
772 APR_CREATE | APR_WRITE | APR_BINARY | APR_EXCL,
773 r->pool);
775 if (rv != APR_SUCCESS) {
776 return rv;
779 amt = sizeof(format);
780 apr_file_write(dobj->tfd, &format, &amt);
782 amt = sizeof(info->expire);
783 apr_file_write(dobj->tfd, &info->expire, &amt);
785 varray = apr_array_make(r->pool, 6, sizeof(char*));
786 tokens_to_array(r->pool, tmp, varray);
788 store_array(dobj->tfd, varray);
790 apr_file_close(dobj->tfd);
792 dobj->tfd = NULL;
794 rv = safe_file_rename(conf, dobj->tempfile, dobj->hdrsfile,
795 r->pool);
796 if (rv != APR_SUCCESS) {
797 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, r->server,
798 "disk_cache: rename tempfile to varyfile failed: %s -> %s",
799 dobj->tempfile, dobj->hdrsfile);
800 apr_file_remove(dobj->tempfile, r->pool);
801 return rv;
804 dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
805 tmp = regen_key(r->pool, r->headers_in, varray, dobj->name);
806 dobj->prefix = dobj->hdrsfile;
807 dobj->hashfile = NULL;
808 dobj->datafile = data_file(r->pool, conf, dobj, tmp);
809 dobj->hdrsfile = header_file(r->pool, conf, dobj, tmp);
814 rv = apr_file_mktemp(&dobj->hfd, dobj->tempfile,
815 APR_CREATE | APR_WRITE | APR_BINARY |
816 APR_BUFFERED | APR_EXCL, r->pool);
818 if (rv != APR_SUCCESS) {
819 return rv;
822 disk_info.format = DISK_FORMAT_VERSION;
823 disk_info.date = info->date;
824 disk_info.expire = info->expire;
825 disk_info.entity_version = dobj->disk_info.entity_version++;
826 disk_info.request_time = info->request_time;
827 disk_info.response_time = info->response_time;
828 disk_info.status = info->status;
830 disk_info.name_len = strlen(dobj->name);
832 iov[0].iov_base = (void*)&disk_info;
833 iov[0].iov_len = sizeof(disk_cache_info_t);
834 iov[1].iov_base = (void*)dobj->name;
835 iov[1].iov_len = disk_info.name_len;
837 rv = apr_file_writev(dobj->hfd, (const struct iovec *) &iov, 2, &amt);
838 if (rv != APR_SUCCESS) {
839 return rv;
842 if (r->headers_out) {
843 apr_table_t *headers_out;
845 headers_out = ap_cache_cacheable_hdrs_out(r->pool, r->headers_out,
846 r->server);
848 if (!apr_table_get(headers_out, "Content-Type")
849 && r->content_type) {
850 apr_table_setn(headers_out, "Content-Type",
851 ap_make_content_type(r, r->content_type));
854 headers_out = apr_table_overlay(r->pool, headers_out,
855 r->err_headers_out);
856 rv = store_table(dobj->hfd, headers_out);
857 if (rv != APR_SUCCESS) {
858 return rv;
862 /* Parse the vary header and dump those fields from the headers_in. */
863 /* FIXME: Make call to the same thing cache_select calls to crack Vary. */
864 if (r->headers_in) {
865 apr_table_t *headers_in;
867 headers_in = ap_cache_cacheable_hdrs_out(r->pool, r->headers_in,
868 r->server);
869 rv = store_table(dobj->hfd, headers_in);
870 if (rv != APR_SUCCESS) {
871 return rv;
875 apr_file_close(dobj->hfd); /* flush and close */
877 /* Remove old file with the same name. If remove fails, then
878 * perhaps we need to create the directory tree where we are
879 * about to write the new headers file.
881 rv = apr_file_remove(dobj->hdrsfile, r->pool);
882 if (rv != APR_SUCCESS) {
883 mkdir_structure(conf, dobj->hdrsfile, r->pool);
886 rv = safe_file_rename(conf, dobj->tempfile, dobj->hdrsfile, r->pool);
887 if (rv != APR_SUCCESS) {
888 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, r->server,
889 "disk_cache: rename tempfile to hdrsfile failed: %s -> %s",
890 dobj->tempfile, dobj->hdrsfile);
891 apr_file_remove(dobj->tempfile, r->pool);
892 return rv;
895 dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
897 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
898 "disk_cache: Stored headers for URL %s", dobj->name);
899 return APR_SUCCESS;
902 apr_status_t store_body(cache_handle_t *h, request_rec *r,
903 apr_bucket_brigade *bb) {
904 apr_bucket *e;
905 apr_status_t rv;
907 disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
908 crccache_client_conf *conf = ap_get_module_config(r->server->module_config,
909 &crccache_client_module);
911 /* We write to a temp file and then atomically rename the file over
912 * in file_cache_el_final().
914 if (!dobj->tfd) {
915 rv = apr_file_mktemp(&dobj->tfd, dobj->tempfile, APR_CREATE | APR_WRITE
916 | APR_BINARY | APR_BUFFERED | APR_EXCL, r->pool);
917 if (rv != APR_SUCCESS) {
918 return rv;
920 dobj->file_size = 0;
923 for (e = APR_BRIGADE_FIRST(bb); e != APR_BRIGADE_SENTINEL(bb); e = APR_BUCKET_NEXT(e)) {
924 const char *str;
925 apr_size_t length, written;
926 rv = apr_bucket_read(e, &str, &length, APR_BLOCK_READ);
927 if (rv != APR_SUCCESS) {
928 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
929 "cache_disk: Error when reading bucket for URL %s",
930 h->cache_obj->key);
931 /* Remove the intermediate cache file and return non-APR_SUCCESS */
932 file_cache_errorcleanup(dobj, r);
933 return rv;
935 rv = apr_file_write_full(dobj->tfd, str, length, &written);
936 if (rv != APR_SUCCESS) {
937 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
938 "cache_disk: Error when writing cache file for URL %s",
939 h->cache_obj->key);
940 /* Remove the intermediate cache file and return non-APR_SUCCESS */
941 file_cache_errorcleanup(dobj, r);
942 return rv;
944 dobj->file_size += written;
945 if (dobj->file_size> conf->maxfs) {
946 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
947 "cache_disk: URL %s failed the size check "
948 "(%" APR_OFF_T_FMT " > %" APR_OFF_T_FMT ")",
949 h->cache_obj->key, dobj->file_size, conf->maxfs);
950 /* Remove the intermediate cache file and return non-APR_SUCCESS */
951 file_cache_errorcleanup(dobj, r);
952 return APR_EGENERAL;
956 /* Was this the final bucket? If yes, close the temp file and perform
957 * sanity checks.
959 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
960 if (r->connection->aborted || r->no_cache) {
961 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
962 "disk_cache: Discarding body for URL %s "
963 "because connection has been aborted.",
964 h->cache_obj->key);
965 /* Remove the intermediate cache file and return non-APR_SUCCESS */
966 file_cache_errorcleanup(dobj, r);
967 return APR_EGENERAL;
969 if (dobj->file_size < conf->minfs) {
970 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
971 "cache_disk: URL %s failed the size check "
972 "(%" APR_OFF_T_FMT " < %" APR_OFF_T_FMT ")",
973 h->cache_obj->key, dobj->file_size, conf->minfs);
974 /* Remove the intermediate cache file and return non-APR_SUCCESS */
975 file_cache_errorcleanup(dobj, r);
976 return APR_EGENERAL;
979 /* All checks were fine. Move tempfile to final destination */
980 /* Link to the perm file, and close the descriptor */
981 file_cache_el_final(dobj, r);
982 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
983 "disk_cache: Body for URL %s cached.", dobj->name);
986 return APR_SUCCESS;