blob: 5a27624dec5bc34d35511a773fb236a707f2eef4 [file] [log] [blame]
William Lallemand41db4602017-10-30 11:15:51 +01001/*
2 * Cache management
3 *
4 * Copyright 2017 HAProxy Technologies
5 * William Lallemand <wlallemand@haproxy.com>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 */
12
Willy Tarreaub2551052020-06-09 09:07:15 +020013#include <import/eb32tree.h>
14#include <import/sha1.h>
15
Willy Tarreau122eba92020-06-04 10:15:32 +020016#include <haproxy/action-t.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020017#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020018#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020019#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020020#include <haproxy/cli.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020021#include <haproxy/errors.h>
Willy Tarreauc7babd82020-06-04 21:29:29 +020022#include <haproxy/filters.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020023#include <haproxy/hash.h>
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +020024#include <haproxy/http.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020025#include <haproxy/http_ana.h>
Willy Tarreau87735332020-06-04 09:08:41 +020026#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020027#include <haproxy/http_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/htx.h>
29#include <haproxy/net_helper.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020030#include <haproxy/proxy.h>
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +010031#include <haproxy/sample.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020032#include <haproxy/shctx.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020033#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020034#include <haproxy/stream_interface.h>
William Lallemand41db4602017-10-30 11:15:51 +010035
Christopher Faulet27d93c32018-12-15 22:32:02 +010036#define CACHE_FLT_F_IMPLICIT_DECL 0x00000001 /* The cache filtre was implicitly declared (ie without
Christopher Faulet99a17a22018-12-11 09:18:27 +010037 * the filter keyword) */
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +020038#define CACHE_FLT_INIT 0x00000002 /* Whether the cache name was freed. */
Christopher Fauletafd819c2018-12-11 08:57:45 +010039
Christopher Fauletf4a4ef72018-12-07 17:39:53 +010040const char *cache_store_flt_id = "cache store filter";
William Lallemand41db4602017-10-30 11:15:51 +010041
Willy Tarreau2231b632019-03-29 18:26:52 +010042extern struct applet http_cache_applet;
William Lallemand41db4602017-10-30 11:15:51 +010043
44struct flt_ops cache_ops;
45
46struct cache {
Willy Tarreaufd5efb52017-11-26 08:54:31 +010047 struct list list; /* cache linked list */
William Lallemand41db4602017-10-30 11:15:51 +010048 struct eb_root entries; /* head of cache entries based on keys */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010049 unsigned int maxage; /* max-age */
50 unsigned int maxblocks;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +020051 unsigned int maxobjsz; /* max-object-size (in bytes) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010052 char id[33]; /* cache name */
William Lallemand41db4602017-10-30 11:15:51 +010053};
54
Christopher Faulet95220e22018-12-07 17:34:39 +010055/* cache config for filters */
56struct cache_flt_conf {
57 union {
58 struct cache *cache; /* cache used by the filter */
59 char *name; /* cache name used during conf parsing */
60 } c;
61 unsigned int flags; /* CACHE_FLT_F_* */
62};
63
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010064
65/*
66 * Vary-related structures and functions
67 */
68enum vary_header_bit {
69 VARY_ACCEPT_ENCODING = (1 << 0),
70 VARY_REFERER = (1 << 1),
71 VARY_LAST /* should always be last */
72};
73
74typedef int(*http_header_normalizer)(struct ist value, char *buf, unsigned int *buf_len);
75
76struct vary_hashing_information {
77 struct ist hdr_name; /* Header name */
78 enum vary_header_bit value; /* Bit repesenting the header in a vary signature */
79 unsigned int hash_length; /* Size of the sub hash for this header's value */
80 http_header_normalizer norm_fn; /* Normalization function */
81};
82
83static int accept_encoding_normalizer(struct ist value, char *buf, unsigned int *buf_len);
84static int default_normalizer(struct ist value, char *buf, unsigned int *buf_len);
85
86/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
87 * added to this array. */
88const struct vary_hashing_information vary_information[] = {
89 { IST("accept-encoding"), VARY_ACCEPT_ENCODING, sizeof(int), &accept_encoding_normalizer },
90 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer },
91};
92
93static int http_request_prebuild_full_secondary_key(struct stream *s);
94static int http_request_build_secondary_key(struct stream *s, int vary_signature);
95static int http_request_reduce_secondary_key(unsigned int vary_signature,
96 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
97
98
William Lallemand41db4602017-10-30 11:15:51 +010099/*
100 * cache ctx for filters
101 */
102struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100103 struct shared_block *first_block;
104};
105
106struct cache_entry {
107 unsigned int latest_validation; /* latest validation date */
108 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200109 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100110
William Lallemand41db4602017-10-30 11:15:51 +0100111 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100112 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200113
114 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
115 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
116
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200117 time_t last_modified; /* Origin server "Last-Modified" header value converted in
118 * seconds since epoch. If no "Last-Modified"
119 * header is found, use "Date" header value,
120 * otherwise use reception time. This field will
121 * be used in case of an "If-Modified-Since"-based
122 * conditional request. */
123
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100124 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
125 * to build secondary keys for this cache entry. */
126 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
127
William Lallemand41db4602017-10-30 11:15:51 +0100128 unsigned char data[0];
129};
130
131#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100132#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100133
134static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200135static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100136static struct cache *tmp_cache_config = NULL;
137
Willy Tarreau8ceae722018-11-26 11:58:30 +0100138DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
139
William Lallemandf528fff2017-11-23 19:43:17 +0100140struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100141{
142 struct eb32_node *node;
143 struct cache_entry *entry;
144
Willy Tarreau8b507582020-02-25 09:35:07 +0100145 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100146 if (!node)
147 return NULL;
148
149 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100150
151 /* if that's not the right node */
152 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
153 return NULL;
154
William Lallemand08727662017-11-21 20:01:27 +0100155 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100156 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100157 } else {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100158 eb32_delete(node);
William Lallemand08727662017-11-21 20:01:27 +0100159 entry->eb.key = 0;
160 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100161 return NULL;
162
163}
164
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100165struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
166 char *secondary_key)
167{
168 struct eb32_node *node = &entry->eb;
169
170 if (!entry->secondary_key_signature)
171 return NULL;
172
173 while (entry && memcmp(entry->secondary_key, secondary_key, HTTP_CACHE_SEC_KEY_LEN) != 0) {
174 node = eb32_next_dup(node);
175 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
176 }
177
178 /* Expired entry */
179 if (entry && entry->expire <= now.tv_sec) {
180 eb32_delete(&entry->eb);
181 entry->eb.key = 0;
182 entry = NULL;
183 }
184
185 return entry;
186}
187
William Lallemand4da3f8a2017-10-31 14:33:34 +0100188static inline struct shared_context *shctx_ptr(struct cache *cache)
189{
190 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
191}
192
William Lallemand77c11972017-10-31 20:43:01 +0100193static inline struct shared_block *block_ptr(struct cache_entry *entry)
194{
195 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
196}
197
198
199
William Lallemand41db4602017-10-30 11:15:51 +0100200static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100201cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100202{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100203 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100204 return 0;
205}
206
Christopher Faulet95220e22018-12-07 17:34:39 +0100207static void
208cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
209{
210 struct cache_flt_conf *cconf = fconf->conf;
211
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200212 if (!(cconf->flags & CACHE_FLT_INIT))
213 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100214 free(cconf);
215}
216
William Lallemand4da3f8a2017-10-31 14:33:34 +0100217static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100218cache_store_check(struct proxy *px, struct flt_conf *fconf)
219{
220 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100221 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100222 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100223 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100224
William Lallemandd1d1e222019-08-28 15:22:49 +0200225 /* Find the cache corresponding to the name in the filter config. The
226 * cache will not be referenced now in the filter config because it is
227 * not fully allocated. This step will be performed during the cache
228 * post_check.
229 */
230 list_for_each_entry(cache, &caches_config, list) {
231 if (!strcmp(cache->id, cconf->c.name))
Christopher Faulet95220e22018-12-07 17:34:39 +0100232 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100233 }
234
235 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
236 proxy_type_str(px), px->id, (char *)cconf->c.name);
237 return 1;
238
239 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100240 /* Here <cache> points on the cache the filter must use and <cconf>
241 * points on the cache filter configuration. */
242
243 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100244 * enabled and if it is after the cache. When the compression is before
245 * the cache, an error is returned. Also check if the cache filter must
246 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100247 list_for_each_entry(f, &px->filter_configs, list) {
248 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100249 /* The compression filter must be evaluated after the cache. */
250 if (comp) {
251 ha_alert("config: %s '%s': unable to enable the compression filter before "
252 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
253 return 1;
254 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100255 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200256 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100257 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200258 else if (f->id == fcgi_flt_id)
259 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100260 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
261 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200262 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100263 * declaration is required. */
264 ha_alert("config: %s '%s': require an explicit filter declaration "
265 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
266 return 1;
267 }
268
Christopher Fauletafd819c2018-12-11 08:57:45 +0100269 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100270 return 0;
271}
272
273static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100274cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100275{
Christopher Faulet65554e12020-03-06 14:52:06 +0100276 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100277
Christopher Faulet65554e12020-03-06 14:52:06 +0100278 st = pool_alloc_dirty(pool_head_cache_st);
279 if (st == NULL)
280 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100281
Christopher Faulet65554e12020-03-06 14:52:06 +0100282 st->first_block = NULL;
283 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100284
Christopher Faulet65554e12020-03-06 14:52:06 +0100285 /* Register post-analyzer on AN_RES_WAIT_HTTP */
286 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100287 return 1;
288}
289
Christopher Faulet65554e12020-03-06 14:52:06 +0100290static void
291cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100292{
293 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100294 struct cache_flt_conf *cconf = FLT_CONF(filter);
295 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100296 struct shared_context *shctx = shctx_ptr(cache);
297
William Lallemand49dc0482017-11-24 14:33:54 +0100298 /* Everything should be released in the http_end filter, but we need to do it
299 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100300 if (st && st->first_block) {
William Lallemand49dc0482017-11-24 14:33:54 +0100301 shctx_lock(shctx);
302 shctx_row_dec_hot(shctx, st->first_block);
303 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100304 }
305 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100306 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100307 filter->ctx = NULL;
308 }
William Lallemand49dc0482017-11-24 14:33:54 +0100309}
310
Christopher Faulet839791a2019-01-07 16:12:07 +0100311static int
312cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
313 unsigned an_bit)
314{
315 struct http_txn *txn = s->txn;
316 struct http_msg *msg = &txn->rsp;
317 struct cache_st *st = filter->ctx;
318
319 if (an_bit != AN_RES_WAIT_HTTP)
320 goto end;
321
322 /* Here we need to check if any compression filter precedes the cache
323 * filter. This is only possible when the compression is configured in
324 * the frontend while the cache filter is configured on the
325 * backend. This case cannot be detected during HAProxy startup. So in
326 * such cases, the cache is disabled.
327 */
328 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
329 pool_free(pool_head_cache_st, st);
330 filter->ctx = NULL;
331 }
332
333 end:
334 return 1;
335}
William Lallemand49dc0482017-11-24 14:33:54 +0100336
337static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100338cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
339{
340 struct cache_st *st = filter->ctx;
341
William Lallemand4da3f8a2017-10-31 14:33:34 +0100342 if (!(msg->chn->flags & CF_ISRESP) || !st)
343 return 1;
344
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200345 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100346 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100347 return 1;
348}
349
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200350static inline void disable_cache_entry(struct cache_st *st,
351 struct filter *filter, struct shared_context *shctx)
352{
353 struct cache_entry *object;
354
355 object = (struct cache_entry *)st->first_block->data;
356 filter->ctx = NULL; /* disable cache */
357 shctx_lock(shctx);
358 shctx_row_dec_hot(shctx, st->first_block);
359 object->eb.key = 0;
360 shctx_unlock(shctx);
361 pool_free(pool_head_cache_st, st);
362}
363
William Lallemand4da3f8a2017-10-31 14:33:34 +0100364static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100365cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
366 unsigned int offset, unsigned int len)
367{
Christopher Faulet95220e22018-12-07 17:34:39 +0100368 struct cache_flt_conf *cconf = FLT_CONF(filter);
369 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100370 struct cache_st *st = filter->ctx;
371 struct htx *htx = htxbuf(&msg->chn->buf);
372 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200373 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100374 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200375 unsigned int orig_len, to_forward;
376 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100377
378 if (!len)
379 return len;
380
381 if (!st->first_block) {
382 unregister_data_filter(s, msg->chn, filter);
383 return len;
384 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100385
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200386 chunk_reset(&trash);
387 orig_len = len;
388 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100389
390 htxret = htx_find_offset(htx, offset);
391 blk = htxret.blk;
392 offset = htxret.ret;
393 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100394 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200395 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100396 struct ist v;
397
398 switch (type) {
399 case HTX_BLK_UNUSED:
400 break;
401
402 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100403 v = htx_get_blk_value(htx, blk);
404 v.ptr += offset;
405 v.len -= offset;
406 if (v.len > len)
407 v.len = len;
408
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200409 info = (type << 28) + v.len;
410 chunk_memcat(&trash, (char *)&info, sizeof(info));
411 chunk_memcat(&trash, v.ptr, v.len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100412 to_forward += v.len;
413 len -= v.len;
414 break;
415
416 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200417 /* Here offset must always be 0 because only
418 * DATA blocks can be partially transferred. */
419 if (offset)
420 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100421 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200422 goto end;
423
424 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
425 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100426 to_forward += sz;
427 len -= sz;
428 break;
429 }
430
431 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100432 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200433
434 end:
435 shctx_lock(shctx);
436 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
437 if (!fb) {
438 shctx_unlock(shctx);
439 goto no_cache;
440 }
441 shctx_unlock(shctx);
442
443 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
444 (unsigned char *)b_head(&trash), b_data(&trash));
445 if (ret < 0)
446 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100447
448 return to_forward;
449
450 no_cache:
451 disable_cache_entry(st, filter, shctx);
452 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200453 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100454}
455
456static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100457cache_store_http_end(struct stream *s, struct filter *filter,
458 struct http_msg *msg)
459{
460 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100461 struct cache_flt_conf *cconf = FLT_CONF(filter);
462 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100463 struct shared_context *shctx = shctx_ptr(cache);
464 struct cache_entry *object;
465
466 if (!(msg->chn->flags & CF_ISRESP))
467 return 1;
468
469 if (st && st->first_block) {
470
471 object = (struct cache_entry *)st->first_block->data;
472
473 /* does not need to test if the insertion worked, if it
474 * doesn't, the blocks will be reused anyway */
475
476 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +0100477 if (eb32_insert(&cache->entries, &object->eb) != &object->eb) {
478 object->eb.key = 0;
479 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100480 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100481 shctx_row_dec_hot(shctx, st->first_block);
482 shctx_unlock(shctx);
483
484 }
485 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100486 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100487 filter->ctx = NULL;
488 }
489
490 return 1;
491}
492
493 /*
494 * This intends to be used when checking HTTP headers for some
495 * word=value directive. Return a pointer to the first character of value, if
496 * the word was not found or if there wasn't any value assigned ot it return NULL
497 */
498char *directive_value(const char *sample, int slen, const char *word, int wlen)
499{
500 int st = 0;
501
502 if (slen < wlen)
503 return 0;
504
505 while (wlen) {
506 char c = *sample ^ *word;
507 if (c && c != ('A' ^ 'a'))
508 return NULL;
509 sample++;
510 word++;
511 slen--;
512 wlen--;
513 }
514
515 while (slen) {
516 if (st == 0) {
517 if (*sample != '=')
518 return NULL;
519 sample++;
520 slen--;
521 st = 1;
522 continue;
523 } else {
524 return (char *)sample;
525 }
526 }
527
528 return NULL;
529}
530
531/*
532 * Return the maxage in seconds of an HTTP response.
533 * Compute the maxage using either:
534 * - the assigned max-age of the cache
535 * - the s-maxage directive
536 * - the max-age directive
537 * - (Expires - Data) headers
538 * - the default-max-age of the cache
539 *
540 */
William Lallemand49b44532017-11-24 18:53:43 +0100541int http_calc_maxage(struct stream *s, struct cache *cache)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100542{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200543 struct htx *htx = htxbuf(&s->res.buf);
544 struct http_hdr_ctx ctx = { .blk = NULL };
William Lallemand4da3f8a2017-10-31 14:33:34 +0100545 int smaxage = -1;
546 int maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100547 int expires = -1;
548 struct tm tm = {};
549 time_t expires_val = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100550
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200551 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
552 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100553
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200554 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
555 if (value) {
556 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100557
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200558 chunk_strncat(chk, value, ctx.value.len - 8 + 1);
559 chunk_strncat(chk, "", 1);
Remi Tricot-Le Breton8c2db712020-10-30 14:26:13 +0100560 smaxage = atoi(chk->area);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100561 }
562
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200563 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
564 if (value) {
565 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200566
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200567 chunk_strncat(chk, value, ctx.value.len - 7 + 1);
568 chunk_strncat(chk, "", 1);
Remi Tricot-Le Breton8c2db712020-10-30 14:26:13 +0100569 maxage = atoi(chk->area);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100570 }
571 }
572
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100573 /* Look for Expires header if no s-maxage or max-age Cache-Control data
574 * was found. */
575 if (maxage == -1 && smaxage == -1) {
576 ctx.blk = NULL;
577 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
578 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
579 expires_val = my_timegm(&tm);
580 /* A request having an expiring date earlier
581 * than the current date should be considered as
582 * stale. */
583 expires = (expires_val >= now.tv_sec) ?
584 (expires_val - now.tv_sec) : 0;
585 }
586 else {
587 /* Following RFC 7234#5.3, an invalid date
588 * format must be treated as a date in the past
589 * so the cache entry must be seen as already
590 * expired. */
591 expires = 0;
592 }
593 }
594 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100595
596
597 if (smaxage > 0)
William Lallemand49b44532017-11-24 18:53:43 +0100598 return MIN(smaxage, cache->maxage);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100599
600 if (maxage > 0)
William Lallemand49b44532017-11-24 18:53:43 +0100601 return MIN(maxage, cache->maxage);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100602
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100603 if (expires >= 0)
604 return MIN(expires, cache->maxage);
605
William Lallemand49b44532017-11-24 18:53:43 +0100606 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100607
608}
609
610
William Lallemanda400a3a2017-11-20 19:13:12 +0100611static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
612{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200613 struct cache_entry *object = (struct cache_entry *)block->data;
614
615 if (first == block && object->eb.key)
616 eb32_delete(&object->eb);
617 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100618}
619
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200620
621/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
622 * date value should be compared to a date determined by in a previous response (for
623 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
624 * value of the response's reception time (by decreasing order of priority). */
625static time_t get_last_modified_time(struct htx *htx)
626{
627 time_t last_modified = 0;
628 struct http_hdr_ctx ctx = { .blk = NULL };
629 struct tm tm = {};
630
631 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
632 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
633 last_modified = my_timegm(&tm);
634 }
635 }
636
637 if (!last_modified) {
638 ctx.blk = NULL;
639 if (http_find_header(htx, ist("date"), &ctx, 1)) {
640 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
641 last_modified = my_timegm(&tm);
642 }
643 }
644 }
645
646 /* Fallback on the current time if no "Last-Modified" or "Date" header
647 * was found. */
648 if (!last_modified)
649 last_modified = now.tv_sec;
650
651 return last_modified;
652}
653
William Lallemand41db4602017-10-30 11:15:51 +0100654/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100655 * Checks the vary header's value. The headers on which vary should be applied
656 * must be explicitely supported in the vary_information array (see cache.c). If
657 * any other header is mentioned, we won't store the response.
658 * Returns 1 if Vary-based storage can work, 0 otherwise.
659 */
660static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
661{
662 unsigned int vary_idx;
663 unsigned int vary_info_count;
664 const struct vary_hashing_information *vary_info;
665 struct http_hdr_ctx ctx = { .blk = NULL };
666
667 int retval = 1;
668
669 *vary_signature = 0;
670
671 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
672 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
673 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
674 vary_info = &vary_information[vary_idx];
675 if (isteqi(ctx.value, vary_info->hdr_name)) {
676 *vary_signature |= vary_info->value;
677 break;
678 }
679 }
680 retval = (vary_idx < vary_info_count);
681 }
682
683 return retval;
684}
685
686
687
688/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500689 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100690 * register a filter to store the data
691 */
692enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200693 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100694{
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200695 unsigned int age;
696 long long hdr_age;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100697 struct http_txn *txn = s->txn;
698 struct http_msg *msg = &txn->rsp;
699 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100700 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100701 struct cache_flt_conf *cconf = rule->arg.act.p[0];
702 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100703 struct cache_st *cache_ctx = NULL;
704 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +0100705 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200706 struct htx *htx;
707 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +0200708 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200709 int32_t pos;
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200710 unsigned int etag_length = 0;
711 unsigned int etag_offset = 0;
712 struct ist header_name = IST_NULL;
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200713 time_t last_modified = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100714
William Lallemand4da3f8a2017-10-31 14:33:34 +0100715 /* Don't cache if the response came from a cache */
716 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
717 s->target == &http_cache_applet.obj_type) {
718 goto out;
719 }
720
721 /* cache only HTTP/1.1 */
722 if (!(txn->req.flags & HTTP_MSGF_VER_11))
723 goto out;
724
Willy Tarreau6905d182019-10-01 17:59:17 +0200725 /* cache only GET method */
726 if (txn->meth != HTTP_METH_GET)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100727 goto out;
728
Willy Tarreauc9036c02019-01-11 19:38:25 +0100729 /* cache key was not computed */
730 if (!key)
731 goto out;
732
William Lallemand4da3f8a2017-10-31 14:33:34 +0100733 /* cache only 200 status code */
734 if (txn->status != 200)
735 goto out;
736
Christopher Faulet839791a2019-01-07 16:12:07 +0100737 /* Find the corresponding filter instance for the current stream */
738 list_for_each_entry(filter, &s->strm_flt.filters, list) {
739 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
740 /* No filter ctx, don't cache anything */
741 if (!filter->ctx)
742 goto out;
743 cache_ctx = filter->ctx;
744 break;
745 }
746 }
747
748 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200749 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100750
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200751 /* Do not cache too big objects. */
752 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
753 htx->data + htx->extra > shctx->max_obj_size)
754 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100755
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200756 /* Does not manage Vary at the moment. We will need a secondary key later for that */
757 ctx.blk = NULL;
758 if (http_find_header(htx, ist("Vary"), &ctx, 0))
759 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100760
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200761 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100762
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +0100763 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200764 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100765
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200766 age = 0;
767 ctx.blk = NULL;
768 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
769 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
770 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
771 hdr_age = CACHE_ENTRY_MAX_AGE;
772 age = hdr_age;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100773 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200774 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100775 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100776
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200777 /* Build a last-modified time that will be stored in the cache_entry and
778 * compared to a future If-Modified-Since client header. */
779 last_modified = get_last_modified_time(htx);
780
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200781 chunk_reset(&trash);
782 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
783 struct htx_blk *blk = htx_get_blk(htx, pos);
784 enum htx_blk_type type = htx_get_blk_type(blk);
785 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100786
Christopher Fauletb0667472019-09-03 22:22:12 +0200787 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200788 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
789 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200790
791 /* Look for optional ETag header.
792 * We need to store the offset of the ETag value in order for
793 * future conditional requests to be able to perform ETag
794 * comparisons. */
795 if (type == HTX_BLK_HDR) {
796 header_name = htx_get_blk_name(htx, blk);
797 if (isteq(header_name, ist("etag"))) {
798 etag_length = sz - istlen(header_name);
799 etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
800 }
801 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200802 if (type == HTX_BLK_EOH)
803 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200804 }
805
Christopher Fauletb0667472019-09-03 22:22:12 +0200806 /* Do not cache objects if the headers are too big. */
807 if (hdrs_len > htx->size - global.tune.maxrewrite)
808 goto out;
809
William Lallemand4da3f8a2017-10-31 14:33:34 +0100810 shctx_lock(shctx);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200811 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry) + trash.data);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100812 if (!first) {
813 shctx_unlock(shctx);
814 goto out;
815 }
816 shctx_unlock(shctx);
817
Willy Tarreau1093a452018-04-06 19:02:25 +0200818 /* the received memory is not initialized, we need at least to mark
819 * the object as not indexed yet.
820 */
821 object = (struct cache_entry *)first->data;
822 object->eb.node.leaf_p = NULL;
823 object->eb.key = 0;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200824 object->age = age;
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200825 object->last_modified = last_modified;
Willy Tarreau1093a452018-04-06 19:02:25 +0200826
William Lallemand4da3f8a2017-10-31 14:33:34 +0100827 /* reserve space for the cache_entry structure */
828 first->len = sizeof(struct cache_entry);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200829 first->last_append = NULL;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100830 /* cache the headers in a http action because it allows to chose what
831 * to cache, for example you might want to cache a response before
832 * modifying some HTTP headers, or on the contrary after modifying
833 * those headers.
834 */
835
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200836 /* Write the ETag information in the cache_entry if needed. */
837 object->etag_length = etag_length;
838 object->etag_offset = etag_offset;
839
William Lallemand4da3f8a2017-10-31 14:33:34 +0100840 /* does not need to be locked because it's in the "hot" list,
841 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200842 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
843 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100844
845 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +0100846 if (cache_ctx) {
847 cache_ctx->first_block = first;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100848
Willy Tarreauc9036c02019-01-11 19:38:25 +0100849 object->eb.key = key;
850
Christopher Faulet839791a2019-01-07 16:12:07 +0100851 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
852 /* Insert the node later on caching success */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100853
Christopher Faulet839791a2019-01-07 16:12:07 +0100854 shctx_lock(shctx);
Christopher Faulet95220e22018-12-07 17:34:39 +0100855
Christopher Faulet839791a2019-01-07 16:12:07 +0100856 old = entry_exist(cconf->c.cache, txn->cache_hash);
857 if (old) {
858 eb32_delete(&old->eb);
859 old->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100860 }
Christopher Faulet839791a2019-01-07 16:12:07 +0100861 shctx_unlock(shctx);
862
863 /* store latest value and expiration time */
864 object->latest_validation = now.tv_sec;
865 object->expire = now.tv_sec + http_calc_maxage(s, cconf->c.cache);
866 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100867 }
868
869out:
870 /* if does not cache */
871 if (first) {
872 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +0100873 first->len = 0;
874 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100875 shctx_row_dec_hot(shctx, first);
876 shctx_unlock(shctx);
877 }
878
William Lallemand41db4602017-10-30 11:15:51 +0100879 return ACT_RET_CONT;
880}
881
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100882#define HTX_CACHE_INIT 0 /* Initial state. */
883#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
884#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200885#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
886#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100887
William Lallemandecb73b12017-11-24 14:33:55 +0100888static void http_cache_applet_release(struct appctx *appctx)
889{
Christopher Faulet95220e22018-12-07 17:34:39 +0100890 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +0100891 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +0100892 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +0100893 struct shared_block *first = block_ptr(cache_ptr);
894
895 shctx_lock(shctx_ptr(cache));
896 shctx_row_dec_hot(shctx_ptr(cache), first);
897 shctx_unlock(shctx_ptr(cache));
898}
899
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200900
901static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
902 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100903{
Christopher Faulet95220e22018-12-07 17:34:39 +0100904 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
905 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200906 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +0200907 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200908 unsigned int max, total;
909 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100910
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200911 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
912 if (!max)
913 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +0200914 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200915 ? (info & 0xff) + ((info >> 8) & 0xfffff)
916 : info & 0xfffffff);
917 if (blksz > max)
918 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100919
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200920 blk = htx_add_blk(htx, type, blksz);
921 if (!blk)
922 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100923
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200924 blk->info = info;
925 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +0200926 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200927 while (blksz) {
928 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +0200929 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200930 offset += max;
931 blksz -= max;
932 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +0200933 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200934 if (blksz || offset == shctx->block_size) {
935 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
936 offset = 0;
937 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100938 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200939 appctx->ctx.cache.offset = offset;
940 appctx->ctx.cache.next = shblk;
941 appctx->ctx.cache.sent += total;
942 return total;
943}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100944
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200945static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
946 uint32_t info, struct shared_block *shblk, unsigned int offset)
947{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100948
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200949 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
950 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
951 unsigned int max, total, rem_data;
952 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100953
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200954 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
955 if (!max)
956 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100957
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200958 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +0200959 if (appctx->ctx.cache.rem_data) {
960 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200961 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +0200962 }
963 else {
964 blksz = (info & 0xfffffff);
965 total = 4;
966 }
967 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200968 rem_data = blksz - max;
969 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100970 }
971
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200972 while (blksz) {
973 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100974
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200975 max = MIN(blksz, shctx->block_size - offset);
976 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
977 offset += sz;
978 blksz -= sz;
979 total += sz;
980 if (sz < max)
981 break;
982 if (blksz || offset == shctx->block_size) {
983 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
984 offset = 0;
985 }
986 }
987
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200988 appctx->ctx.cache.offset = offset;
989 appctx->ctx.cache.next = shblk;
990 appctx->ctx.cache.sent += total;
991 appctx->ctx.cache.rem_data = rem_data + blksz;
992 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100993}
994
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200995static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
996 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100997{
Christopher Faulet95220e22018-12-07 17:34:39 +0100998 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
999 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001000 struct shared_block *shblk;
1001 unsigned int offset, sz;
1002 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001003
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001004 while (len) {
1005 enum htx_blk_type type;
1006 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001007
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001008 shblk = appctx->ctx.cache.next;
1009 offset = appctx->ctx.cache.offset;
1010 if (appctx->ctx.cache.rem_data) {
1011 type = HTX_BLK_DATA;
1012 info = 0;
1013 goto add_data_blk;
1014 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001015
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001016 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001017 sz = MIN(4, shctx->block_size - offset);
1018 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1019 offset += sz;
1020 if (sz < 4) {
1021 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1022 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1023 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001024 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001025
1026 /* Get payload of the next HTX block and insert it. */
1027 type = (info >> 28);
1028 if (type != HTX_BLK_DATA)
1029 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1030 else {
1031 add_data_blk:
1032 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001033 }
1034
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001035 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001036 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001037 total += ret;
1038 len -= ret;
1039
1040 if (appctx->ctx.cache.rem_data || type == mark)
1041 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001042 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001043
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001044 return total;
1045}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001046
1047static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1048{
1049 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1050 unsigned int age;
1051 char *end;
1052
1053 chunk_reset(&trash);
1054 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1055 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1056 age = CACHE_ENTRY_MAX_AGE;
1057 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1058 b_set_data(&trash, end - b_head(&trash));
1059 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1060 return 0;
1061 return 1;
1062}
1063
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001064static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001065{
1066 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1067 struct shared_block *first = block_ptr(cache_ptr);
1068 struct stream_interface *si = appctx->owner;
1069 struct channel *req = si_oc(si);
1070 struct channel *res = si_ic(si);
1071 struct htx *req_htx, *res_htx;
1072 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001073 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001074 size_t ret, total = 0;
1075
1076 res_htx = htxbuf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001077 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001078
1079 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1080 goto out;
1081
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001082 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001083 if (!b_size(&res->buf)) {
1084 si_rx_room_blk(si);
1085 goto out;
1086 }
1087
Willy Tarreauefef3232018-12-16 00:37:45 +01001088 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001089 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001090
1091 if (appctx->st0 == HTX_CACHE_INIT) {
1092 appctx->ctx.cache.next = block_ptr(cache_ptr);
1093 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1094 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001095 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001096 appctx->st0 = HTX_CACHE_HEADER;
1097 }
1098
1099 if (appctx->st0 == HTX_CACHE_HEADER) {
1100 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001101 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1102 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1103 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1104 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001105 goto error;
1106
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001107 /* In case of a conditional request, we might want to send a
1108 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001109 if (appctx->ctx.cache.send_notmodified) {
1110 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1111 /* If replacing the status code fails we need to send the full response. */
1112 appctx->ctx.cache.send_notmodified = 0;
1113 }
1114 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001115
1116 /* Skip response body for HEAD requests or in case of "304 Not
1117 * Modified" response. */
1118 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001119 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001120 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001121 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001122 }
1123
1124 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001125 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1126 if (len) {
1127 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOM);
1128 if (ret < len) {
1129 si_rx_room_blk(si);
1130 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001131 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001132 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001133 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001134 }
1135
1136 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Faulet810df062020-07-22 16:20:34 +02001137 res_htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001138 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
1139 si_rx_room_blk(si);
1140 goto out;
1141 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001142 appctx->st0 = HTX_CACHE_END;
1143 }
1144
1145 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001146 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001147 res->flags |= CF_READ_NULL;
1148 si_shutr(si);
1149 }
1150
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001151 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001152 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001153 if (total)
1154 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001155 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001156
1157 /* eat the whole request */
1158 if (co_data(req)) {
1159 req_htx = htx_from_buf(&req->buf);
1160 co_htx_skip(req, req_htx, co_data(req));
1161 htx_to_buf(req_htx, &req->buf);
1162 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001163 return;
1164
1165 error:
1166 /* Sent and HTTP error 500 */
1167 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001168 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001169 res->buf.data = b_data(errmsg);
1170 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1171 res_htx = htx_from_buf(&res->buf);
1172
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001173 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001174 appctx->st0 = HTX_CACHE_END;
1175 goto end;
1176}
1177
1178
Christopher Faulet95220e22018-12-07 17:34:39 +01001179static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001180{
1181 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001182 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001183
Christopher Faulet95220e22018-12-07 17:34:39 +01001184 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001185 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001186 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001187 }
1188
1189 /* check if a cache filter was already registered with this cache
1190 * name, if that's the case, must use it. */
1191 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001192 if (fconf->id == cache_store_flt_id) {
1193 cconf = fconf->conf;
1194 if (cconf && !strcmp((char *)cconf->c.name, name)) {
1195 rule->arg.act.p[0] = cconf;
1196 return 1;
1197 }
William Lallemand41db4602017-10-30 11:15:51 +01001198 }
1199 }
1200
Christopher Faulet95220e22018-12-07 17:34:39 +01001201 /* Create the filter cache config */
1202 cconf = calloc(1, sizeof(*cconf));
1203 if (!cconf) {
1204 memprintf(err, "out of memory\n");
1205 goto err;
1206 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001207 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001208 cconf->c.name = strdup(name);
1209 if (!cconf->c.name) {
1210 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001211 goto err;
1212 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001213
William Lallemand41db4602017-10-30 11:15:51 +01001214 /* register a filter to fill the cache buffer */
1215 fconf = calloc(1, sizeof(*fconf));
1216 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001217 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001218 goto err;
1219 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001220 fconf->id = cache_store_flt_id;
1221 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001222 fconf->ops = &cache_ops;
1223 LIST_ADDQ(&proxy->filter_configs, &fconf->list);
1224
Christopher Faulet95220e22018-12-07 17:34:39 +01001225 rule->arg.act.p[0] = cconf;
1226 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001227
Christopher Faulet95220e22018-12-07 17:34:39 +01001228 err:
1229 free(cconf);
1230 return 0;
1231}
1232
1233enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1234 struct act_rule *rule, char **err)
1235{
1236 rule->action = ACT_CUSTOM;
1237 rule->action_ptr = http_action_store_cache;
1238
1239 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1240 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001241
Christopher Faulet95220e22018-12-07 17:34:39 +01001242 (*orig_arg)++;
1243 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001244}
1245
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001246/* This produces a sha1 hash of the concatenation of the HTTP method,
1247 * the first occurrence of the Host header followed by the path component
1248 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001249int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001250{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001251 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001252 struct htx *htx = htxbuf(&s->req.buf);
1253 struct htx_sl *sl;
1254 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001255 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001256 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001257 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001258
William Lallemandf528fff2017-11-23 19:43:17 +01001259 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001260 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001261
1262 switch (txn->meth) {
1263 case HTTP_METH_HEAD:
1264 case HTTP_METH_GET:
1265 chunk_memcat(trash, "GET", 3);
1266 break;
1267 default:
1268 return 0;
1269 }
1270
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001271 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001272 uri = htx_sl_req_uri(sl); // whole uri
1273 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001274 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001275
1276 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1277 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1278 * URIs are almost always sent in absolute form with their scheme. In
1279 * this case, the scheme is almost always "https". In order to support
1280 * sharing of cache objects between H1 and H2, we'll hash the absolute
1281 * URI whenever known, or prepend "https://" + the Host header for
1282 * relative URIs. The difference will only appear on absolute HTTP/1
1283 * requests sent to an origin server, which practically is never met in
1284 * the real world so we don't care about the ability to share the same
1285 * key here.URIs are normalized from the absolute URI to an origin form as
1286 * well.
1287 */
1288 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001289 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001290 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1291 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001292 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001293 }
1294
1295 chunk_memcat(trash, uri.ptr, uri.len);
William Lallemandf528fff2017-11-23 19:43:17 +01001296
1297 /* hash everything */
1298 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001299 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001300 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1301
1302 return 1;
1303}
1304
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001305/* Looks for "If-None-Match" headers in the request and compares their value
1306 * with the one that might have been stored in the cache_entry. If any of them
1307 * matches, a "304 Not Modified" response should be sent instead of the cached
1308 * data.
1309 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001310 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1311 *
1312 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1313 * header and compare its value (date) to the one stored in the cache_entry.
1314 * If the request's date is later than the cached one, we also send a
1315 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1316 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001317 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1318 */
1319static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1320 struct cache_entry *entry)
1321{
1322 int retval = 0;
1323
1324 struct http_hdr_ctx ctx = { .blk = NULL };
1325 struct ist cache_entry_etag = IST_NULL;
1326 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001327 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001328
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001329 struct tm tm = {};
1330 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001331
1332 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001333 * cache_entry's ETag in order to perform comparisons.
1334 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001335 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001336 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001337
1338 /* A '*' matches everything. */
1339 if (isteq(ctx.value, ist("*")) != 0) {
1340 retval = 1;
1341 break;
1342 }
1343
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001344 /* No need to rebuild an etag if none was stored in the cache. */
1345 if (entry->etag_length == 0)
1346 break;
1347
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001348 /* Rebuild the stored ETag. */
1349 if (etag_buffer == NULL) {
1350 etag_buffer = get_trash_chunk();
1351
1352 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1353 (unsigned char*)b_orig(etag_buffer),
1354 entry->etag_offset, entry->etag_length) == 0) {
1355 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1356 } else {
1357 /* We could not rebuild the ETag in one go, we
1358 * won't send a "304 Not Modified" response. */
1359 break;
1360 }
1361 }
1362
1363 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1364 retval = 1;
1365 break;
1366 }
1367 }
1368
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001369 /* If the request did not contain an "If-None-Match" header, we look for
1370 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1371 if (retval == 0 && if_none_match_found == 0) {
1372 ctx.blk = NULL;
1373 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1374 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1375 if_modified_since = my_timegm(&tm);
1376
1377 /* We send a "304 Not Modified" response if the
1378 * entry's last modified date is earlier than
1379 * the one found in the "If-Modified-Since"
1380 * header. */
1381 retval = (entry->last_modified <= if_modified_since);
1382 }
1383 }
1384 }
1385
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001386 return retval;
1387}
1388
William Lallemand41db4602017-10-30 11:15:51 +01001389enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1390 struct session *sess, struct stream *s, int flags)
1391{
William Lallemand77c11972017-10-31 20:43:01 +01001392
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001393 struct http_txn *txn = s->txn;
William Lallemand77c11972017-10-31 20:43:01 +01001394 struct cache_entry *res;
Christopher Faulet95220e22018-12-07 17:34:39 +01001395 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1396 struct cache *cache = cconf->c.cache;
William Lallemand77c11972017-10-31 20:43:01 +01001397
Willy Tarreau6905d182019-10-01 17:59:17 +02001398 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1399 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001400 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001401 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001402 txn->flags |= TX_CACHE_IGNORE;
1403
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001404 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001405
Willy Tarreau504455c2017-12-22 17:47:35 +01001406 if ((s->txn->flags & (TX_CACHE_IGNORE|TX_CACHEABLE)) == TX_CACHE_IGNORE)
1407 return ACT_RET_CONT;
1408
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001409 if (!sha1_hosturi(s))
Willy Tarreau7704b1e2017-12-22 16:32:43 +01001410 return ACT_RET_CONT;
William Lallemandf528fff2017-11-23 19:43:17 +01001411
Willy Tarreau504455c2017-12-22 17:47:35 +01001412 if (s->txn->flags & TX_CACHE_IGNORE)
1413 return ACT_RET_CONT;
1414
Willy Tarreaua1214a52018-12-14 14:00:25 +01001415 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001416 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001417 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001418 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001419
William Lallemanda400a3a2017-11-20 19:13:12 +01001420 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001421 res = entry_exist(cache, s->txn->cache_hash);
William Lallemand77c11972017-10-31 20:43:01 +01001422 if (res) {
1423 struct appctx *appctx;
William Lallemanda400a3a2017-11-20 19:13:12 +01001424 shctx_row_inc_hot(shctx_ptr(cache), block_ptr(res));
1425 shctx_unlock(shctx_ptr(cache));
William Lallemand77c11972017-10-31 20:43:01 +01001426 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001427 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001428 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001429 appctx->rule = rule;
1430 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001431 appctx->ctx.cache.next = NULL;
1432 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001433 appctx->ctx.cache.send_notmodified =
1434 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001435
1436 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001437 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_hits, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001438 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001439 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_hits, 1);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001440 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001441 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001442 shctx_lock(shctx_ptr(cache));
1443 shctx_row_dec_hot(shctx_ptr(cache), block_ptr(res));
1444 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001445 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001446 }
1447 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001448 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001449 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001450}
1451
1452
1453enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1454 struct act_rule *rule, char **err)
1455{
William Lallemand41db4602017-10-30 11:15:51 +01001456 rule->action = ACT_CUSTOM;
1457 rule->action_ptr = http_action_req_cache_use;
1458
Christopher Faulet95220e22018-12-07 17:34:39 +01001459 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001460 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001461
1462 (*orig_arg)++;
1463 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001464}
1465
1466int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1467{
1468 int err_code = 0;
1469
1470 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1471
1472 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001473 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001474 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001475 err_code |= ERR_ALERT | ERR_ABORT;
1476 goto out;
1477 }
1478
1479 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1480 err_code |= ERR_ABORT;
1481 goto out;
1482 }
1483
1484 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001485 struct cache *cache_config;
1486
William Lallemand41db4602017-10-30 11:15:51 +01001487 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1488 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001489 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001490 err_code |= ERR_ALERT | ERR_ABORT;
1491 goto out;
1492 }
1493
1494 strlcpy2(tmp_cache_config->id, args[1], 33);
1495 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001496 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001497 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001498 err_code |= ERR_WARN;
1499 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001500
1501 list_for_each_entry(cache_config, &caches_config, list) {
1502 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1503 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1504 file, linenum, tmp_cache_config->id);
1505 err_code |= ERR_ALERT | ERR_ABORT;
1506 goto out;
1507 }
1508 }
1509
William Lallemand49b44532017-11-24 18:53:43 +01001510 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001511 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001512 tmp_cache_config->maxobjsz = 0;
William Lallemand41db4602017-10-30 11:15:51 +01001513 }
1514 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001515 unsigned long int maxsize;
1516 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001517
1518 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1519 err_code |= ERR_ABORT;
1520 goto out;
1521 }
1522
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001523 maxsize = strtoul(args[1], &err, 10);
1524 if (err == args[1] || *err != '\0') {
1525 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1526 file, linenum, args[1]);
1527 err_code |= ERR_ABORT;
1528 goto out;
1529 }
1530
1531 if (maxsize > (UINT_MAX >> 20)) {
1532 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1533 file, linenum, args[1], UINT_MAX >> 20);
1534 err_code |= ERR_ABORT;
1535 goto out;
1536 }
1537
William Lallemand41db4602017-10-30 11:15:51 +01001538 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001539 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001540 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001541 } else if (strcmp(args[0], "max-age") == 0) {
1542 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1543 err_code |= ERR_ABORT;
1544 goto out;
1545 }
1546
1547 if (!*args[1]) {
1548 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1549 file, linenum, args[0]);
1550 err_code |= ERR_WARN;
1551 }
1552
1553 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001554 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001555 unsigned int maxobjsz;
1556 char *err;
1557
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001558 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1559 err_code |= ERR_ABORT;
1560 goto out;
1561 }
1562
1563 if (!*args[1]) {
1564 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1565 file, linenum, args[0]);
1566 err_code |= ERR_WARN;
1567 }
1568
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001569 maxobjsz = strtoul(args[1], &err, 10);
1570 if (err == args[1] || *err != '\0') {
1571 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1572 file, linenum, args[1]);
1573 err_code |= ERR_ABORT;
1574 goto out;
1575 }
1576 tmp_cache_config->maxobjsz = maxobjsz;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001577 }
1578 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001579 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001580 err_code |= ERR_ALERT | ERR_FATAL;
1581 goto out;
1582 }
1583out:
1584 return err_code;
1585}
1586
1587/* once the cache section is parsed */
1588
1589int cfg_post_parse_section_cache()
1590{
William Lallemand41db4602017-10-30 11:15:51 +01001591 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01001592
1593 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01001594
1595 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001596 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001597 err_code |= ERR_FATAL | ERR_ALERT;
1598 goto out;
1599 }
1600
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001601 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001602 /* Default max. file size is a 256th of the cache size. */
1603 tmp_cache_config->maxobjsz =
1604 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001605 }
1606 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
1607 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
1608 err_code |= ERR_FATAL | ERR_ALERT;
1609 goto out;
1610 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001611
William Lallemandd1d1e222019-08-28 15:22:49 +02001612 /* add to the list of cache to init and reinit tmp_cache_config
1613 * for next cache section, if any.
1614 */
1615 LIST_ADDQ(&caches_config, &tmp_cache_config->list);
1616 tmp_cache_config = NULL;
1617 return err_code;
1618 }
1619out:
1620 free(tmp_cache_config);
1621 tmp_cache_config = NULL;
1622 return err_code;
1623
1624}
1625
1626int post_check_cache()
1627{
1628 struct proxy *px;
1629 struct cache *back, *cache_config, *cache;
1630 struct shared_context *shctx;
1631 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01001632 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02001633
1634 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
1635
1636 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
1637 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001638
Frédéric Lécaillebc584492018-10-25 20:18:59 +02001639 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001640 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01001641 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001642 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01001643 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001644
1645 err_code |= ERR_FATAL | ERR_ALERT;
1646 goto out;
1647 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001648 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02001649 /* the cache structure is stored in the shctx and added to the
1650 * caches list, we can remove the entry from the caches_config
1651 * list */
1652 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01001653 cache = (struct cache *)shctx->data;
1654 cache->entries = EB_ROOT_UNIQUE;
William Lallemand41db4602017-10-30 11:15:51 +01001655 LIST_ADDQ(&caches, &cache->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02001656 LIST_DEL(&cache_config->list);
1657 free(cache_config);
1658
1659 /* Find all references for this cache in the existing filters
1660 * (over all proxies) and reference it in matching filters.
1661 */
1662 for (px = proxies_list; px; px = px->next) {
1663 struct flt_conf *fconf;
1664 struct cache_flt_conf *cconf;
1665
1666 list_for_each_entry(fconf, &px->filter_configs, list) {
1667 if (fconf->id != cache_store_flt_id)
1668 continue;
1669
1670 cconf = fconf->conf;
1671 if (!strcmp(cache->id, cconf->c.name)) {
1672 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02001673 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02001674 cconf->c.cache = cache;
1675 break;
1676 }
1677 }
1678 }
William Lallemand41db4602017-10-30 11:15:51 +01001679 }
William Lallemandd1d1e222019-08-28 15:22:49 +02001680
William Lallemand41db4602017-10-30 11:15:51 +01001681out:
William Lallemand41db4602017-10-30 11:15:51 +01001682 return err_code;
1683
William Lallemand41db4602017-10-30 11:15:51 +01001684}
1685
William Lallemand41db4602017-10-30 11:15:51 +01001686struct flt_ops cache_ops = {
1687 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01001688 .check = cache_store_check,
1689 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01001690
Christopher Faulet65554e12020-03-06 14:52:06 +01001691 /* Handle stream init/deinit */
1692 .attach = cache_store_strm_init,
1693 .detach = cache_store_strm_deinit,
1694
William Lallemand4da3f8a2017-10-31 14:33:34 +01001695 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01001696 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01001697
1698 /* Filter HTTP requests and responses */
1699 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001700 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01001701 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01001702};
1703
Christopher Faulet99a17a22018-12-11 09:18:27 +01001704
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01001705int accept_encoding_cmp(const void *a, const void *b)
1706{
1707 const struct ist ist_a = *(const struct ist*)a;
1708 const struct ist ist_b = *(const struct ist*)b;
1709
1710 return istdiff(ist_a, ist_b);
1711}
1712
1713/*
1714 * Build a hash of the accept-encoding header. The different parts of the
1715 * header value are first sorted, appended and then a crc is calculated
1716 * for the newly constructed buffer.
1717 * Returns 0 in case of success.
1718 */
1719static int accept_encoding_normalizer(struct ist value, char *buf, unsigned int *buf_len)
1720{
1721 int retval = 0;
1722 struct ist values[16] = {{}};
1723 unsigned int count = 0;
1724 char *comma = NULL;
1725 struct buffer *trash = get_trash_chunk();
1726 int hash_value = 0;
1727
1728 /* The hash will be built out of a sorted list of accepted encodings. */
1729 while((comma = istchr(value, ',')) != NULL) {
1730 values[count++] = ist2(istptr(value), comma-istptr(value));
1731 value = ist2(comma+1, istlen(value) - (comma-istptr(value)) - 1);
1732 }
1733 values[count++] = value;
1734
1735 /* Sort the values alphabetically. */
1736 qsort(values, count, sizeof(struct ist), &accept_encoding_cmp);
1737
1738 while (count)
1739 chunk_istcat(trash, values[--count]);
1740
1741 hash_value = hash_crc32(b_orig(trash), b_data(trash));
1742
1743 memcpy(buf, &hash_value, sizeof(hash_value));
1744 *buf_len = sizeof(hash_value);
1745
1746 return retval;
1747}
1748
1749/*
1750 * Normalizer used by default for User-Agent and Referer headers. It only
1751 * calculates a simple crc of the whole value.
1752 * Returns 0 in case of success.
1753 */
1754static int default_normalizer(struct ist value, char *buf, unsigned int *buf_len)
1755{
1756 int hash_value = 0;
1757
1758 hash_value = hash_crc32(istptr(value), istlen(value));
1759
1760 memcpy(buf, &hash_value, sizeof(hash_value));
1761 *buf_len = sizeof(hash_value);
1762
1763 return 0;
1764}
1765
1766
1767/*
1768 * Pre-calculate the hashes of all the supported headers (in our Vary
1769 * implementation) of a given request. We have to calculate all the hashes
1770 * in advance because the actual Vary signature won't be known until the first
1771 * response.
1772 * Only the first occurrence of every header will be taken into account in the
1773 * hash.
1774 * If the header is not present, the hash portion of the given header will be
1775 * filled with zeros.
1776 * Returns 0 in case of success.
1777 */
1778static int http_request_prebuild_full_secondary_key(struct stream *s)
1779{
1780 struct http_txn *txn = s->txn;
1781 struct htx *htx = htxbuf(&s->req.buf);
1782 struct http_hdr_ctx ctx = { .blk = NULL };
1783
1784 unsigned int idx;
1785 const struct vary_hashing_information *info = NULL;
1786 unsigned int hash_length = 0;
1787 int retval = 0;
1788 int offset = 0;
1789
1790 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
1791 info = &vary_information[idx];
1792
1793 ctx.blk = NULL;
1794 if (info->norm_fn != NULL && http_find_header(htx, info->hdr_name, &ctx, 1)) {
1795 retval = info->norm_fn(ctx.value, &txn->cache_secondary_hash[offset], &hash_length);
1796 offset += hash_length;
1797 }
1798 else {
1799 /* Fill hash with 0s. */
1800 hash_length = info->hash_length;
1801 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
1802 offset += hash_length;
1803 }
1804 }
1805
1806 return retval;
1807}
1808
1809
1810/*
1811 * Calculate the secondary key for a request for which we already have a known
1812 * vary signature. The key is made by aggregating hashes calculated for every
1813 * header mentioned in the vary signature.
1814 * Only the first occurrence of every header will be taken into account in the
1815 * hash.
1816 * If the header is not present, the hash portion of the given header will be
1817 * filled with zeros.
1818 * Returns 0 in case of success.
1819 */
1820static int http_request_build_secondary_key(struct stream *s, int vary_signature)
1821{
1822 struct http_txn *txn = s->txn;
1823 struct htx *htx = htxbuf(&s->req.buf);
1824 struct http_hdr_ctx ctx = { .blk = NULL };
1825
1826 unsigned int idx;
1827 const struct vary_hashing_information *info = NULL;
1828 unsigned int hash_length = 0;
1829 int retval = 0;
1830 int offset = 0;
1831
1832 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
1833 info = &vary_information[idx];
1834
1835 ctx.blk = NULL;
1836 if ((vary_signature & info->value) && info->norm_fn != NULL &&
1837 http_find_header(htx, info->hdr_name, &ctx, 1)) {
1838 retval = info->norm_fn(ctx.value, &txn->cache_secondary_hash[offset], &hash_length);
1839 offset += hash_length;
1840 }
1841 else {
1842 /* Fill hash with 0s. */
1843 hash_length = info->hash_length;
1844 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
1845 offset += hash_length;
1846 }
1847 }
1848
1849 return retval;
1850}
1851
1852/*
1853 * Build the actual secondary key of a given request out of the prebuilt key and
1854 * the actual vary signature (extracted from the response).
1855 * Returns 0 in case of success.
1856 */
1857static int http_request_reduce_secondary_key(unsigned int vary_signature,
1858 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
1859{
1860 int offset = 0;
1861 int global_offset = 0;
1862 int vary_info_count = 0;
1863 int keep = 0;
1864 unsigned int vary_idx;
1865 const struct vary_hashing_information *vary_info;
1866
1867 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
1868 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
1869 vary_info = &vary_information[vary_idx];
1870 keep = (vary_signature & vary_info->value) ? 0xff : 0;
1871
1872 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
1873 prebuilt_key[global_offset] &= keep;
1874 }
1875 }
1876
1877 return 0;
1878}
1879
1880
Christopher Faulet99a17a22018-12-11 09:18:27 +01001881
1882static int
1883parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
1884 struct flt_conf *fconf, char **err, void *private)
1885{
1886 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01001887 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01001888 char *name = NULL;
1889 int pos = *cur_arg;
1890
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02001891 /* Get the cache filter name. <pos> point on "cache" keyword */
1892 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02001893 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02001894 goto error;
1895 }
1896 name = strdup(args[pos + 1]);
1897 if (!name) {
1898 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
1899 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01001900 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02001901 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01001902
1903 /* Check if an implicit filter with the same name already exists. If so,
1904 * we remove the implicit filter to use the explicit one. */
1905 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
1906 if (f->id != cache_store_flt_id)
1907 continue;
1908
1909 cconf = f->conf;
1910 if (strcmp(name, cconf->c.name)) {
1911 cconf = NULL;
1912 continue;
1913 }
1914
1915 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
1916 cconf = NULL;
1917 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
1918 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01001919 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01001920 }
1921
1922 /* Remove the implicit filter. <cconf> is kept for the explicit one */
1923 LIST_DEL(&f->list);
1924 free(f);
1925 free(name);
1926 break;
1927 }
1928
1929 /* No implicit cache filter found, create configuration for the explicit one */
1930 if (!cconf) {
1931 cconf = calloc(1, sizeof(*cconf));
1932 if (!cconf) {
1933 memprintf(err, "%s: out of memory", args[*cur_arg]);
1934 goto error;
1935 }
1936 cconf->c.name = name;
1937 }
1938
1939 cconf->flags = 0;
1940 fconf->id = cache_store_flt_id;
1941 fconf->conf = cconf;
1942 fconf->ops = &cache_ops;
1943
1944 *cur_arg = pos;
1945 return 0;
1946
1947 error:
1948 free(name);
1949 free(cconf);
1950 return -1;
1951}
1952
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02001953static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01001954{
1955 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1956 return 1;
1957
1958 return 0;
1959}
1960
1961static int cli_io_handler_show_cache(struct appctx *appctx)
1962{
1963 struct cache* cache = appctx->ctx.cli.p0;
1964 struct stream_interface *si = appctx->owner;
1965
William Lallemand1f49a362017-11-21 20:01:26 +01001966 if (cache == NULL) {
1967 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
1968 }
1969
1970 list_for_each_entry_from(cache, &caches, list) {
1971 struct eb32_node *node = NULL;
1972 unsigned int next_key;
1973 struct cache_entry *entry;
1974
William Lallemand1f49a362017-11-21 20:01:26 +01001975 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02001976 if (!next_key) {
1977 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
1978 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01001979 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02001980 return 0;
1981 }
1982 }
William Lallemand1f49a362017-11-21 20:01:26 +01001983
1984 appctx->ctx.cli.p0 = cache;
1985
1986 while (1) {
1987
1988 shctx_lock(shctx_ptr(cache));
1989 node = eb32_lookup_ge(&cache->entries, next_key);
1990 if (!node) {
1991 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02001992 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01001993 break;
1994 }
1995
1996 entry = container_of(node, struct cache_entry, eb);
Willy Tarreau8b507582020-02-25 09:35:07 +01001997 chunk_printf(&trash, "%p hash:%u size:%u (%u blocks), refcount:%u, expire:%d\n", entry, read_u32(entry->hash), block_ptr(entry)->len, block_ptr(entry)->block_count, block_ptr(entry)->refcount, entry->expire - (int)now.tv_sec);
William Lallemand1f49a362017-11-21 20:01:26 +01001998
1999 next_key = node->key + 1;
2000 appctx->ctx.cli.i0 = next_key;
2001
2002 shctx_unlock(shctx_ptr(cache));
2003
2004 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002005 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002006 return 0;
2007 }
2008 }
2009
2010 }
2011
2012 return 1;
2013
2014}
2015
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002016
2017/*
2018 * boolean, returns true if response was built out of a cache entry.
2019 */
2020static int
2021smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2022 const char *kw, void *private)
2023{
2024 smp->data.type = SMP_T_BOOL;
2025 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2026
2027 return 1;
2028}
2029
2030/*
2031 * string, returns cache name (if response came from a cache).
2032 */
2033static int
2034smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2035 const char *kw, void *private)
2036{
2037 struct appctx *appctx = NULL;
2038
2039 struct cache_flt_conf *cconf = NULL;
2040 struct cache *cache = NULL;
2041
2042 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2043 return 0;
2044
2045 /* Get appctx from the stream_interface. */
2046 appctx = si_appctx(&smp->strm->si[1]);
2047 if (appctx && appctx->rule) {
2048 cconf = appctx->rule->arg.act.p[0];
2049 if (cconf) {
2050 cache = cconf->c.cache;
2051
2052 smp->data.type = SMP_T_STR;
2053 smp->flags = SMP_F_CONST;
2054 smp->data.u.str.area = cache->id;
2055 smp->data.u.str.data = strlen(cache->id);
2056 return 1;
2057 }
2058 }
2059
2060 return 0;
2061}
2062
Christopher Faulet99a17a22018-12-11 09:18:27 +01002063/* Declare the filter parser for "cache" keyword */
2064static struct flt_kw_list filter_kws = { "CACHE", { }, {
2065 { "cache", parse_cache_flt, NULL },
2066 { NULL, NULL, NULL },
2067 }
2068};
2069
2070INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2071
William Lallemand1f49a362017-11-21 20:01:26 +01002072static struct cli_kw_list cli_kws = {{},{
William Lallemande899af82017-11-22 16:41:26 +01002073 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
2074 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002075}};
2076
Willy Tarreau0108d902018-11-25 19:14:37 +01002077INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002078
William Lallemand41db4602017-10-30 11:15:51 +01002079static struct action_kw_list http_res_actions = {
2080 .kw = {
2081 { "cache-store", parse_cache_store },
2082 { NULL, NULL }
2083 }
2084};
2085
Willy Tarreau0108d902018-11-25 19:14:37 +01002086INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2087
William Lallemand41db4602017-10-30 11:15:51 +01002088static struct action_kw_list http_req_actions = {
2089 .kw = {
2090 { "cache-use", parse_cache_use },
2091 { NULL, NULL }
2092 }
2093};
2094
Willy Tarreau0108d902018-11-25 19:14:37 +01002095INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2096
Willy Tarreau2231b632019-03-29 18:26:52 +01002097struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002098 .obj_type = OBJ_TYPE_APPLET,
2099 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002100 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002101 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002102};
2103
Willy Tarreaue6552512018-11-26 11:33:13 +01002104/* config parsers for this section */
2105REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002106REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002107
2108
2109/* Note: must not be declared <const> as its list will be overwritten */
2110static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2111 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2112 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2113 { /* END */ },
2114 }
2115};
2116
2117INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);