]> granicus.if.org Git - apache/blob - modules/cache/cache_util.c
Fix a spelling mistake.
[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_rerror(APLOG_MARK, APLOG_ERR, status, r,
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_rerror(APLOG_MARK, APLOG_ERR, APR_EEXIST, r,
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_rerror(APLOG_MARK, APLOG_INFO, status, r,
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_rerror(APLOG_MARK, APLOG_INFO, 0, r,
421                     "Incoming request is asking for an uncached version of "
422                     "%s, but we have been configured to ignore it and serve "
423                     "cached content anyway", r->unparsed_uri);
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_rerror(APLOG_MARK, APLOG_INFO, 0, r,
435                     "Incoming request is asking for a no-store version of "
436                     "%s, but we have been configured to ignore it and serve "
437                     "cached content anyway", r->unparsed_uri);
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     apr_time_t age_c = 0;
455     cache_info *info = &(h->cache_obj->info);
456     const char *warn_head;
457     cache_server_conf *conf =
458       (cache_server_conf *)ap_get_module_config(r->server->module_config,
459                                                 &cache_module);
460
461     /*
462      * We now want to check if our cached data is still fresh. This depends
463      * on a few things, in this order:
464      *
465      * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache
466      * in either the request or the cached response means that we must
467      * perform the request unconditionally, and ignore cached content. We
468      * should never reach here, but if we do, mark the content as stale,
469      * as this is the best we can do.
470      *
471      * - RFC2616 14.32 Pragma: no-cache This is treated the same as
472      * Cache-Control: no-cache.
473      *
474      * - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
475      * proxy-revalidate if the max-stale request header exists, modify the
476      * stale calculations below so that an object can be at most <max-stale>
477      * seconds stale before we request a revalidation, _UNLESS_ a
478      * must-revalidate or proxy-revalidate cached response header exists to
479      * stop us doing this.
480      *
481      * - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
482      * maximum age an object can be before it is considered stale. This
483      * directive has the effect of proxy|must revalidate, which in turn means
484      * simple ignore any max-stale setting.
485      *
486      * - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
487      * requests and responses. If both are specified, the smaller of the two
488      * takes priority.
489      *
490      * - RFC2616 14.21 Expires: if this request header exists in the cached
491      * entity, and it's value is in the past, it has expired.
492      *
493      */
494
495     /* This value comes from the client's initial request. */
496     cc_req = apr_table_get(r->headers_in, "Cache-Control");
497     pragma = apr_table_get(r->headers_in, "Pragma");
498
499     ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
500
501     if (cache->control_in.no_cache) {
502
503         if (!conf->ignorecachecontrol) {
504             /* Treat as stale, causing revalidation */
505             return 0;
506         }
507
508         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
509                 "Incoming request is asking for a uncached version of "
510                 "%s, but we have been configured to ignore it and "
511                 "serve a cached response anyway",
512                 r->unparsed_uri);
513     }
514
515     /* These come from the cached entity. */
516     if (h->cache_obj->info.control.no_cache
517             || h->cache_obj->info.control.no_cache_header
518             || h->cache_obj->info.control.private_header) {
519         /*
520          * The cached entity contained Cache-Control: no-cache, or a
521          * no-cache with a header present, or a private with a header
522          * present, so treat as stale causing revalidation.
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         /*
622          * If none of Expires, Cache-Control: max-age, or Cache-Control:
623          * s-maxage appears in the response, and the response header age
624          * calculated is more than 24 hours add the warning 113
625          */
626         if ((maxage_cresp == -1) && (smaxage == -1) && (apr_table_get(
627                 h->resp_hdrs, "Expires") == NULL) && (age > 86400)) {
628
629             /* Make sure we don't stomp on a previous warning, and don't dup
630              * a 113 marning that is already present. Also, make sure to add
631              * the new warning to the correct *headers_out location.
632              */
633             if ((warn_head == NULL) ||
634                 ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
635                 apr_table_merge(h->resp_hdrs, "Warning",
636                                 "113 Heuristic expiration");
637             }
638         }
639         return 1;    /* Cache object is fresh (enough) */
640     }
641
642     /*
643      * At this point we are stale, but: if we are under load, we may let
644      * a significant number of stale requests through before the first
645      * stale request successfully revalidates itself, causing a sudden
646      * unexpected thundering herd which in turn brings angst and drama.
647      *
648      * So.
649      *
650      * We want the first stale request to go through as normal. But the
651      * second and subsequent request, we must pretend to be fresh until
652      * the first request comes back with either new content or confirmation
653      * that the stale content is still fresh.
654      *
655      * To achieve this, we create a very simple file based lock based on
656      * the key of the cached object. We attempt to open the lock file with
657      * exclusive write access. If we succeed, woohoo! we're first, and we
658      * follow the stale path to the backend server. If we fail, oh well,
659      * we follow the fresh path, and avoid being a thundering herd.
660      *
661      * The lock lives only as long as the stale request that went on ahead.
662      * If the request succeeds, the lock is deleted. If the request fails,
663      * the lock is deleted, and another request gets to make a new lock
664      * and try again.
665      *
666      * At any time, a request marked "no-cache" will force a refresh,
667      * ignoring the lock, ensuring an extended lockout is impossible.
668      *
669      * A lock that exceeds a maximum age will be deleted, and another
670      * request gets to make a new lock and try again.
671      */
672     status = cache_try_lock(conf, cache, r);
673     if (APR_SUCCESS == status) {
674         /* we obtained a lock, follow the stale path */
675         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
676                 "Cache lock obtained for stale cached URL, "
677                 "revalidating entry: %s",
678                 r->unparsed_uri);
679         return 0;
680     }
681     else if (APR_EEXIST == status) {
682         /* lock already exists, return stale data anyway, with a warning */
683         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
684                 "Cache already locked for stale cached URL, "
685                 "pretend it is fresh: %s",
686                 r->unparsed_uri);
687
688         /* make sure we don't stomp on a previous warning */
689         warn_head = apr_table_get(h->resp_hdrs, "Warning");
690         if ((warn_head == NULL) ||
691             ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
692             apr_table_merge(h->resp_hdrs, "Warning",
693                         "110 Response is stale");
694         }
695
696         return 1;
697     }
698     else {
699         /* some other error occurred, just treat the object as stale */
700         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r,
701                 "Attempt to obtain a cache lock for stale "
702                 "cached URL failed, revalidating entry anyway: %s",
703                 r->unparsed_uri);
704         return 0;
705     }
706
707 }
708
709 /*
710  * list is a comma-separated list of case-insensitive tokens, with
711  * optional whitespace around the tokens.
712  * The return returns 1 if the token val is found in the list, or 0
713  * otherwise.
714  */
715 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
716                                     const char *key, char **val)
717 {
718     apr_size_t key_len;
719     const char *next;
720
721     if (!list) {
722         return 0;
723     }
724
725     key_len = strlen(key);
726     next = list;
727
728     for (;;) {
729
730         /* skip whitespace and commas to find the start of the next key */
731         while (*next && (apr_isspace(*next) || (*next == ','))) {
732             next++;
733         }
734
735         if (!*next) {
736             return 0;
737         }
738
739         if (!strncasecmp(next, key, key_len)) {
740             /* this field matches the key (though it might just be
741              * a prefix match, so make sure the match is followed
742              * by either a space or an equals sign)
743              */
744             next += key_len;
745             if (!*next || (*next == '=') || apr_isspace(*next) ||
746                 (*next == ',')) {
747                 /* valid match */
748                 if (val) {
749                     while (*next && (*next != '=') && (*next != ',')) {
750                         next++;
751                     }
752                     if (*next == '=') {
753                         next++;
754                         while (*next && apr_isspace(*next )) {
755                             next++;
756                         }
757                         if (!*next) {
758                             *val = NULL;
759                         }
760                         else {
761                             const char *val_start = next;
762                             while (*next && !apr_isspace(*next) &&
763                                    (*next != ',')) {
764                                 /* EAT QUOTED STRING */
765                                 if (*next == '"' || *next == '\'') {
766                                     char delim = *next;
767                                     while (*++next != delim) {
768                                         if (!*next) {
769                                             return 0;
770                                         }
771                                         else if (*next == '\\') {
772                                             ++next;
773                                         }
774                                     }
775                                 }
776                                 next++;
777                             }
778                             *val = apr_pstrmemdup(p, val_start,
779                                                   next - val_start);
780                         }
781                     }
782                     else {
783                         *val = NULL;
784                     }
785                 }
786                 return 1;
787             }
788         }
789
790         /* skip to the next field */
791         do {
792             /* EAT QUOTED STRING */
793             if (*next == '"' || *next == '\'') {
794                 char delim = *next;
795                 while (*++next != delim) {
796                     if (!*next) {
797                         return 0;
798                     }
799                     else if (*next == '\\') {
800                         ++next;
801                     }
802                 }
803             }
804             next++;
805             if (!*next) {
806                 return 0;
807             }
808         } while (*next != ',');
809     }
810 }
811
812 /* return each comma separated token, one at a time */
813 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
814                                            const char **str)
815 {
816     apr_size_t i;
817     const char *s;
818
819     s = ap_strchr_c(list, ',');
820     if (s != NULL) {
821         i = s - list;
822         do
823             s++;
824         while (apr_isspace(*s))
825             ; /* noop */
826     }
827     else
828         i = strlen(list);
829
830     while (i > 0 && apr_isspace(list[i - 1]))
831         i--;
832
833     *str = s;
834     if (i)
835         return apr_pstrndup(p, list, i);
836     else
837         return NULL;
838 }
839
840 /*
841  * Converts apr_time_t expressed as hex digits to
842  * a true apr_time_t.
843  */
844 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
845 {
846     int i, ch;
847     apr_time_t j;
848     for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
849         ch = x[i];
850         j <<= 4;
851         if (apr_isdigit(ch))
852             j |= ch - '0';
853         else if (apr_isupper(ch))
854             j |= ch - ('A' - 10);
855         else
856             j |= ch - ('a' - 10);
857     }
858     return j;
859 }
860
861 /*
862  * Converts apr_time_t to apr_time_t expressed as hex digits.
863  */
864 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
865 {
866     int i, ch;
867
868     for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
869         ch = (int)(j & 0xF);
870         j >>= 4;
871         if (ch >= 10)
872             y[i] = ch + ('A' - 10);
873         else
874             y[i] = ch + '0';
875     }
876     y[sizeof(j) * 2] = '\0';
877 }
878
879 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
880 {
881     apr_md5_ctx_t context;
882     unsigned char digest[16];
883     char tmp[22];
884     int i, k, d;
885     unsigned int x;
886     static const char enc_table[64] =
887     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
888
889     apr_md5_init(&context);
890     apr_md5_update(&context, (const unsigned char *) it, strlen(it));
891     apr_md5_final(digest, &context);
892
893     /* encode 128 bits as 22 characters, using a modified uuencoding
894      * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
895      * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
896      */
897     for (i = 0, k = 0; i < 15; i += 3) {
898         x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
899         tmp[k++] = enc_table[x >> 18];
900         tmp[k++] = enc_table[(x >> 12) & 0x3f];
901         tmp[k++] = enc_table[(x >> 6) & 0x3f];
902         tmp[k++] = enc_table[x & 0x3f];
903     }
904
905     /* one byte left */
906     x = digest[15];
907     tmp[k++] = enc_table[x >> 2];    /* use up 6 bits */
908     tmp[k++] = enc_table[(x << 4) & 0x3f];
909
910     /* now split into directory levels */
911     for (i = k = d = 0; d < ndepth; ++d) {
912         memcpy(&val[i], &tmp[k], nlength);
913         k += nlength;
914         val[i + nlength] = '/';
915         i += nlength + 1;
916     }
917     memcpy(&val[i], &tmp[k], 22 - k);
918     val[i + 22 - k] = '\0';
919 }
920
921 CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
922                                             int dirlength, const char *name)
923 {
924     char hashfile[66];
925     cache_hash(name, hashfile, dirlevels, dirlength);
926     return apr_pstrdup(p, hashfile);
927 }
928
929 /*
930  * Create a new table consisting of those elements from an
931  * headers table that are allowed to be stored in a cache.
932  */
933 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers(apr_pool_t *pool,
934                                                         apr_table_t *t,
935                                                         server_rec *s)
936 {
937     cache_server_conf *conf;
938     char **header;
939     int i;
940     apr_table_t *headers_out;
941
942     /* Short circuit the common case that there are not
943      * (yet) any headers populated.
944      */
945     if (t == NULL) {
946         return apr_table_make(pool, 10);
947     };
948
949     /* Make a copy of the headers, and remove from
950      * the copy any hop-by-hop headers, as defined in Section
951      * 13.5.1 of RFC 2616
952      */
953     headers_out = apr_table_copy(pool, t);
954
955     apr_table_unset(headers_out, "Connection");
956     apr_table_unset(headers_out, "Keep-Alive");
957     apr_table_unset(headers_out, "Proxy-Authenticate");
958     apr_table_unset(headers_out, "Proxy-Authorization");
959     apr_table_unset(headers_out, "TE");
960     apr_table_unset(headers_out, "Trailers");
961     apr_table_unset(headers_out, "Transfer-Encoding");
962     apr_table_unset(headers_out, "Upgrade");
963
964     conf = (cache_server_conf *)ap_get_module_config(s->module_config,
965                                                      &cache_module);
966
967     /* Remove the user defined headers set with CacheIgnoreHeaders.
968      * This may break RFC 2616 compliance on behalf of the administrator.
969      */
970     header = (char **)conf->ignore_headers->elts;
971     for (i = 0; i < conf->ignore_headers->nelts; i++) {
972         apr_table_unset(headers_out, header[i]);
973     }
974     return headers_out;
975 }
976
977 /*
978  * Create a new table consisting of those elements from an input
979  * headers table that are allowed to be stored in a cache.
980  */
981 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_in(request_rec *r)
982 {
983     return ap_cache_cacheable_headers(r->pool, r->headers_in, r->server);
984 }
985
986 /*
987  * Create a new table consisting of those elements from an output
988  * headers table that are allowed to be stored in a cache;
989  * ensure there is a content type and capture any errors.
990  */
991 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_out(request_rec *r)
992 {
993     apr_table_t *headers_out;
994
995     headers_out = apr_table_overlay(r->pool, r->headers_out,
996                                         r->err_headers_out);
997
998     apr_table_clear(r->err_headers_out);
999
1000     headers_out = ap_cache_cacheable_headers(r->pool, headers_out,
1001                                                   r->server);
1002
1003     if (!apr_table_get(headers_out, "Content-Type")
1004         && r->content_type) {
1005         apr_table_setn(headers_out, "Content-Type",
1006                        ap_make_content_type(r, r->content_type));
1007     }
1008
1009     if (!apr_table_get(headers_out, "Content-Encoding")
1010         && r->content_encoding) {
1011         apr_table_setn(headers_out, "Content-Encoding",
1012                        r->content_encoding);
1013     }
1014
1015     return headers_out;
1016 }
1017
1018 /**
1019  * Parse the Cache-Control and Pragma headers in one go, marking
1020  * which tokens appear within the header. Populate the structure
1021  * passed in.
1022  */
1023 int ap_cache_control(request_rec *r, cache_control_t *cc,
1024         const char *cc_header, const char *pragma_header, apr_table_t *headers)
1025 {
1026     char *last;
1027
1028     if (cc->parsed) {
1029         return cc->cache_control || cc->pragma;
1030     }
1031
1032     cc->parsed = 1;
1033     cc->max_age_value = -1;
1034     cc->max_stale_value = -1;
1035     cc->min_fresh_value = -1;
1036     cc->s_maxage_value = -1;
1037
1038     if (pragma_header) {
1039         char *header = apr_pstrdup(r->pool, pragma_header);
1040         const char *token = apr_strtok(header, ", ", &last);
1041         while (token) {
1042             /* handle most common quickest case... */
1043             if (!strcmp(token, "no-cache")) {
1044                 cc->no_cache = 1;
1045             }
1046             /* ...then try slowest case */
1047             else if (!strcasecmp(token, "no-cache")) {
1048                 cc->no_cache = 1;
1049             }
1050             token = apr_strtok(NULL, ", ", &last);
1051         }
1052         cc->pragma = 1;
1053     }
1054
1055     if (cc_header) {
1056         char *header = apr_pstrdup(r->pool, cc_header);
1057         const char *token = apr_strtok(header, ", ", &last);
1058         while (token) {
1059             switch (token[0]) {
1060             case 'n':
1061             case 'N': {
1062                 /* handle most common quickest cases... */
1063                 if (!strcmp(token, "no-cache")) {
1064                     cc->no_cache = 1;
1065                 }
1066                 else if (!strcmp(token, "no-store")) {
1067                     cc->no_store = 1;
1068                 }
1069                 /* ...then try slowest cases */
1070                 else if (!strncasecmp(token, "no-cache", 8)) {
1071                     if (token[8] == '=') {
1072                         if (apr_table_get(headers, token + 9)) {
1073                             cc->no_cache_header = 1;
1074                         }
1075                     }
1076                     else if (!token[8]) {
1077                         cc->no_cache = 1;
1078                     }
1079                     break;
1080                 }
1081                 else if (!strcasecmp(token, "no-store")) {
1082                     cc->no_store = 1;
1083                 }
1084                 else if (!strcasecmp(token, "no-transform")) {
1085                     cc->no_transform = 1;
1086                 }
1087                 break;
1088             }
1089             case 'm':
1090             case 'M': {
1091                 /* handle most common quickest cases... */
1092                 if (!strcmp(token, "max-age=0")) {
1093                     cc->max_age = 1;
1094                     cc->max_age_value = 0;
1095                 }
1096                 else if (!strcmp(token, "must-revalidate")) {
1097                     cc->must_revalidate = 1;
1098                 }
1099                 /* ...then try slowest cases */
1100                 else if (!strncasecmp(token, "max-age", 7)) {
1101                     if (token[7] == '=') {
1102                         cc->max_age = 1;
1103                         cc->max_age_value = apr_atoi64(token + 8);
1104                     }
1105                     break;
1106                 }
1107                 else if (!strncasecmp(token, "max-stale", 9)) {
1108                     if (token[9] == '=') {
1109                         cc->max_stale = 1;
1110                         cc->max_stale_value = apr_atoi64(token + 10);
1111                     }
1112                     else if (!token[10]) {
1113                         cc->max_stale = 1;
1114                         cc->max_stale_value = -1;
1115                     }
1116                     break;
1117                 }
1118                 else if (!strncasecmp(token, "min-fresh", 9)) {
1119                     if (token[9] == '=') {
1120                         cc->min_fresh = 1;
1121                         cc->min_fresh_value = apr_atoi64(token + 10);
1122                     }
1123                     break;
1124                 }
1125                 else if (!strcasecmp(token, "must-revalidate")) {
1126                     cc->must_revalidate = 1;
1127                 }
1128                 break;
1129             }
1130             case 'o':
1131             case 'O': {
1132                 if (!strcasecmp(token, "only-if-cached")) {
1133                     cc->only_if_cached = 1;
1134                 }
1135                 break;
1136             }
1137             case 'p':
1138             case 'P': {
1139                 /* handle most common quickest cases... */
1140                 if (!strcmp(token, "private")) {
1141                     cc->private = 1;
1142                 }
1143                 /* ...then try slowest cases */
1144                 else if (!strcasecmp(token, "public")) {
1145                     cc->public = 1;
1146                 }
1147                 else if (!strncasecmp(token, "private", 7)) {
1148                     if (token[7] == '=') {
1149                         if (apr_table_get(headers, token + 8)) {
1150                             cc->private_header = 1;
1151                         }
1152                     }
1153                     else if (!token[7]) {
1154                         cc->private = 1;
1155                     }
1156                     break;
1157                 }
1158                 else if (!strcasecmp(token, "proxy-revalidate")) {
1159                     cc->proxy_revalidate = 1;
1160                 }
1161                 break;
1162             }
1163             case 's':
1164             case 'S': {
1165                 if (!strncasecmp(token, "s-maxage", 8)) {
1166                     if (token[8] == '=') {
1167                         cc->s_maxage = 1;
1168                         cc->s_maxage_value = apr_atoi64(token + 9);
1169                     }
1170                     break;
1171                 }
1172                 break;
1173             }
1174             }
1175             token = apr_strtok(NULL, ", ", &last);
1176         }
1177         cc->cache_control = 1;
1178     }
1179
1180     return (cc_header != NULL || pragma_header != NULL);
1181 }