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.
19 #include "mod_cache.h"
21 #include <ap_provider.h>
23 /* -------------------------------------------------------------- */
25 extern module AP_MODULE_DECLARE_DATA cache_module;
27 /* return true if the request is conditional */
28 CACHE_DECLARE(int) ap_cache_request_is_conditional(apr_table_t *table)
30 if (apr_table_get(table, "If-Match") ||
31 apr_table_get(table, "If-None-Match") ||
32 apr_table_get(table, "If-Modified-Since") ||
33 apr_table_get(table, "If-Unmodified-Since")) {
39 CACHE_DECLARE(cache_provider_list *)ap_cache_get_providers(request_rec *r,
40 cache_server_conf *conf,
43 cache_provider_list *providers = NULL;
46 /* we can't cache if there's no URL */
47 /* Is this case even possible?? */
48 if (!url) return NULL;
50 /* loop through all the cacheenable entries */
51 for (i = 0; i < conf->cacheenable->nelts; i++) {
52 struct cache_enable *ent =
53 (struct cache_enable *)conf->cacheenable->elts;
54 if ((ent[i].url) && !strncasecmp(url, ent[i].url, ent[i].urllen)) {
55 /* Fetch from global config and add to the list. */
56 cache_provider *provider;
57 provider = ap_lookup_provider(CACHE_PROVIDER_GROUP, ent[i].type,
63 cache_provider_list *newp;
64 newp = apr_pcalloc(r->pool, sizeof(cache_provider_list));
65 newp->provider_name = ent[i].type;
66 newp->provider = provider;
72 cache_provider_list *last = providers;
83 /* then loop through all the cachedisable entries
84 * Looking for urls that contain the full cachedisable url and possibly
86 * This means we are disabling cachedisable url and below...
88 for (i = 0; i < conf->cachedisable->nelts; i++) {
89 struct cache_disable *ent =
90 (struct cache_disable *)conf->cachedisable->elts;
91 if ((ent[i].url) && !strncasecmp(url, ent[i].url, ent[i].urllen)) {
92 /* Stop searching now. */
101 /* do a HTTP/1.1 age calculation */
102 CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info,
103 const apr_time_t age_value,
106 apr_time_t apparent_age, corrected_received_age, response_delay,
107 corrected_initial_age, resident_time, current_age,
110 age_value_usec = apr_time_from_sec(age_value);
112 /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
114 apparent_age = MAX(0, info->response_time - info->date);
115 corrected_received_age = MAX(apparent_age, age_value_usec);
116 response_delay = info->response_time - info->request_time;
117 corrected_initial_age = corrected_received_age + response_delay;
118 resident_time = now - info->response_time;
119 current_age = corrected_initial_age + resident_time;
121 return apr_time_sec(current_age);
124 CACHE_DECLARE(int) ap_cache_check_freshness(cache_handle_t *h,
127 apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
128 apr_int64_t minfresh;
129 int age_in_errhdr = 0;
130 const char *cc_cresp, *cc_ceresp, *cc_req;
131 const char *agestr = NULL;
132 const char *expstr = NULL;
134 apr_time_t age_c = 0;
135 cache_info *info = &(h->cache_obj->info);
138 * We now want to check if our cached data is still fresh. This depends
139 * on a few things, in this order:
141 * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache in
142 * either the request or the cached response means that we must
143 * revalidate the request unconditionally, overriding any expiration
144 * mechanism. It's equivalent to max-age=0,must-revalidate.
146 * - RFC2616 14.32 Pragma: no-cache This is treated the same as
147 * Cache-Control: no-cache.
149 * - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
150 * proxy-revalidate if the max-stale request header exists, modify the
151 * stale calculations below so that an object can be at most <max-stale>
152 * seconds stale before we request a revalidation, _UNLESS_ a
153 * must-revalidate or proxy-revalidate cached response header exists to
154 * stop us doing this.
156 * - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
157 * maximum age an object can be before it is considered stale. This
158 * directive has the effect of proxy|must revalidate, which in turn means
159 * simple ignore any max-stale setting.
161 * - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
162 * requests and responses. If both are specified, the smaller of the two
165 * - RFC2616 14.21 Expires: if this request header exists in the cached
166 * entity, and it's value is in the past, it has expired.
169 cc_cresp = apr_table_get(h->resp_hdrs, "Cache-Control");
170 cc_ceresp = apr_table_get(h->resp_err_hdrs, "Cache-Control");
171 cc_req = apr_table_get(h->req_hdrs, "Cache-Control");
173 if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
174 age_c = apr_atoi64(agestr);
176 else if ((agestr = apr_table_get(h->resp_err_hdrs, "Age"))) {
177 age_c = apr_atoi64(agestr);
181 if (!(expstr = apr_table_get(h->resp_err_hdrs, "Expires"))) {
182 expstr = apr_table_get(h->resp_hdrs, "Expires");
185 /* calculate age of object */
186 age = ap_cache_current_age(info, age_c, r->request_time);
188 /* extract s-maxage */
189 if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "s-maxage", &val)
191 smaxage = apr_atoi64(val);
193 else if (cc_ceresp && ap_cache_liststr(r->pool, cc_ceresp, "s-maxage", &val)) {
194 smaxage = apr_atoi64(val);
200 /* extract max-age from request */
201 if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-age", &val)
203 maxage_req = apr_atoi64(val);
209 /* extract max-age from response */
210 if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "max-age", &val)
212 maxage_cresp = apr_atoi64(val);
214 else if (cc_ceresp && ap_cache_liststr(r->pool, cc_ceresp, "max-age", &val)) {
215 maxage_cresp = apr_atoi64(val);
223 * if both maxage request and response, the smaller one takes priority
225 if (-1 == maxage_req) {
226 maxage = maxage_cresp;
228 else if (-1 == maxage_cresp) {
232 maxage = MIN(maxage_req, maxage_cresp);
235 /* extract max-stale */
236 if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-stale", &val)) {
238 maxstale = apr_atoi64(val);
242 * If no value is assigned to max-stale, then the client is willing
243 * to accept a stale response of any age (RFC2616 14.9.3). We will
244 * set it to one year in this case as this situation is somewhat
245 * similar to a "never expires" Expires header (RFC2616 14.21)
246 * which is set to a date one year from the time the response is
249 maxstale = APR_INT64_C(86400*365);
256 /* extract min-fresh */
257 if (cc_req && ap_cache_liststr(r->pool, cc_req, "min-fresh", &val)
259 minfresh = apr_atoi64(val);
265 /* override maxstale if must-revalidate or proxy-revalidate */
266 if (maxstale && ((cc_cresp &&
267 ap_cache_liststr(NULL, cc_cresp,
268 "must-revalidate", NULL)) ||
270 ap_cache_liststr(NULL, cc_cresp,
271 "proxy-revalidate", NULL)) ||
273 ap_cache_liststr(NULL, cc_ceresp,
274 "must-revalidate", NULL)) ||
276 ap_cache_liststr(NULL, cc_ceresp,
277 "proxy-revalidate", NULL)))) {
281 /* handle expiration */
282 if (((smaxage != -1) && (age < (smaxage - minfresh))) ||
283 ((maxage != -1) && (age < (maxage + maxstale - minfresh))) ||
284 ((smaxage == -1) && (maxage == -1) &&
285 (info->expire != APR_DATE_BAD) &&
286 (age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh)))) {
287 const char *warn_head;
288 apr_table_t *head_ptr;
290 warn_head = apr_table_get(h->resp_hdrs, "Warning");
291 if (warn_head != NULL) {
292 head_ptr = h->resp_hdrs;
295 warn_head = apr_table_get(h->resp_err_hdrs, "Warning");
296 head_ptr = h->resp_err_hdrs;
299 /* it's fresh darlings... */
300 /* set age header on response */
302 apr_table_set(h->resp_err_hdrs, "Age",
303 apr_psprintf(r->pool, "%lu", (unsigned long)age));
306 apr_table_set(h->resp_hdrs, "Age",
307 apr_psprintf(r->pool, "%lu", (unsigned long)age));
310 /* add warning if maxstale overrode freshness calculation */
311 if (!(((smaxage != -1) && age < smaxage) ||
312 ((maxage != -1) && age < maxage) ||
313 (info->expire != APR_DATE_BAD &&
314 (info->expire - info->date) > age))) {
315 /* make sure we don't stomp on a previous warning */
316 if ((warn_head == NULL) ||
317 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
318 apr_table_merge(head_ptr, "Warning", "110 Response is stale");
322 * If none of Expires, Cache-Control: max-age, or Cache-Control:
323 * s-maxage appears in the response, and the respose header age
324 * calculated is more than 24 hours add the warning 113
326 if ((maxage_cresp == -1) && (smaxage == -1) &&
327 (expstr == NULL) && (age > 86400)) {
329 /* Make sure we don't stomp on a previous warning, and don't dup
330 * a 113 marning that is already present. Also, make sure to add
331 * the new warning to the correct *headers_out location.
333 if ((warn_head == NULL) ||
334 ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
335 apr_table_merge(head_ptr, "Warning", "113 Heuristic expiration");
338 return 1; /* Cache object is fresh (enough) */
340 return 0; /* Cache object is stale */
344 * list is a comma-separated list of case-insensitive tokens, with
345 * optional whitespace around the tokens.
346 * The return returns 1 if the token val is found in the list, or 0
349 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
350 const char *key, char **val)
359 key_len = strlen(key);
364 /* skip whitespace and commas to find the start of the next key */
365 while (*next && (apr_isspace(*next) || (*next == ','))) {
373 if (!strncasecmp(next, key, key_len)) {
374 /* this field matches the key (though it might just be
375 * a prefix match, so make sure the match is followed
376 * by either a space or an equals sign)
379 if (!*next || (*next == '=') || apr_isspace(*next) ||
383 while (*next && (*next != '=') && (*next != ',')) {
388 while (*next && apr_isspace(*next )) {
395 const char *val_start = next;
396 while (*next && !apr_isspace(*next) &&
400 *val = apr_pstrmemdup(p, val_start,
412 /* skip to the next field */
418 } while (*next != ',');
422 /* return each comma separated token, one at a time */
423 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
429 s = ap_strchr_c(list, ',');
434 while (apr_isspace(*s))
440 while (i > 0 && apr_isspace(list[i - 1]))
445 return apr_pstrndup(p, list, i);
451 * Converts apr_time_t expressed as hex digits to
454 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
458 for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
463 else if (apr_isupper(ch))
464 j |= ch - ('A' - 10);
466 j |= ch - ('a' - 10);
472 * Converts apr_time_t to apr_time_t expressed as hex digits.
474 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
478 for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
482 y[i] = ch + ('A' - 10);
486 y[sizeof(j) * 2] = '\0';
489 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
491 apr_md5_ctx_t context;
492 unsigned char digest[16];
496 static const char enc_table[64] =
497 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
499 apr_md5_init(&context);
500 apr_md5_update(&context, (const unsigned char *) it, strlen(it));
501 apr_md5_final(digest, &context);
503 /* encode 128 bits as 22 characters, using a modified uuencoding
504 * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
505 * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
507 for (i = 0, k = 0; i < 15; i += 3) {
508 x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
509 tmp[k++] = enc_table[x >> 18];
510 tmp[k++] = enc_table[(x >> 12) & 0x3f];
511 tmp[k++] = enc_table[(x >> 6) & 0x3f];
512 tmp[k++] = enc_table[x & 0x3f];
517 tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
518 tmp[k++] = enc_table[(x << 4) & 0x3f];
520 /* now split into directory levels */
521 for (i = k = d = 0; d < ndepth; ++d) {
522 memcpy(&val[i], &tmp[k], nlength);
524 val[i + nlength] = '/';
527 memcpy(&val[i], &tmp[k], 22 - k);
528 val[i + 22 - k] = '\0';
531 CACHE_DECLARE(char *)generate_name(apr_pool_t *p, int dirlevels,
532 int dirlength, const char *name)
535 cache_hash(name, hashfile, dirlevels, dirlength);
536 return apr_pstrdup(p, hashfile);
539 /* Create a new table consisting of those elements from an input
540 * headers table that are allowed to be stored in a cache.
542 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_hdrs_out(apr_pool_t *pool,
546 cache_server_conf *conf;
550 /* Make a copy of the headers, and remove from
551 * the copy any hop-by-hop headers, as defined in Section
554 apr_table_t *headers_out;
555 headers_out = apr_table_copy(pool, t);
556 apr_table_unset(headers_out, "Connection");
557 apr_table_unset(headers_out, "Keep-Alive");
558 apr_table_unset(headers_out, "Proxy-Authenticate");
559 apr_table_unset(headers_out, "Proxy-Authorization");
560 apr_table_unset(headers_out, "TE");
561 apr_table_unset(headers_out, "Trailers");
562 apr_table_unset(headers_out, "Transfer-Encoding");
563 apr_table_unset(headers_out, "Upgrade");
565 conf = (cache_server_conf *)ap_get_module_config(s->module_config,
567 /* Remove the user defined headers set with CacheIgnoreHeaders.
568 * This may break RFC 2616 compliance on behalf of the administrator.
570 header = (char **)conf->ignore_headers->elts;
571 for (i = 0; i < conf->ignore_headers->nelts; i++) {
572 apr_table_unset(headers_out, header[i]);