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_rerror(APLOG_MARK, APLOG_ERR, status, r,
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_rerror(APLOG_MARK, APLOG_ERR, APR_EEXIST, r,
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_rerror(APLOG_MARK, APLOG_INFO, status, r,
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_rerror(APLOG_MARK, APLOG_INFO, 0, r,
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_rerror(APLOG_MARK, APLOG_INFO, 0, r,
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 apr_time_t age_c = 0;
455 cache_info *info = &(h->cache_obj->info);
456 const char *warn_head;
457 cache_server_conf *conf =
458 (cache_server_conf *)ap_get_module_config(r->server->module_config,
462 * We now want to check if our cached data is still fresh. This depends
463 * on a few things, in this order:
465 * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache
466 * in either the request or the cached response means that we must
467 * perform the request unconditionally, and ignore cached content. We
468 * should never reach here, but if we do, mark the content as stale,
469 * as this is the best we can do.
471 * - RFC2616 14.32 Pragma: no-cache This is treated the same as
472 * Cache-Control: no-cache.
474 * - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
475 * proxy-revalidate if the max-stale request header exists, modify the
476 * stale calculations below so that an object can be at most <max-stale>
477 * seconds stale before we request a revalidation, _UNLESS_ a
478 * must-revalidate or proxy-revalidate cached response header exists to
479 * stop us doing this.
481 * - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
482 * maximum age an object can be before it is considered stale. This
483 * directive has the effect of proxy|must revalidate, which in turn means
484 * simple ignore any max-stale setting.
486 * - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
487 * requests and responses. If both are specified, the smaller of the two
490 * - RFC2616 14.21 Expires: if this request header exists in the cached
491 * entity, and it's value is in the past, it has expired.
495 /* This value comes from the client's initial request. */
496 cc_req = apr_table_get(r->headers_in, "Cache-Control");
497 pragma = apr_table_get(r->headers_in, "Pragma");
499 ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
501 if (cache->control_in.no_cache) {
503 if (!conf->ignorecachecontrol) {
504 /* Treat as stale, causing revalidation */
508 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
509 "Incoming request is asking for a uncached version of "
510 "%s, but we have been configured to ignore it and "
511 "serve a cached response anyway",
515 /* These come from the cached entity. */
516 if (h->cache_obj->info.control.no_cache
517 || h->cache_obj->info.control.no_cache_header
518 || h->cache_obj->info.control.private_header) {
520 * The cached entity contained Cache-Control: no-cache, or a
521 * no-cache with a header present, or a private with a header
522 * present, so treat as 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");
622 * If none of Expires, Cache-Control: max-age, or Cache-Control:
623 * s-maxage appears in the response, and the response header age
624 * calculated is more than 24 hours add the warning 113
626 if ((maxage_cresp == -1) && (smaxage == -1) && (apr_table_get(
627 h->resp_hdrs, "Expires") == NULL) && (age > 86400)) {
629 /* Make sure we don't stomp on a previous warning, and don't dup
630 * a 113 marning that is already present. Also, make sure to add
631 * the new warning to the correct *headers_out location.
633 if ((warn_head == NULL) ||
634 ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
635 apr_table_merge(h->resp_hdrs, "Warning",
636 "113 Heuristic expiration");
639 return 1; /* Cache object is fresh (enough) */
643 * At this point we are stale, but: if we are under load, we may let
644 * a significant number of stale requests through before the first
645 * stale request successfully revalidates itself, causing a sudden
646 * unexpected thundering herd which in turn brings angst and drama.
650 * We want the first stale request to go through as normal. But the
651 * second and subsequent request, we must pretend to be fresh until
652 * the first request comes back with either new content or confirmation
653 * that the stale content is still fresh.
655 * To achieve this, we create a very simple file based lock based on
656 * the key of the cached object. We attempt to open the lock file with
657 * exclusive write access. If we succeed, woohoo! we're first, and we
658 * follow the stale path to the backend server. If we fail, oh well,
659 * we follow the fresh path, and avoid being a thundering herd.
661 * The lock lives only as long as the stale request that went on ahead.
662 * If the request succeeds, the lock is deleted. If the request fails,
663 * the lock is deleted, and another request gets to make a new lock
666 * At any time, a request marked "no-cache" will force a refresh,
667 * ignoring the lock, ensuring an extended lockout is impossible.
669 * A lock that exceeds a maximum age will be deleted, and another
670 * request gets to make a new lock and try again.
672 status = cache_try_lock(conf, cache, r);
673 if (APR_SUCCESS == status) {
674 /* we obtained a lock, follow the stale path */
675 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
676 "Cache lock obtained for stale cached URL, "
677 "revalidating entry: %s",
681 else if (APR_EEXIST == status) {
682 /* lock already exists, return stale data anyway, with a warning */
683 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
684 "Cache already locked for stale cached URL, "
685 "pretend it is fresh: %s",
688 /* make sure we don't stomp on a previous warning */
689 warn_head = apr_table_get(h->resp_hdrs, "Warning");
690 if ((warn_head == NULL) ||
691 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
692 apr_table_merge(h->resp_hdrs, "Warning",
693 "110 Response is stale");
699 /* some other error occurred, just treat the object as stale */
700 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r,
701 "Attempt to obtain a cache lock for stale "
702 "cached URL failed, revalidating entry anyway: %s",
710 * list is a comma-separated list of case-insensitive tokens, with
711 * optional whitespace around the tokens.
712 * The return returns 1 if the token val is found in the list, or 0
715 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
716 const char *key, char **val)
725 key_len = strlen(key);
730 /* skip whitespace and commas to find the start of the next key */
731 while (*next && (apr_isspace(*next) || (*next == ','))) {
739 if (!strncasecmp(next, key, key_len)) {
740 /* this field matches the key (though it might just be
741 * a prefix match, so make sure the match is followed
742 * by either a space or an equals sign)
745 if (!*next || (*next == '=') || apr_isspace(*next) ||
749 while (*next && (*next != '=') && (*next != ',')) {
754 while (*next && apr_isspace(*next )) {
761 const char *val_start = next;
762 while (*next && !apr_isspace(*next) &&
764 /* EAT QUOTED STRING */
765 if (*next == '"' || *next == '\'') {
767 while (*++next != delim) {
771 else if (*next == '\\') {
778 *val = apr_pstrmemdup(p, val_start,
790 /* skip to the next field */
792 /* EAT QUOTED STRING */
793 if (*next == '"' || *next == '\'') {
795 while (*++next != delim) {
799 else if (*next == '\\') {
808 } while (*next != ',');
812 /* return each comma separated token, one at a time */
813 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
819 s = ap_strchr_c(list, ',');
824 while (apr_isspace(*s))
830 while (i > 0 && apr_isspace(list[i - 1]))
835 return apr_pstrndup(p, list, i);
841 * Converts apr_time_t expressed as hex digits to
844 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
848 for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
853 else if (apr_isupper(ch))
854 j |= ch - ('A' - 10);
856 j |= ch - ('a' - 10);
862 * Converts apr_time_t to apr_time_t expressed as hex digits.
864 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
868 for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
872 y[i] = ch + ('A' - 10);
876 y[sizeof(j) * 2] = '\0';
879 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
881 apr_md5_ctx_t context;
882 unsigned char digest[16];
886 static const char enc_table[64] =
887 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
889 apr_md5_init(&context);
890 apr_md5_update(&context, (const unsigned char *) it, strlen(it));
891 apr_md5_final(digest, &context);
893 /* encode 128 bits as 22 characters, using a modified uuencoding
894 * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
895 * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
897 for (i = 0, k = 0; i < 15; i += 3) {
898 x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
899 tmp[k++] = enc_table[x >> 18];
900 tmp[k++] = enc_table[(x >> 12) & 0x3f];
901 tmp[k++] = enc_table[(x >> 6) & 0x3f];
902 tmp[k++] = enc_table[x & 0x3f];
907 tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
908 tmp[k++] = enc_table[(x << 4) & 0x3f];
910 /* now split into directory levels */
911 for (i = k = d = 0; d < ndepth; ++d) {
912 memcpy(&val[i], &tmp[k], nlength);
914 val[i + nlength] = '/';
917 memcpy(&val[i], &tmp[k], 22 - k);
918 val[i + 22 - k] = '\0';
921 CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
922 int dirlength, const char *name)
925 cache_hash(name, hashfile, dirlevels, dirlength);
926 return apr_pstrdup(p, hashfile);
930 * Create a new table consisting of those elements from an
931 * headers table that are allowed to be stored in a cache.
933 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers(apr_pool_t *pool,
937 cache_server_conf *conf;
940 apr_table_t *headers_out;
942 /* Short circuit the common case that there are not
943 * (yet) any headers populated.
946 return apr_table_make(pool, 10);
949 /* Make a copy of the headers, and remove from
950 * the copy any hop-by-hop headers, as defined in Section
953 headers_out = apr_table_copy(pool, t);
955 apr_table_unset(headers_out, "Connection");
956 apr_table_unset(headers_out, "Keep-Alive");
957 apr_table_unset(headers_out, "Proxy-Authenticate");
958 apr_table_unset(headers_out, "Proxy-Authorization");
959 apr_table_unset(headers_out, "TE");
960 apr_table_unset(headers_out, "Trailers");
961 apr_table_unset(headers_out, "Transfer-Encoding");
962 apr_table_unset(headers_out, "Upgrade");
964 conf = (cache_server_conf *)ap_get_module_config(s->module_config,
967 /* Remove the user defined headers set with CacheIgnoreHeaders.
968 * This may break RFC 2616 compliance on behalf of the administrator.
970 header = (char **)conf->ignore_headers->elts;
971 for (i = 0; i < conf->ignore_headers->nelts; i++) {
972 apr_table_unset(headers_out, header[i]);
978 * Create a new table consisting of those elements from an input
979 * headers table that are allowed to be stored in a cache.
981 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_in(request_rec *r)
983 return ap_cache_cacheable_headers(r->pool, r->headers_in, r->server);
987 * Create a new table consisting of those elements from an output
988 * headers table that are allowed to be stored in a cache;
989 * ensure there is a content type and capture any errors.
991 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_out(request_rec *r)
993 apr_table_t *headers_out;
995 headers_out = apr_table_overlay(r->pool, r->headers_out,
998 apr_table_clear(r->err_headers_out);
1000 headers_out = ap_cache_cacheable_headers(r->pool, headers_out,
1003 if (!apr_table_get(headers_out, "Content-Type")
1004 && r->content_type) {
1005 apr_table_setn(headers_out, "Content-Type",
1006 ap_make_content_type(r, r->content_type));
1009 if (!apr_table_get(headers_out, "Content-Encoding")
1010 && r->content_encoding) {
1011 apr_table_setn(headers_out, "Content-Encoding",
1012 r->content_encoding);
1019 * Parse the Cache-Control and Pragma headers in one go, marking
1020 * which tokens appear within the header. Populate the structure
1023 int ap_cache_control(request_rec *r, cache_control_t *cc,
1024 const char *cc_header, const char *pragma_header, apr_table_t *headers)
1029 return cc->cache_control || cc->pragma;
1033 cc->max_age_value = -1;
1034 cc->max_stale_value = -1;
1035 cc->min_fresh_value = -1;
1036 cc->s_maxage_value = -1;
1038 if (pragma_header) {
1039 char *header = apr_pstrdup(r->pool, pragma_header);
1040 const char *token = apr_strtok(header, ", ", &last);
1042 /* handle most common quickest case... */
1043 if (!strcmp(token, "no-cache")) {
1046 /* ...then try slowest case */
1047 else if (!strcasecmp(token, "no-cache")) {
1050 token = apr_strtok(NULL, ", ", &last);
1056 char *header = apr_pstrdup(r->pool, cc_header);
1057 const char *token = apr_strtok(header, ", ", &last);
1062 /* handle most common quickest cases... */
1063 if (!strcmp(token, "no-cache")) {
1066 else if (!strcmp(token, "no-store")) {
1069 /* ...then try slowest cases */
1070 else if (!strncasecmp(token, "no-cache", 8)) {
1071 if (token[8] == '=') {
1072 if (apr_table_get(headers, token + 9)) {
1073 cc->no_cache_header = 1;
1076 else if (!token[8]) {
1081 else if (!strcasecmp(token, "no-store")) {
1084 else if (!strcasecmp(token, "no-transform")) {
1085 cc->no_transform = 1;
1091 /* handle most common quickest cases... */
1092 if (!strcmp(token, "max-age=0")) {
1094 cc->max_age_value = 0;
1096 else if (!strcmp(token, "must-revalidate")) {
1097 cc->must_revalidate = 1;
1099 /* ...then try slowest cases */
1100 else if (!strncasecmp(token, "max-age", 7)) {
1101 if (token[7] == '=') {
1103 cc->max_age_value = apr_atoi64(token + 8);
1107 else if (!strncasecmp(token, "max-stale", 9)) {
1108 if (token[9] == '=') {
1110 cc->max_stale_value = apr_atoi64(token + 10);
1112 else if (!token[10]) {
1114 cc->max_stale_value = -1;
1118 else if (!strncasecmp(token, "min-fresh", 9)) {
1119 if (token[9] == '=') {
1121 cc->min_fresh_value = apr_atoi64(token + 10);
1125 else if (!strcasecmp(token, "must-revalidate")) {
1126 cc->must_revalidate = 1;
1132 if (!strcasecmp(token, "only-if-cached")) {
1133 cc->only_if_cached = 1;
1139 /* handle most common quickest cases... */
1140 if (!strcmp(token, "private")) {
1143 /* ...then try slowest cases */
1144 else if (!strcasecmp(token, "public")) {
1147 else if (!strncasecmp(token, "private", 7)) {
1148 if (token[7] == '=') {
1149 if (apr_table_get(headers, token + 8)) {
1150 cc->private_header = 1;
1153 else if (!token[7]) {
1158 else if (!strcasecmp(token, "proxy-revalidate")) {
1159 cc->proxy_revalidate = 1;
1165 if (!strncasecmp(token, "s-maxage", 8)) {
1166 if (token[8] == '=') {
1168 cc->s_maxage_value = apr_atoi64(token + 9);
1175 token = apr_strtok(NULL, ", ", &last);
1177 cc->cache_control = 1;
1180 return (cc_header != NULL || pragma_header != NULL);