]> granicus.if.org Git - apache/blob - modules/cache/cache_util.c
Style fixes.
[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 <ap_provider.h>
20
21 /* -------------------------------------------------------------- */
22
23 extern APR_OPTIONAL_FN_TYPE(ap_cache_generate_key) *cache_generate_key;
24
25 extern module AP_MODULE_DECLARE_DATA cache_module;
26
27 /* Determine if "url" matches the hostname, scheme and port and path
28  * in "filter". All but the path comparisons are case-insensitive.
29  */
30 static int uri_meets_conditions(const apr_uri_t filter, const int pathlen,
31         const apr_uri_t url) {
32
33     /* Scheme, hostname port and local part. The filter URI and the
34      * URI we test may have the following shapes:
35      *   /<path>
36      *   <scheme>[:://<hostname>[:<port>][/<path>]]
37      * That is, if there is no scheme then there must be only the path,
38      * and we check only the path; if there is a scheme, we check the
39      * scheme for equality, and then if present we match the hostname,
40      * and then if present match the port, and finally the path if any.
41      *
42      * Note that this means that "/<path>" only matches local paths,
43      * and to match proxied paths one *must* specify the scheme.
44      */
45
46     /* Is the filter is just for a local path or a proxy URI? */
47     if (!filter.scheme) {
48         if (url.scheme || url.hostname) {
49             return 0;
50         }
51     }
52     else {
53         /* The URI scheme must be present and identical except for case. */
54         if (!url.scheme || strcasecmp(filter.scheme, url.scheme)) {
55             return 0;
56         }
57
58         /* If the filter hostname is null or empty it matches any hostname,
59          * if it begins with a "*" it matches the _end_ of the URI hostname
60          * excluding the "*", if it begins with a "." it matches the _end_
61          * of the URI * hostname including the ".", otherwise it must match
62          * the URI hostname exactly. */
63
64         if (filter.hostname && filter.hostname[0]) {
65             if (filter.hostname[0] == '.') {
66                 const size_t fhostlen = strlen(filter.hostname);
67                 const size_t uhostlen = url.hostname ? strlen(url.hostname) : 0;
68
69                 if (fhostlen > uhostlen || strcasecmp(filter.hostname,
70                         url.hostname + uhostlen - fhostlen)) {
71                     return 0;
72                 }
73             }
74             else if (filter.hostname[0] == '*') {
75                 const size_t fhostlen = strlen(filter.hostname + 1);
76                 const size_t uhostlen = url.hostname ? strlen(url.hostname) : 0;
77
78                 if (fhostlen > uhostlen || strcasecmp(filter.hostname + 1,
79                         url.hostname + uhostlen - fhostlen)) {
80                     return 0;
81                 }
82             }
83             else if (!url.hostname || strcasecmp(filter.hostname, url.hostname)) {
84                 return 0;
85             }
86         }
87
88         /* If the filter port is empty it matches any URL port.
89          * If the filter or URL port are missing, or the URL port is
90          * empty, they default to the port for their scheme. */
91
92         if (!(filter.port_str && !filter.port_str[0])) {
93             /* NOTE:  ap_port_of_scheme will return 0 if given NULL input */
94             const unsigned fport = filter.port_str ? filter.port
95                     : apr_uri_port_of_scheme(filter.scheme);
96             const unsigned uport = (url.port_str && url.port_str[0])
97                     ? url.port : apr_uri_port_of_scheme(url.scheme);
98
99             if (fport != uport) {
100                 return 0;
101             }
102         }
103     }
104
105     /* For HTTP caching purposes, an empty (NULL) path is equivalent to
106      * a single "/" path. RFCs 3986/2396
107      */
108     if (!url.path) {
109         if (*filter.path == '/' && pathlen == 1) {
110             return 1;
111         }
112         else {
113             return 0;
114         }
115     }
116
117     /* Url has met all of the filter conditions so far, determine
118      * if the paths match.
119      */
120     return !strncmp(filter.path, url.path, pathlen);
121 }
122
123 CACHE_DECLARE(cache_provider_list *)ap_cache_get_providers(request_rec *r,
124                                                   cache_server_conf *conf,
125                                                   apr_uri_t uri)
126 {
127     cache_provider_list *providers = NULL;
128     int i;
129
130     /* loop through all the cacheenable entries */
131     for (i = 0; i < conf->cacheenable->nelts; i++) {
132         struct cache_enable *ent =
133                                 (struct cache_enable *)conf->cacheenable->elts;
134         if (uri_meets_conditions(ent[i].url, ent[i].pathlen, uri)) {
135             /* Fetch from global config and add to the list. */
136             cache_provider *provider;
137             provider = ap_lookup_provider(CACHE_PROVIDER_GROUP, ent[i].type,
138                                           "0");
139             if (!provider) {
140                 /* Log an error! */
141             }
142             else {
143                 cache_provider_list *newp;
144                 newp = apr_pcalloc(r->pool, sizeof(cache_provider_list));
145                 newp->provider_name = ent[i].type;
146                 newp->provider = provider;
147
148                 if (!providers) {
149                     providers = newp;
150                 }
151                 else {
152                     cache_provider_list *last = providers;
153
154                     while (last->next) {
155                         last = last->next;
156                     }
157                     last->next = newp;
158                 }
159             }
160         }
161     }
162
163     /* then loop through all the cachedisable entries
164      * Looking for urls that contain the full cachedisable url and possibly
165      * more.
166      * This means we are disabling cachedisable url and below...
167      */
168     for (i = 0; i < conf->cachedisable->nelts; i++) {
169         struct cache_disable *ent =
170                                (struct cache_disable *)conf->cachedisable->elts;
171         if (uri_meets_conditions(ent[i].url, ent[i].pathlen, uri)) {
172             /* Stop searching now. */
173             return NULL;
174         }
175     }
176
177     return providers;
178 }
179
180
181 /* do a HTTP/1.1 age calculation */
182 CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info,
183                                                 const apr_time_t age_value,
184                                                 apr_time_t now)
185 {
186     apr_time_t apparent_age, corrected_received_age, response_delay,
187                corrected_initial_age, resident_time, current_age,
188                age_value_usec;
189
190     age_value_usec = apr_time_from_sec(age_value);
191
192     /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
193
194     apparent_age = MAX(0, info->response_time - info->date);
195     corrected_received_age = MAX(apparent_age, age_value_usec);
196     response_delay = info->response_time - info->request_time;
197     corrected_initial_age = corrected_received_age + response_delay;
198     resident_time = now - info->response_time;
199     current_age = corrected_initial_age + resident_time;
200
201     return apr_time_sec(current_age);
202 }
203
204 /**
205  * Try obtain a cache wide lock on the given cache key.
206  *
207  * If we return APR_SUCCESS, we obtained the lock, and we are clear to
208  * proceed to the backend. If we return APR_EEXISTS, then the lock is
209  * already locked, someone else has gone to refresh the backend data
210  * already, so we must return stale data with a warning in the mean
211  * time. If we return anything else, then something has gone pear
212  * shaped, and we allow the request through to the backend regardless.
213  *
214  * This lock is created from the request pool, meaning that should
215  * something go wrong and the lock isn't deleted on return of the
216  * request headers from the backend for whatever reason, at worst the
217  * lock will be cleaned up when the request dies or finishes.
218  *
219  * If something goes truly bananas and the lock isn't deleted when the
220  * request dies, the lock will be trashed when its max-age is reached,
221  * or when a request arrives containing a Cache-Control: no-cache. At
222  * no point is it possible for this lock to permanently deny access to
223  * the backend.
224  */
225 CACHE_DECLARE(apr_status_t) ap_cache_try_lock(cache_server_conf *conf,
226         request_rec *r, char *key) {
227     apr_status_t status;
228     const char *lockname;
229     const char *path;
230     char dir[5];
231     apr_time_t now = apr_time_now();
232     apr_finfo_t finfo;
233     apr_file_t *lockfile;
234     void *dummy;
235
236     finfo.mtime = 0;
237
238     if (!conf || !conf->lock || !conf->lockpath) {
239         /* no locks configured, leave */
240         return APR_SUCCESS;
241     }
242
243     /* lock already obtained earlier? if so, success */
244     apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
245     if (dummy) {
246         return APR_SUCCESS;
247     }
248
249     /* create the key if it doesn't exist */
250     if (!key) {
251         cache_generate_key(r, r->pool, &key);
252     }
253
254     /* create a hashed filename from the key, and save it for later */
255     lockname = ap_cache_generate_name(r->pool, 0, 0, key);
256
257     /* lock files represent discrete just-went-stale URLs "in flight", so
258      * we support a simple two level directory structure, more is overkill.
259      */
260     dir[0] = '/';
261     dir[1] = lockname[0];
262     dir[2] = '/';
263     dir[3] = lockname[1];
264     dir[4] = 0;
265
266     /* make the directories */
267     path = apr_pstrcat(r->pool, conf->lockpath, dir, NULL);
268     if (APR_SUCCESS != (status = apr_dir_make_recursive(path,
269             APR_UREAD|APR_UWRITE|APR_UEXECUTE, r->pool))) {
270         ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
271                      "Could not create a cache lock directory: %s",
272                      path);
273         return status;
274     }
275     lockname = apr_pstrcat(r->pool, path, "/", lockname, NULL);
276     apr_pool_userdata_set(lockname, CACHE_LOCKNAME_KEY, NULL, r->pool);
277
278     /* is an existing lock file too old? */
279     status = apr_stat(&finfo, lockname,
280                 APR_FINFO_MTIME | APR_FINFO_NLINK, r->pool);
281     if (!(APR_STATUS_IS_ENOENT(status)) && APR_SUCCESS != status) {
282         ap_log_error(APLOG_MARK, APLOG_ERR, APR_EEXIST, r->server,
283                      "Could not stat a cache lock file: %s",
284                      lockname);
285         return status;
286     }
287     if ((status == APR_SUCCESS) && (((now - finfo.mtime) > conf->lockmaxage)
288                                   || (now < finfo.mtime))) {
289         ap_log_error(APLOG_MARK, APLOG_INFO, status, r->server,
290                      "Cache lock file for '%s' too old, removing: %s",
291                      r->uri, lockname);
292         apr_file_remove(lockname, r->pool);
293     }
294
295     /* try obtain a lock on the file */
296     if (APR_SUCCESS == (status = apr_file_open(&lockfile, lockname,
297             APR_WRITE | APR_CREATE | APR_EXCL | APR_DELONCLOSE,
298             APR_UREAD | APR_UWRITE, r->pool))) {
299         apr_pool_userdata_set(lockfile, CACHE_LOCKFILE_KEY, NULL, r->pool);
300     }
301     return status;
302
303 }
304
305 /**
306  * Remove the cache lock, if present.
307  *
308  * First, try to close the file handle, whose delete-on-close should
309  * kill the file. Otherwise, just delete the file by name.
310  *
311  * If no lock name has yet been calculated, do the calculation of the
312  * lock name first before trying to delete the file.
313  *
314  * If an optional bucket brigade is passed, the lock will only be
315  * removed if the bucket brigade contains an EOS bucket.
316  */
317 CACHE_DECLARE(apr_status_t) ap_cache_remove_lock(cache_server_conf *conf,
318         request_rec *r, char *key, apr_bucket_brigade *bb) {
319     void *dummy;
320     const char *lockname;
321
322     if (!conf || !conf->lock || !conf->lockpath) {
323         /* no locks configured, leave */
324         return APR_SUCCESS;
325     }
326     if (bb) {
327         apr_bucket *e;
328         int eos_found = 0;
329         for (e = APR_BRIGADE_FIRST(bb);
330              e != APR_BRIGADE_SENTINEL(bb);
331              e = APR_BUCKET_NEXT(e))
332         {
333             if (APR_BUCKET_IS_EOS(e)) {
334                 eos_found = 1;
335                 break;
336             }
337         }
338         if (!eos_found) {
339             /* no eos found in brigade, don't delete anything just yet,
340              * we are not done.
341              */
342             return APR_SUCCESS;
343         }
344     }
345     apr_pool_userdata_get(&dummy, CACHE_LOCKFILE_KEY, r->pool);
346     if (dummy) {
347         return apr_file_close((apr_file_t *)dummy);
348     }
349     apr_pool_userdata_get(&dummy, CACHE_LOCKNAME_KEY, r->pool);
350     lockname = (const char *)dummy;
351     if (!lockname) {
352         char dir[5];
353
354         /* create the key if it doesn't exist */
355         if (!key) {
356             cache_generate_key(r, r->pool, &key);
357         }
358
359         /* create a hashed filename from the key, and save it for later */
360         lockname = ap_cache_generate_name(r->pool, 0, 0, key);
361
362         /* lock files represent discrete just-went-stale URLs "in flight", so
363          * we support a simple two level directory structure, more is overkill.
364          */
365         dir[0] = '/';
366         dir[1] = lockname[0];
367         dir[2] = '/';
368         dir[3] = lockname[1];
369         dir[4] = 0;
370
371         lockname = apr_pstrcat(r->pool, conf->lockpath, dir, "/", lockname, NULL);
372     }
373     return apr_file_remove(lockname, r->pool);
374 }
375
376 CACHE_DECLARE(int) ap_cache_check_freshness(cache_handle_t *h,
377                                             request_rec *r)
378 {
379     apr_status_t status;
380     apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
381     apr_int64_t minfresh;
382     const char *cc_cresp, *cc_req;
383     const char *pragma;
384     const char *agestr = NULL;
385     const char *expstr = NULL;
386     char *val;
387     apr_time_t age_c = 0;
388     cache_info *info = &(h->cache_obj->info);
389     const char *warn_head;
390     cache_server_conf *conf =
391       (cache_server_conf *)ap_get_module_config(r->server->module_config,
392                                                 &cache_module);
393
394     /*
395      * We now want to check if our cached data is still fresh. This depends
396      * on a few things, in this order:
397      *
398      * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache in
399      * either the request or the cached response means that we must
400      * revalidate the request unconditionally, overriding any expiration
401      * mechanism. It's equivalent to max-age=0,must-revalidate.
402      *
403      * - RFC2616 14.32 Pragma: no-cache This is treated the same as
404      * Cache-Control: no-cache.
405      *
406      * - RFC2616 14.9.3 Cache-Control: max-stale, must-revalidate,
407      * proxy-revalidate if the max-stale request header exists, modify the
408      * stale calculations below so that an object can be at most <max-stale>
409      * seconds stale before we request a revalidation, _UNLESS_ a
410      * must-revalidate or proxy-revalidate cached response header exists to
411      * stop us doing this.
412      *
413      * - RFC2616 14.9.3 Cache-Control: s-maxage the origin server specifies the
414      * maximum age an object can be before it is considered stale. This
415      * directive has the effect of proxy|must revalidate, which in turn means
416      * simple ignore any max-stale setting.
417      *
418      * - RFC2616 14.9.4 Cache-Control: max-age this header can appear in both
419      * requests and responses. If both are specified, the smaller of the two
420      * takes priority.
421      *
422      * - RFC2616 14.21 Expires: if this request header exists in the cached
423      * entity, and it's value is in the past, it has expired.
424      *
425      */
426
427     /* This value comes from the client's initial request. */
428     cc_req = apr_table_get(r->headers_in, "Cache-Control");
429     pragma = apr_table_get(r->headers_in, "Pragma");
430
431     if (ap_cache_liststr(NULL, pragma, "no-cache", NULL)
432         || ap_cache_liststr(NULL, cc_req, "no-cache", NULL)) {
433
434         if (!conf->ignorecachecontrol) {
435             /* Treat as stale, causing revalidation */
436             return 0;
437         }
438
439         ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
440                      "Incoming request is asking for a uncached version of "
441                      "%s, but we know better and are ignoring it",
442                      r->unparsed_uri);
443     }
444
445     /* These come from the cached entity. */
446     cc_cresp = apr_table_get(h->resp_hdrs, "Cache-Control");
447     expstr = apr_table_get(h->resp_hdrs, "Expires");
448
449     if (ap_cache_liststr(NULL, cc_cresp, "no-cache", NULL)) {
450         /*
451          * The cached entity contained Cache-Control: no-cache, so treat as
452          * stale causing revalidation
453          */
454         return 0;
455     }
456
457     if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
458         age_c = apr_atoi64(agestr);
459     }
460
461     /* calculate age of object */
462     age = ap_cache_current_age(info, age_c, r->request_time);
463
464     /* extract s-maxage */
465     if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "s-maxage", &val)
466         && val != NULL) {
467         smaxage = apr_atoi64(val);
468     }
469     else {
470         smaxage = -1;
471     }
472
473     /* extract max-age from request */
474     if (!conf->ignorecachecontrol
475         && cc_req && ap_cache_liststr(r->pool, cc_req, "max-age", &val)
476         && val != NULL) {
477         maxage_req = apr_atoi64(val);
478     }
479     else {
480         maxage_req = -1;
481     }
482
483     /* extract max-age from response */
484     if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "max-age", &val)
485         && val != NULL) {
486         maxage_cresp = apr_atoi64(val);
487     }
488     else {
489         maxage_cresp = -1;
490     }
491
492     /*
493      * if both maxage request and response, the smaller one takes priority
494      */
495     if (maxage_req == -1) {
496         maxage = maxage_cresp;
497     }
498     else if (maxage_cresp == -1) {
499         maxage = maxage_req;
500     }
501     else {
502         maxage = MIN(maxage_req, maxage_cresp);
503     }
504
505     /* extract max-stale */
506     if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-stale", &val)) {
507         if(val != NULL) {
508             maxstale = apr_atoi64(val);
509         }
510         else {
511             /*
512              * If no value is assigned to max-stale, then the client is willing
513              * to accept a stale response of any age (RFC2616 14.9.3). We will
514              * set it to one year in this case as this situation is somewhat
515              * similar to a "never expires" Expires header (RFC2616 14.21)
516              * which is set to a date one year from the time the response is
517              * sent in this case.
518              */
519             maxstale = APR_INT64_C(86400*365);
520         }
521     }
522     else {
523         maxstale = 0;
524     }
525
526     /* extract min-fresh */
527     if (!conf->ignorecachecontrol
528         && cc_req && ap_cache_liststr(r->pool, cc_req, "min-fresh", &val)
529         && val != NULL) {
530         minfresh = apr_atoi64(val);
531     }
532     else {
533         minfresh = 0;
534     }
535
536     /* override maxstale if must-revalidate or proxy-revalidate */
537     if (maxstale && ((cc_cresp &&
538                       ap_cache_liststr(NULL, cc_cresp,
539                                        "must-revalidate", NULL)) ||
540                      (cc_cresp &&
541                       ap_cache_liststr(NULL, cc_cresp,
542                                        "proxy-revalidate", NULL)))) {
543         maxstale = 0;
544     }
545
546     /* handle expiration */
547     if (((smaxage != -1) && (age < (smaxage - minfresh))) ||
548         ((maxage != -1) && (age < (maxage + maxstale - minfresh))) ||
549         ((smaxage == -1) && (maxage == -1) &&
550          (info->expire != APR_DATE_BAD) &&
551          (age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh)))) {
552
553         warn_head = apr_table_get(h->resp_hdrs, "Warning");
554
555         /* it's fresh darlings... */
556         /* set age header on response */
557         apr_table_set(h->resp_hdrs, "Age",
558                       apr_psprintf(r->pool, "%lu", (unsigned long)age));
559
560         /* add warning if maxstale overrode freshness calculation */
561         if (!(((smaxage != -1) && age < smaxage) ||
562               ((maxage != -1) && age < maxage) ||
563               (info->expire != APR_DATE_BAD &&
564                (apr_time_sec(info->expire - info->date)) > age))) {
565             /* make sure we don't stomp on a previous warning */
566             if ((warn_head == NULL) ||
567                 ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
568                 apr_table_merge(h->resp_hdrs, "Warning",
569                                 "110 Response is stale");
570             }
571         }
572         /*
573          * If none of Expires, Cache-Control: max-age, or Cache-Control:
574          * s-maxage appears in the response, and the response header age
575          * calculated is more than 24 hours add the warning 113
576          */
577         if ((maxage_cresp == -1) && (smaxage == -1) &&
578             (expstr == NULL) && (age > 86400)) {
579
580             /* Make sure we don't stomp on a previous warning, and don't dup
581              * a 113 marning that is already present. Also, make sure to add
582              * the new warning to the correct *headers_out location.
583              */
584             if ((warn_head == NULL) ||
585                 ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
586                 apr_table_merge(h->resp_hdrs, "Warning",
587                                 "113 Heuristic expiration");
588             }
589         }
590         return 1;    /* Cache object is fresh (enough) */
591     }
592
593     /*
594      * At this point we are stale, but: if we are under load, we may let
595      * a significant number of stale requests through before the first
596      * stale request successfully revalidates itself, causing a sudden
597      * unexpected thundering herd which in turn brings angst and drama.
598      *
599      * So.
600      *
601      * We want the first stale request to go through as normal. But the
602      * second and subsequent request, we must pretend to be fresh until
603      * the first request comes back with either new content or confirmation
604      * that the stale content is still fresh.
605      *
606      * To achieve this, we create a very simple file based lock based on
607      * the key of the cached object. We attempt to open the lock file with
608      * exclusive write access. If we succeed, woohoo! we're first, and we
609      * follow the stale path to the backend server. If we fail, oh well,
610      * we follow the fresh path, and avoid being a thundering herd.
611      *
612      * The lock lives only as long as the stale request that went on ahead.
613      * If the request succeeds, the lock is deleted. If the request fails,
614      * the lock is deleted, and another request gets to make a new lock
615      * and try again.
616      *
617      * At any time, a request marked "no-cache" will force a refresh,
618      * ignoring the lock, ensuring an extended lockout is impossible.
619      *
620      * A lock that exceeds a maximum age will be deleted, and another
621      * request gets to make a new lock and try again.
622      */
623     status = ap_cache_try_lock(conf, r, (char *)h->cache_obj->key);
624     if (APR_SUCCESS == status) {
625         /* we obtained a lock, follow the stale path */
626         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
627                      "Cache lock obtained for stale cached URL, "
628                      "revalidating entry: %s",
629                      r->unparsed_uri);
630         return 0;
631     }
632     else if (APR_EEXIST == status) {
633         /* lock already exists, return stale data anyway, with a warning */
634         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
635                      "Cache already locked for stale cached URL, "
636                      "pretend it is fresh: %s",
637                      r->unparsed_uri);
638
639         /* make sure we don't stomp on a previous warning */
640         warn_head = apr_table_get(h->resp_hdrs, "Warning");
641         if ((warn_head == NULL) ||
642             ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
643             apr_table_merge(h->resp_hdrs, "Warning",
644                         "110 Response is stale");
645         }
646
647         return 1;
648     }
649     else {
650         /* some other error occurred, just treat the object as stale */
651         ap_log_error(APLOG_MARK, APLOG_DEBUG, status, r->server,
652                      "Attempt to obtain a cache lock for stale "
653                      "cached URL failed, revalidating entry anyway: %s",
654                      r->unparsed_uri);
655         return 0;
656     }
657
658 }
659
660 /*
661  * list is a comma-separated list of case-insensitive tokens, with
662  * optional whitespace around the tokens.
663  * The return returns 1 if the token val is found in the list, or 0
664  * otherwise.
665  */
666 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
667                                     const char *key, char **val)
668 {
669     apr_size_t key_len;
670     const char *next;
671
672     if (!list) {
673         return 0;
674     }
675
676     key_len = strlen(key);
677     next = list;
678
679     for (;;) {
680
681         /* skip whitespace and commas to find the start of the next key */
682         while (*next && (apr_isspace(*next) || (*next == ','))) {
683             next++;
684         }
685
686         if (!*next) {
687             return 0;
688         }
689
690         if (!strncasecmp(next, key, key_len)) {
691             /* this field matches the key (though it might just be
692              * a prefix match, so make sure the match is followed
693              * by either a space or an equals sign)
694              */
695             next += key_len;
696             if (!*next || (*next == '=') || apr_isspace(*next) ||
697                 (*next == ',')) {
698                 /* valid match */
699                 if (val) {
700                     while (*next && (*next != '=') && (*next != ',')) {
701                         next++;
702                     }
703                     if (*next == '=') {
704                         next++;
705                         while (*next && apr_isspace(*next )) {
706                             next++;
707                         }
708                         if (!*next) {
709                             *val = NULL;
710                         }
711                         else {
712                             const char *val_start = next;
713                             while (*next && !apr_isspace(*next) &&
714                                    (*next != ',')) {
715                                 next++;
716                             }
717                             *val = apr_pstrmemdup(p, val_start,
718                                                   next - val_start);
719                         }
720                     }
721                     else {
722                         *val = NULL;
723                     }
724                 }
725                 return 1;
726             }
727         }
728
729         /* skip to the next field */
730         do {
731             next++;
732             if (!*next) {
733                 return 0;
734             }
735         } while (*next != ',');
736     }
737 }
738
739 /* return each comma separated token, one at a time */
740 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
741                                            const char **str)
742 {
743     apr_size_t i;
744     const char *s;
745
746     s = ap_strchr_c(list, ',');
747     if (s != NULL) {
748         i = s - list;
749         do
750             s++;
751         while (apr_isspace(*s))
752             ; /* noop */
753     }
754     else
755         i = strlen(list);
756
757     while (i > 0 && apr_isspace(list[i - 1]))
758         i--;
759
760     *str = s;
761     if (i)
762         return apr_pstrndup(p, list, i);
763     else
764         return NULL;
765 }
766
767 /*
768  * Converts apr_time_t expressed as hex digits to
769  * a true apr_time_t.
770  */
771 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x)
772 {
773     int i, ch;
774     apr_time_t j;
775     for (i = 0, j = 0; i < sizeof(j) * 2; i++) {
776         ch = x[i];
777         j <<= 4;
778         if (apr_isdigit(ch))
779             j |= ch - '0';
780         else if (apr_isupper(ch))
781             j |= ch - ('A' - 10);
782         else
783             j |= ch - ('a' - 10);
784     }
785     return j;
786 }
787
788 /*
789  * Converts apr_time_t to apr_time_t expressed as hex digits.
790  */
791 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y)
792 {
793     int i, ch;
794
795     for (i = (sizeof(j) * 2)-1; i >= 0; i--) {
796         ch = (int)(j & 0xF);
797         j >>= 4;
798         if (ch >= 10)
799             y[i] = ch + ('A' - 10);
800         else
801             y[i] = ch + '0';
802     }
803     y[sizeof(j) * 2] = '\0';
804 }
805
806 static void cache_hash(const char *it, char *val, int ndepth, int nlength)
807 {
808     apr_md5_ctx_t context;
809     unsigned char digest[16];
810     char tmp[22];
811     int i, k, d;
812     unsigned int x;
813     static const char enc_table[64] =
814     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
815
816     apr_md5_init(&context);
817     apr_md5_update(&context, (const unsigned char *) it, strlen(it));
818     apr_md5_final(digest, &context);
819
820     /* encode 128 bits as 22 characters, using a modified uuencoding
821      * the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
822      * 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
823      */
824     for (i = 0, k = 0; i < 15; i += 3) {
825         x = (digest[i] << 16) | (digest[i + 1] << 8) | digest[i + 2];
826         tmp[k++] = enc_table[x >> 18];
827         tmp[k++] = enc_table[(x >> 12) & 0x3f];
828         tmp[k++] = enc_table[(x >> 6) & 0x3f];
829         tmp[k++] = enc_table[x & 0x3f];
830     }
831
832     /* one byte left */
833     x = digest[15];
834     tmp[k++] = enc_table[x >> 2];    /* use up 6 bits */
835     tmp[k++] = enc_table[(x << 4) & 0x3f];
836
837     /* now split into directory levels */
838     for (i = k = d = 0; d < ndepth; ++d) {
839         memcpy(&val[i], &tmp[k], nlength);
840         k += nlength;
841         val[i + nlength] = '/';
842         i += nlength + 1;
843     }
844     memcpy(&val[i], &tmp[k], 22 - k);
845     val[i + 22 - k] = '\0';
846 }
847
848 CACHE_DECLARE(char *)ap_cache_generate_name(apr_pool_t *p, int dirlevels,
849                                             int dirlength, const char *name)
850 {
851     char hashfile[66];
852     cache_hash(name, hashfile, dirlevels, dirlength);
853     return apr_pstrdup(p, hashfile);
854 }
855
856 /*
857  * Create a new table consisting of those elements from an
858  * headers table that are allowed to be stored in a cache.
859  */
860 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers(apr_pool_t *pool,
861                                                         apr_table_t *t,
862                                                         server_rec *s)
863 {
864     cache_server_conf *conf;
865     char **header;
866     int i;
867     apr_table_t *headers_out;
868
869     /* Short circuit the common case that there are not
870      * (yet) any headers populated.
871      */
872     if (t == NULL) {
873         return apr_table_make(pool, 10);
874     };
875
876     /* Make a copy of the headers, and remove from
877      * the copy any hop-by-hop headers, as defined in Section
878      * 13.5.1 of RFC 2616
879      */
880     headers_out = apr_table_copy(pool, t);
881
882     apr_table_unset(headers_out, "Connection");
883     apr_table_unset(headers_out, "Keep-Alive");
884     apr_table_unset(headers_out, "Proxy-Authenticate");
885     apr_table_unset(headers_out, "Proxy-Authorization");
886     apr_table_unset(headers_out, "TE");
887     apr_table_unset(headers_out, "Trailers");
888     apr_table_unset(headers_out, "Transfer-Encoding");
889     apr_table_unset(headers_out, "Upgrade");
890
891     conf = (cache_server_conf *)ap_get_module_config(s->module_config,
892                                                      &cache_module);
893
894     /* Remove the user defined headers set with CacheIgnoreHeaders.
895      * This may break RFC 2616 compliance on behalf of the administrator.
896      */
897     header = (char **)conf->ignore_headers->elts;
898     for (i = 0; i < conf->ignore_headers->nelts; i++) {
899         apr_table_unset(headers_out, header[i]);
900     }
901     return headers_out;
902 }
903
904 /*
905  * Legacy call - functionally equivalent to ap_cache_cacheable_headers.
906  * @deprecated @see ap_cache_cacheable_headers
907  */
908 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_hdrs_out(apr_pool_t *p,
909                                                         apr_table_t *t,
910                                                         server_rec *s)
911 {
912     return ap_cache_cacheable_headers(p,t,s);
913 }
914
915 /*
916  * Create a new table consisting of those elements from an input
917  * headers table that are allowed to be stored in a cache.
918  */
919 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_in(request_rec *r)
920 {
921     return ap_cache_cacheable_headers(r->pool, r->headers_in, r->server);
922 }
923
924 /*
925  * Create a new table consisting of those elements from an output
926  * headers table that are allowed to be stored in a cache;
927  * ensure there is a content type and capture any errors.
928  */
929 CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_headers_out(request_rec *r)
930 {
931     apr_table_t *headers_out;
932
933     headers_out = apr_table_overlay(r->pool, r->headers_out,
934                                         r->err_headers_out);
935
936     apr_table_clear(r->err_headers_out);
937
938     headers_out = ap_cache_cacheable_headers(r->pool, headers_out,
939                                                   r->server);
940
941     if (!apr_table_get(headers_out, "Content-Type")
942         && r->content_type) {
943         apr_table_setn(headers_out, "Content-Type",
944                        ap_make_content_type(r, r->content_type));
945     }
946
947     if (!apr_table_get(headers_out, "Content-Encoding")
948         && r->content_encoding) {
949         apr_table_setn(headers_out, "Content-Encoding",
950                        r->content_encoding);
951     }
952
953     return headers_out;
954 }