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
/* Determine if "url" matches the hostname, scheme and port and path
28
* in "filter". All but the path comparisons are case-insensitive.
30
static int uri_meets_conditions(apr_uri_t filter, int pathlen, apr_uri_t url)
32
/* Compare the hostnames */
37
else if (strcasecmp(filter.hostname, url.hostname)) {
42
/* Compare the schemes */
47
else if (strcasecmp(filter.scheme, url.scheme)) {
52
/* Compare the ports */
54
if (url.port_str && filter.port != url.port) {
57
/* NOTE: ap_port_of_scheme will return 0 if given NULL input */
58
else if (filter.port != apr_uri_port_of_scheme(url.scheme)) {
62
else if(url.port_str && filter.scheme) {
63
if (apr_uri_port_of_scheme(filter.scheme) == url.port) {
68
/* Url has met all of the filter conditions so far, determine
71
return !strncmp(filter.path, url.path, pathlen);
74
CACHE_DECLARE(cache_provider_list *)ap_cache_get_providers(request_rec *r,
75
cache_server_conf *conf,
78
cache_provider_list *providers = NULL;
81
/* loop through all the cacheenable entries */
82
for (i = 0; i < conf->cacheenable->nelts; i++) {
83
struct cache_enable *ent =
84
(struct cache_enable *)conf->cacheenable->elts;
85
if (uri_meets_conditions(ent[i].url, ent[i].pathlen, uri)) {
86
/* Fetch from global config and add to the list. */
87
cache_provider *provider;
88
provider = ap_lookup_provider(CACHE_PROVIDER_GROUP, ent[i].type,
94
cache_provider_list *newp;
95
newp = apr_pcalloc(r->pool, sizeof(cache_provider_list));
96
newp->provider_name = ent[i].type;
97
newp->provider = provider;
103
cache_provider_list *last = providers;
114
/* then loop through all the cachedisable entries
115
* Looking for urls that contain the full cachedisable url and possibly
117
* This means we are disabling cachedisable url and below...
119
for (i = 0; i < conf->cachedisable->nelts; i++) {
120
struct cache_disable *ent =
121
(struct cache_disable *)conf->cachedisable->elts;
122
if (uri_meets_conditions(ent[i].url, ent[i].pathlen, uri)) {
123
/* Stop searching now. */
132
/* do a HTTP/1.1 age calculation */
133
CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info,
134
const apr_time_t age_value,
137
apr_time_t apparent_age, corrected_received_age, response_delay,
138
corrected_initial_age, resident_time, current_age,
141
age_value_usec = apr_time_from_sec(age_value);
143
/* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
145
apparent_age = MAX(0, info->response_time - info->date);
146
corrected_received_age = MAX(apparent_age, age_value_usec);
147
response_delay = info->response_time - info->request_time;
148
corrected_initial_age = corrected_received_age + response_delay;
149
resident_time = now - info->response_time;
150
current_age = corrected_initial_age + resident_time;
152
return apr_time_sec(current_age);
155
CACHE_DECLARE(int) ap_cache_check_freshness(cache_handle_t *h,
158
apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
159
apr_int64_t minfresh;
160
const char *cc_cresp, *cc_req;
162
const char *agestr = NULL;
163
const char *expstr = NULL;
165
apr_time_t age_c = 0;
166
cache_info *info = &(h->cache_obj->info);
167
cache_server_conf *conf =
168
(cache_server_conf *)ap_get_module_config(r->server->module_config,
172
* We now want to check if our cached data is still fresh. This depends
173
* on a few things, in this order:
175
* - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache in
176
* either the request or the cached response means that we must
177
* revalidate the request unconditionally, overriding any expiration
178
* mechanism. It's equivalent to max-age=0,must-revalidate.
180
* - RFC2616 14.32 Pragma: no-cache This is treated the same as
181
* Cache-Control: no-cache.
183
* - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
184
* proxy-revalidate if the max-stale request header exists, modify the
185
* stale calculations below so that an object can be at most <max-stale>
186
* seconds stale before we request a revalidation, _UNLESS_ a
187
* must-revalidate or proxy-revalidate cached response header exists to
188
* stop us doing this.
190
* - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
191
* maximum age an object can be before it is considered stale. This
192
* directive has the effect of proxy|must revalidate, which in turn means
193
* simple ignore any max-stale setting.
195
* - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
196
* requests and responses. If both are specified, the smaller of the two
199
* - RFC2616 14.21 Expires: if this request header exists in the cached
200
* entity, and it's value is in the past, it has expired.
204
/* This value comes from the client's initial request. */
205
cc_req = apr_table_get(r->headers_in, "Cache-Control");
206
pragma = apr_table_get(r->headers_in, "Pragma");
208
if (ap_cache_liststr(NULL, pragma, "no-cache", NULL)
209
|| ap_cache_liststr(NULL, cc_req, "no-cache", NULL)) {
211
if (!conf->ignorecachecontrol) {
212
/* Treat as stale, causing revalidation */
216
ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
217
"Incoming request is asking for a uncached version of "
218
"%s, but we know better and are ignoring it",
222
/* These come from the cached entity. */
223
cc_cresp = apr_table_get(h->resp_hdrs, "Cache-Control");
224
expstr = apr_table_get(h->resp_hdrs, "Expires");
226
if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
227
age_c = apr_atoi64(agestr);
230
/* calculate age of object */
231
age = ap_cache_current_age(info, age_c, r->request_time);
233
/* extract s-maxage */
234
if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "s-maxage", &val)) {
235
smaxage = apr_atoi64(val);
241
/* extract max-age from request */
242
if (!conf->ignorecachecontrol
243
&& cc_req && ap_cache_liststr(r->pool, cc_req, "max-age", &val)) {
244
maxage_req = apr_atoi64(val);
250
/* extract max-age from response */
251
if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "max-age", &val)) {
252
maxage_cresp = apr_atoi64(val);
259
* if both maxage request and response, the smaller one takes priority
261
if (maxage_req == -1) {
262
maxage = maxage_cresp;
264
else if (maxage_cresp == -1) {
268
maxage = MIN(maxage_req, maxage_cresp);
271
/* extract max-stale */
272
if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-stale", &val)) {
273
maxstale = apr_atoi64(val);
279
/* extract min-fresh */
280
if (!conf->ignorecachecontrol
281
&& cc_req && ap_cache_liststr(r->pool, cc_req, "min-fresh", &val)) {
282
minfresh = apr_atoi64(val);
288
/* override maxstale if must-revalidate or proxy-revalidate */
289
if (maxstale && ((cc_cresp &&
290
ap_cache_liststr(NULL, cc_cresp,
291
"must-revalidate", NULL)) ||
293
ap_cache_liststr(NULL, cc_cresp,
294
"proxy-revalidate", NULL)))) {
298
/* handle expiration */
299
if (((smaxage != -1) && (age < (smaxage - minfresh))) ||
300
((maxage != -1) && (age < (maxage + maxstale - minfresh))) ||
301
((smaxage == -1) && (maxage == -1) &&
302
(info->expire != APR_DATE_BAD) &&
303
(age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh)))) {
304
const char *warn_head;
306
warn_head = apr_table_get(h->resp_hdrs, "Warning");
308
/* it's fresh darlings... */
309
/* set age header on response */
310
apr_table_set(h->resp_hdrs, "Age",
311
apr_psprintf(r->pool, "%lu", (unsigned long)age));
313
/* add warning if maxstale overrode freshness calculation */
314
if (!(((smaxage != -1) && age < smaxage) ||
315
((maxage != -1) && age < maxage) ||
316
(info->expire != APR_DATE_BAD &&
317
(info->expire - info->date) > age))) {
318
/* make sure we don't stomp on a previous warning */
319
if ((warn_head == NULL) ||
320
((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
321
apr_table_merge(h->resp_hdrs, "Warning",
322
"110 Response is stale");
326
* If none of Expires, Cache-Control: max-age, or Cache-Control:
327
* s-maxage appears in the response, and the respose header age
328
* calculated is more than 24 hours add the warning 113
330
if ((maxage_cresp == -1) && (smaxage == -1) &&
331
(expstr == NULL) && (age > 86400)) {
333
/* Make sure we don't stomp on a previous warning, and don't dup
334
* a 113 marning that is already present. Also, make sure to add
335
* the new warning to the correct *headers_out location.
337
if ((warn_head == NULL) ||
338
((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
339
apr_table_merge(h->resp_hdrs, "Warning",
340
"113 Heuristic expiration");
343
return 1; /* Cache object is fresh (enough) */
346
return 0; /* Cache object is stale */
350
* list is a comma-separated list of case-insensitive tokens, with
351
* optional whitespace around the tokens.
352
* The return returns 1 if the token val is found in the list, or 0
355
CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
356
const char *key, char **val)
365
key_len = strlen(key);
370
/* skip whitespace and commas to find the start of the next key */
371
while (*next && (apr_isspace(*next) || (*next == ','))) {
379
if (!strncasecmp(next, key, key_len)) {
380
/* this field matches the key (though it might just be
381
* a prefix match, so make sure the match is followed
382
* by either a space or an equals sign)
385
if (!*next || (*next == '=') || apr_isspace(*next) ||
389
while (*next && (*next != '=') && (*next != ',')) {
394
while (*next && apr_isspace(*next )) {
401
const char *val_start = next;
402
while (*next && !apr_isspace(*next) &&
406
*val = apr_pstrmemdup(p, val_start,
415
/* skip to the next field */
421
} while (*next != ',');
425
/* return each comma separated token, one at a time */
426
CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
432
s = ap_strchr_c(list, ',');
437
while (apr_isspace(*s))
443
while (i > 0 && apr_isspace(list[i - 1]))
448
return apr_pstrndup(p, list, i);
454
* Converts apr_time_t expressed as hex digits to
457
CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
461
for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
466
else if (apr_isupper(ch))
467
j |= ch - ('A' - 10);
469
j |= ch - ('a' - 10);
475
* Converts apr_time_t to apr_time_t expressed as hex digits.
477
CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
481
for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
485
y[i] = ch + ('A' - 10);
489
y[sizeof(j) * 2] = '\0';
492
static void cache_hash(const char *it, char *val, int ndepth, int nlength)
494
apr_md5_ctx_t context;
495
unsigned char digest[16];
499
static const char enc_table[64] =
500
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
502
apr_md5_init(&context);
503
apr_md5_update(&context, (const unsigned char *) it, strlen(it));
504
apr_md5_final(digest, &context);
506
/* encode 128 bits as 22 characters, using a modified uuencoding
507
* the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
508
* 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
510
for (i = 0, k = 0; i < 15; i += 3) {
511
x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
512
tmp[k++] = enc_table[x >> 18];
513
tmp[k++] = enc_table[(x >> 12) & 0x3f];
514
tmp[k++] = enc_table[(x >> 6) & 0x3f];
515
tmp[k++] = enc_table[x & 0x3f];
520
tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
521
tmp[k++] = enc_table[(x << 4) & 0x3f];
523
/* now split into directory levels */
524
for (i = k = d = 0; d < ndepth; ++d) {
525
memcpy(&val[i], &tmp[k], nlength);
527
val[i + nlength] = '/';
530
memcpy(&val[i], &tmp[k], 22 - k);
531
val[i + 22 - k] = '\0';
534
CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
535
int dirlength, const char *name)
538
cache_hash(name, hashfile, dirlevels, dirlength);
539
return apr_pstrdup(p, hashfile);
542
/* Create a new table consisting of those elements from an input
543
* headers table that are allowed to be stored in a cache.
545
CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_hdrs_out(apr_pool_t *pool,
549
cache_server_conf *conf;
553
/* Make a copy of the headers, and remove from
554
* the copy any hop-by-hop headers, as defined in Section
557
apr_table_t *headers_out;
558
headers_out = apr_table_copy(pool, t);
559
apr_table_unset(headers_out, "Connection");
560
apr_table_unset(headers_out, "Keep-Alive");
561
apr_table_unset(headers_out, "Proxy-Authenticate");
562
apr_table_unset(headers_out, "Proxy-Authorization");
563
apr_table_unset(headers_out, "TE");
564
apr_table_unset(headers_out, "Trailers");
565
apr_table_unset(headers_out, "Transfer-Encoding");
566
apr_table_unset(headers_out, "Upgrade");
568
conf = (cache_server_conf *)ap_get_module_config(s->module_config,
570
/* Remove the user defined headers set with CacheIgnoreHeaders.
571
* This may break RFC 2616 compliance on behalf of the administrator.
573
header = (char **)conf->ignore_headers->elts;
574
for (i = 0; i < conf->ignore_headers->nelts; i++) {
575
apr_table_unset(headers_out, header[i]);