blob: 705ed446cdc4e0cd35dcc1dbe0da5c686a3b0ced [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) */
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +010052 unsigned int max_secondary_entries; /* maximum number of secondary entries with the same primary hash */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +010053 uint8_t vary_processing_enabled; /* boolean : manage Vary header (disabled by default) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010054 char id[33]; /* cache name */
William Lallemand41db4602017-10-30 11:15:51 +010055};
56
Christopher Faulet95220e22018-12-07 17:34:39 +010057/* cache config for filters */
58struct cache_flt_conf {
59 union {
60 struct cache *cache; /* cache used by the filter */
61 char *name; /* cache name used during conf parsing */
62 } c;
63 unsigned int flags; /* CACHE_FLT_F_* */
64};
65
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010066
67/*
68 * Vary-related structures and functions
69 */
70enum vary_header_bit {
71 VARY_ACCEPT_ENCODING = (1 << 0),
72 VARY_REFERER = (1 << 1),
73 VARY_LAST /* should always be last */
74};
75
76typedef int(*http_header_normalizer)(struct ist value, char *buf, unsigned int *buf_len);
77
78struct vary_hashing_information {
79 struct ist hdr_name; /* Header name */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +050080 enum vary_header_bit value; /* Bit representing the header in a vary signature */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010081 unsigned int hash_length; /* Size of the sub hash for this header's value */
82 http_header_normalizer norm_fn; /* Normalization function */
83};
84
85static int accept_encoding_normalizer(struct ist value, char *buf, unsigned int *buf_len);
86static int default_normalizer(struct ist value, char *buf, unsigned int *buf_len);
87
88/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
89 * added to this array. */
90const struct vary_hashing_information vary_information[] = {
91 { IST("accept-encoding"), VARY_ACCEPT_ENCODING, sizeof(int), &accept_encoding_normalizer },
92 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer },
93};
94
95static int http_request_prebuild_full_secondary_key(struct stream *s);
96static int http_request_build_secondary_key(struct stream *s, int vary_signature);
97static int http_request_reduce_secondary_key(unsigned int vary_signature,
98 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
99
100
William Lallemand41db4602017-10-30 11:15:51 +0100101/*
102 * cache ctx for filters
103 */
104struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100105 struct shared_block *first_block;
106};
107
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100108#define DEFAULT_MAX_SECONDARY_ENTRY 10
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100109
William Lallemand41db4602017-10-30 11:15:51 +0100110struct cache_entry {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100111 unsigned int complete; /* An entry won't be valid until complete is not null. */
William Lallemand41db4602017-10-30 11:15:51 +0100112 unsigned int latest_validation; /* latest validation date */
113 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200114 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100115
William Lallemand41db4602017-10-30 11:15:51 +0100116 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100117 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200118
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100119 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
120 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
121 * to build secondary keys for this cache entry. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100122 unsigned int secondary_entries_count; /* Should only be filled in the last entry of a list of dup entries */
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100123 unsigned int last_clear_ts; /* Timestamp of the last call to clear_expired_duplicates. */
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100124
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200125 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
126 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
127
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200128 time_t last_modified; /* Origin server "Last-Modified" header value converted in
129 * seconds since epoch. If no "Last-Modified"
130 * header is found, use "Date" header value,
131 * otherwise use reception time. This field will
132 * be used in case of an "If-Modified-Since"-based
133 * conditional request. */
134
William Lallemand41db4602017-10-30 11:15:51 +0100135 unsigned char data[0];
136};
137
138#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100139#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100140
141static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200142static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100143static struct cache *tmp_cache_config = NULL;
144
Willy Tarreau8ceae722018-11-26 11:58:30 +0100145DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
146
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100147static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry);
148static void delete_entry(struct cache_entry *del_entry);
149
William Lallemandf528fff2017-11-23 19:43:17 +0100150struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100151{
152 struct eb32_node *node;
153 struct cache_entry *entry;
154
Willy Tarreau8b507582020-02-25 09:35:07 +0100155 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100156 if (!node)
157 return NULL;
158
159 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100160
161 /* if that's not the right node */
162 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
163 return NULL;
164
William Lallemand08727662017-11-21 20:01:27 +0100165 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100166 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100167 } else {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100168 delete_entry(entry);
William Lallemand08727662017-11-21 20:01:27 +0100169 entry->eb.key = 0;
170 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100171 return NULL;
172
173}
174
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100175/*
176 * There can be multiple entries with the same primary key in the ebtree so in
177 * order to get the proper one out of the list, we use a secondary_key.
178 * This function simply iterates over all the entries with the same primary_key
179 * until it finds the right one.
180 * Returns the cache_entry in case of success, NULL otherwise.
181 */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100182struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
183 char *secondary_key)
184{
185 struct eb32_node *node = &entry->eb;
186
187 if (!entry->secondary_key_signature)
188 return NULL;
189
190 while (entry && memcmp(entry->secondary_key, secondary_key, HTTP_CACHE_SEC_KEY_LEN) != 0) {
191 node = eb32_next_dup(node);
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100192
193 /* Make the best use of this iteration and clear expired entries
194 * when we find them. Calling delete_entry would be too costly
195 * so we simply call eb32_delete. The secondary_entry count will
196 * be updated when we try to insert a new entry to this list. */
197 if (entry->expire <= now.tv_sec) {
198 eb32_delete(&entry->eb);
199 entry->eb.key = 0;
200 }
201
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100202 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
203 }
204
205 /* Expired entry */
206 if (entry && entry->expire <= now.tv_sec) {
207 eb32_delete(&entry->eb);
208 entry->eb.key = 0;
209 entry = NULL;
210 }
211
212 return entry;
213}
214
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100215
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100216/*
217 * Remove all expired entries from a list of duplicates.
218 * Return the number of alive entries in the list and sets dup_tail to the
219 * current last item of the list.
220 */
221static unsigned int clear_expired_duplicates(struct eb32_node **dup_tail)
222{
223 unsigned int entry_count = 0;
224 struct cache_entry *entry = NULL;
225 struct eb32_node *prev = *dup_tail;
226 struct eb32_node *tail = NULL;
227
228 while (prev) {
229 entry = container_of(prev, struct cache_entry, eb);
230 prev = eb32_prev_dup(prev);
231 if (entry->expire <= now.tv_sec) {
232 eb32_delete(&entry->eb);
233 entry->eb.key = 0;
234 }
235 else {
236 if (!tail)
237 tail = &entry->eb;
238 ++entry_count;
239 }
240 }
241
242 *dup_tail = tail;
243
244 return entry_count;
245}
246
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100247
248/*
249 * This function inserts a cache_entry in the cache's ebtree. In case of
250 * duplicate entries (vary), it then checks that the number of entries did not
251 * reach the max number of secondary entries. If this entry should not have been
252 * created, remove it.
253 * In the regular case (unique entries), this function does not do more than a
254 * simple insert. In case of secondary entries, it will at most cost an
255 * insertion+max_sec_entries time checks and entry deletion.
256 * Returns the newly inserted node in case of success, NULL otherwise.
257 */
258static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry)
259{
260 struct eb32_node *prev = NULL;
261 struct cache_entry *entry = NULL;
262 unsigned int entry_count = 0;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100263 unsigned int last_clear_ts = now.tv_sec;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100264
265 struct eb32_node *node = eb32_insert(&cache->entries, &new_entry->eb);
266
267 /* We should not have multiple entries with the same primary key unless
268 * the entry has a non null vary signature. */
269 if (!new_entry->secondary_key_signature)
270 return node;
271
272 prev = eb32_prev_dup(node);
273 if (prev != NULL) {
274 /* The last entry of a duplicate list should contain the current
275 * number of entries in the list. */
276 entry = container_of(prev, struct cache_entry, eb);
277 entry_count = entry->secondary_entries_count;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100278 last_clear_ts = entry->last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100279
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100280 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100281 /* Some entries of the duplicate list might be expired so
282 * we will iterate over all the items in order to free some
283 * space. In order to avoid going over the same list too
284 * often, we first check the timestamp of the last check
285 * performed. */
286 if (last_clear_ts == now.tv_sec) {
287 /* Too many entries for this primary key, clear the
288 * one that was inserted. */
289 eb32_delete(node);
290 node->key = 0;
291 return NULL;
292 }
293
294 entry_count = clear_expired_duplicates(&prev);
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100295 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100296 /* Still too many entries for this primary key, delete
297 * the newly inserted one. */
298 entry = container_of(prev, struct cache_entry, eb);
299 entry->last_clear_ts = now.tv_sec;
300 eb32_delete(node);
301 node->key = 0;
302 return NULL;
303 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100304 }
305 }
306
307 new_entry->secondary_entries_count = entry_count + 1;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100308 new_entry->last_clear_ts = last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100309
310 return node;
311}
312
313
314/*
315 * This function removes an entry from the ebtree. If the entry was a duplicate
316 * (in case of Vary), it updates the secondary entry counter in another
317 * duplicate entry (the last entry of the dup list).
318 */
319static void delete_entry(struct cache_entry *del_entry)
320{
321 struct eb32_node *prev = NULL, *next = NULL;
322 struct cache_entry *entry = NULL;
323 struct eb32_node *last = NULL;
324
325 if (del_entry->secondary_key_signature) {
326 next = &del_entry->eb;
327
328 /* Look for last entry of the duplicates list. */
329 while ((next = eb32_next_dup(next))) {
330 last = next;
331 }
332
333 if (last) {
334 entry = container_of(last, struct cache_entry, eb);
335 --entry->secondary_entries_count;
336 }
337 else {
338 /* The current entry is the last one, look for the
339 * previous one to update its counter. */
340 prev = eb32_prev_dup(&del_entry->eb);
341 if (prev) {
342 entry = container_of(prev, struct cache_entry, eb);
343 entry->secondary_entries_count = del_entry->secondary_entries_count - 1;
344 }
345 }
346 }
347 eb32_delete(&del_entry->eb);
348 del_entry->eb.key = 0;
349}
350
351
William Lallemand4da3f8a2017-10-31 14:33:34 +0100352static inline struct shared_context *shctx_ptr(struct cache *cache)
353{
354 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
355}
356
William Lallemand77c11972017-10-31 20:43:01 +0100357static inline struct shared_block *block_ptr(struct cache_entry *entry)
358{
359 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
360}
361
362
363
William Lallemand41db4602017-10-30 11:15:51 +0100364static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100365cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100366{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100367 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100368 return 0;
369}
370
Christopher Faulet95220e22018-12-07 17:34:39 +0100371static void
372cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
373{
374 struct cache_flt_conf *cconf = fconf->conf;
375
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200376 if (!(cconf->flags & CACHE_FLT_INIT))
377 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100378 free(cconf);
379}
380
William Lallemand4da3f8a2017-10-31 14:33:34 +0100381static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100382cache_store_check(struct proxy *px, struct flt_conf *fconf)
383{
384 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100385 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100386 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100387 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100388
William Lallemandd1d1e222019-08-28 15:22:49 +0200389 /* Find the cache corresponding to the name in the filter config. The
390 * cache will not be referenced now in the filter config because it is
391 * not fully allocated. This step will be performed during the cache
392 * post_check.
393 */
394 list_for_each_entry(cache, &caches_config, list) {
395 if (!strcmp(cache->id, cconf->c.name))
Christopher Faulet95220e22018-12-07 17:34:39 +0100396 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100397 }
398
399 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
400 proxy_type_str(px), px->id, (char *)cconf->c.name);
401 return 1;
402
403 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100404 /* Here <cache> points on the cache the filter must use and <cconf>
405 * points on the cache filter configuration. */
406
407 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100408 * enabled and if it is after the cache. When the compression is before
409 * the cache, an error is returned. Also check if the cache filter must
410 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100411 list_for_each_entry(f, &px->filter_configs, list) {
412 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100413 /* The compression filter must be evaluated after the cache. */
414 if (comp) {
415 ha_alert("config: %s '%s': unable to enable the compression filter before "
416 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
417 return 1;
418 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100419 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200420 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100421 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200422 else if (f->id == fcgi_flt_id)
423 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100424 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
425 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200426 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100427 * declaration is required. */
428 ha_alert("config: %s '%s': require an explicit filter declaration "
429 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
430 return 1;
431 }
432
Christopher Fauletafd819c2018-12-11 08:57:45 +0100433 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100434 return 0;
435}
436
437static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100438cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100439{
Christopher Faulet65554e12020-03-06 14:52:06 +0100440 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100441
Christopher Faulet65554e12020-03-06 14:52:06 +0100442 st = pool_alloc_dirty(pool_head_cache_st);
443 if (st == NULL)
444 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100445
Christopher Faulet65554e12020-03-06 14:52:06 +0100446 st->first_block = NULL;
447 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100448
Christopher Faulet65554e12020-03-06 14:52:06 +0100449 /* Register post-analyzer on AN_RES_WAIT_HTTP */
450 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100451 return 1;
452}
453
Christopher Faulet65554e12020-03-06 14:52:06 +0100454static void
455cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100456{
457 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100458 struct cache_flt_conf *cconf = FLT_CONF(filter);
459 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100460 struct shared_context *shctx = shctx_ptr(cache);
461
William Lallemand49dc0482017-11-24 14:33:54 +0100462 /* Everything should be released in the http_end filter, but we need to do it
463 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100464 if (st && st->first_block) {
William Lallemand49dc0482017-11-24 14:33:54 +0100465 shctx_lock(shctx);
466 shctx_row_dec_hot(shctx, st->first_block);
467 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100468 }
469 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100470 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100471 filter->ctx = NULL;
472 }
William Lallemand49dc0482017-11-24 14:33:54 +0100473}
474
Christopher Faulet839791a2019-01-07 16:12:07 +0100475static int
476cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
477 unsigned an_bit)
478{
479 struct http_txn *txn = s->txn;
480 struct http_msg *msg = &txn->rsp;
481 struct cache_st *st = filter->ctx;
482
483 if (an_bit != AN_RES_WAIT_HTTP)
484 goto end;
485
486 /* Here we need to check if any compression filter precedes the cache
487 * filter. This is only possible when the compression is configured in
488 * the frontend while the cache filter is configured on the
489 * backend. This case cannot be detected during HAProxy startup. So in
490 * such cases, the cache is disabled.
491 */
492 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
493 pool_free(pool_head_cache_st, st);
494 filter->ctx = NULL;
495 }
496
497 end:
498 return 1;
499}
William Lallemand49dc0482017-11-24 14:33:54 +0100500
501static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100502cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
503{
504 struct cache_st *st = filter->ctx;
505
William Lallemand4da3f8a2017-10-31 14:33:34 +0100506 if (!(msg->chn->flags & CF_ISRESP) || !st)
507 return 1;
508
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200509 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100510 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100511 return 1;
512}
513
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200514static inline void disable_cache_entry(struct cache_st *st,
515 struct filter *filter, struct shared_context *shctx)
516{
517 struct cache_entry *object;
518
519 object = (struct cache_entry *)st->first_block->data;
520 filter->ctx = NULL; /* disable cache */
521 shctx_lock(shctx);
522 shctx_row_dec_hot(shctx, st->first_block);
Remi Tricot-Le Breton964caaf2020-12-15 14:30:12 +0100523 eb32_delete(&object->eb);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200524 object->eb.key = 0;
525 shctx_unlock(shctx);
526 pool_free(pool_head_cache_st, st);
527}
528
William Lallemand4da3f8a2017-10-31 14:33:34 +0100529static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100530cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
531 unsigned int offset, unsigned int len)
532{
Christopher Faulet95220e22018-12-07 17:34:39 +0100533 struct cache_flt_conf *cconf = FLT_CONF(filter);
534 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100535 struct cache_st *st = filter->ctx;
536 struct htx *htx = htxbuf(&msg->chn->buf);
537 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200538 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100539 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200540 unsigned int orig_len, to_forward;
541 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100542
543 if (!len)
544 return len;
545
546 if (!st->first_block) {
547 unregister_data_filter(s, msg->chn, filter);
548 return len;
549 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100550
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200551 chunk_reset(&trash);
552 orig_len = len;
553 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100554
555 htxret = htx_find_offset(htx, offset);
556 blk = htxret.blk;
557 offset = htxret.ret;
558 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100559 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200560 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100561 struct ist v;
562
563 switch (type) {
564 case HTX_BLK_UNUSED:
565 break;
566
567 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100568 v = htx_get_blk_value(htx, blk);
569 v.ptr += offset;
570 v.len -= offset;
571 if (v.len > len)
572 v.len = len;
573
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200574 info = (type << 28) + v.len;
575 chunk_memcat(&trash, (char *)&info, sizeof(info));
576 chunk_memcat(&trash, v.ptr, v.len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100577 to_forward += v.len;
578 len -= v.len;
579 break;
580
581 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200582 /* Here offset must always be 0 because only
583 * DATA blocks can be partially transferred. */
584 if (offset)
585 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100586 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200587 goto end;
588
589 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
590 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100591 to_forward += sz;
592 len -= sz;
593 break;
594 }
595
596 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100597 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200598
599 end:
600 shctx_lock(shctx);
601 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
602 if (!fb) {
603 shctx_unlock(shctx);
604 goto no_cache;
605 }
606 shctx_unlock(shctx);
607
608 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
609 (unsigned char *)b_head(&trash), b_data(&trash));
610 if (ret < 0)
611 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100612
613 return to_forward;
614
615 no_cache:
616 disable_cache_entry(st, filter, shctx);
617 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200618 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100619}
620
621static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100622cache_store_http_end(struct stream *s, struct filter *filter,
623 struct http_msg *msg)
624{
625 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100626 struct cache_flt_conf *cconf = FLT_CONF(filter);
627 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100628 struct shared_context *shctx = shctx_ptr(cache);
629 struct cache_entry *object;
630
631 if (!(msg->chn->flags & CF_ISRESP))
632 return 1;
633
634 if (st && st->first_block) {
635
636 object = (struct cache_entry *)st->first_block->data;
637
William Lallemand4da3f8a2017-10-31 14:33:34 +0100638 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100639 /* The whole payload was cached, the entry can now be used. */
640 object->complete = 1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100641 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100642 shctx_row_dec_hot(shctx, st->first_block);
643 shctx_unlock(shctx);
644
645 }
646 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100647 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100648 filter->ctx = NULL;
649 }
650
651 return 1;
652}
653
654 /*
655 * This intends to be used when checking HTTP headers for some
656 * word=value directive. Return a pointer to the first character of value, if
657 * the word was not found or if there wasn't any value assigned ot it return NULL
658 */
659char *directive_value(const char *sample, int slen, const char *word, int wlen)
660{
661 int st = 0;
662
663 if (slen < wlen)
664 return 0;
665
666 while (wlen) {
667 char c = *sample ^ *word;
668 if (c && c != ('A' ^ 'a'))
669 return NULL;
670 sample++;
671 word++;
672 slen--;
673 wlen--;
674 }
675
676 while (slen) {
677 if (st == 0) {
678 if (*sample != '=')
679 return NULL;
680 sample++;
681 slen--;
682 st = 1;
683 continue;
684 } else {
685 return (char *)sample;
686 }
687 }
688
689 return NULL;
690}
691
692/*
693 * Return the maxage in seconds of an HTTP response.
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100694 * The returned value will always take the cache's configuration into account
695 * (cache->maxage) but the actual max age of the response will be set in the
696 * true_maxage parameter. It will be used to determine if a response is already
697 * stale or not.
William Lallemand4da3f8a2017-10-31 14:33:34 +0100698 * Compute the maxage using either:
699 * - the assigned max-age of the cache
700 * - the s-maxage directive
701 * - the max-age directive
702 * - (Expires - Data) headers
703 * - the default-max-age of the cache
704 *
705 */
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100706int http_calc_maxage(struct stream *s, struct cache *cache, int *true_maxage)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100707{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200708 struct htx *htx = htxbuf(&s->res.buf);
709 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100710 long smaxage = -1;
711 long maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100712 int expires = -1;
713 struct tm tm = {};
714 time_t expires_val = 0;
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100715 char *endptr = NULL;
716 int offset = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100717
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100718 /* The Cache-Control max-age and s-maxage directives should be followed by
719 * a positive numerical value (see RFC 7234#5.2.1.1). According to the
720 * specs, a sender "should not" generate a quoted-string value but we will
721 * still accept this format since it isn't strictly forbidden. */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200722 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
723 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100724
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200725 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
726 if (value) {
727 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100728
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200729 chunk_strncat(chk, value, ctx.value.len - 8 + 1);
730 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100731 offset = (*chk->area == '"') ? 1 : 0;
732 smaxage = strtol(chk->area + offset, &endptr, 10);
733 if (unlikely(smaxage < 0 || endptr == chk->area))
734 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100735 }
736
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200737 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
738 if (value) {
739 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200740
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200741 chunk_strncat(chk, value, ctx.value.len - 7 + 1);
742 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100743 offset = (*chk->area == '"') ? 1 : 0;
744 maxage = strtol(chk->area + offset, &endptr, 10);
745 if (unlikely(maxage < 0 || endptr == chk->area))
746 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100747 }
748 }
749
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100750 /* Look for Expires header if no s-maxage or max-age Cache-Control data
751 * was found. */
752 if (maxage == -1 && smaxage == -1) {
753 ctx.blk = NULL;
754 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
755 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
756 expires_val = my_timegm(&tm);
757 /* A request having an expiring date earlier
758 * than the current date should be considered as
759 * stale. */
760 expires = (expires_val >= now.tv_sec) ?
761 (expires_val - now.tv_sec) : 0;
762 }
763 else {
764 /* Following RFC 7234#5.3, an invalid date
765 * format must be treated as a date in the past
766 * so the cache entry must be seen as already
767 * expired. */
768 expires = 0;
769 }
770 }
771 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100772
773
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100774 if (smaxage > 0) {
775 if (true_maxage)
776 *true_maxage = smaxage;
William Lallemand49b44532017-11-24 18:53:43 +0100777 return MIN(smaxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100778 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100779
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100780 if (maxage > 0) {
781 if (true_maxage)
782 *true_maxage = maxage;
William Lallemand49b44532017-11-24 18:53:43 +0100783 return MIN(maxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100784 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100785
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100786 if (expires >= 0) {
787 if (true_maxage)
788 *true_maxage = expires;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100789 return MIN(expires, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100790 }
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100791
William Lallemand49b44532017-11-24 18:53:43 +0100792 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100793
794}
795
796
William Lallemanda400a3a2017-11-20 19:13:12 +0100797static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
798{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200799 struct cache_entry *object = (struct cache_entry *)block->data;
800
801 if (first == block && object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100802 delete_entry(object);
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200803 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100804}
805
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200806
807/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
808 * date value should be compared to a date determined by in a previous response (for
809 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
810 * value of the response's reception time (by decreasing order of priority). */
811static time_t get_last_modified_time(struct htx *htx)
812{
813 time_t last_modified = 0;
814 struct http_hdr_ctx ctx = { .blk = NULL };
815 struct tm tm = {};
816
817 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
818 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
819 last_modified = my_timegm(&tm);
820 }
821 }
822
823 if (!last_modified) {
824 ctx.blk = NULL;
825 if (http_find_header(htx, ist("date"), &ctx, 1)) {
826 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
827 last_modified = my_timegm(&tm);
828 }
829 }
830 }
831
832 /* Fallback on the current time if no "Last-Modified" or "Date" header
833 * was found. */
834 if (!last_modified)
835 last_modified = now.tv_sec;
836
837 return last_modified;
838}
839
William Lallemand41db4602017-10-30 11:15:51 +0100840/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100841 * Checks the vary header's value. The headers on which vary should be applied
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500842 * must be explicitly supported in the vary_information array (see cache.c). If
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100843 * any other header is mentioned, we won't store the response.
844 * Returns 1 if Vary-based storage can work, 0 otherwise.
845 */
846static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
847{
848 unsigned int vary_idx;
849 unsigned int vary_info_count;
850 const struct vary_hashing_information *vary_info;
851 struct http_hdr_ctx ctx = { .blk = NULL };
852
853 int retval = 1;
854
855 *vary_signature = 0;
856
857 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
858 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
859 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
860 vary_info = &vary_information[vary_idx];
861 if (isteqi(ctx.value, vary_info->hdr_name)) {
862 *vary_signature |= vary_info->value;
863 break;
864 }
865 }
866 retval = (vary_idx < vary_info_count);
867 }
868
869 return retval;
870}
871
872
873
874/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500875 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100876 * register a filter to store the data
877 */
878enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200879 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100880{
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200881 long long hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100882 int effective_maxage = 0;
883 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100884 struct http_txn *txn = s->txn;
885 struct http_msg *msg = &txn->rsp;
886 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100887 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100888 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100889 struct cache *cache = cconf->c.cache;
890 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100891 struct cache_st *cache_ctx = NULL;
892 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +0100893 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200894 struct htx *htx;
895 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +0200896 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200897 int32_t pos;
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200898 struct ist header_name = IST_NULL;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100899 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100900
William Lallemand4da3f8a2017-10-31 14:33:34 +0100901 /* Don't cache if the response came from a cache */
902 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
903 s->target == &http_cache_applet.obj_type) {
904 goto out;
905 }
906
907 /* cache only HTTP/1.1 */
908 if (!(txn->req.flags & HTTP_MSGF_VER_11))
909 goto out;
910
Willy Tarreau6905d182019-10-01 17:59:17 +0200911 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +0100912 if (txn->meth != HTTP_METH_GET) {
913 /* In case of successful unsafe method on a stored resource, the
914 * cached entry must be invalidated (see RFC7234#4.4).
915 * A "non-error response" is one with a 2xx (Successful) or 3xx
916 * (Redirection) status code. */
917 if (txn->status >= 200 && txn->status < 400) {
918 switch (txn->meth) {
919 case HTTP_METH_OPTIONS:
920 case HTTP_METH_GET:
921 case HTTP_METH_HEAD:
922 case HTTP_METH_TRACE:
923 break;
924
925 default: /* Any unsafe method */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500926 /* Discard any corresponding entry in case of successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +0100927 * unsafe request (such as PUT, POST or DELETE). */
928 shctx_lock(shctx);
929
930 old = entry_exist(cconf->c.cache, txn->cache_hash);
931 if (old) {
932 eb32_delete(&old->eb);
933 old->eb.key = 0;
934 }
935 shctx_unlock(shctx);
936 }
937 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100938 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +0100939 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100940
Willy Tarreauc9036c02019-01-11 19:38:25 +0100941 /* cache key was not computed */
942 if (!key)
943 goto out;
944
William Lallemand4da3f8a2017-10-31 14:33:34 +0100945 /* cache only 200 status code */
946 if (txn->status != 200)
947 goto out;
948
Christopher Faulet839791a2019-01-07 16:12:07 +0100949 /* Find the corresponding filter instance for the current stream */
950 list_for_each_entry(filter, &s->strm_flt.filters, list) {
951 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
952 /* No filter ctx, don't cache anything */
953 if (!filter->ctx)
954 goto out;
955 cache_ctx = filter->ctx;
956 break;
957 }
958 }
959
960 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200961 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100962
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200963 /* Do not cache too big objects. */
964 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
965 htx->data + htx->extra > shctx->max_obj_size)
966 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100967
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100968 /* Only a subset of headers are supported in our Vary implementation. If
969 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100970 * able to use the cache. Likewise, if Vary header support is disabled,
971 * avoid caching responses that contain such a header. */
972 ctx.blk = NULL;
973 if (cache->vary_processing_enabled) {
974 if (!http_check_vary_header(htx, &vary_signature))
975 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100976 if (vary_signature)
977 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100978 }
979 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200980 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100981 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100982
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200983 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100984
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +0100985 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200986 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100987
988 shctx_lock(shctx);
989 old = entry_exist(cache, txn->cache_hash);
990 if (old) {
991 if (vary_signature)
992 old = secondary_entry_exist(cconf->c.cache, old,
993 txn->cache_secondary_hash);
994 if (old) {
995 if (!old->complete) {
996 /* An entry with the same primary key is already being
997 * created, we should not try to store the current
998 * response because it will waste space in the cache. */
999 shctx_unlock(shctx);
1000 goto out;
1001 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001002 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001003 old->eb.key = 0;
1004 }
1005 }
1006 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1007 if (!first) {
1008 shctx_unlock(shctx);
1009 goto out;
1010 }
1011 /* the received memory is not initialized, we need at least to mark
1012 * the object as not indexed yet.
1013 */
1014 object = (struct cache_entry *)first->data;
1015 memset(object, 0, sizeof(*object));
1016 object->eb.key = key;
1017 object->secondary_key_signature = vary_signature;
1018 /* We need to temporarily set a valid expiring time until the actual one
1019 * is set by the end of this function (in case of concurrent accesses to
1020 * the same resource). This way the second access will find an existing
1021 * but not yet usable entry in the tree and will avoid storing its data. */
1022 object->expire = now.tv_sec + 2;
1023
1024 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1025 if (vary_signature)
1026 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1027
1028 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001029 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001030 object->eb.key = 0;
1031 shctx_unlock(shctx);
1032 goto out;
1033 }
1034 shctx_unlock(shctx);
1035
1036 /* reserve space for the cache_entry structure */
1037 first->len = sizeof(struct cache_entry);
1038 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001039
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001040 /* Determine the entry's maximum age (taking into account the cache's
1041 * configuration) as well as the response's explicit max age (extracted
1042 * from cache-control directives or the expires header). */
1043 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1044
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001045 ctx.blk = NULL;
1046 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
1047 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1048 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1049 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001050 /* A response with an Age value greater than its
1051 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001052 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001053 if (unlikely(object->age > true_maxage))
1054 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001055 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001056 else
1057 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001058 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001059 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001060
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001061 /* Build a last-modified time that will be stored in the cache_entry and
1062 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001063 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001064
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001065 chunk_reset(&trash);
1066 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1067 struct htx_blk *blk = htx_get_blk(htx, pos);
1068 enum htx_blk_type type = htx_get_blk_type(blk);
1069 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001070
Christopher Fauletb0667472019-09-03 22:22:12 +02001071 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001072 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1073 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001074
1075 /* Look for optional ETag header.
1076 * We need to store the offset of the ETag value in order for
1077 * future conditional requests to be able to perform ETag
1078 * comparisons. */
1079 if (type == HTX_BLK_HDR) {
1080 header_name = htx_get_blk_name(htx, blk);
1081 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001082 object->etag_length = sz - istlen(header_name);
1083 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001084 }
1085 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001086 if (type == HTX_BLK_EOH)
1087 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001088 }
1089
Christopher Fauletb0667472019-09-03 22:22:12 +02001090 /* Do not cache objects if the headers are too big. */
1091 if (hdrs_len > htx->size - global.tune.maxrewrite)
1092 goto out;
1093
William Lallemand4da3f8a2017-10-31 14:33:34 +01001094 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001095 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001096 shctx_unlock(shctx);
1097 goto out;
1098 }
1099 shctx_unlock(shctx);
1100
William Lallemand4da3f8a2017-10-31 14:33:34 +01001101 /* cache the headers in a http action because it allows to chose what
1102 * to cache, for example you might want to cache a response before
1103 * modifying some HTTP headers, or on the contrary after modifying
1104 * those headers.
1105 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001106 /* does not need to be locked because it's in the "hot" list,
1107 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001108 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1109 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001110
1111 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001112 if (cache_ctx) {
1113 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001114 /* store latest value and expiration time */
1115 object->latest_validation = now.tv_sec;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001116 object->expire = now.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001117 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001118 }
1119
1120out:
1121 /* if does not cache */
1122 if (first) {
1123 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001124 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001125 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001126 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001127 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001128 shctx_row_dec_hot(shctx, first);
1129 shctx_unlock(shctx);
1130 }
1131
William Lallemand41db4602017-10-30 11:15:51 +01001132 return ACT_RET_CONT;
1133}
1134
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001135#define HTX_CACHE_INIT 0 /* Initial state. */
1136#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1137#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001138#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1139#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001140
William Lallemandecb73b12017-11-24 14:33:55 +01001141static void http_cache_applet_release(struct appctx *appctx)
1142{
Christopher Faulet95220e22018-12-07 17:34:39 +01001143 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +01001144 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001145 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001146 struct shared_block *first = block_ptr(cache_ptr);
1147
1148 shctx_lock(shctx_ptr(cache));
1149 shctx_row_dec_hot(shctx_ptr(cache), first);
1150 shctx_unlock(shctx_ptr(cache));
1151}
1152
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001153
1154static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1155 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001156{
Christopher Faulet95220e22018-12-07 17:34:39 +01001157 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1158 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001159 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001160 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001161 unsigned int max, total;
1162 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001163
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001164 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1165 if (!max)
1166 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001167 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001168 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1169 : info & 0xfffffff);
1170 if (blksz > max)
1171 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001172
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001173 blk = htx_add_blk(htx, type, blksz);
1174 if (!blk)
1175 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001176
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001177 blk->info = info;
1178 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001179 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001180 while (blksz) {
1181 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001182 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001183 offset += max;
1184 blksz -= max;
1185 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001186 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001187 if (blksz || offset == shctx->block_size) {
1188 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1189 offset = 0;
1190 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001191 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001192 appctx->ctx.cache.offset = offset;
1193 appctx->ctx.cache.next = shblk;
1194 appctx->ctx.cache.sent += total;
1195 return total;
1196}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001197
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001198static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1199 uint32_t info, struct shared_block *shblk, unsigned int offset)
1200{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001201
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001202 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1203 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1204 unsigned int max, total, rem_data;
1205 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001206
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001207 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1208 if (!max)
1209 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001210
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001211 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001212 if (appctx->ctx.cache.rem_data) {
1213 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001214 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001215 }
1216 else {
1217 blksz = (info & 0xfffffff);
1218 total = 4;
1219 }
1220 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001221 rem_data = blksz - max;
1222 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001223 }
1224
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001225 while (blksz) {
1226 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001227
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001228 max = MIN(blksz, shctx->block_size - offset);
1229 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1230 offset += sz;
1231 blksz -= sz;
1232 total += sz;
1233 if (sz < max)
1234 break;
1235 if (blksz || offset == shctx->block_size) {
1236 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1237 offset = 0;
1238 }
1239 }
1240
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001241 appctx->ctx.cache.offset = offset;
1242 appctx->ctx.cache.next = shblk;
1243 appctx->ctx.cache.sent += total;
1244 appctx->ctx.cache.rem_data = rem_data + blksz;
1245 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001246}
1247
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001248static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1249 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001250{
Christopher Faulet95220e22018-12-07 17:34:39 +01001251 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1252 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001253 struct shared_block *shblk;
1254 unsigned int offset, sz;
1255 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001256
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001257 while (len) {
1258 enum htx_blk_type type;
1259 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001260
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001261 shblk = appctx->ctx.cache.next;
1262 offset = appctx->ctx.cache.offset;
1263 if (appctx->ctx.cache.rem_data) {
1264 type = HTX_BLK_DATA;
1265 info = 0;
1266 goto add_data_blk;
1267 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001268
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001269 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001270 sz = MIN(4, shctx->block_size - offset);
1271 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1272 offset += sz;
1273 if (sz < 4) {
1274 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1275 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1276 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001277 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001278
1279 /* Get payload of the next HTX block and insert it. */
1280 type = (info >> 28);
1281 if (type != HTX_BLK_DATA)
1282 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1283 else {
1284 add_data_blk:
1285 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001286 }
1287
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001288 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001289 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001290 total += ret;
1291 len -= ret;
1292
1293 if (appctx->ctx.cache.rem_data || type == mark)
1294 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001295 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001296
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001297 return total;
1298}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001299
1300static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1301{
1302 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1303 unsigned int age;
1304 char *end;
1305
1306 chunk_reset(&trash);
1307 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1308 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1309 age = CACHE_ENTRY_MAX_AGE;
1310 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1311 b_set_data(&trash, end - b_head(&trash));
1312 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1313 return 0;
1314 return 1;
1315}
1316
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001317static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001318{
1319 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1320 struct shared_block *first = block_ptr(cache_ptr);
1321 struct stream_interface *si = appctx->owner;
1322 struct channel *req = si_oc(si);
1323 struct channel *res = si_ic(si);
1324 struct htx *req_htx, *res_htx;
1325 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001326 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001327 size_t ret, total = 0;
1328
1329 res_htx = htxbuf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001330 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001331
1332 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1333 goto out;
1334
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001335 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001336 if (!b_size(&res->buf)) {
1337 si_rx_room_blk(si);
1338 goto out;
1339 }
1340
Willy Tarreauefef3232018-12-16 00:37:45 +01001341 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001342 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001343
1344 if (appctx->st0 == HTX_CACHE_INIT) {
1345 appctx->ctx.cache.next = block_ptr(cache_ptr);
1346 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1347 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001348 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001349 appctx->st0 = HTX_CACHE_HEADER;
1350 }
1351
1352 if (appctx->st0 == HTX_CACHE_HEADER) {
1353 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001354 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1355 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1356 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1357 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001358 goto error;
1359
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001360 /* In case of a conditional request, we might want to send a
1361 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001362 if (appctx->ctx.cache.send_notmodified) {
1363 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1364 /* If replacing the status code fails we need to send the full response. */
1365 appctx->ctx.cache.send_notmodified = 0;
1366 }
1367 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001368
1369 /* Skip response body for HEAD requests or in case of "304 Not
1370 * Modified" response. */
1371 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001372 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001373 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001374 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001375 }
1376
1377 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001378 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1379 if (len) {
1380 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOM);
1381 if (ret < len) {
1382 si_rx_room_blk(si);
1383 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001384 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001385 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001386 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001387 }
1388
1389 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Faulet810df062020-07-22 16:20:34 +02001390 res_htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001391 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
1392 si_rx_room_blk(si);
1393 goto out;
1394 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001395 appctx->st0 = HTX_CACHE_END;
1396 }
1397
1398 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001399 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001400 res->flags |= CF_READ_NULL;
1401 si_shutr(si);
1402 }
1403
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001404 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001405 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001406 if (total)
1407 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001408 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001409
1410 /* eat the whole request */
1411 if (co_data(req)) {
1412 req_htx = htx_from_buf(&req->buf);
1413 co_htx_skip(req, req_htx, co_data(req));
1414 htx_to_buf(req_htx, &req->buf);
1415 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001416 return;
1417
1418 error:
1419 /* Sent and HTTP error 500 */
1420 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001421 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001422 res->buf.data = b_data(errmsg);
1423 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1424 res_htx = htx_from_buf(&res->buf);
1425
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001426 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001427 appctx->st0 = HTX_CACHE_END;
1428 goto end;
1429}
1430
1431
Christopher Faulet95220e22018-12-07 17:34:39 +01001432static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001433{
1434 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001435 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001436
Christopher Faulet95220e22018-12-07 17:34:39 +01001437 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001438 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001439 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001440 }
1441
1442 /* check if a cache filter was already registered with this cache
1443 * name, if that's the case, must use it. */
1444 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001445 if (fconf->id == cache_store_flt_id) {
1446 cconf = fconf->conf;
1447 if (cconf && !strcmp((char *)cconf->c.name, name)) {
1448 rule->arg.act.p[0] = cconf;
1449 return 1;
1450 }
William Lallemand41db4602017-10-30 11:15:51 +01001451 }
1452 }
1453
Christopher Faulet95220e22018-12-07 17:34:39 +01001454 /* Create the filter cache config */
1455 cconf = calloc(1, sizeof(*cconf));
1456 if (!cconf) {
1457 memprintf(err, "out of memory\n");
1458 goto err;
1459 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001460 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001461 cconf->c.name = strdup(name);
1462 if (!cconf->c.name) {
1463 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001464 goto err;
1465 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001466
William Lallemand41db4602017-10-30 11:15:51 +01001467 /* register a filter to fill the cache buffer */
1468 fconf = calloc(1, sizeof(*fconf));
1469 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001470 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001471 goto err;
1472 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001473 fconf->id = cache_store_flt_id;
1474 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001475 fconf->ops = &cache_ops;
1476 LIST_ADDQ(&proxy->filter_configs, &fconf->list);
1477
Christopher Faulet95220e22018-12-07 17:34:39 +01001478 rule->arg.act.p[0] = cconf;
1479 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001480
Christopher Faulet95220e22018-12-07 17:34:39 +01001481 err:
1482 free(cconf);
1483 return 0;
1484}
1485
1486enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1487 struct act_rule *rule, char **err)
1488{
1489 rule->action = ACT_CUSTOM;
1490 rule->action_ptr = http_action_store_cache;
1491
1492 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1493 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001494
Christopher Faulet95220e22018-12-07 17:34:39 +01001495 (*orig_arg)++;
1496 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001497}
1498
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001499/* This produces a sha1 hash of the concatenation of the HTTP method,
1500 * the first occurrence of the Host header followed by the path component
1501 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001502int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001503{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001504 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001505 struct htx *htx = htxbuf(&s->req.buf);
1506 struct htx_sl *sl;
1507 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001508 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001509 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001510 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001511
William Lallemandf528fff2017-11-23 19:43:17 +01001512 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001513 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001514
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001515 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001516 uri = htx_sl_req_uri(sl); // whole uri
1517 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001518 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001519
1520 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1521 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1522 * URIs are almost always sent in absolute form with their scheme. In
1523 * this case, the scheme is almost always "https". In order to support
1524 * sharing of cache objects between H1 and H2, we'll hash the absolute
1525 * URI whenever known, or prepend "https://" + the Host header for
1526 * relative URIs. The difference will only appear on absolute HTTP/1
1527 * requests sent to an origin server, which practically is never met in
1528 * the real world so we don't care about the ability to share the same
1529 * key here.URIs are normalized from the absolute URI to an origin form as
1530 * well.
1531 */
1532 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001533 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001534 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1535 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001536 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001537 }
1538
1539 chunk_memcat(trash, uri.ptr, uri.len);
William Lallemandf528fff2017-11-23 19:43:17 +01001540
1541 /* hash everything */
1542 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001543 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001544 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1545
1546 return 1;
1547}
1548
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001549/* Looks for "If-None-Match" headers in the request and compares their value
1550 * with the one that might have been stored in the cache_entry. If any of them
1551 * matches, a "304 Not Modified" response should be sent instead of the cached
1552 * data.
1553 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001554 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1555 *
1556 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1557 * header and compare its value (date) to the one stored in the cache_entry.
1558 * If the request's date is later than the cached one, we also send a
1559 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1560 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001561 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1562 */
1563static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1564 struct cache_entry *entry)
1565{
1566 int retval = 0;
1567
1568 struct http_hdr_ctx ctx = { .blk = NULL };
1569 struct ist cache_entry_etag = IST_NULL;
1570 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001571 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001572
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001573 struct tm tm = {};
1574 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001575
1576 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001577 * cache_entry's ETag in order to perform comparisons.
1578 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001579 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001580 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001581
1582 /* A '*' matches everything. */
1583 if (isteq(ctx.value, ist("*")) != 0) {
1584 retval = 1;
1585 break;
1586 }
1587
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001588 /* No need to rebuild an etag if none was stored in the cache. */
1589 if (entry->etag_length == 0)
1590 break;
1591
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001592 /* Rebuild the stored ETag. */
1593 if (etag_buffer == NULL) {
1594 etag_buffer = get_trash_chunk();
1595
1596 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1597 (unsigned char*)b_orig(etag_buffer),
1598 entry->etag_offset, entry->etag_length) == 0) {
1599 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1600 } else {
1601 /* We could not rebuild the ETag in one go, we
1602 * won't send a "304 Not Modified" response. */
1603 break;
1604 }
1605 }
1606
1607 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1608 retval = 1;
1609 break;
1610 }
1611 }
1612
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001613 /* If the request did not contain an "If-None-Match" header, we look for
1614 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1615 if (retval == 0 && if_none_match_found == 0) {
1616 ctx.blk = NULL;
1617 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1618 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1619 if_modified_since = my_timegm(&tm);
1620
1621 /* We send a "304 Not Modified" response if the
1622 * entry's last modified date is earlier than
1623 * the one found in the "If-Modified-Since"
1624 * header. */
1625 retval = (entry->last_modified <= if_modified_since);
1626 }
1627 }
1628 }
1629
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001630 return retval;
1631}
1632
William Lallemand41db4602017-10-30 11:15:51 +01001633enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1634 struct session *sess, struct stream *s, int flags)
1635{
William Lallemand77c11972017-10-31 20:43:01 +01001636
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001637 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001638 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001639 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1640 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001641 struct shared_block *entry_block;
1642
William Lallemand77c11972017-10-31 20:43:01 +01001643
Willy Tarreau6905d182019-10-01 17:59:17 +02001644 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1645 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001646 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001647 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001648 txn->flags |= TX_CACHE_IGNORE;
1649
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001650 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001651
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001652 /* The request's hash has to be calculated for all requests, even POSTs
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001653 * or PUTs for instance because RFC7234 specifies that a successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001654 * "unsafe" method on a stored resource must invalidate it
1655 * (see RFC7234#4.4). */
1656 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001657 return ACT_RET_CONT;
1658
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001659 if ((s->txn->flags & (TX_CACHE_IGNORE|TX_CACHEABLE)) == TX_CACHE_IGNORE)
Willy Tarreau7704b1e2017-12-22 16:32:43 +01001660 return ACT_RET_CONT;
William Lallemandf528fff2017-11-23 19:43:17 +01001661
Willy Tarreau504455c2017-12-22 17:47:35 +01001662 if (s->txn->flags & TX_CACHE_IGNORE)
1663 return ACT_RET_CONT;
1664
Willy Tarreaua1214a52018-12-14 14:00:25 +01001665 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001666 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001667 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001668 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001669
William Lallemanda400a3a2017-11-20 19:13:12 +01001670 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001671 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001672 /* We must not use an entry that is not complete. */
1673 if (res && res->complete) {
William Lallemand77c11972017-10-31 20:43:01 +01001674 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001675 entry_block = block_ptr(res);
1676 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001677 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001678
1679 /* In case of Vary, we could have multiple entries with the same
1680 * primary hash. We need to calculate the secondary has in order
1681 * to find the actual entry we want (if it exists). */
1682 if (res->secondary_key_signature) {
1683 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1684 shctx_lock(shctx_ptr(cache));
1685 sec_entry = secondary_entry_exist(cache, res,
1686 s->txn->cache_secondary_hash);
1687 if (sec_entry && sec_entry != res) {
1688 /* The wrong row was added to the hot list. */
1689 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1690 entry_block = block_ptr(sec_entry);
1691 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1692 }
1693 res = sec_entry;
1694 shctx_unlock(shctx_ptr(cache));
1695 }
1696 else
1697 res = NULL;
1698 }
1699
1700 /* We looked for a valid secondary entry and could not find one,
1701 * the request must be forwarded to the server. */
1702 if (!res) {
1703 shctx_lock(shctx_ptr(cache));
1704 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1705 shctx_unlock(shctx_ptr(cache));
1706 return ACT_RET_CONT;
1707 }
1708
William Lallemand77c11972017-10-31 20:43:01 +01001709 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001710 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001711 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001712 appctx->rule = rule;
1713 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001714 appctx->ctx.cache.next = NULL;
1715 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001716 appctx->ctx.cache.send_notmodified =
1717 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001718
1719 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001720 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_hits, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001721 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001722 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_hits, 1);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001723 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001724 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001725 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001726 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001727 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001728 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001729 }
1730 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001731 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001732
1733 /* Shared context does not need to be locked while we calculate the
1734 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001735 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001736 /* Build a complete secondary hash until the server response
1737 * tells us which fields should be kept (if any). */
1738 http_request_prebuild_full_secondary_key(s);
1739 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001740 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001741}
1742
1743
1744enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1745 struct act_rule *rule, char **err)
1746{
William Lallemand41db4602017-10-30 11:15:51 +01001747 rule->action = ACT_CUSTOM;
1748 rule->action_ptr = http_action_req_cache_use;
1749
Christopher Faulet95220e22018-12-07 17:34:39 +01001750 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001751 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001752
1753 (*orig_arg)++;
1754 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001755}
1756
1757int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1758{
1759 int err_code = 0;
1760
1761 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1762
1763 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001764 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001765 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001766 err_code |= ERR_ALERT | ERR_ABORT;
1767 goto out;
1768 }
1769
1770 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1771 err_code |= ERR_ABORT;
1772 goto out;
1773 }
1774
1775 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001776 struct cache *cache_config;
1777
William Lallemand41db4602017-10-30 11:15:51 +01001778 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1779 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001780 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001781 err_code |= ERR_ALERT | ERR_ABORT;
1782 goto out;
1783 }
1784
1785 strlcpy2(tmp_cache_config->id, args[1], 33);
1786 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001787 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001788 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001789 err_code |= ERR_WARN;
1790 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001791
1792 list_for_each_entry(cache_config, &caches_config, list) {
1793 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1794 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1795 file, linenum, tmp_cache_config->id);
1796 err_code |= ERR_ALERT | ERR_ABORT;
1797 goto out;
1798 }
1799 }
1800
William Lallemand49b44532017-11-24 18:53:43 +01001801 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001802 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001803 tmp_cache_config->maxobjsz = 0;
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001804 tmp_cache_config->max_secondary_entries = DEFAULT_MAX_SECONDARY_ENTRY;
William Lallemand41db4602017-10-30 11:15:51 +01001805 }
1806 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001807 unsigned long int maxsize;
1808 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001809
1810 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1811 err_code |= ERR_ABORT;
1812 goto out;
1813 }
1814
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001815 maxsize = strtoul(args[1], &err, 10);
1816 if (err == args[1] || *err != '\0') {
1817 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1818 file, linenum, args[1]);
1819 err_code |= ERR_ABORT;
1820 goto out;
1821 }
1822
1823 if (maxsize > (UINT_MAX >> 20)) {
1824 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1825 file, linenum, args[1], UINT_MAX >> 20);
1826 err_code |= ERR_ABORT;
1827 goto out;
1828 }
1829
William Lallemand41db4602017-10-30 11:15:51 +01001830 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001831 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001832 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001833 } else if (strcmp(args[0], "max-age") == 0) {
1834 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1835 err_code |= ERR_ABORT;
1836 goto out;
1837 }
1838
1839 if (!*args[1]) {
1840 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1841 file, linenum, args[0]);
1842 err_code |= ERR_WARN;
1843 }
1844
1845 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001846 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001847 unsigned int maxobjsz;
1848 char *err;
1849
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001850 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1851 err_code |= ERR_ABORT;
1852 goto out;
1853 }
1854
1855 if (!*args[1]) {
1856 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1857 file, linenum, args[0]);
1858 err_code |= ERR_WARN;
1859 }
1860
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001861 maxobjsz = strtoul(args[1], &err, 10);
1862 if (err == args[1] || *err != '\0') {
1863 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1864 file, linenum, args[1]);
1865 err_code |= ERR_ABORT;
1866 goto out;
1867 }
1868 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001869 } else if (strcmp(args[0], "process-vary") == 0) {
1870 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1871 err_code |= ERR_ABORT;
1872 goto out;
1873 }
1874
1875 if (!*args[1]) {
1876 ha_warning("parsing [%s:%d]: '%s' expects 0 or 1 (disable or enable vary processing).\n",
1877 file, linenum, args[0]);
1878 err_code |= ERR_WARN;
1879 }
1880
1881 tmp_cache_config->vary_processing_enabled = atoi(args[1]);
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001882 } else if (strcmp(args[0], "max-secondary-entries") == 0) {
1883 unsigned int max_sec_entries;
1884 char *err;
1885
1886 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1887 err_code |= ERR_ABORT;
1888 goto out;
1889 }
1890
1891 if (!*args[1]) {
1892 ha_warning("parsing [%s:%d]: '%s' expects a strictly positive number.\n",
1893 file, linenum, args[0]);
1894 err_code |= ERR_WARN;
1895 }
1896
1897 max_sec_entries = strtoul(args[1], &err, 10);
1898 if (err == args[1] || *err != '\0' || max_sec_entries == 0) {
1899 ha_warning("parsing [%s:%d]: max-secondary-entries wrong value '%s'\n",
1900 file, linenum, args[1]);
1901 err_code |= ERR_ABORT;
1902 goto out;
1903 }
1904 tmp_cache_config->max_secondary_entries = max_sec_entries;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001905 }
1906 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001907 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001908 err_code |= ERR_ALERT | ERR_FATAL;
1909 goto out;
1910 }
1911out:
1912 return err_code;
1913}
1914
1915/* once the cache section is parsed */
1916
1917int cfg_post_parse_section_cache()
1918{
William Lallemand41db4602017-10-30 11:15:51 +01001919 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01001920
1921 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01001922
1923 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001924 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001925 err_code |= ERR_FATAL | ERR_ALERT;
1926 goto out;
1927 }
1928
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001929 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001930 /* Default max. file size is a 256th of the cache size. */
1931 tmp_cache_config->maxobjsz =
1932 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001933 }
1934 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
1935 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
1936 err_code |= ERR_FATAL | ERR_ALERT;
1937 goto out;
1938 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001939
William Lallemandd1d1e222019-08-28 15:22:49 +02001940 /* add to the list of cache to init and reinit tmp_cache_config
1941 * for next cache section, if any.
1942 */
1943 LIST_ADDQ(&caches_config, &tmp_cache_config->list);
1944 tmp_cache_config = NULL;
1945 return err_code;
1946 }
1947out:
1948 free(tmp_cache_config);
1949 tmp_cache_config = NULL;
1950 return err_code;
1951
1952}
1953
1954int post_check_cache()
1955{
1956 struct proxy *px;
1957 struct cache *back, *cache_config, *cache;
1958 struct shared_context *shctx;
1959 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01001960 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02001961
1962 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
1963
1964 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
1965 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001966
Frédéric Lécaillebc584492018-10-25 20:18:59 +02001967 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001968 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01001969 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001970 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01001971 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001972
1973 err_code |= ERR_FATAL | ERR_ALERT;
1974 goto out;
1975 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001976 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02001977 /* the cache structure is stored in the shctx and added to the
1978 * caches list, we can remove the entry from the caches_config
1979 * list */
1980 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01001981 cache = (struct cache *)shctx->data;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001982 cache->entries = EB_ROOT;
William Lallemand41db4602017-10-30 11:15:51 +01001983 LIST_ADDQ(&caches, &cache->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02001984 LIST_DEL(&cache_config->list);
1985 free(cache_config);
1986
1987 /* Find all references for this cache in the existing filters
1988 * (over all proxies) and reference it in matching filters.
1989 */
1990 for (px = proxies_list; px; px = px->next) {
1991 struct flt_conf *fconf;
1992 struct cache_flt_conf *cconf;
1993
1994 list_for_each_entry(fconf, &px->filter_configs, list) {
1995 if (fconf->id != cache_store_flt_id)
1996 continue;
1997
1998 cconf = fconf->conf;
1999 if (!strcmp(cache->id, cconf->c.name)) {
2000 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02002001 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02002002 cconf->c.cache = cache;
2003 break;
2004 }
2005 }
2006 }
William Lallemand41db4602017-10-30 11:15:51 +01002007 }
William Lallemandd1d1e222019-08-28 15:22:49 +02002008
William Lallemand41db4602017-10-30 11:15:51 +01002009out:
William Lallemand41db4602017-10-30 11:15:51 +01002010 return err_code;
2011
William Lallemand41db4602017-10-30 11:15:51 +01002012}
2013
William Lallemand41db4602017-10-30 11:15:51 +01002014struct flt_ops cache_ops = {
2015 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01002016 .check = cache_store_check,
2017 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01002018
Christopher Faulet65554e12020-03-06 14:52:06 +01002019 /* Handle stream init/deinit */
2020 .attach = cache_store_strm_init,
2021 .detach = cache_store_strm_deinit,
2022
William Lallemand4da3f8a2017-10-31 14:33:34 +01002023 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01002024 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002025
2026 /* Filter HTTP requests and responses */
2027 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01002028 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002029 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01002030};
2031
Christopher Faulet99a17a22018-12-11 09:18:27 +01002032
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002033int accept_encoding_cmp(const void *a, const void *b)
2034{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002035 unsigned int int_a = *(unsigned int*)a;
2036 unsigned int int_b = *(unsigned int*)b;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002037
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002038 if (int_a < int_b)
2039 return -1;
2040 if (int_a > int_b)
2041 return 1;
2042 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002043}
2044
Tim Duesterhus23b29452020-11-24 22:22:56 +01002045#define ACCEPT_ENCODING_MAX_ENTRIES 16
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002046/*
2047 * Build a hash of the accept-encoding header. The different parts of the
2048 * header value are first sorted, appended and then a crc is calculated
2049 * for the newly constructed buffer.
2050 * Returns 0 in case of success.
2051 */
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002052static int accept_encoding_normalizer(struct ist full_value, char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002053{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002054 unsigned int values[ACCEPT_ENCODING_MAX_ENTRIES] = {};
Tim Duesterhus23b29452020-11-24 22:22:56 +01002055 size_t count = 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002056 char *comma = NULL;
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002057 unsigned int hash_value = 0;
2058 unsigned int prev = 0, curr = 0;
2059
2060 /* Turn accept-encoding value to lower case */
2061 full_value = ist2bin_lc(istptr(full_value), full_value);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002062
2063 /* The hash will be built out of a sorted list of accepted encodings. */
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002064 while (count < (ACCEPT_ENCODING_MAX_ENTRIES - 1) && (comma = istchr(full_value, ',')) != NULL) {
2065 size_t length = comma - istptr(full_value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002066
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002067 values[count++] = hash_crc32(istptr(full_value), length);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002068
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002069 full_value = istadv(full_value, length + 1);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002070
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002071 }
2072 values[count++] = hash_crc32(istptr(full_value), istlen(full_value));
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002073
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002074 /* Sort the values alphabetically. */
2075 qsort(values, count, sizeof(*values), &accept_encoding_cmp);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002076
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002077 while (count) {
2078 curr = values[--count];
2079 if (curr != prev) {
2080 hash_value ^= curr;
2081 }
2082 prev = curr;
2083 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002084
2085 memcpy(buf, &hash_value, sizeof(hash_value));
2086 *buf_len = sizeof(hash_value);
2087
Tim Duesterhus23b29452020-11-24 22:22:56 +01002088 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002089}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002090#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002091
2092/*
2093 * Normalizer used by default for User-Agent and Referer headers. It only
2094 * calculates a simple crc of the whole value.
2095 * Returns 0 in case of success.
2096 */
2097static int default_normalizer(struct ist value, char *buf, unsigned int *buf_len)
2098{
2099 int hash_value = 0;
2100
2101 hash_value = hash_crc32(istptr(value), istlen(value));
2102
2103 memcpy(buf, &hash_value, sizeof(hash_value));
2104 *buf_len = sizeof(hash_value);
2105
2106 return 0;
2107}
2108
2109
2110/*
2111 * Pre-calculate the hashes of all the supported headers (in our Vary
2112 * implementation) of a given request. We have to calculate all the hashes
2113 * in advance because the actual Vary signature won't be known until the first
2114 * response.
2115 * Only the first occurrence of every header will be taken into account in the
2116 * hash.
2117 * If the header is not present, the hash portion of the given header will be
2118 * filled with zeros.
2119 * Returns 0 in case of success.
2120 */
2121static int http_request_prebuild_full_secondary_key(struct stream *s)
2122{
2123 struct http_txn *txn = s->txn;
2124 struct htx *htx = htxbuf(&s->req.buf);
2125 struct http_hdr_ctx ctx = { .blk = NULL };
2126
2127 unsigned int idx;
2128 const struct vary_hashing_information *info = NULL;
2129 unsigned int hash_length = 0;
2130 int retval = 0;
2131 int offset = 0;
2132
2133 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
2134 info = &vary_information[idx];
2135
2136 ctx.blk = NULL;
2137 if (info->norm_fn != NULL && http_find_header(htx, info->hdr_name, &ctx, 1)) {
2138 retval = info->norm_fn(ctx.value, &txn->cache_secondary_hash[offset], &hash_length);
2139 offset += hash_length;
2140 }
2141 else {
2142 /* Fill hash with 0s. */
2143 hash_length = info->hash_length;
2144 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2145 offset += hash_length;
2146 }
2147 }
2148
2149 return retval;
2150}
2151
2152
2153/*
2154 * Calculate the secondary key for a request for which we already have a known
2155 * vary signature. The key is made by aggregating hashes calculated for every
2156 * header mentioned in the vary signature.
2157 * Only the first occurrence of every header will be taken into account in the
2158 * hash.
2159 * If the header is not present, the hash portion of the given header will be
2160 * filled with zeros.
2161 * Returns 0 in case of success.
2162 */
2163static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2164{
2165 struct http_txn *txn = s->txn;
2166 struct htx *htx = htxbuf(&s->req.buf);
2167 struct http_hdr_ctx ctx = { .blk = NULL };
2168
2169 unsigned int idx;
2170 const struct vary_hashing_information *info = NULL;
2171 unsigned int hash_length = 0;
2172 int retval = 0;
2173 int offset = 0;
2174
2175 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
2176 info = &vary_information[idx];
2177
2178 ctx.blk = NULL;
2179 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2180 http_find_header(htx, info->hdr_name, &ctx, 1)) {
2181 retval = info->norm_fn(ctx.value, &txn->cache_secondary_hash[offset], &hash_length);
2182 offset += hash_length;
2183 }
2184 else {
2185 /* Fill hash with 0s. */
2186 hash_length = info->hash_length;
2187 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2188 offset += hash_length;
2189 }
2190 }
2191
2192 return retval;
2193}
2194
2195/*
2196 * Build the actual secondary key of a given request out of the prebuilt key and
2197 * the actual vary signature (extracted from the response).
2198 * Returns 0 in case of success.
2199 */
2200static int http_request_reduce_secondary_key(unsigned int vary_signature,
2201 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2202{
2203 int offset = 0;
2204 int global_offset = 0;
2205 int vary_info_count = 0;
2206 int keep = 0;
2207 unsigned int vary_idx;
2208 const struct vary_hashing_information *vary_info;
2209
2210 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2211 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2212 vary_info = &vary_information[vary_idx];
2213 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2214
2215 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2216 prebuilt_key[global_offset] &= keep;
2217 }
2218 }
2219
2220 return 0;
2221}
2222
2223
Christopher Faulet99a17a22018-12-11 09:18:27 +01002224
2225static int
2226parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2227 struct flt_conf *fconf, char **err, void *private)
2228{
2229 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002230 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002231 char *name = NULL;
2232 int pos = *cur_arg;
2233
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002234 /* Get the cache filter name. <pos> point on "cache" keyword */
2235 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002236 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002237 goto error;
2238 }
2239 name = strdup(args[pos + 1]);
2240 if (!name) {
2241 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2242 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002243 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002244 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002245
2246 /* Check if an implicit filter with the same name already exists. If so,
2247 * we remove the implicit filter to use the explicit one. */
2248 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2249 if (f->id != cache_store_flt_id)
2250 continue;
2251
2252 cconf = f->conf;
2253 if (strcmp(name, cconf->c.name)) {
2254 cconf = NULL;
2255 continue;
2256 }
2257
2258 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2259 cconf = NULL;
2260 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2261 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002262 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002263 }
2264
2265 /* Remove the implicit filter. <cconf> is kept for the explicit one */
2266 LIST_DEL(&f->list);
2267 free(f);
2268 free(name);
2269 break;
2270 }
2271
2272 /* No implicit cache filter found, create configuration for the explicit one */
2273 if (!cconf) {
2274 cconf = calloc(1, sizeof(*cconf));
2275 if (!cconf) {
2276 memprintf(err, "%s: out of memory", args[*cur_arg]);
2277 goto error;
2278 }
2279 cconf->c.name = name;
2280 }
2281
2282 cconf->flags = 0;
2283 fconf->id = cache_store_flt_id;
2284 fconf->conf = cconf;
2285 fconf->ops = &cache_ops;
2286
2287 *cur_arg = pos;
2288 return 0;
2289
2290 error:
2291 free(name);
2292 free(cconf);
2293 return -1;
2294}
2295
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002296static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002297{
2298 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2299 return 1;
2300
2301 return 0;
2302}
2303
2304static int cli_io_handler_show_cache(struct appctx *appctx)
2305{
2306 struct cache* cache = appctx->ctx.cli.p0;
2307 struct stream_interface *si = appctx->owner;
2308
William Lallemand1f49a362017-11-21 20:01:26 +01002309 if (cache == NULL) {
2310 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
2311 }
2312
2313 list_for_each_entry_from(cache, &caches, list) {
2314 struct eb32_node *node = NULL;
2315 unsigned int next_key;
2316 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002317 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002318
William Lallemand1f49a362017-11-21 20:01:26 +01002319 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002320 if (!next_key) {
2321 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
2322 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002323 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002324 return 0;
2325 }
2326 }
William Lallemand1f49a362017-11-21 20:01:26 +01002327
2328 appctx->ctx.cli.p0 = cache;
2329
2330 while (1) {
2331
2332 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002333 if (!node || (node = eb32_next_dup(node)) == NULL)
2334 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002335 if (!node) {
2336 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02002337 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002338 break;
2339 }
2340
2341 entry = container_of(node, struct cache_entry, eb);
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002342 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2343 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2344 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2345 chunk_appendf(&trash, " size:%u (%u blocks), refcount:%u, expire:%d\n", 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 +01002346
2347 next_key = node->key + 1;
2348 appctx->ctx.cli.i0 = next_key;
2349
2350 shctx_unlock(shctx_ptr(cache));
2351
2352 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002353 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002354 return 0;
2355 }
2356 }
2357
2358 }
2359
2360 return 1;
2361
2362}
2363
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002364
2365/*
2366 * boolean, returns true if response was built out of a cache entry.
2367 */
2368static int
2369smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2370 const char *kw, void *private)
2371{
2372 smp->data.type = SMP_T_BOOL;
2373 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2374
2375 return 1;
2376}
2377
2378/*
2379 * string, returns cache name (if response came from a cache).
2380 */
2381static int
2382smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2383 const char *kw, void *private)
2384{
2385 struct appctx *appctx = NULL;
2386
2387 struct cache_flt_conf *cconf = NULL;
2388 struct cache *cache = NULL;
2389
2390 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2391 return 0;
2392
2393 /* Get appctx from the stream_interface. */
2394 appctx = si_appctx(&smp->strm->si[1]);
2395 if (appctx && appctx->rule) {
2396 cconf = appctx->rule->arg.act.p[0];
2397 if (cconf) {
2398 cache = cconf->c.cache;
2399
2400 smp->data.type = SMP_T_STR;
2401 smp->flags = SMP_F_CONST;
2402 smp->data.u.str.area = cache->id;
2403 smp->data.u.str.data = strlen(cache->id);
2404 return 1;
2405 }
2406 }
2407
2408 return 0;
2409}
2410
Christopher Faulet99a17a22018-12-11 09:18:27 +01002411/* Declare the filter parser for "cache" keyword */
2412static struct flt_kw_list filter_kws = { "CACHE", { }, {
2413 { "cache", parse_cache_flt, NULL },
2414 { NULL, NULL, NULL },
2415 }
2416};
2417
2418INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2419
William Lallemand1f49a362017-11-21 20:01:26 +01002420static struct cli_kw_list cli_kws = {{},{
William Lallemande899af82017-11-22 16:41:26 +01002421 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
2422 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002423}};
2424
Willy Tarreau0108d902018-11-25 19:14:37 +01002425INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002426
William Lallemand41db4602017-10-30 11:15:51 +01002427static struct action_kw_list http_res_actions = {
2428 .kw = {
2429 { "cache-store", parse_cache_store },
2430 { NULL, NULL }
2431 }
2432};
2433
Willy Tarreau0108d902018-11-25 19:14:37 +01002434INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2435
William Lallemand41db4602017-10-30 11:15:51 +01002436static struct action_kw_list http_req_actions = {
2437 .kw = {
2438 { "cache-use", parse_cache_use },
2439 { NULL, NULL }
2440 }
2441};
2442
Willy Tarreau0108d902018-11-25 19:14:37 +01002443INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2444
Willy Tarreau2231b632019-03-29 18:26:52 +01002445struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002446 .obj_type = OBJ_TYPE_APPLET,
2447 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002448 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002449 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002450};
2451
Willy Tarreaue6552512018-11-26 11:33:13 +01002452/* config parsers for this section */
2453REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002454REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002455
2456
2457/* Note: must not be declared <const> as its list will be overwritten */
2458static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2459 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2460 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2461 { /* END */ },
2462 }
2463};
2464
2465INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);