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 #define CACHE_SEPARATOR ", "
32 /* Determine if "url" matches the hostname, scheme and port and path
33 * in "filter". All but the path comparisons are case-insensitive.
35 static int uri_meets_conditions(const apr_uri_t *filter, const int pathlen,
39 /* Scheme, hostname port and local part. The filter URI and the
40 * URI we test may have the following shapes:
42 * <scheme>[:://<hostname>[:<port>][/<path>]]
43 * That is, if there is no scheme then there must be only the path,
44 * and we check only the path; if there is a scheme, we check the
45 * scheme for equality, and then if present we match the hostname,
46 * and then if present match the port, and finally the path if any.
48 * Note that this means that "/<path>" only matches local paths,
49 * and to match proxied paths one *must* specify the scheme.
52 /* Is the filter is just for a local path or a proxy URI? */
53 if (!filter->scheme) {
54 if (url->scheme || url->hostname) {
59 /* The URI scheme must be present and identical except for case. */
60 if (!url->scheme || strcasecmp(filter->scheme, url->scheme)) {
64 /* If the filter hostname is null or empty it matches any hostname,
65 * if it begins with a "*" it matches the _end_ of the URI hostname
66 * excluding the "*", if it begins with a "." it matches the _end_
67 * of the URI * hostname including the ".", otherwise it must match
68 * the URI hostname exactly. */
70 if (filter->hostname && filter->hostname[0]) {
71 if (filter->hostname[0] == '.') {
72 const size_t fhostlen = strlen(filter->hostname);
73 const size_t uhostlen = url->hostname ? strlen(url->hostname) : 0;
75 if (fhostlen > uhostlen || strcasecmp(filter->hostname,
76 url->hostname + uhostlen - fhostlen)) {
80 else if (filter->hostname[0] == '*') {
81 const size_t fhostlen = strlen(filter->hostname + 1);
82 const size_t uhostlen = url->hostname ? strlen(url->hostname) : 0;
84 if (fhostlen > uhostlen || strcasecmp(filter->hostname + 1,
85 url->hostname + uhostlen - fhostlen)) {
89 else if (!url->hostname || strcasecmp(filter->hostname, url->hostname)) {
94 /* If the filter port is empty it matches any URL port.
95 * If the filter or URL port are missing, or the URL port is
96 * empty, they default to the port for their scheme. */
98 if (!(filter->port_str && !filter->port_str[0])) {
99 /* NOTE: ap_port_of_scheme will return 0 if given NULL input */
100 const unsigned fport = filter->port_str ? filter->port
101 : apr_uri_port_of_scheme(filter->scheme);
102 const unsigned uport = (url->port_str && url->port_str[0])
103 ? url->port : apr_uri_port_of_scheme(url->scheme);
105 if (fport != uport) {
111 /* For HTTP caching purposes, an empty (NULL) path is equivalent to
112 * a single "/" path. RFCs 3986/2396
115 if (*filter->path == '/' && pathlen == 1) {
123 /* Url has met all of the filter conditions so far, determine
124 * if the paths match.
126 return !strncmp(filter->path, url->path, pathlen);
129 static cache_provider_list *get_provider(request_rec *r, struct cache_enable *ent,
130 cache_provider_list *providers)
132 /* Fetch from global config and add to the list. */
133 cache_provider *provider;
134 provider = ap_lookup_provider(CACHE_PROVIDER_GROUP, ent->type,
140 cache_provider_list *newp;
141 newp = apr_pcalloc(r->pool, sizeof(cache_provider_list));
142 newp->provider_name = ent->type;
143 newp->provider = provider;
149 cache_provider_list *last = providers;
152 if (last->provider == provider) {
157 if (last->provider == provider) {
167 cache_provider_list *cache_get_providers(request_rec *r,
168 cache_server_conf *conf,
171 cache_dir_conf *dconf = dconf = ap_get_module_config(r->per_dir_config, &cache_module);
172 cache_provider_list *providers = NULL;
175 /* per directory cache disable */
176 if (dconf->disable) {
180 /* global cache disable */
181 for (i = 0; i < conf->cachedisable->nelts; i++) {
182 struct cache_disable *ent =
183 (struct cache_disable *)conf->cachedisable->elts;
184 if (uri_meets_conditions(&ent[i].url, ent[i].pathlen, &uri)) {
185 /* Stop searching now. */
190 /* loop through all the per directory cacheenable entries */
191 for (i = 0; i < dconf->cacheenable->nelts; i++) {
192 struct cache_enable *ent =
193 (struct cache_enable *)dconf->cacheenable->elts;
194 providers = get_provider(r, &ent[i], providers);
197 /* loop through all the global cacheenable entries */
198 for (i = 0; i < conf->cacheenable->nelts; i++) {
199 struct cache_enable *ent =
200 (struct cache_enable *)conf->cacheenable->elts;
201 if (uri_meets_conditions(&ent[i].url, ent[i].pathlen, &uri)) {
202 providers = get_provider(r, &ent[i], providers);
210 /* do a HTTP/1.1 age calculation */
211 CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info,
212 const apr_time_t age_value,
215 apr_time_t apparent_age, corrected_received_age, response_delay,
216 corrected_initial_age, resident_time, current_age,
219 age_value_usec = apr_time_from_sec(age_value);
221 /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
223 apparent_age = MAX(0, info->response_time - info->date);
224 corrected_received_age = MAX(apparent_age, age_value_usec);
225 response_delay = info->response_time - info->request_time;
226 corrected_initial_age = corrected_received_age + response_delay;
227 resident_time = now - info->response_time;
228 current_age = corrected_initial_age + resident_time;
230 if (current_age < 0) {
234 return apr_time_sec(current_age);
238 * Try obtain a cache wide lock on the given cache key.
240 * If we return APR_SUCCESS, we obtained the lock, and we are clear to
241 * proceed to the backend. If we return APR_EEXISTS, then the lock is
242 * already locked, someone else has gone to refresh the backend data
243 * already, so we must return stale data with a warning in the mean
244 * time. If we return anything else, then something has gone pear
245 * shaped, and we allow the request through to the backend regardless.
247 * This lock is created from the request pool, meaning that should
248 * something go wrong and the lock isn't deleted on return of the
249 * request headers from the backend for whatever reason, at worst the
250 * lock will be cleaned up when the request dies or finishes.
252 * If something goes truly bananas and the lock isn't deleted when the
253 * request dies, the lock will be trashed when its max-age is reached,
254 * or when a request arrives containing a Cache-Control: no-cache. At
255 * no point is it possible for this lock to permanently deny access to
258 apr_status_t cache_try_lock(cache_server_conf *conf, cache_request_rec *cache,
262 const char *lockname;
265 apr_time_t now = apr_time_now();
267 apr_file_t *lockfile;
272 if (!conf || !conf->lock || !conf->lockpath) {
273 /* no locks configured, leave */
277 /* lock already obtained earlier? if so, success */
278 apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
283 /* create the key if it doesn't exist */
285 cache_generate_key(r, r->pool, &cache->key);
288 /* create a hashed filename from the key, and save it for later */
289 lockname = ap_cache_generate_name(r->pool, 0, 0, cache->key);
291 /* lock files represent discrete just-went-stale URLs "in flight", so
292 * we support a simple two level directory structure, more is overkill.
295 dir[1] = lockname[0];
297 dir[3] = lockname[1];
300 /* make the directories */
301 path = apr_pstrcat(r->pool, conf->lockpath, dir, NULL);
302 if (APR_SUCCESS != (status = apr_dir_make_recursive(path,
303 APR_UREAD|APR_UWRITE|APR_UEXECUTE, r->pool))) {
304 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
305 "Could not create a cache lock directory: %s",
309 lockname = apr_pstrcat(r->pool, path, "/", lockname, NULL);
310 apr_pool_userdata_set(lockname, CACHE_LOCKNAME_KEY, NULL, r->pool);
312 /* is an existing lock file too old? */
313 status = apr_stat(&finfo, lockname,
314 APR_FINFO_MTIME | APR_FINFO_NLINK, r->pool);
315 if (!(APR_STATUS_IS_ENOENT(status)) && APR_SUCCESS != status) {
316 ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EEXIST, r,
317 "Could not stat a cache lock file: %s",
321 if ((status == APR_SUCCESS) && (((now - finfo.mtime) > conf->lockmaxage)
322 || (now < finfo.mtime))) {
323 ap_log_rerror(APLOG_MARK, APLOG_INFO, status, r,
324 "Cache lock file for '%s' too old, removing: %s",
326 apr_file_remove(lockname, r->pool);
329 /* try obtain a lock on the file */
330 if (APR_SUCCESS == (status = apr_file_open(&lockfile, lockname,
331 APR_WRITE | APR_CREATE | APR_EXCL | APR_DELONCLOSE,
332 APR_UREAD | APR_UWRITE, r->pool))) {
333 apr_pool_userdata_set(lockfile, CACHE_LOCKFILE_KEY, NULL, r->pool);
340 * Remove the cache lock, if present.
342 * First, try to close the file handle, whose delete-on-close should
343 * kill the file. Otherwise, just delete the file by name.
345 * If no lock name has yet been calculated, do the calculation of the
346 * lock name first before trying to delete the file.
348 * If an optional bucket brigade is passed, the lock will only be
349 * removed if the bucket brigade contains an EOS bucket.
351 apr_status_t cache_remove_lock(cache_server_conf *conf,
352 cache_request_rec *cache, request_rec *r, apr_bucket_brigade *bb)
355 const char *lockname;
357 if (!conf || !conf->lock || !conf->lockpath) {
358 /* no locks configured, leave */
364 for (e = APR_BRIGADE_FIRST(bb);
365 e != APR_BRIGADE_SENTINEL(bb);
366 e = APR_BUCKET_NEXT(e))
368 if (APR_BUCKET_IS_EOS(e)) {
374 /* no eos found in brigade, don't delete anything just yet,
380 apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
382 return apr_file_close((apr_file_t *)dummy);
384 apr_pool_userdata_get(&dummy, CACHE_LOCKNAME_KEY, r->pool);
385 lockname = (const char *)dummy;
389 /* create the key if it doesn't exist */
391 cache_generate_key(r, r->pool, &cache->key);
394 /* create a hashed filename from the key, and save it for later */
395 lockname = ap_cache_generate_name(r->pool, 0, 0, cache->key);
397 /* lock files represent discrete just-went-stale URLs "in flight", so
398 * we support a simple two level directory structure, more is overkill.
401 dir[1] = lockname[0];
403 dir[3] = lockname[1];
406 lockname = apr_pstrcat(r->pool, conf->lockpath, dir, "/", lockname, NULL);
408 return apr_file_remove(lockname, r->pool);
411 CACHE_DECLARE(int) ap_cache_check_allowed(cache_request_rec *cache, request_rec *r) {
414 cache_server_conf *conf =
415 (cache_server_conf *)ap_get_module_config(r->server->module_config,
419 * At this point, we may have data cached, but the request may have
420 * specified that cached data may not be used in a response.
422 * This is covered under RFC2616 section 14.9.4 (Cache Revalidation and
425 * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache, or Pragma:
426 * no-cache. The server MUST NOT use a cached copy when responding to such
429 * - RFC2616 14.9.2 What May be Stored by Caches. If Cache-Control:
430 * no-store arrives, do not serve from the cache.
433 /* This value comes from the client's initial request. */
434 cc_req = apr_table_get(r->headers_in, "Cache-Control");
435 pragma = apr_table_get(r->headers_in, "Pragma");
437 ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
439 if (cache->control_in.no_cache) {
441 if (!conf->ignorecachecontrol) {
445 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
446 "Incoming request is asking for an uncached version of "
447 "%s, but we have been configured to ignore it and serve "
448 "cached content anyway", r->unparsed_uri);
452 if (cache->control_in.no_store) {
454 if (!conf->ignorecachecontrol) {
455 /* We're not allowed to serve a cached copy */
459 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
460 "Incoming request is asking for a no-store version of "
461 "%s, but we have been configured to ignore it and serve "
462 "cached content anyway", r->unparsed_uri);
470 int cache_check_freshness(cache_handle_t *h, cache_request_rec *cache,
474 apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
475 apr_int64_t minfresh;
478 const char *agestr = NULL;
479 apr_time_t age_c = 0;
480 cache_info *info = &(h->cache_obj->info);
481 const char *warn_head;
482 cache_server_conf *conf =
483 (cache_server_conf *)ap_get_module_config(r->server->module_config,
487 * We now want to check if our cached data is still fresh. This depends
488 * on a few things, in this order:
490 * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache
491 * in either the request or the cached response means that we must
492 * perform the request unconditionally, and ignore cached content. We
493 * should never reach here, but if we do, mark the content as stale,
494 * as this is the best we can do.
496 * - RFC2616 14.32 Pragma: no-cache This is treated the same as
497 * Cache-Control: no-cache.
499 * - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
500 * proxy-revalidate if the max-stale request header exists, modify the
501 * stale calculations below so that an object can be at most <max-stale>
502 * seconds stale before we request a revalidation, _UNLESS_ a
503 * must-revalidate or proxy-revalidate cached response header exists to
504 * stop us doing this.
506 * - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
507 * maximum age an object can be before it is considered stale. This
508 * directive has the effect of proxy|must revalidate, which in turn means
509 * simple ignore any max-stale setting.
511 * - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
512 * requests and responses. If both are specified, the smaller of the two
515 * - RFC2616 14.21 Expires: if this request header exists in the cached
516 * entity, and it's value is in the past, it has expired.
520 /* This value comes from the client's initial request. */
521 cc_req = apr_table_get(r->headers_in, "Cache-Control");
522 pragma = apr_table_get(r->headers_in, "Pragma");
524 ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
526 if (cache->control_in.no_cache) {
528 if (!conf->ignorecachecontrol) {
529 /* Treat as stale, causing revalidation */
533 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
534 "Incoming request is asking for a uncached version of "
535 "%s, but we have been configured to ignore it and "
536 "serve a cached response anyway",
540 /* These come from the cached entity. */
541 if (h->cache_obj->info.control.no_cache
542 || h->cache_obj->info.control.no_cache_header
543 || h->cache_obj->info.control.private_header) {
545 * The cached entity contained Cache-Control: no-cache, or a
546 * no-cache with a header present, or a private with a header
547 * present, so treat as stale causing revalidation.
552 if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
553 age_c = apr_atoi64(agestr);
556 /* calculate age of object */
557 age = ap_cache_current_age(info, age_c, r->request_time);
559 /* extract s-maxage */
560 smaxage = h->cache_obj->info.control.s_maxage_value;
562 /* extract max-age from request */
564 if (!conf->ignorecachecontrol) {
565 maxage_req = cache->control_in.max_age_value;
569 * extract max-age from response, if both s-maxage and max-age, s-maxage
573 maxage_cresp = smaxage;
576 maxage_cresp = h->cache_obj->info.control.max_age_value;
580 * if both maxage request and response, the smaller one takes priority
582 if (maxage_req == -1) {
583 maxage = maxage_cresp;
585 else if (maxage_cresp == -1) {
589 maxage = MIN(maxage_req, maxage_cresp);
592 /* extract max-stale */
593 if (cache->control_in.max_stale) {
594 if(cache->control_in.max_stale_value != -1) {
595 maxstale = cache->control_in.max_stale_value;
599 * If no value is assigned to max-stale, then the client is willing
600 * to accept a stale response of any age (RFC2616 14.9.3). We will
601 * set it to one year in this case as this situation is somewhat
602 * similar to a "never expires" Expires header (RFC2616 14.21)
603 * which is set to a date one year from the time the response is
606 maxstale = APR_INT64_C(86400*365);
613 /* extract min-fresh */
614 if (!conf->ignorecachecontrol && cache->control_in.min_fresh) {
615 minfresh = cache->control_in.min_fresh_value;
621 /* override maxstale if must-revalidate, proxy-revalidate or s-maxage */
622 if (maxstale && (h->cache_obj->info.control.must_revalidate
623 || h->cache_obj->info.control.proxy_revalidate || smaxage != -1)) {
627 /* handle expiration */
628 if (((maxage != -1) && (age < (maxage + maxstale - minfresh))) ||
629 ((smaxage == -1) && (maxage == -1) &&
630 (info->expire != APR_DATE_BAD) &&
631 (age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh)))) {
633 warn_head = apr_table_get(h->resp_hdrs, "Warning");
635 /* it's fresh darlings... */
636 /* set age header on response */
637 apr_table_set(h->resp_hdrs, "Age",
638 apr_psprintf(r->pool, "%lu", (unsigned long)age));
640 /* add warning if maxstale overrode freshness calculation */
641 if (!(((maxage != -1) && age < maxage) ||
642 (info->expire != APR_DATE_BAD &&
643 (apr_time_sec(info->expire - info->date)) > age))) {
644 /* make sure we don't stomp on a previous warning */
645 if ((warn_head == NULL) ||
646 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
647 apr_table_merge(h->resp_hdrs, "Warning",
648 "110 Response is stale");
653 * If none of Expires, Cache-Control: max-age, or Cache-Control:
654 * s-maxage appears in the response, and the response header age
655 * calculated is more than 24 hours add the warning 113
657 if ((maxage_cresp == -1) && (smaxage == -1) && (apr_table_get(
658 h->resp_hdrs, "Expires") == NULL) && (age > 86400)) {
660 /* Make sure we don't stomp on a previous warning, and don't dup
661 * a 113 marning that is already present. Also, make sure to add
662 * the new warning to the correct *headers_out location.
664 if ((warn_head == NULL) ||
665 ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
666 apr_table_merge(h->resp_hdrs, "Warning",
667 "113 Heuristic expiration");
670 return 1; /* Cache object is fresh (enough) */
674 * At this point we are stale, but: if we are under load, we may let
675 * a significant number of stale requests through before the first
676 * stale request successfully revalidates itself, causing a sudden
677 * unexpected thundering herd which in turn brings angst and drama.
681 * We want the first stale request to go through as normal. But the
682 * second and subsequent request, we must pretend to be fresh until
683 * the first request comes back with either new content or confirmation
684 * that the stale content is still fresh.
686 * To achieve this, we create a very simple file based lock based on
687 * the key of the cached object. We attempt to open the lock file with
688 * exclusive write access. If we succeed, woohoo! we're first, and we
689 * follow the stale path to the backend server. If we fail, oh well,
690 * we follow the fresh path, and avoid being a thundering herd.
692 * The lock lives only as long as the stale request that went on ahead.
693 * If the request succeeds, the lock is deleted. If the request fails,
694 * the lock is deleted, and another request gets to make a new lock
697 * At any time, a request marked "no-cache" will force a refresh,
698 * ignoring the lock, ensuring an extended lockout is impossible.
700 * A lock that exceeds a maximum age will be deleted, and another
701 * request gets to make a new lock and try again.
703 status = cache_try_lock(conf, cache, r);
704 if (APR_SUCCESS == status) {
705 /* we obtained a lock, follow the stale path */
706 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
707 "Cache lock obtained for stale cached URL, "
708 "revalidating entry: %s",
712 else if (APR_EEXIST == status) {
713 /* lock already exists, return stale data anyway, with a warning */
714 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
715 "Cache already locked for stale cached URL, "
716 "pretend it is fresh: %s",
719 /* make sure we don't stomp on a previous warning */
720 warn_head = apr_table_get(h->resp_hdrs, "Warning");
721 if ((warn_head == NULL) ||
722 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
723 apr_table_merge(h->resp_hdrs, "Warning",
724 "110 Response is stale");
730 /* some other error occurred, just treat the object as stale */
731 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r,
732 "Attempt to obtain a cache lock for stale "
733 "cached URL failed, revalidating entry anyway: %s",
741 * list is a comma-separated list of case-insensitive tokens, with
742 * optional whitespace around the tokens.
743 * The return returns 1 if the token val is found in the list, or 0
746 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
747 const char *key, char **val)
756 key_len = strlen(key);
761 /* skip whitespace and commas to find the start of the next key */
762 while (*next && (apr_isspace(*next) || (*next == ','))) {
770 if (!strncasecmp(next, key, key_len)) {
771 /* this field matches the key (though it might just be
772 * a prefix match, so make sure the match is followed
773 * by either a space or an equals sign)
776 if (!*next || (*next == '=') || apr_isspace(*next) ||
780 while (*next && (*next != '=') && (*next != ',')) {
785 while (*next && apr_isspace(*next )) {
792 const char *val_start = next;
793 while (*next && !apr_isspace(*next) &&
795 /* EAT QUOTED STRING */
796 if (*next == '"' || *next == '\'') {
798 while (*++next != delim) {
802 else if (*next == '\\') {
809 *val = apr_pstrmemdup(p, val_start,
821 /* skip to the next field */
823 /* EAT QUOTED STRING */
824 if (*next == '"' || *next == '\'') {
826 while (*++next != delim) {
830 else if (*next == '\\') {
839 } while (*next != ',');
843 /* return each comma separated token, one at a time */
844 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
850 s = ap_strchr_c(list, ',');
855 while (apr_isspace(*s))
861 while (i > 0 && apr_isspace(list[i - 1]))
866 return apr_pstrndup(p, list, i);
872 * Converts apr_time_t expressed as hex digits to
875 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
879 for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
884 else if (apr_isupper(ch))
885 j |= ch - ('A' - 10);
887 j |= ch - ('a' - 10);
893 * Converts apr_time_t to apr_time_t expressed as hex digits.
895 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
899 for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
903 y[i] = ch + ('A' - 10);
907 y[sizeof(j) * 2] = '\0';
910 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
912 apr_md5_ctx_t context;
913 unsigned char digest[16];
917 static const char enc_table[64] =
918 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
920 apr_md5_init(&context);
921 apr_md5_update(&context, (const unsigned char *) it, strlen(it));
922 apr_md5_final(digest, &context);
924 /* encode 128 bits as 22 characters, using a modified uuencoding
925 * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
926 * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
928 for (i = 0, k = 0; i < 15; i += 3) {
929 x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
930 tmp[k++] = enc_table[x >> 18];
931 tmp[k++] = enc_table[(x >> 12) & 0x3f];
932 tmp[k++] = enc_table[(x >> 6) & 0x3f];
933 tmp[k++] = enc_table[x & 0x3f];
938 tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
939 tmp[k++] = enc_table[(x << 4) & 0x3f];
941 /* now split into directory levels */
942 for (i = k = d = 0; d < ndepth; ++d) {
943 memcpy(&val[i], &tmp[k], nlength);
945 val[i + nlength] = '/';
948 memcpy(&val[i], &tmp[k], 22 - k);
949 val[i + 22 - k] = '\0';
952 CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
953 int dirlength, const char *name)
956 cache_hash(name, hashfile, dirlevels, dirlength);
957 return apr_pstrdup(p, hashfile);
961 * Create a new table consisting of those elements from an
962 * headers table that are allowed to be stored in a cache.
964 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers(apr_pool_t *pool,
968 cache_server_conf *conf;
971 apr_table_t *headers_out;
973 /* Short circuit the common case that there are not
974 * (yet) any headers populated.
977 return apr_table_make(pool, 10);
980 /* Make a copy of the headers, and remove from
981 * the copy any hop-by-hop headers, as defined in Section
984 headers_out = apr_table_copy(pool, t);
986 apr_table_unset(headers_out, "Connection");
987 apr_table_unset(headers_out, "Keep-Alive");
988 apr_table_unset(headers_out, "Proxy-Authenticate");
989 apr_table_unset(headers_out, "Proxy-Authorization");
990 apr_table_unset(headers_out, "TE");
991 apr_table_unset(headers_out, "Trailers");
992 apr_table_unset(headers_out, "Transfer-Encoding");
993 apr_table_unset(headers_out, "Upgrade");
995 conf = (cache_server_conf *)ap_get_module_config(s->module_config,
998 /* Remove the user defined headers set with CacheIgnoreHeaders.
999 * This may break RFC 2616 compliance on behalf of the administrator.
1001 header = (char **)conf->ignore_headers->elts;
1002 for (i = 0; i < conf->ignore_headers->nelts; i++) {
1003 apr_table_unset(headers_out, header[i]);
1009 * Create a new table consisting of those elements from an input
1010 * headers table that are allowed to be stored in a cache.
1012 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_in(request_rec *r)
1014 return ap_cache_cacheable_headers(r->pool, r->headers_in, r->server);
1018 * Create a new table consisting of those elements from an output
1019 * headers table that are allowed to be stored in a cache;
1020 * ensure there is a content type and capture any errors.
1022 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_out(request_rec *r)
1024 apr_table_t *headers_out;
1026 headers_out = apr_table_overlay(r->pool, r->headers_out,
1027 r->err_headers_out);
1029 apr_table_clear(r->err_headers_out);
1031 headers_out = ap_cache_cacheable_headers(r->pool, headers_out,
1034 if (!apr_table_get(headers_out, "Content-Type")
1035 && r->content_type) {
1036 apr_table_setn(headers_out, "Content-Type",
1037 ap_make_content_type(r, r->content_type));
1040 if (!apr_table_get(headers_out, "Content-Encoding")
1041 && r->content_encoding) {
1042 apr_table_setn(headers_out, "Content-Encoding",
1043 r->content_encoding);
1050 * String tokenizer that ignores separator characters within quoted strings
1051 * and escaped characters, as per RFC2616 section 2.2.
1053 static char *cache_strqtok(char *str, const char *sep, char **last)
1058 if (!str) { /* subsequent call */
1059 str = *last; /* start where we left off */
1062 /* skip characters in sep (will terminate at '\0') */
1063 while (*str && ap_strchr_c(sep, *str)) {
1067 if (!*str) { /* no more tokens */
1073 /* skip valid token characters to terminate token and
1074 * prepare for the next call (will terminate at '\0)
1075 * on the way, ignore all quoted strings, and within
1076 * quoted strings, escaped characters.
1081 if (**last == '\"') {
1085 else if (!ap_strchr_c(sep, **last)) {
1093 if (**last == '\"') {
1097 else if (**last == '\\') {
1118 * Parse the Cache-Control and Pragma headers in one go, marking
1119 * which tokens appear within the header. Populate the structure
1122 int ap_cache_control(request_rec *r, cache_control_t *cc,
1123 const char *cc_header, const char *pragma_header, apr_table_t *headers)
1128 return cc->cache_control || cc->pragma;
1132 cc->max_age_value = -1;
1133 cc->max_stale_value = -1;
1134 cc->min_fresh_value = -1;
1135 cc->s_maxage_value = -1;
1137 if (pragma_header) {
1138 char *header = apr_pstrdup(r->pool, pragma_header);
1139 const char *token = cache_strqtok(header, CACHE_SEPARATOR, &last);
1141 /* handle most common quickest case... */
1142 if (!strcmp(token, "no-cache")) {
1145 /* ...then try slowest case */
1146 else if (!strcasecmp(token, "no-cache")) {
1149 token = cache_strqtok(NULL, CACHE_SEPARATOR, &last);
1155 char *header = apr_pstrdup(r->pool, cc_header);
1156 const char *token = cache_strqtok(header, CACHE_SEPARATOR, &last);
1161 /* handle most common quickest cases... */
1162 if (!strcmp(token, "no-cache")) {
1165 else if (!strcmp(token, "no-store")) {
1168 /* ...then try slowest cases */
1169 else if (!strncasecmp(token, "no-cache", 8)) {
1170 if (token[8] == '=') {
1171 if (apr_table_get(headers, token + 9)) {
1172 cc->no_cache_header = 1;
1175 else if (!token[8]) {
1180 else if (!strcasecmp(token, "no-store")) {
1183 else if (!strcasecmp(token, "no-transform")) {
1184 cc->no_transform = 1;
1190 /* handle most common quickest cases... */
1191 if (!strcmp(token, "max-age=0")) {
1193 cc->max_age_value = 0;
1195 else if (!strcmp(token, "must-revalidate")) {
1196 cc->must_revalidate = 1;
1198 /* ...then try slowest cases */
1199 else if (!strncasecmp(token, "max-age", 7)) {
1200 if (token[7] == '=') {
1202 cc->max_age_value = apr_atoi64(token + 8);
1206 else if (!strncasecmp(token, "max-stale", 9)) {
1207 if (token[9] == '=') {
1209 cc->max_stale_value = apr_atoi64(token + 10);
1211 else if (!token[10]) {
1213 cc->max_stale_value = -1;
1217 else if (!strncasecmp(token, "min-fresh", 9)) {
1218 if (token[9] == '=') {
1220 cc->min_fresh_value = apr_atoi64(token + 10);
1224 else if (!strcasecmp(token, "must-revalidate")) {
1225 cc->must_revalidate = 1;
1231 if (!strcasecmp(token, "only-if-cached")) {
1232 cc->only_if_cached = 1;
1238 /* handle most common quickest cases... */
1239 if (!strcmp(token, "private")) {
1242 /* ...then try slowest cases */
1243 else if (!strcasecmp(token, "public")) {
1246 else if (!strncasecmp(token, "private", 7)) {
1247 if (token[7] == '=') {
1248 if (apr_table_get(headers, token + 8)) {
1249 cc->private_header = 1;
1252 else if (!token[7]) {
1257 else if (!strcasecmp(token, "proxy-revalidate")) {
1258 cc->proxy_revalidate = 1;
1264 if (!strncasecmp(token, "s-maxage", 8)) {
1265 if (token[8] == '=') {
1267 cc->s_maxage_value = apr_atoi64(token + 9);
1274 token = cache_strqtok(NULL, CACHE_SEPARATOR, &last);
1276 cc->cache_control = 1;
1279 return (cc_header != NULL || pragma_header != NULL);