]> granicus.if.org Git - apache/blob - modules/cache/cache_util.c
mod_cache: Make CacheEnable and CacheDisable configurable per
[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 #define CACHE_SEPARATOR ",   "
31
32 /* Determine if "url" matches the hostname, scheme and port and path
33  * in "filter". All but the path comparisons are case-insensitive.
34  */
35 static int uri_meets_conditions(const apr_uri_t *filter, const int pathlen,
36                                 const apr_uri_t *url)
37 {
38
39     /* Scheme, hostname port and local part. The filter URI and the
40      * URI we test may have the following shapes:
41      *   /<path>
42      *   <scheme>[:://<hostname>[:<port>][/<path>]]
43      * That is, if there is no scheme then there must be only the path,
44      * and we check only the path; if there is a scheme, we check the
45      * scheme for equality, and then if present we match the hostname,
46      * and then if present match the port, and finally the path if any.
47      *
48      * Note that this means that "/<path>" only matches local paths,
49      * and to match proxied paths one *must* specify the scheme.
50      */
51
52     /* Is the filter is just for a local path or a proxy URI? */
53     if (!filter->scheme) {
54         if (url->scheme || url->hostname) {
55             return 0;
56         }
57     }
58     else {
59         /* The URI scheme must be present and identical except for case. */
60         if (!url->scheme || strcasecmp(filter->scheme, url->scheme)) {
61             return 0;
62         }
63
64         /* If the filter hostname is null or empty it matches any hostname,
65          * if it begins with a "*" it matches the _end_ of the URI hostname
66          * excluding the "*", if it begins with a "." it matches the _end_
67          * of the URI * hostname including the ".", otherwise it must match
68          * the URI hostname exactly. */
69
70         if (filter->hostname && filter->hostname[0]) {
71             if (filter->hostname[0] == '.') {
72                 const size_t fhostlen = strlen(filter->hostname);
73                 const size_t uhostlen = url->hostname ? strlen(url->hostname) : 0;
74
75                 if (fhostlen > uhostlen || strcasecmp(filter->hostname,
76                         url->hostname + uhostlen - fhostlen)) {
77                     return 0;
78                 }
79             }
80             else if (filter->hostname[0] == '*') {
81                 const size_t fhostlen = strlen(filter->hostname + 1);
82                 const size_t uhostlen = url->hostname ? strlen(url->hostname) : 0;
83
84                 if (fhostlen > uhostlen || strcasecmp(filter->hostname + 1,
85                         url->hostname + uhostlen - fhostlen)) {
86                     return 0;
87                 }
88             }
89             else if (!url->hostname || strcasecmp(filter->hostname, url->hostname)) {
90                 return 0;
91             }
92         }
93
94         /* If the filter port is empty it matches any URL port.
95          * If the filter or URL port are missing, or the URL port is
96          * empty, they default to the port for their scheme. */
97
98         if (!(filter->port_str && !filter->port_str[0])) {
99             /* NOTE:  ap_port_of_scheme will return 0 if given NULL input */
100             const unsigned fport = filter->port_str ? filter->port
101                     : apr_uri_port_of_scheme(filter->scheme);
102             const unsigned uport = (url->port_str && url->port_str[0])
103                     ? url->port : apr_uri_port_of_scheme(url->scheme);
104
105             if (fport != uport) {
106                 return 0;
107             }
108         }
109     }
110
111     /* For HTTP caching purposes, an empty (NULL) path is equivalent to
112      * a single "/" path. RFCs 3986/2396
113      */
114     if (!url->path) {
115         if (*filter->path == '/' && pathlen == 1) {
116             return 1;
117         }
118         else {
119             return 0;
120         }
121     }
122
123     /* Url has met all of the filter conditions so far, determine
124      * if the paths match.
125      */
126     return !strncmp(filter->path, url->path, pathlen);
127 }
128
129 static cache_provider_list *get_provider(request_rec *r, struct cache_enable *ent,
130         cache_provider_list *providers)
131 {
132     /* Fetch from global config and add to the list. */
133     cache_provider *provider;
134     provider = ap_lookup_provider(CACHE_PROVIDER_GROUP, ent->type,
135                                   "0");
136     if (!provider) {
137         /* Log an error! */
138     }
139     else {
140         cache_provider_list *newp;
141         newp = apr_pcalloc(r->pool, sizeof(cache_provider_list));
142         newp->provider_name = ent->type;
143         newp->provider = provider;
144
145         if (!providers) {
146             providers = newp;
147         }
148         else {
149             cache_provider_list *last = providers;
150
151             while (last->next) {
152                 if (last->provider == provider) {
153                     return providers;
154                 }
155                 last = last->next;
156             }
157             if (last->provider == provider) {
158                 return providers;
159             }
160             last->next = newp;
161         }
162     }
163
164     return providers;
165 }
166
167 cache_provider_list *cache_get_providers(request_rec *r,
168         cache_server_conf *conf,
169         apr_uri_t uri)
170 {
171     cache_dir_conf *dconf = dconf = ap_get_module_config(r->per_dir_config, &cache_module);
172     cache_provider_list *providers = NULL;
173     int i;
174
175     /* per directory cache disable */
176     if (dconf->disable) {
177         return NULL;
178     }
179
180     /* global cache disable */
181     for (i = 0; i < conf->cachedisable->nelts; i++) {
182         struct cache_disable *ent =
183                                (struct cache_disable *)conf->cachedisable->elts;
184         if (uri_meets_conditions(&ent[i].url, ent[i].pathlen, &uri)) {
185             /* Stop searching now. */
186             return NULL;
187         }
188     }
189
190     /* loop through all the per directory cacheenable entries */
191     for (i = 0; i < dconf->cacheenable->nelts; i++) {
192         struct cache_enable *ent =
193                                 (struct cache_enable *)dconf->cacheenable->elts;
194         providers = get_provider(r, &ent[i], providers);
195     }
196
197     /* loop through all the global cacheenable entries */
198     for (i = 0; i < conf->cacheenable->nelts; i++) {
199         struct cache_enable *ent =
200                                 (struct cache_enable *)conf->cacheenable->elts;
201         if (uri_meets_conditions(&ent[i].url, ent[i].pathlen, &uri)) {
202             providers = get_provider(r, &ent[i], providers);
203         }
204     }
205
206     return providers;
207 }
208
209
210 /* do a HTTP/1.1 age calculation */
211 CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info,
212                                                 const apr_time_t age_value,
213                                                 apr_time_t now)
214 {
215     apr_time_t apparent_age, corrected_received_age, response_delay,
216                corrected_initial_age, resident_time, current_age,
217                age_value_usec;
218
219     age_value_usec = apr_time_from_sec(age_value);
220
221     /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
222
223     apparent_age = MAX(0, info->response_time - info->date);
224     corrected_received_age = MAX(apparent_age, age_value_usec);
225     response_delay = info->response_time - info->request_time;
226     corrected_initial_age = corrected_received_age + response_delay;
227     resident_time = now - info->response_time;
228     current_age = corrected_initial_age + resident_time;
229
230     if (current_age < 0) {
231         current_age = 0;
232     }
233
234     return apr_time_sec(current_age);
235 }
236
237 /**
238  * Try obtain a cache wide lock on the given cache key.
239  *
240  * If we return APR_SUCCESS, we obtained the lock, and we are clear to
241  * proceed to the backend. If we return APR_EEXISTS, then the lock is
242  * already locked, someone else has gone to refresh the backend data
243  * already, so we must return stale data with a warning in the mean
244  * time. If we return anything else, then something has gone pear
245  * shaped, and we allow the request through to the backend regardless.
246  *
247  * This lock is created from the request pool, meaning that should
248  * something go wrong and the lock isn't deleted on return of the
249  * request headers from the backend for whatever reason, at worst the
250  * lock will be cleaned up when the request dies or finishes.
251  *
252  * If something goes truly bananas and the lock isn't deleted when the
253  * request dies, the lock will be trashed when its max-age is reached,
254  * or when a request arrives containing a Cache-Control: no-cache. At
255  * no point is it possible for this lock to permanently deny access to
256  * the backend.
257  */
258 apr_status_t cache_try_lock(cache_server_conf *conf, cache_request_rec *cache,
259         request_rec *r)
260 {
261     apr_status_t status;
262     const char *lockname;
263     const char *path;
264     char dir[5];
265     apr_time_t now = apr_time_now();
266     apr_finfo_t finfo;
267     apr_file_t *lockfile;
268     void *dummy;
269
270     finfo.mtime = 0;
271
272     if (!conf || !conf->lock || !conf->lockpath) {
273         /* no locks configured, leave */
274         return APR_SUCCESS;
275     }
276
277     /* lock already obtained earlier? if so, success */
278     apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
279     if (dummy) {
280         return APR_SUCCESS;
281     }
282
283     /* create the key if it doesn't exist */
284     if (!cache->key) {
285         cache_generate_key(r, r->pool, &cache->key);
286     }
287
288     /* create a hashed filename from the key, and save it for later */
289     lockname = ap_cache_generate_name(r->pool, 0, 0, cache->key);
290
291     /* lock files represent discrete just-went-stale URLs "in flight", so
292      * we support a simple two level directory structure, more is overkill.
293      */
294     dir[0] = '/';
295     dir[1] = lockname[0];
296     dir[2] = '/';
297     dir[3] = lockname[1];
298     dir[4] = 0;
299
300     /* make the directories */
301     path = apr_pstrcat(r->pool, conf->lockpath, dir, NULL);
302     if (APR_SUCCESS != (status = apr_dir_make_recursive(path,
303             APR_UREAD|APR_UWRITE|APR_UEXECUTE, r->pool))) {
304         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
305                 "Could not create a cache lock directory: %s",
306                 path);
307         return status;
308     }
309     lockname = apr_pstrcat(r->pool, path, "/", lockname, NULL);
310     apr_pool_userdata_set(lockname, CACHE_LOCKNAME_KEY, NULL, r->pool);
311
312     /* is an existing lock file too old? */
313     status = apr_stat(&finfo, lockname,
314                 APR_FINFO_MTIME | APR_FINFO_NLINK, r->pool);
315     if (!(APR_STATUS_IS_ENOENT(status)) && APR_SUCCESS != status) {
316         ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EEXIST, r,
317                 "Could not stat a cache lock file: %s",
318                 lockname);
319         return status;
320     }
321     if ((status == APR_SUCCESS) && (((now - finfo.mtime) > conf->lockmaxage)
322                                   || (now < finfo.mtime))) {
323         ap_log_rerror(APLOG_MARK, APLOG_INFO, status, r,
324                 "Cache lock file for '%s' too old, removing: %s",
325                 r->uri, lockname);
326         apr_file_remove(lockname, r->pool);
327     }
328
329     /* try obtain a lock on the file */
330     if (APR_SUCCESS == (status = apr_file_open(&lockfile, lockname,
331             APR_WRITE | APR_CREATE | APR_EXCL | APR_DELONCLOSE,
332             APR_UREAD | APR_UWRITE, r->pool))) {
333         apr_pool_userdata_set(lockfile, CACHE_LOCKFILE_KEY, NULL, r->pool);
334     }
335     return status;
336
337 }
338
339 /**
340  * Remove the cache lock, if present.
341  *
342  * First, try to close the file handle, whose delete-on-close should
343  * kill the file. Otherwise, just delete the file by name.
344  *
345  * If no lock name has yet been calculated, do the calculation of the
346  * lock name first before trying to delete the file.
347  *
348  * If an optional bucket brigade is passed, the lock will only be
349  * removed if the bucket brigade contains an EOS bucket.
350  */
351 apr_status_t cache_remove_lock(cache_server_conf *conf,
352         cache_request_rec *cache, request_rec *r, apr_bucket_brigade *bb)
353 {
354     void *dummy;
355     const char *lockname;
356
357     if (!conf || !conf->lock || !conf->lockpath) {
358         /* no locks configured, leave */
359         return APR_SUCCESS;
360     }
361     if (bb) {
362         apr_bucket *e;
363         int eos_found = 0;
364         for (e = APR_BRIGADE_FIRST(bb);
365              e != APR_BRIGADE_SENTINEL(bb);
366              e = APR_BUCKET_NEXT(e))
367         {
368             if (APR_BUCKET_IS_EOS(e)) {
369                 eos_found = 1;
370                 break;
371             }
372         }
373         if (!eos_found) {
374             /* no eos found in brigade, don't delete anything just yet,
375              * we are not done.
376              */
377             return APR_SUCCESS;
378         }
379     }
380     apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
381     if (dummy) {
382         return apr_file_close((apr_file_t *)dummy);
383     }
384     apr_pool_userdata_get(&dummy, CACHE_LOCKNAME_KEY, r->pool);
385     lockname = (const char *)dummy;
386     if (!lockname) {
387         char dir[5];
388
389         /* create the key if it doesn't exist */
390         if (!cache->key) {
391             cache_generate_key(r, r->pool, &cache->key);
392         }
393
394         /* create a hashed filename from the key, and save it for later */
395         lockname = ap_cache_generate_name(r->pool, 0, 0, cache->key);
396
397         /* lock files represent discrete just-went-stale URLs "in flight", so
398          * we support a simple two level directory structure, more is overkill.
399          */
400         dir[0] = '/';
401         dir[1] = lockname[0];
402         dir[2] = '/';
403         dir[3] = lockname[1];
404         dir[4] = 0;
405
406         lockname = apr_pstrcat(r->pool, conf->lockpath, dir, "/", lockname, NULL);
407     }
408     return apr_file_remove(lockname, r->pool);
409 }
410
411 CACHE_DECLARE(int) ap_cache_check_allowed(cache_request_rec *cache, request_rec *r) {
412     const char *cc_req;
413     const char *pragma;
414     cache_server_conf *conf =
415       (cache_server_conf *)ap_get_module_config(r->server->module_config,
416                                                 &cache_module);
417
418     /*
419      * At this point, we may have data cached, but the request may have
420      * specified that cached data may not be used in a response.
421      *
422      * This is covered under RFC2616 section 14.9.4 (Cache Revalidation and
423      * Reload Controls).
424      *
425      * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache, or Pragma:
426      * no-cache. The server MUST NOT use a cached copy when responding to such
427      * a request.
428      *
429      * - RFC2616 14.9.2 What May be Stored by Caches. If Cache-Control:
430      * no-store arrives, do not serve from the cache.
431      */
432
433     /* This value comes from the client's initial request. */
434     cc_req = apr_table_get(r->headers_in, "Cache-Control");
435     pragma = apr_table_get(r->headers_in, "Pragma");
436
437     ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
438
439     if (cache->control_in.no_cache) {
440
441         if (!conf->ignorecachecontrol) {
442             return 0;
443         }
444         else {
445             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
446                     "Incoming request is asking for an uncached version of "
447                     "%s, but we have been configured to ignore it and serve "
448                     "cached content anyway", r->unparsed_uri);
449         }
450     }
451
452     if (cache->control_in.no_store) {
453
454         if (!conf->ignorecachecontrol) {
455             /* We're not allowed to serve a cached copy */
456             return 0;
457         }
458         else {
459             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
460                     "Incoming request is asking for a no-store version of "
461                     "%s, but we have been configured to ignore it and serve "
462                     "cached content anyway", r->unparsed_uri);
463         }
464     }
465
466     return 1;
467 }
468
469
470 int cache_check_freshness(cache_handle_t *h, cache_request_rec *cache,
471         request_rec *r)
472 {
473     apr_status_t status;
474     apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
475     apr_int64_t minfresh;
476     const char *cc_req;
477     const char *pragma;
478     const char *agestr = NULL;
479     apr_time_t age_c = 0;
480     cache_info *info = &(h->cache_obj->info);
481     const char *warn_head;
482     cache_server_conf *conf =
483       (cache_server_conf *)ap_get_module_config(r->server->module_config,
484                                                 &cache_module);
485
486     /*
487      * We now want to check if our cached data is still fresh. This depends
488      * on a few things, in this order:
489      *
490      * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache
491      * in either the request or the cached response means that we must
492      * perform the request unconditionally, and ignore cached content. We
493      * should never reach here, but if we do, mark the content as stale,
494      * as this is the best we can do.
495      *
496      * - RFC2616 14.32 Pragma: no-cache This is treated the same as
497      * Cache-Control: no-cache.
498      *
499      * - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
500      * proxy-revalidate if the max-stale request header exists, modify the
501      * stale calculations below so that an object can be at most <max-stale>
502      * seconds stale before we request a revalidation, _UNLESS_ a
503      * must-revalidate or proxy-revalidate cached response header exists to
504      * stop us doing this.
505      *
506      * - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
507      * maximum age an object can be before it is considered stale. This
508      * directive has the effect of proxy|must revalidate, which in turn means
509      * simple ignore any max-stale setting.
510      *
511      * - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
512      * requests and responses. If both are specified, the smaller of the two
513      * takes priority.
514      *
515      * - RFC2616 14.21 Expires: if this request header exists in the cached
516      * entity, and it's value is in the past, it has expired.
517      *
518      */
519
520     /* This value comes from the client's initial request. */
521     cc_req = apr_table_get(r->headers_in, "Cache-Control");
522     pragma = apr_table_get(r->headers_in, "Pragma");
523
524     ap_cache_control(r, &cache->control_in, cc_req, pragma, r->headers_in);
525
526     if (cache->control_in.no_cache) {
527
528         if (!conf->ignorecachecontrol) {
529             /* Treat as stale, causing revalidation */
530             return 0;
531         }
532
533         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
534                 "Incoming request is asking for a uncached version of "
535                 "%s, but we have been configured to ignore it and "
536                 "serve a cached response anyway",
537                 r->unparsed_uri);
538     }
539
540     /* These come from the cached entity. */
541     if (h->cache_obj->info.control.no_cache
542             || h->cache_obj->info.control.no_cache_header
543             || h->cache_obj->info.control.private_header) {
544         /*
545          * The cached entity contained Cache-Control: no-cache, or a
546          * no-cache with a header present, or a private with a header
547          * present, so treat as stale causing revalidation.
548          */
549         return 0;
550     }
551
552     if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
553         age_c = apr_atoi64(agestr);
554     }
555
556     /* calculate age of object */
557     age = ap_cache_current_age(info, age_c, r->request_time);
558
559     /* extract s-maxage */
560     smaxage = h->cache_obj->info.control.s_maxage_value;
561
562     /* extract max-age from request */
563     maxage_req = -1;
564     if (!conf->ignorecachecontrol) {
565         maxage_req = cache->control_in.max_age_value;
566     }
567
568     /*
569      * extract max-age from response, if both s-maxage and max-age, s-maxage
570      * takes priority
571      */
572     if (smaxage != -1) {
573         maxage_cresp = smaxage;
574     }
575     else {
576         maxage_cresp = h->cache_obj->info.control.max_age_value;
577     }
578
579     /*
580      * if both maxage request and response, the smaller one takes priority
581      */
582     if (maxage_req == -1) {
583         maxage = maxage_cresp;
584     }
585     else if (maxage_cresp == -1) {
586         maxage = maxage_req;
587     }
588     else {
589         maxage = MIN(maxage_req, maxage_cresp);
590     }
591
592     /* extract max-stale */
593     if (cache->control_in.max_stale) {
594         if(cache->control_in.max_stale_value != -1) {
595             maxstale = cache->control_in.max_stale_value;
596         }
597         else {
598             /*
599              * If no value is assigned to max-stale, then the client is willing
600              * to accept a stale response of any age (RFC2616 14.9.3). We will
601              * set it to one year in this case as this situation is somewhat
602              * similar to a "never expires" Expires header (RFC2616 14.21)
603              * which is set to a date one year from the time the response is
604              * sent in this case.
605              */
606             maxstale = APR_INT64_C(86400*365);
607         }
608     }
609     else {
610         maxstale = 0;
611     }
612
613     /* extract min-fresh */
614     if (!conf->ignorecachecontrol && cache->control_in.min_fresh) {
615         minfresh = cache->control_in.min_fresh_value;
616     }
617     else {
618         minfresh = 0;
619     }
620
621     /* override maxstale if must-revalidate, proxy-revalidate or s-maxage */
622     if (maxstale && (h->cache_obj->info.control.must_revalidate
623             || h->cache_obj->info.control.proxy_revalidate || smaxage != -1)) {
624         maxstale = 0;
625     }
626
627     /* handle expiration */
628     if (((maxage != -1) && (age < (maxage + maxstale - minfresh))) ||
629         ((smaxage == -1) && (maxage == -1) &&
630          (info->expire != APR_DATE_BAD) &&
631          (age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh)))) {
632
633         warn_head = apr_table_get(h->resp_hdrs, "Warning");
634
635         /* it's fresh darlings... */
636         /* set age header on response */
637         apr_table_set(h->resp_hdrs, "Age",
638                       apr_psprintf(r->pool, "%lu", (unsigned long)age));
639
640         /* add warning if maxstale overrode freshness calculation */
641         if (!(((maxage != -1) && age < maxage) ||
642               (info->expire != APR_DATE_BAD &&
643                (apr_time_sec(info->expire - info->date)) > age))) {
644             /* make sure we don't stomp on a previous warning */
645             if ((warn_head == NULL) ||
646                 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
647                 apr_table_merge(h->resp_hdrs, "Warning",
648                                 "110 Response is stale");
649             }
650         }
651
652         /*
653          * If none of Expires, Cache-Control: max-age, or Cache-Control:
654          * s-maxage appears in the response, and the response header age
655          * calculated is more than 24 hours add the warning 113
656          */
657         if ((maxage_cresp == -1) && (smaxage == -1) && (apr_table_get(
658                 h->resp_hdrs, "Expires") == NULL) && (age > 86400)) {
659
660             /* Make sure we don't stomp on a previous warning, and don't dup
661              * a 113 marning that is already present. Also, make sure to add
662              * the new warning to the correct *headers_out location.
663              */
664             if ((warn_head == NULL) ||
665                 ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
666                 apr_table_merge(h->resp_hdrs, "Warning",
667                                 "113 Heuristic expiration");
668             }
669         }
670         return 1;    /* Cache object is fresh (enough) */
671     }
672
673     /*
674      * At this point we are stale, but: if we are under load, we may let
675      * a significant number of stale requests through before the first
676      * stale request successfully revalidates itself, causing a sudden
677      * unexpected thundering herd which in turn brings angst and drama.
678      *
679      * So.
680      *
681      * We want the first stale request to go through as normal. But the
682      * second and subsequent request, we must pretend to be fresh until
683      * the first request comes back with either new content or confirmation
684      * that the stale content is still fresh.
685      *
686      * To achieve this, we create a very simple file based lock based on
687      * the key of the cached object. We attempt to open the lock file with
688      * exclusive write access. If we succeed, woohoo! we're first, and we
689      * follow the stale path to the backend server. If we fail, oh well,
690      * we follow the fresh path, and avoid being a thundering herd.
691      *
692      * The lock lives only as long as the stale request that went on ahead.
693      * If the request succeeds, the lock is deleted. If the request fails,
694      * the lock is deleted, and another request gets to make a new lock
695      * and try again.
696      *
697      * At any time, a request marked "no-cache" will force a refresh,
698      * ignoring the lock, ensuring an extended lockout is impossible.
699      *
700      * A lock that exceeds a maximum age will be deleted, and another
701      * request gets to make a new lock and try again.
702      */
703     status = cache_try_lock(conf, cache, r);
704     if (APR_SUCCESS == status) {
705         /* we obtained a lock, follow the stale path */
706         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
707                 "Cache lock obtained for stale cached URL, "
708                 "revalidating entry: %s",
709                 r->unparsed_uri);
710         return 0;
711     }
712     else if (APR_EEXIST == status) {
713         /* lock already exists, return stale data anyway, with a warning */
714         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
715                 "Cache already locked for stale cached URL, "
716                 "pretend it is fresh: %s",
717                 r->unparsed_uri);
718
719         /* make sure we don't stomp on a previous warning */
720         warn_head = apr_table_get(h->resp_hdrs, "Warning");
721         if ((warn_head == NULL) ||
722             ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
723             apr_table_merge(h->resp_hdrs, "Warning",
724                         "110 Response is stale");
725         }
726
727         return 1;
728     }
729     else {
730         /* some other error occurred, just treat the object as stale */
731         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r,
732                 "Attempt to obtain a cache lock for stale "
733                 "cached URL failed, revalidating entry anyway: %s",
734                 r->unparsed_uri);
735         return 0;
736     }
737
738 }
739
740 /*
741  * list is a comma-separated list of case-insensitive tokens, with
742  * optional whitespace around the tokens.
743  * The return returns 1 if the token val is found in the list, or 0
744  * otherwise.
745  */
746 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
747                                     const char *key, char **val)
748 {
749     apr_size_t key_len;
750     const char *next;
751
752     if (!list) {
753         return 0;
754     }
755
756     key_len = strlen(key);
757     next = list;
758
759     for (;;) {
760
761         /* skip whitespace and commas to find the start of the next key */
762         while (*next && (apr_isspace(*next) || (*next == ','))) {
763             next++;
764         }
765
766         if (!*next) {
767             return 0;
768         }
769
770         if (!strncasecmp(next, key, key_len)) {
771             /* this field matches the key (though it might just be
772              * a prefix match, so make sure the match is followed
773              * by either a space or an equals sign)
774              */
775             next += key_len;
776             if (!*next || (*next == '=') || apr_isspace(*next) ||
777                 (*next == ',')) {
778                 /* valid match */
779                 if (val) {
780                     while (*next && (*next != '=') && (*next != ',')) {
781                         next++;
782                     }
783                     if (*next == '=') {
784                         next++;
785                         while (*next && apr_isspace(*next )) {
786                             next++;
787                         }
788                         if (!*next) {
789                             *val = NULL;
790                         }
791                         else {
792                             const char *val_start = next;
793                             while (*next && !apr_isspace(*next) &&
794                                    (*next != ',')) {
795                                 /* EAT QUOTED STRING */
796                                 if (*next == '"' || *next == '\'') {
797                                     char delim = *next;
798                                     while (*++next != delim) {
799                                         if (!*next) {
800                                             return 0;
801                                         }
802                                         else if (*next == '\\') {
803                                             ++next;
804                                         }
805                                     }
806                                 }
807                                 next++;
808                             }
809                             *val = apr_pstrmemdup(p, val_start,
810                                                   next - val_start);
811                         }
812                     }
813                     else {
814                         *val = NULL;
815                     }
816                 }
817                 return 1;
818             }
819         }
820
821         /* skip to the next field */
822         do {
823             /* EAT QUOTED STRING */
824             if (*next == '"' || *next == '\'') {
825                 char delim = *next;
826                 while (*++next != delim) {
827                     if (!*next) {
828                         return 0;
829                     }
830                     else if (*next == '\\') {
831                         ++next;
832                     }
833                 }
834             }
835             next++;
836             if (!*next) {
837                 return 0;
838             }
839         } while (*next != ',');
840     }
841 }
842
843 /* return each comma separated token, one at a time */
844 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
845                                            const char **str)
846 {
847     apr_size_t i;
848     const char *s;
849
850     s = ap_strchr_c(list, ',');
851     if (s != NULL) {
852         i = s - list;
853         do
854             s++;
855         while (apr_isspace(*s))
856             ; /* noop */
857     }
858     else
859         i = strlen(list);
860
861     while (i > 0 && apr_isspace(list[i - 1]))
862         i--;
863
864     *str = s;
865     if (i)
866         return apr_pstrndup(p, list, i);
867     else
868         return NULL;
869 }
870
871 /*
872  * Converts apr_time_t expressed as hex digits to
873  * a true apr_time_t.
874  */
875 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
876 {
877     int i, ch;
878     apr_time_t j;
879     for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
880         ch = x[i];
881         j <<= 4;
882         if (apr_isdigit(ch))
883             j |= ch - '0';
884         else if (apr_isupper(ch))
885             j |= ch - ('A' - 10);
886         else
887             j |= ch - ('a' - 10);
888     }
889     return j;
890 }
891
892 /*
893  * Converts apr_time_t to apr_time_t expressed as hex digits.
894  */
895 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
896 {
897     int i, ch;
898
899     for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
900         ch = (int)(j & 0xF);
901         j >>= 4;
902         if (ch >= 10)
903             y[i] = ch + ('A' - 10);
904         else
905             y[i] = ch + '0';
906     }
907     y[sizeof(j) * 2] = '\0';
908 }
909
910 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
911 {
912     apr_md5_ctx_t context;
913     unsigned char digest[16];
914     char tmp[22];
915     int i, k, d;
916     unsigned int x;
917     static const char enc_table[64] =
918     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
919
920     apr_md5_init(&context);
921     apr_md5_update(&context, (const unsigned char *) it, strlen(it));
922     apr_md5_final(digest, &context);
923
924     /* encode 128 bits as 22 characters, using a modified uuencoding
925      * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
926      * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
927      */
928     for (i = 0, k = 0; i < 15; i += 3) {
929         x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
930         tmp[k++] = enc_table[x >> 18];
931         tmp[k++] = enc_table[(x >> 12) & 0x3f];
932         tmp[k++] = enc_table[(x >> 6) & 0x3f];
933         tmp[k++] = enc_table[x & 0x3f];
934     }
935
936     /* one byte left */
937     x = digest[15];
938     tmp[k++] = enc_table[x >> 2];    /* use up 6 bits */
939     tmp[k++] = enc_table[(x << 4) & 0x3f];
940
941     /* now split into directory levels */
942     for (i = k = d = 0; d < ndepth; ++d) {
943         memcpy(&val[i], &tmp[k], nlength);
944         k += nlength;
945         val[i + nlength] = '/';
946         i += nlength + 1;
947     }
948     memcpy(&val[i], &tmp[k], 22 - k);
949     val[i + 22 - k] = '\0';
950 }
951
952 CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
953                                             int dirlength, const char *name)
954 {
955     char hashfile[66];
956     cache_hash(name, hashfile, dirlevels, dirlength);
957     return apr_pstrdup(p, hashfile);
958 }
959
960 /*
961  * Create a new table consisting of those elements from an
962  * headers table that are allowed to be stored in a cache.
963  */
964 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers(apr_pool_t *pool,
965                                                         apr_table_t *t,
966                                                         server_rec *s)
967 {
968     cache_server_conf *conf;
969     char **header;
970     int i;
971     apr_table_t *headers_out;
972
973     /* Short circuit the common case that there are not
974      * (yet) any headers populated.
975      */
976     if (t == NULL) {
977         return apr_table_make(pool, 10);
978     };
979
980     /* Make a copy of the headers, and remove from
981      * the copy any hop-by-hop headers, as defined in Section
982      * 13.5.1 of RFC 2616
983      */
984     headers_out = apr_table_copy(pool, t);
985
986     apr_table_unset(headers_out, "Connection");
987     apr_table_unset(headers_out, "Keep-Alive");
988     apr_table_unset(headers_out, "Proxy-Authenticate");
989     apr_table_unset(headers_out, "Proxy-Authorization");
990     apr_table_unset(headers_out, "TE");
991     apr_table_unset(headers_out, "Trailers");
992     apr_table_unset(headers_out, "Transfer-Encoding");
993     apr_table_unset(headers_out, "Upgrade");
994
995     conf = (cache_server_conf *)ap_get_module_config(s->module_config,
996                                                      &cache_module);
997
998     /* Remove the user defined headers set with CacheIgnoreHeaders.
999      * This may break RFC 2616 compliance on behalf of the administrator.
1000      */
1001     header = (char **)conf->ignore_headers->elts;
1002     for (i = 0; i < conf->ignore_headers->nelts; i++) {
1003         apr_table_unset(headers_out, header[i]);
1004     }
1005     return headers_out;
1006 }
1007
1008 /*
1009  * Create a new table consisting of those elements from an input
1010  * headers table that are allowed to be stored in a cache.
1011  */
1012 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_in(request_rec *r)
1013 {
1014     return ap_cache_cacheable_headers(r->pool, r->headers_in, r->server);
1015 }
1016
1017 /*
1018  * Create a new table consisting of those elements from an output
1019  * headers table that are allowed to be stored in a cache;
1020  * ensure there is a content type and capture any errors.
1021  */
1022 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_out(request_rec *r)
1023 {
1024     apr_table_t *headers_out;
1025
1026     headers_out = apr_table_overlay(r->pool, r->headers_out,
1027                                         r->err_headers_out);
1028
1029     apr_table_clear(r->err_headers_out);
1030
1031     headers_out = ap_cache_cacheable_headers(r->pool, headers_out,
1032                                                   r->server);
1033
1034     if (!apr_table_get(headers_out, "Content-Type")
1035         && r->content_type) {
1036         apr_table_setn(headers_out, "Content-Type",
1037                        ap_make_content_type(r, r->content_type));
1038     }
1039
1040     if (!apr_table_get(headers_out, "Content-Encoding")
1041         && r->content_encoding) {
1042         apr_table_setn(headers_out, "Content-Encoding",
1043                        r->content_encoding);
1044     }
1045
1046     return headers_out;
1047 }
1048
1049 /**
1050  * String tokenizer that ignores separator characters within quoted strings
1051  * and escaped characters, as per RFC2616 section 2.2.
1052  */
1053 static char *cache_strqtok(char *str, const char *sep, char **last)
1054 {
1055     char *token;
1056     int quoted = 0;
1057
1058     if (!str) {         /* subsequent call */
1059         str = *last;    /* start where we left off */
1060     }
1061
1062     /* skip characters in sep (will terminate at '\0') */
1063     while (*str && ap_strchr_c(sep, *str)) {
1064         ++str;
1065     }
1066
1067     if (!*str) {        /* no more tokens */
1068         return NULL;
1069     }
1070
1071     token = str;
1072
1073     /* skip valid token characters to terminate token and
1074      * prepare for the next call (will terminate at '\0)
1075      * on the way, ignore all quoted strings, and within
1076      * quoted strings, escaped characters.
1077      */
1078     *last = token;
1079     while (**last) {
1080         if (!quoted) {
1081             if (**last == '\"') {
1082                 quoted = 1;
1083                 ++*last;
1084             }
1085             else if (!ap_strchr_c(sep, **last)) {
1086                 ++*last;
1087             }
1088             else {
1089                 break;
1090             }
1091         }
1092         else {
1093             if (**last == '\"') {
1094                 quoted = 0;
1095                 ++*last;
1096             }
1097             else if (**last == '\\') {
1098                 ++*last;
1099                 if (**last) {
1100                     ++*last;
1101                 }
1102             }
1103             else {
1104                 ++*last;
1105             }
1106         }
1107     }
1108
1109     if (**last) {
1110         **last = '\0';
1111         ++*last;
1112     }
1113
1114     return token;
1115 }
1116
1117 /**
1118  * Parse the Cache-Control and Pragma headers in one go, marking
1119  * which tokens appear within the header. Populate the structure
1120  * passed in.
1121  */
1122 int ap_cache_control(request_rec *r, cache_control_t *cc,
1123         const char *cc_header, const char *pragma_header, apr_table_t *headers)
1124 {
1125     char *last;
1126
1127     if (cc->parsed) {
1128         return cc->cache_control || cc->pragma;
1129     }
1130
1131     cc->parsed = 1;
1132     cc->max_age_value = -1;
1133     cc->max_stale_value = -1;
1134     cc->min_fresh_value = -1;
1135     cc->s_maxage_value = -1;
1136
1137     if (pragma_header) {
1138         char *header = apr_pstrdup(r->pool, pragma_header);
1139         const char *token = cache_strqtok(header, CACHE_SEPARATOR, &last);
1140         while (token) {
1141             /* handle most common quickest case... */
1142             if (!strcmp(token, "no-cache")) {
1143                 cc->no_cache = 1;
1144             }
1145             /* ...then try slowest case */
1146             else if (!strcasecmp(token, "no-cache")) {
1147                 cc->no_cache = 1;
1148             }
1149             token = cache_strqtok(NULL, CACHE_SEPARATOR, &last);
1150         }
1151         cc->pragma = 1;
1152     }
1153
1154     if (cc_header) {
1155         char *header = apr_pstrdup(r->pool, cc_header);
1156         const char *token = cache_strqtok(header, CACHE_SEPARATOR, &last);
1157         while (token) {
1158             switch (token[0]) {
1159             case 'n':
1160             case 'N': {
1161                 /* handle most common quickest cases... */
1162                 if (!strcmp(token, "no-cache")) {
1163                     cc->no_cache = 1;
1164                 }
1165                 else if (!strcmp(token, "no-store")) {
1166                     cc->no_store = 1;
1167                 }
1168                 /* ...then try slowest cases */
1169                 else if (!strncasecmp(token, "no-cache", 8)) {
1170                     if (token[8] == '=') {
1171                         if (apr_table_get(headers, token + 9)) {
1172                             cc->no_cache_header = 1;
1173                         }
1174                     }
1175                     else if (!token[8]) {
1176                         cc->no_cache = 1;
1177                     }
1178                     break;
1179                 }
1180                 else if (!strcasecmp(token, "no-store")) {
1181                     cc->no_store = 1;
1182                 }
1183                 else if (!strcasecmp(token, "no-transform")) {
1184                     cc->no_transform = 1;
1185                 }
1186                 break;
1187             }
1188             case 'm':
1189             case 'M': {
1190                 /* handle most common quickest cases... */
1191                 if (!strcmp(token, "max-age=0")) {
1192                     cc->max_age = 1;
1193                     cc->max_age_value = 0;
1194                 }
1195                 else if (!strcmp(token, "must-revalidate")) {
1196                     cc->must_revalidate = 1;
1197                 }
1198                 /* ...then try slowest cases */
1199                 else if (!strncasecmp(token, "max-age", 7)) {
1200                     if (token[7] == '=') {
1201                         cc->max_age = 1;
1202                         cc->max_age_value = apr_atoi64(token + 8);
1203                     }
1204                     break;
1205                 }
1206                 else if (!strncasecmp(token, "max-stale", 9)) {
1207                     if (token[9] == '=') {
1208                         cc->max_stale = 1;
1209                         cc->max_stale_value = apr_atoi64(token + 10);
1210                     }
1211                     else if (!token[10]) {
1212                         cc->max_stale = 1;
1213                         cc->max_stale_value = -1;
1214                     }
1215                     break;
1216                 }
1217                 else if (!strncasecmp(token, "min-fresh", 9)) {
1218                     if (token[9] == '=') {
1219                         cc->min_fresh = 1;
1220                         cc->min_fresh_value = apr_atoi64(token + 10);
1221                     }
1222                     break;
1223                 }
1224                 else if (!strcasecmp(token, "must-revalidate")) {
1225                     cc->must_revalidate = 1;
1226                 }
1227                 break;
1228             }
1229             case 'o':
1230             case 'O': {
1231                 if (!strcasecmp(token, "only-if-cached")) {
1232                     cc->only_if_cached = 1;
1233                 }
1234                 break;
1235             }
1236             case 'p':
1237             case 'P': {
1238                 /* handle most common quickest cases... */
1239                 if (!strcmp(token, "private")) {
1240                     cc->private = 1;
1241                 }
1242                 /* ...then try slowest cases */
1243                 else if (!strcasecmp(token, "public")) {
1244                     cc->public = 1;
1245                 }
1246                 else if (!strncasecmp(token, "private", 7)) {
1247                     if (token[7] == '=') {
1248                         if (apr_table_get(headers, token + 8)) {
1249                             cc->private_header = 1;
1250                         }
1251                     }
1252                     else if (!token[7]) {
1253                         cc->private = 1;
1254                     }
1255                     break;
1256                 }
1257                 else if (!strcasecmp(token, "proxy-revalidate")) {
1258                     cc->proxy_revalidate = 1;
1259                 }
1260                 break;
1261             }
1262             case 's':
1263             case 'S': {
1264                 if (!strncasecmp(token, "s-maxage", 8)) {
1265                     if (token[8] == '=') {
1266                         cc->s_maxage = 1;
1267                         cc->s_maxage_value = apr_atoi64(token + 9);
1268                     }
1269                     break;
1270                 }
1271                 break;
1272             }
1273             }
1274             token = cache_strqtok(NULL, CACHE_SEPARATOR, &last);
1275         }
1276         cc->cache_control = 1;
1277     }
1278
1279     return (cc_header != NULL || pragma_header != NULL);
1280 }