]> granicus.if.org Git - apache/blob - modules/cache/cache_util.c
As cache_control_t is public, make ap_cache_control() public with it. Bump
[apache] / modules / cache / cache_util.c
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "mod_cache.h"
18
19 #include "cache_util.h"
20 #include <ap_provider.h>
21
22 APLOG_USE_MODULE(cache);
23
24 /* -------------------------------------------------------------- */
25
26 extern APR_OPTIONAL_FN_TYPE(ap_cache_generate_key) *cache_generate_key;
27
28 extern module AP_MODULE_DECLARE_DATA cache_module;
29
30 /* Determine if "url" matches the hostname, scheme and port and path
31  * in "filter". All but the path comparisons are case-insensitive.
32  */
33 static int uri_meets_conditions(const apr_uri_t *filter, const int pathlen,
34                                 const apr_uri_t *url)
35 {
36
37     /* Scheme, hostname port and local part. The filter URI and the
38      * URI we test may have the following shapes:
39      *   /<path>
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.
45      *
46      * Note that this means that "/<path>" only matches local paths,
47      * and to match proxied paths one *must* specify the scheme.
48      */
49
50     /* Is the filter is just for a local path or a proxy URI? */
51     if (!filter->scheme) {
52         if (url->scheme || url->hostname) {
53             return 0;
54         }
55     }
56     else {
57         /* The URI scheme must be present and identical except for case. */
58         if (!url->scheme || strcasecmp(filter->scheme, url->scheme)) {
59             return 0;
60         }
61
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. */
67
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;
72
73                 if (fhostlen > uhostlen || strcasecmp(filter->hostname,
74                         url->hostname + uhostlen - fhostlen)) {
75                     return 0;
76                 }
77             }
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;
81
82                 if (fhostlen > uhostlen || strcasecmp(filter->hostname + 1,
83                         url->hostname + uhostlen - fhostlen)) {
84                     return 0;
85                 }
86             }
87             else if (!url->hostname || strcasecmp(filter->hostname, url->hostname)) {
88                 return 0;
89             }
90         }
91
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. */
95
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);
102
103             if (fport != uport) {
104                 return 0;
105             }
106         }
107     }
108
109     /* For HTTP caching purposes, an empty (NULL) path is equivalent to
110      * a single "/" path. RFCs 3986/2396
111      */
112     if (!url->path) {
113         if (*filter->path == '/' && pathlen == 1) {
114             return 1;
115         }
116         else {
117             return 0;
118         }
119     }
120
121     /* Url has met all of the filter conditions so far, determine
122      * if the paths match.
123      */
124     return !strncmp(filter->path, url->path, pathlen);
125 }
126
127 cache_provider_list *cache_get_providers(request_rec *r,
128         cache_server_conf *conf,
129         apr_uri_t uri)
130 {
131     cache_provider_list *providers = NULL;
132     int i;
133
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,
142                                           "0");
143             if (!provider) {
144                 /* Log an error! */
145             }
146             else {
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;
151
152                 if (!providers) {
153                     providers = newp;
154                 }
155                 else {
156                     cache_provider_list *last = providers;
157
158                     while (last->next) {
159                         last = last->next;
160                     }
161                     last->next = newp;
162                 }
163             }
164         }
165     }
166
167     /* then loop through all the cachedisable entries
168      * Looking for urls that contain the full cachedisable url and possibly
169      * more.
170      * This means we are disabling cachedisable url and below...
171      */
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. */
177             return NULL;
178         }
179     }
180
181     return providers;
182 }
183
184
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,
188                                                 apr_time_t now)
189 {
190     apr_time_t apparent_age, corrected_received_age, response_delay,
191                corrected_initial_age, resident_time, current_age,
192                age_value_usec;
193
194     age_value_usec = apr_time_from_sec(age_value);
195
196     /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
197
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;
204
205     if (current_age < 0) {
206         current_age = 0;
207     }
208
209     return apr_time_sec(current_age);
210 }
211
212 /**
213  * Try obtain a cache wide lock on the given cache key.
214  *
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.
221  *
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.
226  *
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
231  * the backend.
232  */
233 apr_status_t cache_try_lock(cache_server_conf *conf, cache_request_rec *cache,
234         request_rec *r)
235 {
236     apr_status_t status;
237     const char *lockname;
238     const char *path;
239     char dir[5];
240     apr_time_t now = apr_time_now();
241     apr_finfo_t finfo;
242     apr_file_t *lockfile;
243     void *dummy;
244
245     finfo.mtime = 0;
246
247     if (!conf || !conf->lock || !conf->lockpath) {
248         /* no locks configured, leave */
249         return APR_SUCCESS;
250     }
251
252     /* lock already obtained earlier? if so, success */
253     apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
254     if (dummy) {
255         return APR_SUCCESS;
256     }
257
258     /* create the key if it doesn't exist */
259     if (!cache->key) {
260         cache_generate_key(r, r->pool, &cache->key);
261     }
262
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);
265
266     /* lock files represent discrete just-went-stale URLs "in flight", so
267      * we support a simple two level directory structure, more is overkill.
268      */
269     dir[0] = '/';
270     dir[1] = lockname[0];
271     dir[2] = '/';
272     dir[3] = lockname[1];
273     dir[4] = 0;
274
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",
281                      path);
282         return status;
283     }
284     lockname = apr_pstrcat(r->pool, path, "/", lockname, NULL);
285     apr_pool_userdata_set(lockname, CACHE_LOCKNAME_KEY, NULL, r->pool);
286
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",
293                      lockname);
294         return status;
295     }
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",
300                      r->uri, lockname);
301         apr_file_remove(lockname, r->pool);
302     }
303
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);
309     }
310     return status;
311
312 }
313
314 /**
315  * Remove the cache lock, if present.
316  *
317  * First, try to close the file handle, whose delete-on-close should
318  * kill the file. Otherwise, just delete the file by name.
319  *
320  * If no lock name has yet been calculated, do the calculation of the
321  * lock name first before trying to delete the file.
322  *
323  * If an optional bucket brigade is passed, the lock will only be
324  * removed if the bucket brigade contains an EOS bucket.
325  */
326 apr_status_t cache_remove_lock(cache_server_conf *conf,
327         cache_request_rec *cache, request_rec *r, apr_bucket_brigade *bb)
328 {
329     void *dummy;
330     const char *lockname;
331
332     if (!conf || !conf->lock || !conf->lockpath) {
333         /* no locks configured, leave */
334         return APR_SUCCESS;
335     }
336     if (bb) {
337         apr_bucket *e;
338         int eos_found = 0;
339         for (e = APR_BRIGADE_FIRST(bb);
340              e != APR_BRIGADE_SENTINEL(bb);
341              e = APR_BUCKET_NEXT(e))
342         {
343             if (APR_BUCKET_IS_EOS(e)) {
344                 eos_found = 1;
345                 break;
346             }
347         }
348         if (!eos_found) {
349             /* no eos found in brigade, don't delete anything just yet,
350              * we are not done.
351              */
352             return APR_SUCCESS;
353         }
354     }
355     apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
356     if (dummy) {
357         return apr_file_close((apr_file_t *)dummy);
358     }
359     apr_pool_userdata_get(&dummy, CACHE_LOCKNAME_KEY, r->pool);
360     lockname = (const char *)dummy;
361     if (!lockname) {
362         char dir[5];
363
364         /* create the key if it doesn't exist */
365         if (!cache->key) {
366             cache_generate_key(r, r->pool, &cache->key);
367         }
368
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);
371
372         /* lock files represent discrete just-went-stale URLs "in flight", so
373          * we support a simple two level directory structure, more is overkill.
374          */
375         dir[0] = '/';
376         dir[1] = lockname[0];
377         dir[2] = '/';
378         dir[3] = lockname[1];
379         dir[4] = 0;
380
381         lockname = apr_pstrcat(r->pool, conf->lockpath, dir, "/", lockname, NULL);
382     }
383     return apr_file_remove(lockname, r->pool);
384 }
385
386 CACHE_DECLARE(int) ap_cache_check_allowed(cache_request_rec *cache, request_rec *r) {
387     const char *cc_req;
388     const char *pragma;
389     cache_server_conf *conf =
390       (cache_server_conf *)ap_get_module_config(r->server->module_config,
391                                                 &cache_module);
392
393     /*
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.
396      *
397      * This is covered under RFC2616 section 14.9.4 (Cache Revalidation and
398      * Reload Controls).
399      *
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
402      * a request.
403      *
404      * - RFC2616 14.9.2 What May be Stored by Caches. If Cache-Control:
405      * no-store arrives, do not serve from the cache.
406      */
407
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");
411
412     ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
413
414     if (cache->control_in.no_cache) {
415
416         if (!conf->ignorecachecontrol) {
417             return 0;
418         }
419         else {
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);
424         }
425     }
426
427     if (cache->control_in.no_store) {
428
429         if (!conf->ignorecachecontrol) {
430             /* We're not allowed to serve a cached copy */
431             return 0;
432         }
433         else {
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);
438         }
439     }
440
441     return 1;
442 }
443
444
445 int cache_check_freshness(cache_handle_t *h, cache_request_rec *cache,
446         request_rec *r)
447 {
448     apr_status_t status;
449     apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
450     apr_int64_t minfresh;
451     const char *cc_req;
452     const char *pragma;
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,
460                                                 &cache_module);
461
462     /*
463      * We now want to check if our cached data is still fresh. This depends
464      * on a few things, in this order:
465      *
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.
471      *
472      * - RFC2616 14.32 Pragma: no-cache This is treated the same as
473      * Cache-Control: no-cache.
474      *
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.
481      *
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.
486      *
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
489      * takes priority.
490      *
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.
493      *
494      */
495
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");
499
500     ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
501
502     if (cache->control_in.no_cache) {
503
504         if (!conf->ignorecachecontrol) {
505             /* Treat as stale, causing revalidation */
506             return 0;
507         }
508
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",
513                      r->unparsed_uri);
514     }
515
516     /* These come from the cached entity. */
517     expstr = apr_table_get(h->resp_hdrs, "Expires");
518
519     if (h->cache_obj->info.control.no_cache) {
520         /*
521          * The cached entity contained Cache-Control: no-cache, so treat as
522          * stale causing revalidation
523          */
524         return 0;
525     }
526
527     if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
528         age_c = apr_atoi64(agestr);
529     }
530
531     /* calculate age of object */
532     age = ap_cache_current_age(info, age_c, r->request_time);
533
534     /* extract s-maxage */
535     smaxage = h->cache_obj->info.control.s_maxage_value;
536
537     /* extract max-age from request */
538     maxage_req = -1;
539     if (!conf->ignorecachecontrol) {
540         maxage_req = cache->control_in.max_age_value;
541     }
542
543     /* extract max-age from response */
544     maxage_cresp = h->cache_obj->info.control.max_age_value;
545
546     /*
547      * if both maxage request and response, the smaller one takes priority
548      */
549     if (maxage_req == -1) {
550         maxage = maxage_cresp;
551     }
552     else if (maxage_cresp == -1) {
553         maxage = maxage_req;
554     }
555     else {
556         maxage = MIN(maxage_req, maxage_cresp);
557     }
558
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;
563         }
564         else {
565             /*
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
571              * sent in this case.
572              */
573             maxstale = APR_INT64_C(86400*365);
574         }
575     }
576     else {
577         maxstale = 0;
578     }
579
580     /* extract min-fresh */
581     if (!conf->ignorecachecontrol && cache->control_in.min_fresh) {
582         minfresh = cache->control_in.min_fresh_value;
583     }
584     else {
585         minfresh = 0;
586     }
587
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)) {
591         maxstale = 0;
592     }
593
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)))) {
600
601         warn_head = apr_table_get(h->resp_hdrs, "Warning");
602
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));
607
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");
618             }
619         }
620         /*
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
624          */
625         if ((maxage_cresp == -1) && (smaxage == -1) &&
626             (expstr == NULL) && (age > 86400)) {
627
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.
631              */
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");
636             }
637         }
638         return 1;    /* Cache object is fresh (enough) */
639     }
640
641     /*
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.
646      *
647      * So.
648      *
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.
653      *
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.
659      *
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
663      * and try again.
664      *
665      * At any time, a request marked "no-cache" will force a refresh,
666      * ignoring the lock, ensuring an extended lockout is impossible.
667      *
668      * A lock that exceeds a maximum age will be deleted, and another
669      * request gets to make a new lock and try again.
670      */
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",
677                      r->unparsed_uri);
678         return 0;
679     }
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",
685                      r->unparsed_uri);
686
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");
693         }
694
695         return 1;
696     }
697     else {
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",
702                      r->unparsed_uri);
703         return 0;
704     }
705
706 }
707
708 /*
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
712  * otherwise.
713  */
714 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
715                                     const char *key, char **val)
716 {
717     apr_size_t key_len;
718     const char *next;
719
720     if (!list) {
721         return 0;
722     }
723
724     key_len = strlen(key);
725     next = list;
726
727     for (;;) {
728
729         /* skip whitespace and commas to find the start of the next key */
730         while (*next && (apr_isspace(*next) || (*next == ','))) {
731             next++;
732         }
733
734         if (!*next) {
735             return 0;
736         }
737
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)
742              */
743             next += key_len;
744             if (!*next || (*next == '=') || apr_isspace(*next) ||
745                 (*next == ',')) {
746                 /* valid match */
747                 if (val) {
748                     while (*next && (*next != '=') && (*next != ',')) {
749                         next++;
750                     }
751                     if (*next == '=') {
752                         next++;
753                         while (*next && apr_isspace(*next )) {
754                             next++;
755                         }
756                         if (!*next) {
757                             *val = NULL;
758                         }
759                         else {
760                             const char *val_start = next;
761                             while (*next && !apr_isspace(*next) &&
762                                    (*next != ',')) {
763                                 next++;
764                             }
765                             *val = apr_pstrmemdup(p, val_start,
766                                                   next - val_start);
767                         }
768                     }
769                     else {
770                         *val = NULL;
771                     }
772                 }
773                 return 1;
774             }
775         }
776
777         /* skip to the next field */
778         do {
779             next++;
780             if (!*next) {
781                 return 0;
782             }
783         } while (*next != ',');
784     }
785 }
786
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,
789                                            const char **str)
790 {
791     apr_size_t i;
792     const char *s;
793
794     s = ap_strchr_c(list, ',');
795     if (s != NULL) {
796         i = s - list;
797         do
798             s++;
799         while (apr_isspace(*s))
800             ; /* noop */
801     }
802     else
803         i = strlen(list);
804
805     while (i > 0 && apr_isspace(list[i - 1]))
806         i--;
807
808     *str = s;
809     if (i)
810         return apr_pstrndup(p, list, i);
811     else
812         return NULL;
813 }
814
815 /*
816  * Converts apr_time_t expressed as hex digits to
817  * a true apr_time_t.
818  */
819 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
820 {
821     int i, ch;
822     apr_time_t j;
823     for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
824         ch = x[i];
825         j <<= 4;
826         if (apr_isdigit(ch))
827             j |= ch - '0';
828         else if (apr_isupper(ch))
829             j |= ch - ('A' - 10);
830         else
831             j |= ch - ('a' - 10);
832     }
833     return j;
834 }
835
836 /*
837  * Converts apr_time_t to apr_time_t expressed as hex digits.
838  */
839 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
840 {
841     int i, ch;
842
843     for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
844         ch = (int)(j & 0xF);
845         j >>= 4;
846         if (ch >= 10)
847             y[i] = ch + ('A' - 10);
848         else
849             y[i] = ch + '0';
850     }
851     y[sizeof(j) * 2] = '\0';
852 }
853
854 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
855 {
856     apr_md5_ctx_t context;
857     unsigned char digest[16];
858     char tmp[22];
859     int i, k, d;
860     unsigned int x;
861     static const char enc_table[64] =
862     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
863
864     apr_md5_init(&context);
865     apr_md5_update(&context, (const unsigned char *) it, strlen(it));
866     apr_md5_final(digest, &context);
867
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
871      */
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];
878     }
879
880     /* one byte left */
881     x = digest[15];
882     tmp[k++] = enc_table[x >> 2];    /* use up 6 bits */
883     tmp[k++] = enc_table[(x << 4) & 0x3f];
884
885     /* now split into directory levels */
886     for (i = k = d = 0; d < ndepth; ++d) {
887         memcpy(&val[i], &tmp[k], nlength);
888         k += nlength;
889         val[i + nlength] = '/';
890         i += nlength + 1;
891     }
892     memcpy(&val[i], &tmp[k], 22 - k);
893     val[i + 22 - k] = '\0';
894 }
895
896 CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
897                                             int dirlength, const char *name)
898 {
899     char hashfile[66];
900     cache_hash(name, hashfile, dirlevels, dirlength);
901     return apr_pstrdup(p, hashfile);
902 }
903
904 /*
905  * Create a new table consisting of those elements from an
906  * headers table that are allowed to be stored in a cache.
907  */
908 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers(apr_pool_t *pool,
909                                                         apr_table_t *t,
910                                                         server_rec *s)
911 {
912     cache_server_conf *conf;
913     char **header;
914     int i;
915     apr_table_t *headers_out;
916
917     /* Short circuit the common case that there are not
918      * (yet) any headers populated.
919      */
920     if (t == NULL) {
921         return apr_table_make(pool, 10);
922     };
923
924     /* Make a copy of the headers, and remove from
925      * the copy any hop-by-hop headers, as defined in Section
926      * 13.5.1 of RFC 2616
927      */
928     headers_out = apr_table_copy(pool, t);
929
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");
938
939     conf = (cache_server_conf *)ap_get_module_config(s->module_config,
940                                                      &cache_module);
941
942     /* Remove the user defined headers set with CacheIgnoreHeaders.
943      * This may break RFC 2616 compliance on behalf of the administrator.
944      */
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]);
948     }
949     return headers_out;
950 }
951
952 /*
953  * Create a new table consisting of those elements from an input
954  * headers table that are allowed to be stored in a cache.
955  */
956 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_in(request_rec *r)
957 {
958     return ap_cache_cacheable_headers(r->pool, r->headers_in, r->server);
959 }
960
961 /*
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.
965  */
966 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_out(request_rec *r)
967 {
968     apr_table_t *headers_out;
969
970     headers_out = apr_table_overlay(r->pool, r->headers_out,
971                                         r->err_headers_out);
972
973     apr_table_clear(r->err_headers_out);
974
975     headers_out = ap_cache_cacheable_headers(r->pool, headers_out,
976                                                   r->server);
977
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));
982     }
983
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);
988     }
989
990     return headers_out;
991 }
992
993 /**
994  * Parse the Cache-Control and Pragma headers in one go, marking
995  * which tokens appear within the header. Populate the structure
996  * passed in.
997  */
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)
1000 {
1001     char *last;
1002
1003     if (cc->parsed) {
1004         return cc->cache_control || cc->pragma;
1005     }
1006
1007     cc->parsed = 1;
1008     cc->max_age_value = -1;
1009     cc->max_stale_value = -1;
1010     cc->min_fresh_value = -1;
1011     cc->s_maxage_value = -1;
1012
1013     if (pragma_header) {
1014         char *header = apr_pstrdup(r->pool, pragma_header);
1015         const char *token = apr_strtok(header, ", ", &last);
1016         while (token) {
1017             /* handle most common quickest case... */
1018             if (!strcmp(token, "no-cache")) {
1019                 cc->no_cache = 1;
1020             }
1021             /* ...then try slowest case */
1022             else if (!strcasecmp(token, "no-cache")) {
1023                 cc->no_cache = 1;
1024             }
1025             token = apr_strtok(NULL, ", ", &last);
1026         }
1027         cc->pragma = 1;
1028     }
1029
1030     if (cc_header) {
1031         char *header = apr_pstrdup(r->pool, cc_header);
1032         const char *token = apr_strtok(header, ", ", &last);
1033         while (token) {
1034             switch (token[0]) {
1035             case 'n':
1036             case 'N': {
1037                 /* handle most common quickest cases... */
1038                 if (!strcmp(token, "no-cache")) {
1039                     cc->no_cache = 1;
1040                 }
1041                 else if (!strcmp(token, "no-store")) {
1042                     cc->no_store = 1;
1043                 }
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;
1049                         }
1050                     }
1051                     else if (!token[8]) {
1052                         cc->no_cache = 1;
1053                     }
1054                     break;
1055                 }
1056                 else if (!strcasecmp(token, "no-store")) {
1057                     cc->no_store = 1;
1058                 }
1059                 else if (!strcasecmp(token, "no-transform")) {
1060                     cc->no_transform = 1;
1061                 }
1062                 break;
1063             }
1064             case 'm':
1065             case 'M': {
1066                 /* handle most common quickest cases... */
1067                 if (!strcmp(token, "max-age=0")) {
1068                     cc->max_age = 1;
1069                     cc->max_age_value = 0;
1070                 }
1071                 else if (!strcmp(token, "must-revalidate")) {
1072                     cc->must_revalidate = 1;
1073                 }
1074                 /* ...then try slowest cases */
1075                 else if (!strncasecmp(token, "max-age", 7)) {
1076                     if (token[7] == '=') {
1077                         cc->max_age = 1;
1078                         cc->max_age_value = apr_atoi64(token + 8);
1079                     }
1080                     break;
1081                 }
1082                 else if (!strncasecmp(token, "max-stale", 9)) {
1083                     if (token[9] == '=') {
1084                         cc->max_stale = 1;
1085                         cc->max_stale_value = apr_atoi64(token + 10);
1086                     }
1087                     else if (!token[10]) {
1088                         cc->max_stale = 1;
1089                         cc->max_stale_value = -1;
1090                     }
1091                     break;
1092                 }
1093                 else if (!strncasecmp(token, "min-fresh", 9)) {
1094                     if (token[9] == '=') {
1095                         cc->min_fresh = 1;
1096                         cc->min_fresh_value = apr_atoi64(token + 10);
1097                     }
1098                     break;
1099                 }
1100                 else if (!strcasecmp(token, "must-revalidate")) {
1101                     cc->must_revalidate = 1;
1102                 }
1103                 break;
1104             }
1105             case 'o':
1106             case 'O': {
1107                 if (!strcasecmp(token, "only-if-cached")) {
1108                     cc->only_if_cached = 1;
1109                 }
1110                 break;
1111             }
1112             case 'p':
1113             case 'P': {
1114                 /* handle most common quickest cases... */
1115                 if (!strcmp(token, "private")) {
1116                     cc->private = 1;
1117                 }
1118                 /* ...then try slowest cases */
1119                 else if (!strcasecmp(token, "public")) {
1120                     cc->public = 1;
1121                 }
1122                 else if (!strncasecmp(token, "private", 7)) {
1123                     if (token[7] == '=') {
1124                         if (apr_table_get(headers, token + 8)) {
1125                             cc->private_header = 1;
1126                         }
1127                     }
1128                     else if (!token[7]) {
1129                         cc->private = 1;
1130                     }
1131                     break;
1132                 }
1133                 else if (!strcasecmp(token, "proxy-revalidate")) {
1134                     cc->proxy_revalidate = 1;
1135                 }
1136                 break;
1137             }
1138             case 's':
1139             case 'S': {
1140                 if (!strncasecmp(token, "s-maxage", 8)) {
1141                     if (token[8] == '=') {
1142                         cc->s_maxage = 1;
1143                         cc->s_maxage_value = apr_atoi64(token + 9);
1144                     }
1145                     break;
1146                 }
1147                 break;
1148             }
1149             }
1150             token = apr_strtok(NULL, ", ", &last);
1151         }
1152         cc->cache_control = 1;
1153     }
1154
1155     return (cc_header != NULL || pragma_header != NULL);
1156 }