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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "mod_cache.h"
19 #include "cache_util.h"
20 #include <ap_provider.h>
22 APLOG_USE_MODULE(cache);
24 /* -------------------------------------------------------------- */
26 extern APR_OPTIONAL_FN_TYPE(ap_cache_generate_key) *cache_generate_key;
28 extern module AP_MODULE_DECLARE_DATA cache_module;
30 /* Determine if "url" matches the hostname, scheme and port and path
31 * in "filter". All but the path comparisons are case-insensitive.
33 static int uri_meets_conditions(const apr_uri_t *filter, const int pathlen,
37 /* Scheme, hostname port and local part. The filter URI and the
38 * URI we test may have the following shapes:
40 * <scheme>[:://<hostname>[:<port>][/<path>]]
41 * That is, if there is no scheme then there must be only the path,
42 * and we check only the path; if there is a scheme, we check the
43 * scheme for equality, and then if present we match the hostname,
44 * and then if present match the port, and finally the path if any.
46 * Note that this means that "/<path>" only matches local paths,
47 * and to match proxied paths one *must* specify the scheme.
50 /* Is the filter is just for a local path or a proxy URI? */
51 if (!filter->scheme) {
52 if (url->scheme || url->hostname) {
57 /* The URI scheme must be present and identical except for case. */
58 if (!url->scheme || strcasecmp(filter->scheme, url->scheme)) {
62 /* If the filter hostname is null or empty it matches any hostname,
63 * if it begins with a "*" it matches the _end_ of the URI hostname
64 * excluding the "*", if it begins with a "." it matches the _end_
65 * of the URI * hostname including the ".", otherwise it must match
66 * the URI hostname exactly. */
68 if (filter->hostname && filter->hostname[0]) {
69 if (filter->hostname[0] == '.') {
70 const size_t fhostlen = strlen(filter->hostname);
71 const size_t uhostlen = url->hostname ? strlen(url->hostname) : 0;
73 if (fhostlen > uhostlen || strcasecmp(filter->hostname,
74 url->hostname + uhostlen - fhostlen)) {
78 else if (filter->hostname[0] == '*') {
79 const size_t fhostlen = strlen(filter->hostname + 1);
80 const size_t uhostlen = url->hostname ? strlen(url->hostname) : 0;
82 if (fhostlen > uhostlen || strcasecmp(filter->hostname + 1,
83 url->hostname + uhostlen - fhostlen)) {
87 else if (!url->hostname || strcasecmp(filter->hostname, url->hostname)) {
92 /* If the filter port is empty it matches any URL port.
93 * If the filter or URL port are missing, or the URL port is
94 * empty, they default to the port for their scheme. */
96 if (!(filter->port_str && !filter->port_str[0])) {
97 /* NOTE: ap_port_of_scheme will return 0 if given NULL input */
98 const unsigned fport = filter->port_str ? filter->port
99 : apr_uri_port_of_scheme(filter->scheme);
100 const unsigned uport = (url->port_str && url->port_str[0])
101 ? url->port : apr_uri_port_of_scheme(url->scheme);
103 if (fport != uport) {
109 /* For HTTP caching purposes, an empty (NULL) path is equivalent to
110 * a single "/" path. RFCs 3986/2396
113 if (*filter->path == '/' && pathlen == 1) {
121 /* Url has met all of the filter conditions so far, determine
122 * if the paths match.
124 return !strncmp(filter->path, url->path, pathlen);
127 cache_provider_list *cache_get_providers(request_rec *r,
128 cache_server_conf *conf,
131 cache_provider_list *providers = NULL;
134 /* loop through all the cacheenable entries */
135 for (i = 0; i < conf->cacheenable->nelts; i++) {
136 struct cache_enable *ent =
137 (struct cache_enable *)conf->cacheenable->elts;
138 if (uri_meets_conditions(&ent[i].url, ent[i].pathlen, &uri)) {
139 /* Fetch from global config and add to the list. */
140 cache_provider *provider;
141 provider = ap_lookup_provider(CACHE_PROVIDER_GROUP, ent[i].type,
147 cache_provider_list *newp;
148 newp = apr_pcalloc(r->pool, sizeof(cache_provider_list));
149 newp->provider_name = ent[i].type;
150 newp->provider = provider;
156 cache_provider_list *last = providers;
167 /* then loop through all the cachedisable entries
168 * Looking for urls that contain the full cachedisable url and possibly
170 * This means we are disabling cachedisable url and below...
172 for (i = 0; i < conf->cachedisable->nelts; i++) {
173 struct cache_disable *ent =
174 (struct cache_disable *)conf->cachedisable->elts;
175 if (uri_meets_conditions(&ent[i].url, ent[i].pathlen, &uri)) {
176 /* Stop searching now. */
185 /* do a HTTP/1.1 age calculation */
186 CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info,
187 const apr_time_t age_value,
190 apr_time_t apparent_age, corrected_received_age, response_delay,
191 corrected_initial_age, resident_time, current_age,
194 age_value_usec = apr_time_from_sec(age_value);
196 /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
198 apparent_age = MAX(0, info->response_time - info->date);
199 corrected_received_age = MAX(apparent_age, age_value_usec);
200 response_delay = info->response_time - info->request_time;
201 corrected_initial_age = corrected_received_age + response_delay;
202 resident_time = now - info->response_time;
203 current_age = corrected_initial_age + resident_time;
205 if (current_age < 0) {
209 return apr_time_sec(current_age);
213 * Try obtain a cache wide lock on the given cache key.
215 * If we return APR_SUCCESS, we obtained the lock, and we are clear to
216 * proceed to the backend. If we return APR_EEXISTS, then the lock is
217 * already locked, someone else has gone to refresh the backend data
218 * already, so we must return stale data with a warning in the mean
219 * time. If we return anything else, then something has gone pear
220 * shaped, and we allow the request through to the backend regardless.
222 * This lock is created from the request pool, meaning that should
223 * something go wrong and the lock isn't deleted on return of the
224 * request headers from the backend for whatever reason, at worst the
225 * lock will be cleaned up when the request dies or finishes.
227 * If something goes truly bananas and the lock isn't deleted when the
228 * request dies, the lock will be trashed when its max-age is reached,
229 * or when a request arrives containing a Cache-Control: no-cache. At
230 * no point is it possible for this lock to permanently deny access to
233 apr_status_t cache_try_lock(cache_server_conf *conf, cache_request_rec *cache,
237 const char *lockname;
240 apr_time_t now = apr_time_now();
242 apr_file_t *lockfile;
247 if (!conf || !conf->lock || !conf->lockpath) {
248 /* no locks configured, leave */
252 /* lock already obtained earlier? if so, success */
253 apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
258 /* create the key if it doesn't exist */
260 cache_generate_key(r, r->pool, &cache->key);
263 /* create a hashed filename from the key, and save it for later */
264 lockname = ap_cache_generate_name(r->pool, 0, 0, cache->key);
266 /* lock files represent discrete just-went-stale URLs "in flight", so
267 * we support a simple two level directory structure, more is overkill.
270 dir[1] = lockname[0];
272 dir[3] = lockname[1];
275 /* make the directories */
276 path = apr_pstrcat(r->pool, conf->lockpath, dir, NULL);
277 if (APR_SUCCESS != (status = apr_dir_make_recursive(path,
278 APR_UREAD|APR_UWRITE|APR_UEXECUTE, r->pool))) {
279 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
280 "Could not create a cache lock directory: %s",
284 lockname = apr_pstrcat(r->pool, path, "/", lockname, NULL);
285 apr_pool_userdata_set(lockname, CACHE_LOCKNAME_KEY, NULL, r->pool);
287 /* is an existing lock file too old? */
288 status = apr_stat(&finfo, lockname,
289 APR_FINFO_MTIME | APR_FINFO_NLINK, r->pool);
290 if (!(APR_STATUS_IS_ENOENT(status)) && APR_SUCCESS != status) {
291 ap_log_error(APLOG_MARK, APLOG_ERR, APR_EEXIST, r->server,
292 "Could not stat a cache lock file: %s",
296 if ((status == APR_SUCCESS) && (((now - finfo.mtime) > conf->lockmaxage)
297 || (now < finfo.mtime))) {
298 ap_log_error(APLOG_MARK, APLOG_INFO, status, r->server,
299 "Cache lock file for '%s' too old, removing: %s",
301 apr_file_remove(lockname, r->pool);
304 /* try obtain a lock on the file */
305 if (APR_SUCCESS == (status = apr_file_open(&lockfile, lockname,
306 APR_WRITE | APR_CREATE | APR_EXCL | APR_DELONCLOSE,
307 APR_UREAD | APR_UWRITE, r->pool))) {
308 apr_pool_userdata_set(lockfile, CACHE_LOCKFILE_KEY, NULL, r->pool);
315 * Remove the cache lock, if present.
317 * First, try to close the file handle, whose delete-on-close should
318 * kill the file. Otherwise, just delete the file by name.
320 * If no lock name has yet been calculated, do the calculation of the
321 * lock name first before trying to delete the file.
323 * If an optional bucket brigade is passed, the lock will only be
324 * removed if the bucket brigade contains an EOS bucket.
326 apr_status_t cache_remove_lock(cache_server_conf *conf,
327 cache_request_rec *cache, request_rec *r, apr_bucket_brigade *bb)
330 const char *lockname;
332 if (!conf || !conf->lock || !conf->lockpath) {
333 /* no locks configured, leave */
339 for (e = APR_BRIGADE_FIRST(bb);
340 e != APR_BRIGADE_SENTINEL(bb);
341 e = APR_BUCKET_NEXT(e))
343 if (APR_BUCKET_IS_EOS(e)) {
349 /* no eos found in brigade, don't delete anything just yet,
355 apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
357 return apr_file_close((apr_file_t *)dummy);
359 apr_pool_userdata_get(&dummy, CACHE_LOCKNAME_KEY, r->pool);
360 lockname = (const char *)dummy;
364 /* create the key if it doesn't exist */
366 cache_generate_key(r, r->pool, &cache->key);
369 /* create a hashed filename from the key, and save it for later */
370 lockname = ap_cache_generate_name(r->pool, 0, 0, cache->key);
372 /* lock files represent discrete just-went-stale URLs "in flight", so
373 * we support a simple two level directory structure, more is overkill.
376 dir[1] = lockname[0];
378 dir[3] = lockname[1];
381 lockname = apr_pstrcat(r->pool, conf->lockpath, dir, "/", lockname, NULL);
383 return apr_file_remove(lockname, r->pool);
386 CACHE_DECLARE(int) ap_cache_check_allowed(cache_request_rec *cache, request_rec *r) {
389 cache_server_conf *conf =
390 (cache_server_conf *)ap_get_module_config(r->server->module_config,
394 * At this point, we may have data cached, but the request may have
395 * specified that cached data may not be used in a response.
397 * This is covered under RFC2616 section 14.9.4 (Cache Revalidation and
400 * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache, or Pragma:
401 * no-cache. The server MUST NOT use a cached copy when responding to such
404 * - RFC2616 14.9.2 What May be Stored by Caches. If Cache-Control:
405 * no-store arrives, do not serve from the cache.
408 /* This value comes from the client's initial request. */
409 cc_req = apr_table_get(r->headers_in, "Cache-Control");
410 pragma = apr_table_get(r->headers_in, "Pragma");
412 ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
414 if (cache->control_in.no_cache) {
416 if (!conf->ignorecachecontrol) {
420 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
421 "Incoming request is asking for an uncached version of "
422 "%s, but we have been configured to ignore it and serve "
423 "cached content anyway", r->unparsed_uri);
427 if (cache->control_in.no_store) {
429 if (!conf->ignorecachecontrol) {
430 /* We're not allowed to serve a cached copy */
434 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
435 "Incoming request is asking for a no-store version of "
436 "%s, but we have been configured to ignore it and serve "
437 "cached content anyway", r->unparsed_uri);
445 int cache_check_freshness(cache_handle_t *h, cache_request_rec *cache,
449 apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
450 apr_int64_t minfresh;
453 const char *agestr = NULL;
454 const char *expstr = NULL;
455 apr_time_t age_c = 0;
456 cache_info *info = &(h->cache_obj->info);
457 const char *warn_head;
458 cache_server_conf *conf =
459 (cache_server_conf *)ap_get_module_config(r->server->module_config,
463 * We now want to check if our cached data is still fresh. This depends
464 * on a few things, in this order:
466 * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache
467 * in either the request or the cached response means that we must
468 * perform the request unconditionally, and ignore cached content. We
469 * should never reach here, but if we do, mark the content as stale,
470 * as this is the best we can do.
472 * - RFC2616 14.32 Pragma: no-cache This is treated the same as
473 * Cache-Control: no-cache.
475 * - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
476 * proxy-revalidate if the max-stale request header exists, modify the
477 * stale calculations below so that an object can be at most <max-stale>
478 * seconds stale before we request a revalidation, _UNLESS_ a
479 * must-revalidate or proxy-revalidate cached response header exists to
480 * stop us doing this.
482 * - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
483 * maximum age an object can be before it is considered stale. This
484 * directive has the effect of proxy|must revalidate, which in turn means
485 * simple ignore any max-stale setting.
487 * - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
488 * requests and responses. If both are specified, the smaller of the two
491 * - RFC2616 14.21 Expires: if this request header exists in the cached
492 * entity, and it's value is in the past, it has expired.
496 /* This value comes from the client's initial request. */
497 cc_req = apr_table_get(r->headers_in, "Cache-Control");
498 pragma = apr_table_get(r->headers_in, "Pragma");
500 ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
502 if (cache->control_in.no_cache) {
504 if (!conf->ignorecachecontrol) {
505 /* Treat as stale, causing revalidation */
509 ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
510 "Incoming request is asking for a uncached version of "
511 "%s, but we have been configured to ignore it and "
512 "serve a cached response anyway",
516 /* These come from the cached entity. */
517 expstr = apr_table_get(h->resp_hdrs, "Expires");
519 if (h->cache_obj->info.control.no_cache) {
521 * The cached entity contained Cache-Control: no-cache, so treat as
522 * stale causing revalidation
527 if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
528 age_c = apr_atoi64(agestr);
531 /* calculate age of object */
532 age = ap_cache_current_age(info, age_c, r->request_time);
534 /* extract s-maxage */
535 smaxage = h->cache_obj->info.control.s_maxage_value;
537 /* extract max-age from request */
539 if (!conf->ignorecachecontrol) {
540 maxage_req = cache->control_in.max_age_value;
543 /* extract max-age from response */
544 maxage_cresp = h->cache_obj->info.control.max_age_value;
547 * if both maxage request and response, the smaller one takes priority
549 if (maxage_req == -1) {
550 maxage = maxage_cresp;
552 else if (maxage_cresp == -1) {
556 maxage = MIN(maxage_req, maxage_cresp);
559 /* extract max-stale */
560 if (cache->control_in.max_stale) {
561 if(cache->control_in.max_stale_value != -1) {
562 maxstale = cache->control_in.max_stale_value;
566 * If no value is assigned to max-stale, then the client is willing
567 * to accept a stale response of any age (RFC2616 14.9.3). We will
568 * set it to one year in this case as this situation is somewhat
569 * similar to a "never expires" Expires header (RFC2616 14.21)
570 * which is set to a date one year from the time the response is
573 maxstale = APR_INT64_C(86400*365);
580 /* extract min-fresh */
581 if (!conf->ignorecachecontrol && cache->control_in.min_fresh) {
582 minfresh = cache->control_in.min_fresh_value;
588 /* override maxstale if must-revalidate or proxy-revalidate */
589 if (maxstale && (h->cache_obj->info.control.must_revalidate
590 || h->cache_obj->info.control.proxy_revalidate)) {
594 /* handle expiration */
595 if (((smaxage != -1) && (age < (smaxage - minfresh))) ||
596 ((maxage != -1) && (age < (maxage + maxstale - minfresh))) ||
597 ((smaxage == -1) && (maxage == -1) &&
598 (info->expire != APR_DATE_BAD) &&
599 (age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh)))) {
601 warn_head = apr_table_get(h->resp_hdrs, "Warning");
603 /* it's fresh darlings... */
604 /* set age header on response */
605 apr_table_set(h->resp_hdrs, "Age",
606 apr_psprintf(r->pool, "%lu", (unsigned long)age));
608 /* add warning if maxstale overrode freshness calculation */
609 if (!(((smaxage != -1) && age < smaxage) ||
610 ((maxage != -1) && age < maxage) ||
611 (info->expire != APR_DATE_BAD &&
612 (apr_time_sec(info->expire - info->date)) > age))) {
613 /* make sure we don't stomp on a previous warning */
614 if ((warn_head == NULL) ||
615 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
616 apr_table_merge(h->resp_hdrs, "Warning",
617 "110 Response is stale");
621 * If none of Expires, Cache-Control: max-age, or Cache-Control:
622 * s-maxage appears in the response, and the response header age
623 * calculated is more than 24 hours add the warning 113
625 if ((maxage_cresp == -1) && (smaxage == -1) &&
626 (expstr == NULL) && (age > 86400)) {
628 /* Make sure we don't stomp on a previous warning, and don't dup
629 * a 113 marning that is already present. Also, make sure to add
630 * the new warning to the correct *headers_out location.
632 if ((warn_head == NULL) ||
633 ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
634 apr_table_merge(h->resp_hdrs, "Warning",
635 "113 Heuristic expiration");
638 return 1; /* Cache object is fresh (enough) */
642 * At this point we are stale, but: if we are under load, we may let
643 * a significant number of stale requests through before the first
644 * stale request successfully revalidates itself, causing a sudden
645 * unexpected thundering herd which in turn brings angst and drama.
649 * We want the first stale request to go through as normal. But the
650 * second and subsequent request, we must pretend to be fresh until
651 * the first request comes back with either new content or confirmation
652 * that the stale content is still fresh.
654 * To achieve this, we create a very simple file based lock based on
655 * the key of the cached object. We attempt to open the lock file with
656 * exclusive write access. If we succeed, woohoo! we're first, and we
657 * follow the stale path to the backend server. If we fail, oh well,
658 * we follow the fresh path, and avoid being a thundering herd.
660 * The lock lives only as long as the stale request that went on ahead.
661 * If the request succeeds, the lock is deleted. If the request fails,
662 * the lock is deleted, and another request gets to make a new lock
665 * At any time, a request marked "no-cache" will force a refresh,
666 * ignoring the lock, ensuring an extended lockout is impossible.
668 * A lock that exceeds a maximum age will be deleted, and another
669 * request gets to make a new lock and try again.
671 status = cache_try_lock(conf, cache, r);
672 if (APR_SUCCESS == status) {
673 /* we obtained a lock, follow the stale path */
674 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
675 "Cache lock obtained for stale cached URL, "
676 "revalidating entry: %s",
680 else if (APR_EEXIST == status) {
681 /* lock already exists, return stale data anyway, with a warning */
682 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
683 "Cache already locked for stale cached URL, "
684 "pretend it is fresh: %s",
687 /* make sure we don't stomp on a previous warning */
688 warn_head = apr_table_get(h->resp_hdrs, "Warning");
689 if ((warn_head == NULL) ||
690 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
691 apr_table_merge(h->resp_hdrs, "Warning",
692 "110 Response is stale");
698 /* some other error occurred, just treat the object as stale */
699 ap_log_error(APLOG_MARK, APLOG_DEBUG, status, r->server,
700 "Attempt to obtain a cache lock for stale "
701 "cached URL failed, revalidating entry anyway: %s",
709 * list is a comma-separated list of case-insensitive tokens, with
710 * optional whitespace around the tokens.
711 * The return returns 1 if the token val is found in the list, or 0
714 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
715 const char *key, char **val)
724 key_len = strlen(key);
729 /* skip whitespace and commas to find the start of the next key */
730 while (*next && (apr_isspace(*next) || (*next == ','))) {
738 if (!strncasecmp(next, key, key_len)) {
739 /* this field matches the key (though it might just be
740 * a prefix match, so make sure the match is followed
741 * by either a space or an equals sign)
744 if (!*next || (*next == '=') || apr_isspace(*next) ||
748 while (*next && (*next != '=') && (*next != ',')) {
753 while (*next && apr_isspace(*next )) {
760 const char *val_start = next;
761 while (*next && !apr_isspace(*next) &&
765 *val = apr_pstrmemdup(p, val_start,
777 /* skip to the next field */
783 } while (*next != ',');
787 /* return each comma separated token, one at a time */
788 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
794 s = ap_strchr_c(list, ',');
799 while (apr_isspace(*s))
805 while (i > 0 && apr_isspace(list[i - 1]))
810 return apr_pstrndup(p, list, i);
816 * Converts apr_time_t expressed as hex digits to
819 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
823 for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
828 else if (apr_isupper(ch))
829 j |= ch - ('A' - 10);
831 j |= ch - ('a' - 10);
837 * Converts apr_time_t to apr_time_t expressed as hex digits.
839 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
843 for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
847 y[i] = ch + ('A' - 10);
851 y[sizeof(j) * 2] = '\0';
854 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
856 apr_md5_ctx_t context;
857 unsigned char digest[16];
861 static const char enc_table[64] =
862 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
864 apr_md5_init(&context);
865 apr_md5_update(&context, (const unsigned char *) it, strlen(it));
866 apr_md5_final(digest, &context);
868 /* encode 128 bits as 22 characters, using a modified uuencoding
869 * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
870 * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
872 for (i = 0, k = 0; i < 15; i += 3) {
873 x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
874 tmp[k++] = enc_table[x >> 18];
875 tmp[k++] = enc_table[(x >> 12) & 0x3f];
876 tmp[k++] = enc_table[(x >> 6) & 0x3f];
877 tmp[k++] = enc_table[x & 0x3f];
882 tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
883 tmp[k++] = enc_table[(x << 4) & 0x3f];
885 /* now split into directory levels */
886 for (i = k = d = 0; d < ndepth; ++d) {
887 memcpy(&val[i], &tmp[k], nlength);
889 val[i + nlength] = '/';
892 memcpy(&val[i], &tmp[k], 22 - k);
893 val[i + 22 - k] = '\0';
896 CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
897 int dirlength, const char *name)
900 cache_hash(name, hashfile, dirlevels, dirlength);
901 return apr_pstrdup(p, hashfile);
905 * Create a new table consisting of those elements from an
906 * headers table that are allowed to be stored in a cache.
908 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers(apr_pool_t *pool,
912 cache_server_conf *conf;
915 apr_table_t *headers_out;
917 /* Short circuit the common case that there are not
918 * (yet) any headers populated.
921 return apr_table_make(pool, 10);
924 /* Make a copy of the headers, and remove from
925 * the copy any hop-by-hop headers, as defined in Section
928 headers_out = apr_table_copy(pool, t);
930 apr_table_unset(headers_out, "Connection");
931 apr_table_unset(headers_out, "Keep-Alive");
932 apr_table_unset(headers_out, "Proxy-Authenticate");
933 apr_table_unset(headers_out, "Proxy-Authorization");
934 apr_table_unset(headers_out, "TE");
935 apr_table_unset(headers_out, "Trailers");
936 apr_table_unset(headers_out, "Transfer-Encoding");
937 apr_table_unset(headers_out, "Upgrade");
939 conf = (cache_server_conf *)ap_get_module_config(s->module_config,
942 /* Remove the user defined headers set with CacheIgnoreHeaders.
943 * This may break RFC 2616 compliance on behalf of the administrator.
945 header = (char **)conf->ignore_headers->elts;
946 for (i = 0; i < conf->ignore_headers->nelts; i++) {
947 apr_table_unset(headers_out, header[i]);
953 * Create a new table consisting of those elements from an input
954 * headers table that are allowed to be stored in a cache.
956 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_in(request_rec *r)
958 return ap_cache_cacheable_headers(r->pool, r->headers_in, r->server);
962 * Create a new table consisting of those elements from an output
963 * headers table that are allowed to be stored in a cache;
964 * ensure there is a content type and capture any errors.
966 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_out(request_rec *r)
968 apr_table_t *headers_out;
970 headers_out = apr_table_overlay(r->pool, r->headers_out,
973 apr_table_clear(r->err_headers_out);
975 headers_out = ap_cache_cacheable_headers(r->pool, headers_out,
978 if (!apr_table_get(headers_out, "Content-Type")
979 && r->content_type) {
980 apr_table_setn(headers_out, "Content-Type",
981 ap_make_content_type(r, r->content_type));
984 if (!apr_table_get(headers_out, "Content-Encoding")
985 && r->content_encoding) {
986 apr_table_setn(headers_out, "Content-Encoding",
987 r->content_encoding);
994 * Parse the Cache-Control and Pragma headers in one go, marking
995 * which tokens appear within the header. Populate the structure
998 int ap_cache_control(request_rec *r, cache_control_t *cc,
999 const char *cc_header, const char *pragma_header, apr_table_t *headers)
1004 return cc->cache_control || cc->pragma;
1008 cc->max_age_value = -1;
1009 cc->max_stale_value = -1;
1010 cc->min_fresh_value = -1;
1011 cc->s_maxage_value = -1;
1013 if (pragma_header) {
1014 char *header = apr_pstrdup(r->pool, pragma_header);
1015 const char *token = apr_strtok(header, ", ", &last);
1017 /* handle most common quickest case... */
1018 if (!strcmp(token, "no-cache")) {
1021 /* ...then try slowest case */
1022 else if (!strcasecmp(token, "no-cache")) {
1025 token = apr_strtok(NULL, ", ", &last);
1031 char *header = apr_pstrdup(r->pool, cc_header);
1032 const char *token = apr_strtok(header, ", ", &last);
1037 /* handle most common quickest cases... */
1038 if (!strcmp(token, "no-cache")) {
1041 else if (!strcmp(token, "no-store")) {
1044 /* ...then try slowest cases */
1045 else if (!strncasecmp(token, "no-cache", 8)) {
1046 if (token[8] == '=') {
1047 if (apr_table_get(headers, token + 9)) {
1048 cc->no_cache_header = 1;
1051 else if (!token[8]) {
1056 else if (!strcasecmp(token, "no-store")) {
1059 else if (!strcasecmp(token, "no-transform")) {
1060 cc->no_transform = 1;
1066 /* handle most common quickest cases... */
1067 if (!strcmp(token, "max-age=0")) {
1069 cc->max_age_value = 0;
1071 else if (!strcmp(token, "must-revalidate")) {
1072 cc->must_revalidate = 1;
1074 /* ...then try slowest cases */
1075 else if (!strncasecmp(token, "max-age", 7)) {
1076 if (token[7] == '=') {
1078 cc->max_age_value = apr_atoi64(token + 8);
1082 else if (!strncasecmp(token, "max-stale", 9)) {
1083 if (token[9] == '=') {
1085 cc->max_stale_value = apr_atoi64(token + 10);
1087 else if (!token[10]) {
1089 cc->max_stale_value = -1;
1093 else if (!strncasecmp(token, "min-fresh", 9)) {
1094 if (token[9] == '=') {
1096 cc->min_fresh_value = apr_atoi64(token + 10);
1100 else if (!strcasecmp(token, "must-revalidate")) {
1101 cc->must_revalidate = 1;
1107 if (!strcasecmp(token, "only-if-cached")) {
1108 cc->only_if_cached = 1;
1114 /* handle most common quickest cases... */
1115 if (!strcmp(token, "private")) {
1118 /* ...then try slowest cases */
1119 else if (!strcasecmp(token, "public")) {
1122 else if (!strncasecmp(token, "private", 7)) {
1123 if (token[7] == '=') {
1124 if (apr_table_get(headers, token + 8)) {
1125 cc->private_header = 1;
1128 else if (!token[7]) {
1133 else if (!strcasecmp(token, "proxy-revalidate")) {
1134 cc->proxy_revalidate = 1;
1140 if (!strncasecmp(token, "s-maxage", 8)) {
1141 if (token[8] == '=') {
1143 cc->s_maxage_value = apr_atoi64(token + 9);
1150 token = apr_strtok(NULL, ", ", &last);
1152 cc->cache_control = 1;
1155 return (cc_header != NULL || pragma_header != NULL);