blob: 60946decddbde1a3683704b09246f3bbd1fe4699 [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 Breton754b2422020-11-16 15:56:10 +010052 uint8_t vary_processing_enabled; /* boolean : manage Vary header (disabled by default) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010053 char id[33]; /* cache name */
William Lallemand41db4602017-10-30 11:15:51 +010054};
55
Christopher Faulet95220e22018-12-07 17:34:39 +010056/* cache config for filters */
57struct cache_flt_conf {
58 union {
59 struct cache *cache; /* cache used by the filter */
60 char *name; /* cache name used during conf parsing */
61 } c;
62 unsigned int flags; /* CACHE_FLT_F_* */
63};
64
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010065
66/*
67 * Vary-related structures and functions
68 */
69enum vary_header_bit {
70 VARY_ACCEPT_ENCODING = (1 << 0),
71 VARY_REFERER = (1 << 1),
72 VARY_LAST /* should always be last */
73};
74
75typedef int(*http_header_normalizer)(struct ist value, char *buf, unsigned int *buf_len);
76
77struct vary_hashing_information {
78 struct ist hdr_name; /* Header name */
79 enum vary_header_bit value; /* Bit repesenting the header in a vary signature */
80 unsigned int hash_length; /* Size of the sub hash for this header's value */
81 http_header_normalizer norm_fn; /* Normalization function */
82};
83
84static int accept_encoding_normalizer(struct ist value, char *buf, unsigned int *buf_len);
85static int default_normalizer(struct ist value, char *buf, unsigned int *buf_len);
86
87/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
88 * added to this array. */
89const struct vary_hashing_information vary_information[] = {
90 { IST("accept-encoding"), VARY_ACCEPT_ENCODING, sizeof(int), &accept_encoding_normalizer },
91 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer },
92};
93
94static int http_request_prebuild_full_secondary_key(struct stream *s);
95static int http_request_build_secondary_key(struct stream *s, int vary_signature);
96static int http_request_reduce_secondary_key(unsigned int vary_signature,
97 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
98
99
William Lallemand41db4602017-10-30 11:15:51 +0100100/*
101 * cache ctx for filters
102 */
103struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100104 struct shared_block *first_block;
105};
106
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100107#define SECONDARY_ENTRY_MAX_COUNT 10
108
William Lallemand41db4602017-10-30 11:15:51 +0100109struct cache_entry {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100110 unsigned int complete; /* An entry won't be valid until complete is not null. */
William Lallemand41db4602017-10-30 11:15:51 +0100111 unsigned int latest_validation; /* latest validation date */
112 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200113 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100114
William Lallemand41db4602017-10-30 11:15:51 +0100115 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100116 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200117
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100118 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
119 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
120 * to build secondary keys for this cache entry. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100121 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 +0100122 unsigned int last_clear_ts; /* Timestamp of the last call to clear_expired_duplicates. */
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100123
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200124 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
125 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
126
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200127 time_t last_modified; /* Origin server "Last-Modified" header value converted in
128 * seconds since epoch. If no "Last-Modified"
129 * header is found, use "Date" header value,
130 * otherwise use reception time. This field will
131 * be used in case of an "If-Modified-Since"-based
132 * conditional request. */
133
William Lallemand41db4602017-10-30 11:15:51 +0100134 unsigned char data[0];
135};
136
137#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100138#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100139
140static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200141static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100142static struct cache *tmp_cache_config = NULL;
143
Willy Tarreau8ceae722018-11-26 11:58:30 +0100144DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
145
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100146static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry);
147static void delete_entry(struct cache_entry *del_entry);
148
William Lallemandf528fff2017-11-23 19:43:17 +0100149struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100150{
151 struct eb32_node *node;
152 struct cache_entry *entry;
153
Willy Tarreau8b507582020-02-25 09:35:07 +0100154 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100155 if (!node)
156 return NULL;
157
158 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100159
160 /* if that's not the right node */
161 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
162 return NULL;
163
William Lallemand08727662017-11-21 20:01:27 +0100164 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100165 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100166 } else {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100167 delete_entry(entry);
William Lallemand08727662017-11-21 20:01:27 +0100168 entry->eb.key = 0;
169 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100170 return NULL;
171
172}
173
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100174/*
175 * There can be multiple entries with the same primary key in the ebtree so in
176 * order to get the proper one out of the list, we use a secondary_key.
177 * This function simply iterates over all the entries with the same primary_key
178 * until it finds the right one.
179 * Returns the cache_entry in case of success, NULL otherwise.
180 */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100181struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
182 char *secondary_key)
183{
184 struct eb32_node *node = &entry->eb;
185
186 if (!entry->secondary_key_signature)
187 return NULL;
188
189 while (entry && memcmp(entry->secondary_key, secondary_key, HTTP_CACHE_SEC_KEY_LEN) != 0) {
190 node = eb32_next_dup(node);
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100191
192 /* Make the best use of this iteration and clear expired entries
193 * when we find them. Calling delete_entry would be too costly
194 * so we simply call eb32_delete. The secondary_entry count will
195 * be updated when we try to insert a new entry to this list. */
196 if (entry->expire <= now.tv_sec) {
197 eb32_delete(&entry->eb);
198 entry->eb.key = 0;
199 }
200
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100201 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
202 }
203
204 /* Expired entry */
205 if (entry && entry->expire <= now.tv_sec) {
206 eb32_delete(&entry->eb);
207 entry->eb.key = 0;
208 entry = NULL;
209 }
210
211 return entry;
212}
213
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100214
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100215/*
216 * Remove all expired entries from a list of duplicates.
217 * Return the number of alive entries in the list and sets dup_tail to the
218 * current last item of the list.
219 */
220static unsigned int clear_expired_duplicates(struct eb32_node **dup_tail)
221{
222 unsigned int entry_count = 0;
223 struct cache_entry *entry = NULL;
224 struct eb32_node *prev = *dup_tail;
225 struct eb32_node *tail = NULL;
226
227 while (prev) {
228 entry = container_of(prev, struct cache_entry, eb);
229 prev = eb32_prev_dup(prev);
230 if (entry->expire <= now.tv_sec) {
231 eb32_delete(&entry->eb);
232 entry->eb.key = 0;
233 }
234 else {
235 if (!tail)
236 tail = &entry->eb;
237 ++entry_count;
238 }
239 }
240
241 *dup_tail = tail;
242
243 return entry_count;
244}
245
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100246
247/*
248 * This function inserts a cache_entry in the cache's ebtree. In case of
249 * duplicate entries (vary), it then checks that the number of entries did not
250 * reach the max number of secondary entries. If this entry should not have been
251 * created, remove it.
252 * In the regular case (unique entries), this function does not do more than a
253 * simple insert. In case of secondary entries, it will at most cost an
254 * insertion+max_sec_entries time checks and entry deletion.
255 * Returns the newly inserted node in case of success, NULL otherwise.
256 */
257static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry)
258{
259 struct eb32_node *prev = NULL;
260 struct cache_entry *entry = NULL;
261 unsigned int entry_count = 0;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100262 unsigned int last_clear_ts = now.tv_sec;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100263
264 struct eb32_node *node = eb32_insert(&cache->entries, &new_entry->eb);
265
266 /* We should not have multiple entries with the same primary key unless
267 * the entry has a non null vary signature. */
268 if (!new_entry->secondary_key_signature)
269 return node;
270
271 prev = eb32_prev_dup(node);
272 if (prev != NULL) {
273 /* The last entry of a duplicate list should contain the current
274 * number of entries in the list. */
275 entry = container_of(prev, struct cache_entry, eb);
276 entry_count = entry->secondary_entries_count;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100277 last_clear_ts = entry->last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100278
279 if (entry_count >= SECONDARY_ENTRY_MAX_COUNT) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100280 /* Some entries of the duplicate list might be expired so
281 * we will iterate over all the items in order to free some
282 * space. In order to avoid going over the same list too
283 * often, we first check the timestamp of the last check
284 * performed. */
285 if (last_clear_ts == now.tv_sec) {
286 /* Too many entries for this primary key, clear the
287 * one that was inserted. */
288 eb32_delete(node);
289 node->key = 0;
290 return NULL;
291 }
292
293 entry_count = clear_expired_duplicates(&prev);
294 if (entry_count >= SECONDARY_ENTRY_MAX_COUNT) {
295 /* Still too many entries for this primary key, delete
296 * the newly inserted one. */
297 entry = container_of(prev, struct cache_entry, eb);
298 entry->last_clear_ts = now.tv_sec;
299 eb32_delete(node);
300 node->key = 0;
301 return NULL;
302 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100303 }
304 }
305
306 new_entry->secondary_entries_count = entry_count + 1;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100307 new_entry->last_clear_ts = last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100308
309 return node;
310}
311
312
313/*
314 * This function removes an entry from the ebtree. If the entry was a duplicate
315 * (in case of Vary), it updates the secondary entry counter in another
316 * duplicate entry (the last entry of the dup list).
317 */
318static void delete_entry(struct cache_entry *del_entry)
319{
320 struct eb32_node *prev = NULL, *next = NULL;
321 struct cache_entry *entry = NULL;
322 struct eb32_node *last = NULL;
323
324 if (del_entry->secondary_key_signature) {
325 next = &del_entry->eb;
326
327 /* Look for last entry of the duplicates list. */
328 while ((next = eb32_next_dup(next))) {
329 last = next;
330 }
331
332 if (last) {
333 entry = container_of(last, struct cache_entry, eb);
334 --entry->secondary_entries_count;
335 }
336 else {
337 /* The current entry is the last one, look for the
338 * previous one to update its counter. */
339 prev = eb32_prev_dup(&del_entry->eb);
340 if (prev) {
341 entry = container_of(prev, struct cache_entry, eb);
342 entry->secondary_entries_count = del_entry->secondary_entries_count - 1;
343 }
344 }
345 }
346 eb32_delete(&del_entry->eb);
347 del_entry->eb.key = 0;
348}
349
350
William Lallemand4da3f8a2017-10-31 14:33:34 +0100351static inline struct shared_context *shctx_ptr(struct cache *cache)
352{
353 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
354}
355
William Lallemand77c11972017-10-31 20:43:01 +0100356static inline struct shared_block *block_ptr(struct cache_entry *entry)
357{
358 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
359}
360
361
362
William Lallemand41db4602017-10-30 11:15:51 +0100363static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100364cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100365{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100366 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100367 return 0;
368}
369
Christopher Faulet95220e22018-12-07 17:34:39 +0100370static void
371cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
372{
373 struct cache_flt_conf *cconf = fconf->conf;
374
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200375 if (!(cconf->flags & CACHE_FLT_INIT))
376 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100377 free(cconf);
378}
379
William Lallemand4da3f8a2017-10-31 14:33:34 +0100380static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100381cache_store_check(struct proxy *px, struct flt_conf *fconf)
382{
383 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100384 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100385 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100386 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100387
William Lallemandd1d1e222019-08-28 15:22:49 +0200388 /* Find the cache corresponding to the name in the filter config. The
389 * cache will not be referenced now in the filter config because it is
390 * not fully allocated. This step will be performed during the cache
391 * post_check.
392 */
393 list_for_each_entry(cache, &caches_config, list) {
394 if (!strcmp(cache->id, cconf->c.name))
Christopher Faulet95220e22018-12-07 17:34:39 +0100395 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100396 }
397
398 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
399 proxy_type_str(px), px->id, (char *)cconf->c.name);
400 return 1;
401
402 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100403 /* Here <cache> points on the cache the filter must use and <cconf>
404 * points on the cache filter configuration. */
405
406 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100407 * enabled and if it is after the cache. When the compression is before
408 * the cache, an error is returned. Also check if the cache filter must
409 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100410 list_for_each_entry(f, &px->filter_configs, list) {
411 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100412 /* The compression filter must be evaluated after the cache. */
413 if (comp) {
414 ha_alert("config: %s '%s': unable to enable the compression filter before "
415 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
416 return 1;
417 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100418 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200419 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100420 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200421 else if (f->id == fcgi_flt_id)
422 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100423 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
424 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200425 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100426 * declaration is required. */
427 ha_alert("config: %s '%s': require an explicit filter declaration "
428 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
429 return 1;
430 }
431
Christopher Fauletafd819c2018-12-11 08:57:45 +0100432 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100433 return 0;
434}
435
436static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100437cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100438{
Christopher Faulet65554e12020-03-06 14:52:06 +0100439 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100440
Christopher Faulet65554e12020-03-06 14:52:06 +0100441 st = pool_alloc_dirty(pool_head_cache_st);
442 if (st == NULL)
443 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100444
Christopher Faulet65554e12020-03-06 14:52:06 +0100445 st->first_block = NULL;
446 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100447
Christopher Faulet65554e12020-03-06 14:52:06 +0100448 /* Register post-analyzer on AN_RES_WAIT_HTTP */
449 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100450 return 1;
451}
452
Christopher Faulet65554e12020-03-06 14:52:06 +0100453static void
454cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100455{
456 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100457 struct cache_flt_conf *cconf = FLT_CONF(filter);
458 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100459 struct shared_context *shctx = shctx_ptr(cache);
460
William Lallemand49dc0482017-11-24 14:33:54 +0100461 /* Everything should be released in the http_end filter, but we need to do it
462 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100463 if (st && st->first_block) {
William Lallemand49dc0482017-11-24 14:33:54 +0100464 shctx_lock(shctx);
465 shctx_row_dec_hot(shctx, st->first_block);
466 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100467 }
468 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100469 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100470 filter->ctx = NULL;
471 }
William Lallemand49dc0482017-11-24 14:33:54 +0100472}
473
Christopher Faulet839791a2019-01-07 16:12:07 +0100474static int
475cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
476 unsigned an_bit)
477{
478 struct http_txn *txn = s->txn;
479 struct http_msg *msg = &txn->rsp;
480 struct cache_st *st = filter->ctx;
481
482 if (an_bit != AN_RES_WAIT_HTTP)
483 goto end;
484
485 /* Here we need to check if any compression filter precedes the cache
486 * filter. This is only possible when the compression is configured in
487 * the frontend while the cache filter is configured on the
488 * backend. This case cannot be detected during HAProxy startup. So in
489 * such cases, the cache is disabled.
490 */
491 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
492 pool_free(pool_head_cache_st, st);
493 filter->ctx = NULL;
494 }
495
496 end:
497 return 1;
498}
William Lallemand49dc0482017-11-24 14:33:54 +0100499
500static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100501cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
502{
503 struct cache_st *st = filter->ctx;
504
William Lallemand4da3f8a2017-10-31 14:33:34 +0100505 if (!(msg->chn->flags & CF_ISRESP) || !st)
506 return 1;
507
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200508 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100509 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100510 return 1;
511}
512
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200513static inline void disable_cache_entry(struct cache_st *st,
514 struct filter *filter, struct shared_context *shctx)
515{
516 struct cache_entry *object;
517
518 object = (struct cache_entry *)st->first_block->data;
519 filter->ctx = NULL; /* disable cache */
520 shctx_lock(shctx);
521 shctx_row_dec_hot(shctx, st->first_block);
Remi Tricot-Le Breton964caaf2020-12-15 14:30:12 +0100522 eb32_delete(&object->eb);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200523 object->eb.key = 0;
524 shctx_unlock(shctx);
525 pool_free(pool_head_cache_st, st);
526}
527
William Lallemand4da3f8a2017-10-31 14:33:34 +0100528static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100529cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
530 unsigned int offset, unsigned int len)
531{
Christopher Faulet95220e22018-12-07 17:34:39 +0100532 struct cache_flt_conf *cconf = FLT_CONF(filter);
533 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100534 struct cache_st *st = filter->ctx;
535 struct htx *htx = htxbuf(&msg->chn->buf);
536 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200537 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100538 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200539 unsigned int orig_len, to_forward;
540 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100541
542 if (!len)
543 return len;
544
545 if (!st->first_block) {
546 unregister_data_filter(s, msg->chn, filter);
547 return len;
548 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100549
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200550 chunk_reset(&trash);
551 orig_len = len;
552 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100553
554 htxret = htx_find_offset(htx, offset);
555 blk = htxret.blk;
556 offset = htxret.ret;
557 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100558 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200559 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100560 struct ist v;
561
562 switch (type) {
563 case HTX_BLK_UNUSED:
564 break;
565
566 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100567 v = htx_get_blk_value(htx, blk);
568 v.ptr += offset;
569 v.len -= offset;
570 if (v.len > len)
571 v.len = len;
572
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200573 info = (type << 28) + v.len;
574 chunk_memcat(&trash, (char *)&info, sizeof(info));
575 chunk_memcat(&trash, v.ptr, v.len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100576 to_forward += v.len;
577 len -= v.len;
578 break;
579
580 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200581 /* Here offset must always be 0 because only
582 * DATA blocks can be partially transferred. */
583 if (offset)
584 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100585 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200586 goto end;
587
588 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
589 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100590 to_forward += sz;
591 len -= sz;
592 break;
593 }
594
595 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100596 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200597
598 end:
599 shctx_lock(shctx);
600 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
601 if (!fb) {
602 shctx_unlock(shctx);
603 goto no_cache;
604 }
605 shctx_unlock(shctx);
606
607 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
608 (unsigned char *)b_head(&trash), b_data(&trash));
609 if (ret < 0)
610 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100611
612 return to_forward;
613
614 no_cache:
615 disable_cache_entry(st, filter, shctx);
616 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200617 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100618}
619
620static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100621cache_store_http_end(struct stream *s, struct filter *filter,
622 struct http_msg *msg)
623{
624 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100625 struct cache_flt_conf *cconf = FLT_CONF(filter);
626 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100627 struct shared_context *shctx = shctx_ptr(cache);
628 struct cache_entry *object;
629
630 if (!(msg->chn->flags & CF_ISRESP))
631 return 1;
632
633 if (st && st->first_block) {
634
635 object = (struct cache_entry *)st->first_block->data;
636
William Lallemand4da3f8a2017-10-31 14:33:34 +0100637 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100638 /* The whole payload was cached, the entry can now be used. */
639 object->complete = 1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100640 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100641 shctx_row_dec_hot(shctx, st->first_block);
642 shctx_unlock(shctx);
643
644 }
645 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100646 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100647 filter->ctx = NULL;
648 }
649
650 return 1;
651}
652
653 /*
654 * This intends to be used when checking HTTP headers for some
655 * word=value directive. Return a pointer to the first character of value, if
656 * the word was not found or if there wasn't any value assigned ot it return NULL
657 */
658char *directive_value(const char *sample, int slen, const char *word, int wlen)
659{
660 int st = 0;
661
662 if (slen < wlen)
663 return 0;
664
665 while (wlen) {
666 char c = *sample ^ *word;
667 if (c && c != ('A' ^ 'a'))
668 return NULL;
669 sample++;
670 word++;
671 slen--;
672 wlen--;
673 }
674
675 while (slen) {
676 if (st == 0) {
677 if (*sample != '=')
678 return NULL;
679 sample++;
680 slen--;
681 st = 1;
682 continue;
683 } else {
684 return (char *)sample;
685 }
686 }
687
688 return NULL;
689}
690
691/*
692 * Return the maxage in seconds of an HTTP response.
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100693 * The returned value will always take the cache's configuration into account
694 * (cache->maxage) but the actual max age of the response will be set in the
695 * true_maxage parameter. It will be used to determine if a response is already
696 * stale or not.
William Lallemand4da3f8a2017-10-31 14:33:34 +0100697 * Compute the maxage using either:
698 * - the assigned max-age of the cache
699 * - the s-maxage directive
700 * - the max-age directive
701 * - (Expires - Data) headers
702 * - the default-max-age of the cache
703 *
704 */
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100705int http_calc_maxage(struct stream *s, struct cache *cache, int *true_maxage)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100706{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200707 struct htx *htx = htxbuf(&s->res.buf);
708 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100709 long smaxage = -1;
710 long maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100711 int expires = -1;
712 struct tm tm = {};
713 time_t expires_val = 0;
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100714 char *endptr = NULL;
715 int offset = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100716
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100717 /* The Cache-Control max-age and s-maxage directives should be followed by
718 * a positive numerical value (see RFC 7234#5.2.1.1). According to the
719 * specs, a sender "should not" generate a quoted-string value but we will
720 * still accept this format since it isn't strictly forbidden. */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200721 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
722 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100723
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200724 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
725 if (value) {
726 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100727
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200728 chunk_strncat(chk, value, ctx.value.len - 8 + 1);
729 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100730 offset = (*chk->area == '"') ? 1 : 0;
731 smaxage = strtol(chk->area + offset, &endptr, 10);
732 if (unlikely(smaxage < 0 || endptr == chk->area))
733 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100734 }
735
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200736 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
737 if (value) {
738 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200739
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200740 chunk_strncat(chk, value, ctx.value.len - 7 + 1);
741 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100742 offset = (*chk->area == '"') ? 1 : 0;
743 maxage = strtol(chk->area + offset, &endptr, 10);
744 if (unlikely(maxage < 0 || endptr == chk->area))
745 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100746 }
747 }
748
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100749 /* Look for Expires header if no s-maxage or max-age Cache-Control data
750 * was found. */
751 if (maxage == -1 && smaxage == -1) {
752 ctx.blk = NULL;
753 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
754 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
755 expires_val = my_timegm(&tm);
756 /* A request having an expiring date earlier
757 * than the current date should be considered as
758 * stale. */
759 expires = (expires_val >= now.tv_sec) ?
760 (expires_val - now.tv_sec) : 0;
761 }
762 else {
763 /* Following RFC 7234#5.3, an invalid date
764 * format must be treated as a date in the past
765 * so the cache entry must be seen as already
766 * expired. */
767 expires = 0;
768 }
769 }
770 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100771
772
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100773 if (smaxage > 0) {
774 if (true_maxage)
775 *true_maxage = smaxage;
William Lallemand49b44532017-11-24 18:53:43 +0100776 return MIN(smaxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100777 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100778
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100779 if (maxage > 0) {
780 if (true_maxage)
781 *true_maxage = maxage;
William Lallemand49b44532017-11-24 18:53:43 +0100782 return MIN(maxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100783 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100784
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100785 if (expires >= 0) {
786 if (true_maxage)
787 *true_maxage = expires;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100788 return MIN(expires, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100789 }
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100790
William Lallemand49b44532017-11-24 18:53:43 +0100791 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100792
793}
794
795
William Lallemanda400a3a2017-11-20 19:13:12 +0100796static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
797{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200798 struct cache_entry *object = (struct cache_entry *)block->data;
799
800 if (first == block && object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100801 delete_entry(object);
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200802 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100803}
804
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200805
806/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
807 * date value should be compared to a date determined by in a previous response (for
808 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
809 * value of the response's reception time (by decreasing order of priority). */
810static time_t get_last_modified_time(struct htx *htx)
811{
812 time_t last_modified = 0;
813 struct http_hdr_ctx ctx = { .blk = NULL };
814 struct tm tm = {};
815
816 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
817 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
818 last_modified = my_timegm(&tm);
819 }
820 }
821
822 if (!last_modified) {
823 ctx.blk = NULL;
824 if (http_find_header(htx, ist("date"), &ctx, 1)) {
825 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
826 last_modified = my_timegm(&tm);
827 }
828 }
829 }
830
831 /* Fallback on the current time if no "Last-Modified" or "Date" header
832 * was found. */
833 if (!last_modified)
834 last_modified = now.tv_sec;
835
836 return last_modified;
837}
838
William Lallemand41db4602017-10-30 11:15:51 +0100839/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100840 * Checks the vary header's value. The headers on which vary should be applied
841 * must be explicitely supported in the vary_information array (see cache.c). If
842 * any other header is mentioned, we won't store the response.
843 * Returns 1 if Vary-based storage can work, 0 otherwise.
844 */
845static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
846{
847 unsigned int vary_idx;
848 unsigned int vary_info_count;
849 const struct vary_hashing_information *vary_info;
850 struct http_hdr_ctx ctx = { .blk = NULL };
851
852 int retval = 1;
853
854 *vary_signature = 0;
855
856 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
857 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
858 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
859 vary_info = &vary_information[vary_idx];
860 if (isteqi(ctx.value, vary_info->hdr_name)) {
861 *vary_signature |= vary_info->value;
862 break;
863 }
864 }
865 retval = (vary_idx < vary_info_count);
866 }
867
868 return retval;
869}
870
871
872
873/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500874 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100875 * register a filter to store the data
876 */
877enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200878 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100879{
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200880 long long hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100881 int effective_maxage = 0;
882 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100883 struct http_txn *txn = s->txn;
884 struct http_msg *msg = &txn->rsp;
885 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100886 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100887 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100888 struct cache *cache = cconf->c.cache;
889 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100890 struct cache_st *cache_ctx = NULL;
891 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +0100892 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200893 struct htx *htx;
894 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +0200895 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200896 int32_t pos;
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200897 struct ist header_name = IST_NULL;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100898 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100899
William Lallemand4da3f8a2017-10-31 14:33:34 +0100900 /* Don't cache if the response came from a cache */
901 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
902 s->target == &http_cache_applet.obj_type) {
903 goto out;
904 }
905
906 /* cache only HTTP/1.1 */
907 if (!(txn->req.flags & HTTP_MSGF_VER_11))
908 goto out;
909
Willy Tarreau6905d182019-10-01 17:59:17 +0200910 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +0100911 if (txn->meth != HTTP_METH_GET) {
912 /* In case of successful unsafe method on a stored resource, the
913 * cached entry must be invalidated (see RFC7234#4.4).
914 * A "non-error response" is one with a 2xx (Successful) or 3xx
915 * (Redirection) status code. */
916 if (txn->status >= 200 && txn->status < 400) {
917 switch (txn->meth) {
918 case HTTP_METH_OPTIONS:
919 case HTTP_METH_GET:
920 case HTTP_METH_HEAD:
921 case HTTP_METH_TRACE:
922 break;
923
924 default: /* Any unsafe method */
925 /* Discard any corresponding entry in case of sucessful
926 * unsafe request (such as PUT, POST or DELETE). */
927 shctx_lock(shctx);
928
929 old = entry_exist(cconf->c.cache, txn->cache_hash);
930 if (old) {
931 eb32_delete(&old->eb);
932 old->eb.key = 0;
933 }
934 shctx_unlock(shctx);
935 }
936 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100937 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +0100938 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100939
Willy Tarreauc9036c02019-01-11 19:38:25 +0100940 /* cache key was not computed */
941 if (!key)
942 goto out;
943
William Lallemand4da3f8a2017-10-31 14:33:34 +0100944 /* cache only 200 status code */
945 if (txn->status != 200)
946 goto out;
947
Christopher Faulet839791a2019-01-07 16:12:07 +0100948 /* Find the corresponding filter instance for the current stream */
949 list_for_each_entry(filter, &s->strm_flt.filters, list) {
950 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
951 /* No filter ctx, don't cache anything */
952 if (!filter->ctx)
953 goto out;
954 cache_ctx = filter->ctx;
955 break;
956 }
957 }
958
959 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200960 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100961
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200962 /* Do not cache too big objects. */
963 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
964 htx->data + htx->extra > shctx->max_obj_size)
965 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100966
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100967 /* Only a subset of headers are supported in our Vary implementation. If
968 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100969 * able to use the cache. Likewise, if Vary header support is disabled,
970 * avoid caching responses that contain such a header. */
971 ctx.blk = NULL;
972 if (cache->vary_processing_enabled) {
973 if (!http_check_vary_header(htx, &vary_signature))
974 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100975 if (vary_signature)
976 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100977 }
978 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200979 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100980 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100981
Christopher Fauletfc9cfe42019-07-16 14:54:53 +0200982 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100983
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +0100984 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200985 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100986
987 shctx_lock(shctx);
988 old = entry_exist(cache, txn->cache_hash);
989 if (old) {
990 if (vary_signature)
991 old = secondary_entry_exist(cconf->c.cache, old,
992 txn->cache_secondary_hash);
993 if (old) {
994 if (!old->complete) {
995 /* An entry with the same primary key is already being
996 * created, we should not try to store the current
997 * response because it will waste space in the cache. */
998 shctx_unlock(shctx);
999 goto out;
1000 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001001 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001002 old->eb.key = 0;
1003 }
1004 }
1005 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1006 if (!first) {
1007 shctx_unlock(shctx);
1008 goto out;
1009 }
1010 /* the received memory is not initialized, we need at least to mark
1011 * the object as not indexed yet.
1012 */
1013 object = (struct cache_entry *)first->data;
1014 memset(object, 0, sizeof(*object));
1015 object->eb.key = key;
1016 object->secondary_key_signature = vary_signature;
1017 /* We need to temporarily set a valid expiring time until the actual one
1018 * is set by the end of this function (in case of concurrent accesses to
1019 * the same resource). This way the second access will find an existing
1020 * but not yet usable entry in the tree and will avoid storing its data. */
1021 object->expire = now.tv_sec + 2;
1022
1023 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1024 if (vary_signature)
1025 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1026
1027 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001028 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001029 object->eb.key = 0;
1030 shctx_unlock(shctx);
1031 goto out;
1032 }
1033 shctx_unlock(shctx);
1034
1035 /* reserve space for the cache_entry structure */
1036 first->len = sizeof(struct cache_entry);
1037 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001038
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001039 /* Determine the entry's maximum age (taking into account the cache's
1040 * configuration) as well as the response's explicit max age (extracted
1041 * from cache-control directives or the expires header). */
1042 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1043
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001044 ctx.blk = NULL;
1045 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
1046 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1047 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1048 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001049 /* A response with an Age value greater than its
1050 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001051 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001052 if (unlikely(object->age > true_maxage))
1053 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001054 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001055 else
1056 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001057 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001058 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001059
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001060 /* Build a last-modified time that will be stored in the cache_entry and
1061 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001062 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001063
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001064 chunk_reset(&trash);
1065 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1066 struct htx_blk *blk = htx_get_blk(htx, pos);
1067 enum htx_blk_type type = htx_get_blk_type(blk);
1068 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001069
Christopher Fauletb0667472019-09-03 22:22:12 +02001070 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001071 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1072 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001073
1074 /* Look for optional ETag header.
1075 * We need to store the offset of the ETag value in order for
1076 * future conditional requests to be able to perform ETag
1077 * comparisons. */
1078 if (type == HTX_BLK_HDR) {
1079 header_name = htx_get_blk_name(htx, blk);
1080 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001081 object->etag_length = sz - istlen(header_name);
1082 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001083 }
1084 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001085 if (type == HTX_BLK_EOH)
1086 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001087 }
1088
Christopher Fauletb0667472019-09-03 22:22:12 +02001089 /* Do not cache objects if the headers are too big. */
1090 if (hdrs_len > htx->size - global.tune.maxrewrite)
1091 goto out;
1092
William Lallemand4da3f8a2017-10-31 14:33:34 +01001093 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001094 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001095 shctx_unlock(shctx);
1096 goto out;
1097 }
1098 shctx_unlock(shctx);
1099
William Lallemand4da3f8a2017-10-31 14:33:34 +01001100 /* cache the headers in a http action because it allows to chose what
1101 * to cache, for example you might want to cache a response before
1102 * modifying some HTTP headers, or on the contrary after modifying
1103 * those headers.
1104 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001105 /* does not need to be locked because it's in the "hot" list,
1106 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001107 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1108 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001109
1110 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001111 if (cache_ctx) {
1112 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001113 /* store latest value and expiration time */
1114 object->latest_validation = now.tv_sec;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001115 object->expire = now.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001116 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001117 }
1118
1119out:
1120 /* if does not cache */
1121 if (first) {
1122 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001123 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001124 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001125 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001126 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001127 shctx_row_dec_hot(shctx, first);
1128 shctx_unlock(shctx);
1129 }
1130
William Lallemand41db4602017-10-30 11:15:51 +01001131 return ACT_RET_CONT;
1132}
1133
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001134#define HTX_CACHE_INIT 0 /* Initial state. */
1135#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1136#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001137#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1138#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001139
William Lallemandecb73b12017-11-24 14:33:55 +01001140static void http_cache_applet_release(struct appctx *appctx)
1141{
Christopher Faulet95220e22018-12-07 17:34:39 +01001142 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +01001143 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001144 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001145 struct shared_block *first = block_ptr(cache_ptr);
1146
1147 shctx_lock(shctx_ptr(cache));
1148 shctx_row_dec_hot(shctx_ptr(cache), first);
1149 shctx_unlock(shctx_ptr(cache));
1150}
1151
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001152
1153static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1154 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001155{
Christopher Faulet95220e22018-12-07 17:34:39 +01001156 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1157 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001158 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001159 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001160 unsigned int max, total;
1161 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001162
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001163 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1164 if (!max)
1165 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001166 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001167 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1168 : info & 0xfffffff);
1169 if (blksz > max)
1170 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001171
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001172 blk = htx_add_blk(htx, type, blksz);
1173 if (!blk)
1174 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001175
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001176 blk->info = info;
1177 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001178 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001179 while (blksz) {
1180 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001181 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001182 offset += max;
1183 blksz -= max;
1184 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001185 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001186 if (blksz || offset == shctx->block_size) {
1187 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1188 offset = 0;
1189 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001190 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001191 appctx->ctx.cache.offset = offset;
1192 appctx->ctx.cache.next = shblk;
1193 appctx->ctx.cache.sent += total;
1194 return total;
1195}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001196
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001197static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1198 uint32_t info, struct shared_block *shblk, unsigned int offset)
1199{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001200
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001201 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1202 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1203 unsigned int max, total, rem_data;
1204 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001205
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001206 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1207 if (!max)
1208 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001209
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001210 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001211 if (appctx->ctx.cache.rem_data) {
1212 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001213 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001214 }
1215 else {
1216 blksz = (info & 0xfffffff);
1217 total = 4;
1218 }
1219 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001220 rem_data = blksz - max;
1221 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001222 }
1223
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001224 while (blksz) {
1225 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001226
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001227 max = MIN(blksz, shctx->block_size - offset);
1228 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1229 offset += sz;
1230 blksz -= sz;
1231 total += sz;
1232 if (sz < max)
1233 break;
1234 if (blksz || offset == shctx->block_size) {
1235 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1236 offset = 0;
1237 }
1238 }
1239
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001240 appctx->ctx.cache.offset = offset;
1241 appctx->ctx.cache.next = shblk;
1242 appctx->ctx.cache.sent += total;
1243 appctx->ctx.cache.rem_data = rem_data + blksz;
1244 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001245}
1246
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001247static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1248 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001249{
Christopher Faulet95220e22018-12-07 17:34:39 +01001250 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1251 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001252 struct shared_block *shblk;
1253 unsigned int offset, sz;
1254 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001255
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001256 while (len) {
1257 enum htx_blk_type type;
1258 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001259
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001260 shblk = appctx->ctx.cache.next;
1261 offset = appctx->ctx.cache.offset;
1262 if (appctx->ctx.cache.rem_data) {
1263 type = HTX_BLK_DATA;
1264 info = 0;
1265 goto add_data_blk;
1266 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001267
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001268 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001269 sz = MIN(4, shctx->block_size - offset);
1270 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1271 offset += sz;
1272 if (sz < 4) {
1273 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1274 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1275 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001276 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001277
1278 /* Get payload of the next HTX block and insert it. */
1279 type = (info >> 28);
1280 if (type != HTX_BLK_DATA)
1281 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1282 else {
1283 add_data_blk:
1284 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001285 }
1286
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001287 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001288 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001289 total += ret;
1290 len -= ret;
1291
1292 if (appctx->ctx.cache.rem_data || type == mark)
1293 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001294 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001295
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001296 return total;
1297}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001298
1299static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1300{
1301 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1302 unsigned int age;
1303 char *end;
1304
1305 chunk_reset(&trash);
1306 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1307 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1308 age = CACHE_ENTRY_MAX_AGE;
1309 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1310 b_set_data(&trash, end - b_head(&trash));
1311 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1312 return 0;
1313 return 1;
1314}
1315
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001316static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001317{
1318 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1319 struct shared_block *first = block_ptr(cache_ptr);
1320 struct stream_interface *si = appctx->owner;
1321 struct channel *req = si_oc(si);
1322 struct channel *res = si_ic(si);
1323 struct htx *req_htx, *res_htx;
1324 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001325 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001326 size_t ret, total = 0;
1327
1328 res_htx = htxbuf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001329 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001330
1331 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1332 goto out;
1333
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001334 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001335 if (!b_size(&res->buf)) {
1336 si_rx_room_blk(si);
1337 goto out;
1338 }
1339
Willy Tarreauefef3232018-12-16 00:37:45 +01001340 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001341 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001342
1343 if (appctx->st0 == HTX_CACHE_INIT) {
1344 appctx->ctx.cache.next = block_ptr(cache_ptr);
1345 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1346 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001347 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001348 appctx->st0 = HTX_CACHE_HEADER;
1349 }
1350
1351 if (appctx->st0 == HTX_CACHE_HEADER) {
1352 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001353 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1354 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1355 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1356 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001357 goto error;
1358
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001359 /* In case of a conditional request, we might want to send a
1360 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001361 if (appctx->ctx.cache.send_notmodified) {
1362 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1363 /* If replacing the status code fails we need to send the full response. */
1364 appctx->ctx.cache.send_notmodified = 0;
1365 }
1366 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001367
1368 /* Skip response body for HEAD requests or in case of "304 Not
1369 * Modified" response. */
1370 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001371 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001372 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001373 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001374 }
1375
1376 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001377 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1378 if (len) {
1379 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOM);
1380 if (ret < len) {
1381 si_rx_room_blk(si);
1382 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001383 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001384 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001385 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001386 }
1387
1388 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Faulet810df062020-07-22 16:20:34 +02001389 res_htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001390 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
1391 si_rx_room_blk(si);
1392 goto out;
1393 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001394 appctx->st0 = HTX_CACHE_END;
1395 }
1396
1397 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001398 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001399 res->flags |= CF_READ_NULL;
1400 si_shutr(si);
1401 }
1402
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001403 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001404 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001405 if (total)
1406 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001407 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001408
1409 /* eat the whole request */
1410 if (co_data(req)) {
1411 req_htx = htx_from_buf(&req->buf);
1412 co_htx_skip(req, req_htx, co_data(req));
1413 htx_to_buf(req_htx, &req->buf);
1414 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001415 return;
1416
1417 error:
1418 /* Sent and HTTP error 500 */
1419 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001420 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001421 res->buf.data = b_data(errmsg);
1422 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1423 res_htx = htx_from_buf(&res->buf);
1424
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001425 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001426 appctx->st0 = HTX_CACHE_END;
1427 goto end;
1428}
1429
1430
Christopher Faulet95220e22018-12-07 17:34:39 +01001431static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001432{
1433 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001434 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001435
Christopher Faulet95220e22018-12-07 17:34:39 +01001436 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001437 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001438 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001439 }
1440
1441 /* check if a cache filter was already registered with this cache
1442 * name, if that's the case, must use it. */
1443 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001444 if (fconf->id == cache_store_flt_id) {
1445 cconf = fconf->conf;
1446 if (cconf && !strcmp((char *)cconf->c.name, name)) {
1447 rule->arg.act.p[0] = cconf;
1448 return 1;
1449 }
William Lallemand41db4602017-10-30 11:15:51 +01001450 }
1451 }
1452
Christopher Faulet95220e22018-12-07 17:34:39 +01001453 /* Create the filter cache config */
1454 cconf = calloc(1, sizeof(*cconf));
1455 if (!cconf) {
1456 memprintf(err, "out of memory\n");
1457 goto err;
1458 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001459 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001460 cconf->c.name = strdup(name);
1461 if (!cconf->c.name) {
1462 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001463 goto err;
1464 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001465
William Lallemand41db4602017-10-30 11:15:51 +01001466 /* register a filter to fill the cache buffer */
1467 fconf = calloc(1, sizeof(*fconf));
1468 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001469 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001470 goto err;
1471 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001472 fconf->id = cache_store_flt_id;
1473 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001474 fconf->ops = &cache_ops;
1475 LIST_ADDQ(&proxy->filter_configs, &fconf->list);
1476
Christopher Faulet95220e22018-12-07 17:34:39 +01001477 rule->arg.act.p[0] = cconf;
1478 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001479
Christopher Faulet95220e22018-12-07 17:34:39 +01001480 err:
1481 free(cconf);
1482 return 0;
1483}
1484
1485enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1486 struct act_rule *rule, char **err)
1487{
1488 rule->action = ACT_CUSTOM;
1489 rule->action_ptr = http_action_store_cache;
1490
1491 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1492 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001493
Christopher Faulet95220e22018-12-07 17:34:39 +01001494 (*orig_arg)++;
1495 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001496}
1497
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001498/* This produces a sha1 hash of the concatenation of the HTTP method,
1499 * the first occurrence of the Host header followed by the path component
1500 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001501int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001502{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001503 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001504 struct htx *htx = htxbuf(&s->req.buf);
1505 struct htx_sl *sl;
1506 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001507 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001508 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001509 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001510
William Lallemandf528fff2017-11-23 19:43:17 +01001511 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001512 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001513
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001514 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001515 uri = htx_sl_req_uri(sl); // whole uri
1516 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001517 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001518
1519 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1520 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1521 * URIs are almost always sent in absolute form with their scheme. In
1522 * this case, the scheme is almost always "https". In order to support
1523 * sharing of cache objects between H1 and H2, we'll hash the absolute
1524 * URI whenever known, or prepend "https://" + the Host header for
1525 * relative URIs. The difference will only appear on absolute HTTP/1
1526 * requests sent to an origin server, which practically is never met in
1527 * the real world so we don't care about the ability to share the same
1528 * key here.URIs are normalized from the absolute URI to an origin form as
1529 * well.
1530 */
1531 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001532 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001533 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1534 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001535 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001536 }
1537
1538 chunk_memcat(trash, uri.ptr, uri.len);
William Lallemandf528fff2017-11-23 19:43:17 +01001539
1540 /* hash everything */
1541 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001542 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001543 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1544
1545 return 1;
1546}
1547
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001548/* Looks for "If-None-Match" headers in the request and compares their value
1549 * with the one that might have been stored in the cache_entry. If any of them
1550 * matches, a "304 Not Modified" response should be sent instead of the cached
1551 * data.
1552 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001553 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1554 *
1555 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1556 * header and compare its value (date) to the one stored in the cache_entry.
1557 * If the request's date is later than the cached one, we also send a
1558 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1559 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001560 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1561 */
1562static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1563 struct cache_entry *entry)
1564{
1565 int retval = 0;
1566
1567 struct http_hdr_ctx ctx = { .blk = NULL };
1568 struct ist cache_entry_etag = IST_NULL;
1569 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001570 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001571
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001572 struct tm tm = {};
1573 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001574
1575 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001576 * cache_entry's ETag in order to perform comparisons.
1577 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001578 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001579 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001580
1581 /* A '*' matches everything. */
1582 if (isteq(ctx.value, ist("*")) != 0) {
1583 retval = 1;
1584 break;
1585 }
1586
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001587 /* No need to rebuild an etag if none was stored in the cache. */
1588 if (entry->etag_length == 0)
1589 break;
1590
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001591 /* Rebuild the stored ETag. */
1592 if (etag_buffer == NULL) {
1593 etag_buffer = get_trash_chunk();
1594
1595 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1596 (unsigned char*)b_orig(etag_buffer),
1597 entry->etag_offset, entry->etag_length) == 0) {
1598 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1599 } else {
1600 /* We could not rebuild the ETag in one go, we
1601 * won't send a "304 Not Modified" response. */
1602 break;
1603 }
1604 }
1605
1606 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1607 retval = 1;
1608 break;
1609 }
1610 }
1611
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001612 /* If the request did not contain an "If-None-Match" header, we look for
1613 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1614 if (retval == 0 && if_none_match_found == 0) {
1615 ctx.blk = NULL;
1616 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1617 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1618 if_modified_since = my_timegm(&tm);
1619
1620 /* We send a "304 Not Modified" response if the
1621 * entry's last modified date is earlier than
1622 * the one found in the "If-Modified-Since"
1623 * header. */
1624 retval = (entry->last_modified <= if_modified_since);
1625 }
1626 }
1627 }
1628
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001629 return retval;
1630}
1631
William Lallemand41db4602017-10-30 11:15:51 +01001632enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1633 struct session *sess, struct stream *s, int flags)
1634{
William Lallemand77c11972017-10-31 20:43:01 +01001635
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001636 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001637 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001638 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1639 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001640 struct shared_block *entry_block;
1641
William Lallemand77c11972017-10-31 20:43:01 +01001642
Willy Tarreau6905d182019-10-01 17:59:17 +02001643 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1644 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001645 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001646 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001647 txn->flags |= TX_CACHE_IGNORE;
1648
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001649 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001650
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001651 /* The request's hash has to be calculated for all requests, even POSTs
1652 * or PUTs for instance because RFC7234 specifies that a sucessful
1653 * "unsafe" method on a stored resource must invalidate it
1654 * (see RFC7234#4.4). */
1655 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001656 return ACT_RET_CONT;
1657
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001658 if ((s->txn->flags & (TX_CACHE_IGNORE|TX_CACHEABLE)) == TX_CACHE_IGNORE)
Willy Tarreau7704b1e2017-12-22 16:32:43 +01001659 return ACT_RET_CONT;
William Lallemandf528fff2017-11-23 19:43:17 +01001660
Willy Tarreau504455c2017-12-22 17:47:35 +01001661 if (s->txn->flags & TX_CACHE_IGNORE)
1662 return ACT_RET_CONT;
1663
Willy Tarreaua1214a52018-12-14 14:00:25 +01001664 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001665 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001666 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001667 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001668
William Lallemanda400a3a2017-11-20 19:13:12 +01001669 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001670 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001671 /* We must not use an entry that is not complete. */
1672 if (res && res->complete) {
William Lallemand77c11972017-10-31 20:43:01 +01001673 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001674 entry_block = block_ptr(res);
1675 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001676 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001677
1678 /* In case of Vary, we could have multiple entries with the same
1679 * primary hash. We need to calculate the secondary has in order
1680 * to find the actual entry we want (if it exists). */
1681 if (res->secondary_key_signature) {
1682 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1683 shctx_lock(shctx_ptr(cache));
1684 sec_entry = secondary_entry_exist(cache, res,
1685 s->txn->cache_secondary_hash);
1686 if (sec_entry && sec_entry != res) {
1687 /* The wrong row was added to the hot list. */
1688 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1689 entry_block = block_ptr(sec_entry);
1690 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1691 }
1692 res = sec_entry;
1693 shctx_unlock(shctx_ptr(cache));
1694 }
1695 else
1696 res = NULL;
1697 }
1698
1699 /* We looked for a valid secondary entry and could not find one,
1700 * the request must be forwarded to the server. */
1701 if (!res) {
1702 shctx_lock(shctx_ptr(cache));
1703 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1704 shctx_unlock(shctx_ptr(cache));
1705 return ACT_RET_CONT;
1706 }
1707
William Lallemand77c11972017-10-31 20:43:01 +01001708 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001709 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001710 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001711 appctx->rule = rule;
1712 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001713 appctx->ctx.cache.next = NULL;
1714 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001715 appctx->ctx.cache.send_notmodified =
1716 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001717
1718 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001719 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_hits, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001720 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001721 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_hits, 1);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001722 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001723 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001724 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001725 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001726 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001727 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001728 }
1729 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001730 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001731
1732 /* Shared context does not need to be locked while we calculate the
1733 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001734 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001735 /* Build a complete secondary hash until the server response
1736 * tells us which fields should be kept (if any). */
1737 http_request_prebuild_full_secondary_key(s);
1738 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001739 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001740}
1741
1742
1743enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1744 struct act_rule *rule, char **err)
1745{
William Lallemand41db4602017-10-30 11:15:51 +01001746 rule->action = ACT_CUSTOM;
1747 rule->action_ptr = http_action_req_cache_use;
1748
Christopher Faulet95220e22018-12-07 17:34:39 +01001749 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001750 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001751
1752 (*orig_arg)++;
1753 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001754}
1755
1756int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1757{
1758 int err_code = 0;
1759
1760 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1761
1762 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001763 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001764 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001765 err_code |= ERR_ALERT | ERR_ABORT;
1766 goto out;
1767 }
1768
1769 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1770 err_code |= ERR_ABORT;
1771 goto out;
1772 }
1773
1774 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001775 struct cache *cache_config;
1776
William Lallemand41db4602017-10-30 11:15:51 +01001777 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1778 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001779 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001780 err_code |= ERR_ALERT | ERR_ABORT;
1781 goto out;
1782 }
1783
1784 strlcpy2(tmp_cache_config->id, args[1], 33);
1785 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001786 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001787 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001788 err_code |= ERR_WARN;
1789 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001790
1791 list_for_each_entry(cache_config, &caches_config, list) {
1792 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1793 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1794 file, linenum, tmp_cache_config->id);
1795 err_code |= ERR_ALERT | ERR_ABORT;
1796 goto out;
1797 }
1798 }
1799
William Lallemand49b44532017-11-24 18:53:43 +01001800 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001801 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001802 tmp_cache_config->maxobjsz = 0;
William Lallemand41db4602017-10-30 11:15:51 +01001803 }
1804 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001805 unsigned long int maxsize;
1806 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001807
1808 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1809 err_code |= ERR_ABORT;
1810 goto out;
1811 }
1812
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001813 maxsize = strtoul(args[1], &err, 10);
1814 if (err == args[1] || *err != '\0') {
1815 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1816 file, linenum, args[1]);
1817 err_code |= ERR_ABORT;
1818 goto out;
1819 }
1820
1821 if (maxsize > (UINT_MAX >> 20)) {
1822 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1823 file, linenum, args[1], UINT_MAX >> 20);
1824 err_code |= ERR_ABORT;
1825 goto out;
1826 }
1827
William Lallemand41db4602017-10-30 11:15:51 +01001828 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001829 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001830 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001831 } else if (strcmp(args[0], "max-age") == 0) {
1832 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1833 err_code |= ERR_ABORT;
1834 goto out;
1835 }
1836
1837 if (!*args[1]) {
1838 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1839 file, linenum, args[0]);
1840 err_code |= ERR_WARN;
1841 }
1842
1843 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001844 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001845 unsigned int maxobjsz;
1846 char *err;
1847
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001848 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1849 err_code |= ERR_ABORT;
1850 goto out;
1851 }
1852
1853 if (!*args[1]) {
1854 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1855 file, linenum, args[0]);
1856 err_code |= ERR_WARN;
1857 }
1858
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001859 maxobjsz = strtoul(args[1], &err, 10);
1860 if (err == args[1] || *err != '\0') {
1861 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1862 file, linenum, args[1]);
1863 err_code |= ERR_ABORT;
1864 goto out;
1865 }
1866 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001867 } else if (strcmp(args[0], "process-vary") == 0) {
1868 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1869 err_code |= ERR_ABORT;
1870 goto out;
1871 }
1872
1873 if (!*args[1]) {
1874 ha_warning("parsing [%s:%d]: '%s' expects 0 or 1 (disable or enable vary processing).\n",
1875 file, linenum, args[0]);
1876 err_code |= ERR_WARN;
1877 }
1878
1879 tmp_cache_config->vary_processing_enabled = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001880 }
1881 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001882 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001883 err_code |= ERR_ALERT | ERR_FATAL;
1884 goto out;
1885 }
1886out:
1887 return err_code;
1888}
1889
1890/* once the cache section is parsed */
1891
1892int cfg_post_parse_section_cache()
1893{
William Lallemand41db4602017-10-30 11:15:51 +01001894 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01001895
1896 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01001897
1898 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001899 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001900 err_code |= ERR_FATAL | ERR_ALERT;
1901 goto out;
1902 }
1903
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001904 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001905 /* Default max. file size is a 256th of the cache size. */
1906 tmp_cache_config->maxobjsz =
1907 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001908 }
1909 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
1910 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
1911 err_code |= ERR_FATAL | ERR_ALERT;
1912 goto out;
1913 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001914
William Lallemandd1d1e222019-08-28 15:22:49 +02001915 /* add to the list of cache to init and reinit tmp_cache_config
1916 * for next cache section, if any.
1917 */
1918 LIST_ADDQ(&caches_config, &tmp_cache_config->list);
1919 tmp_cache_config = NULL;
1920 return err_code;
1921 }
1922out:
1923 free(tmp_cache_config);
1924 tmp_cache_config = NULL;
1925 return err_code;
1926
1927}
1928
1929int post_check_cache()
1930{
1931 struct proxy *px;
1932 struct cache *back, *cache_config, *cache;
1933 struct shared_context *shctx;
1934 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01001935 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02001936
1937 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
1938
1939 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
1940 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001941
Frédéric Lécaillebc584492018-10-25 20:18:59 +02001942 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001943 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01001944 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001945 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01001946 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001947
1948 err_code |= ERR_FATAL | ERR_ALERT;
1949 goto out;
1950 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001951 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02001952 /* the cache structure is stored in the shctx and added to the
1953 * caches list, we can remove the entry from the caches_config
1954 * list */
1955 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01001956 cache = (struct cache *)shctx->data;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001957 cache->entries = EB_ROOT;
William Lallemand41db4602017-10-30 11:15:51 +01001958 LIST_ADDQ(&caches, &cache->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02001959 LIST_DEL(&cache_config->list);
1960 free(cache_config);
1961
1962 /* Find all references for this cache in the existing filters
1963 * (over all proxies) and reference it in matching filters.
1964 */
1965 for (px = proxies_list; px; px = px->next) {
1966 struct flt_conf *fconf;
1967 struct cache_flt_conf *cconf;
1968
1969 list_for_each_entry(fconf, &px->filter_configs, list) {
1970 if (fconf->id != cache_store_flt_id)
1971 continue;
1972
1973 cconf = fconf->conf;
1974 if (!strcmp(cache->id, cconf->c.name)) {
1975 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02001976 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02001977 cconf->c.cache = cache;
1978 break;
1979 }
1980 }
1981 }
William Lallemand41db4602017-10-30 11:15:51 +01001982 }
William Lallemandd1d1e222019-08-28 15:22:49 +02001983
William Lallemand41db4602017-10-30 11:15:51 +01001984out:
William Lallemand41db4602017-10-30 11:15:51 +01001985 return err_code;
1986
William Lallemand41db4602017-10-30 11:15:51 +01001987}
1988
William Lallemand41db4602017-10-30 11:15:51 +01001989struct flt_ops cache_ops = {
1990 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01001991 .check = cache_store_check,
1992 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01001993
Christopher Faulet65554e12020-03-06 14:52:06 +01001994 /* Handle stream init/deinit */
1995 .attach = cache_store_strm_init,
1996 .detach = cache_store_strm_deinit,
1997
William Lallemand4da3f8a2017-10-31 14:33:34 +01001998 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01001999 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002000
2001 /* Filter HTTP requests and responses */
2002 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01002003 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002004 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01002005};
2006
Christopher Faulet99a17a22018-12-11 09:18:27 +01002007
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002008int accept_encoding_cmp(const void *a, const void *b)
2009{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002010 unsigned int int_a = *(unsigned int*)a;
2011 unsigned int int_b = *(unsigned int*)b;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002012
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002013 if (int_a < int_b)
2014 return -1;
2015 if (int_a > int_b)
2016 return 1;
2017 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002018}
2019
Tim Duesterhus23b29452020-11-24 22:22:56 +01002020#define ACCEPT_ENCODING_MAX_ENTRIES 16
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002021/*
2022 * Build a hash of the accept-encoding header. The different parts of the
2023 * header value are first sorted, appended and then a crc is calculated
2024 * for the newly constructed buffer.
2025 * Returns 0 in case of success.
2026 */
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002027static int accept_encoding_normalizer(struct ist full_value, char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002028{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002029 unsigned int values[ACCEPT_ENCODING_MAX_ENTRIES] = {};
Tim Duesterhus23b29452020-11-24 22:22:56 +01002030 size_t count = 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002031 char *comma = NULL;
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002032 unsigned int hash_value = 0;
2033 unsigned int prev = 0, curr = 0;
2034
2035 /* Turn accept-encoding value to lower case */
2036 full_value = ist2bin_lc(istptr(full_value), full_value);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002037
2038 /* The hash will be built out of a sorted list of accepted encodings. */
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002039 while (count < (ACCEPT_ENCODING_MAX_ENTRIES - 1) && (comma = istchr(full_value, ',')) != NULL) {
2040 size_t length = comma - istptr(full_value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002041
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002042 values[count++] = hash_crc32(istptr(full_value), length);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002043
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002044 full_value = istadv(full_value, length + 1);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002045
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002046 }
2047 values[count++] = hash_crc32(istptr(full_value), istlen(full_value));
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002048
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002049 /* Sort the values alphabetically. */
2050 qsort(values, count, sizeof(*values), &accept_encoding_cmp);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002051
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002052 while (count) {
2053 curr = values[--count];
2054 if (curr != prev) {
2055 hash_value ^= curr;
2056 }
2057 prev = curr;
2058 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002059
2060 memcpy(buf, &hash_value, sizeof(hash_value));
2061 *buf_len = sizeof(hash_value);
2062
Tim Duesterhus23b29452020-11-24 22:22:56 +01002063 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002064}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002065#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002066
2067/*
2068 * Normalizer used by default for User-Agent and Referer headers. It only
2069 * calculates a simple crc of the whole value.
2070 * Returns 0 in case of success.
2071 */
2072static int default_normalizer(struct ist value, char *buf, unsigned int *buf_len)
2073{
2074 int hash_value = 0;
2075
2076 hash_value = hash_crc32(istptr(value), istlen(value));
2077
2078 memcpy(buf, &hash_value, sizeof(hash_value));
2079 *buf_len = sizeof(hash_value);
2080
2081 return 0;
2082}
2083
2084
2085/*
2086 * Pre-calculate the hashes of all the supported headers (in our Vary
2087 * implementation) of a given request. We have to calculate all the hashes
2088 * in advance because the actual Vary signature won't be known until the first
2089 * response.
2090 * Only the first occurrence of every header will be taken into account in the
2091 * hash.
2092 * If the header is not present, the hash portion of the given header will be
2093 * filled with zeros.
2094 * Returns 0 in case of success.
2095 */
2096static int http_request_prebuild_full_secondary_key(struct stream *s)
2097{
2098 struct http_txn *txn = s->txn;
2099 struct htx *htx = htxbuf(&s->req.buf);
2100 struct http_hdr_ctx ctx = { .blk = NULL };
2101
2102 unsigned int idx;
2103 const struct vary_hashing_information *info = NULL;
2104 unsigned int hash_length = 0;
2105 int retval = 0;
2106 int offset = 0;
2107
2108 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
2109 info = &vary_information[idx];
2110
2111 ctx.blk = NULL;
2112 if (info->norm_fn != NULL && http_find_header(htx, info->hdr_name, &ctx, 1)) {
2113 retval = info->norm_fn(ctx.value, &txn->cache_secondary_hash[offset], &hash_length);
2114 offset += hash_length;
2115 }
2116 else {
2117 /* Fill hash with 0s. */
2118 hash_length = info->hash_length;
2119 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2120 offset += hash_length;
2121 }
2122 }
2123
2124 return retval;
2125}
2126
2127
2128/*
2129 * Calculate the secondary key for a request for which we already have a known
2130 * vary signature. The key is made by aggregating hashes calculated for every
2131 * header mentioned in the vary signature.
2132 * Only the first occurrence of every header will be taken into account in the
2133 * hash.
2134 * If the header is not present, the hash portion of the given header will be
2135 * filled with zeros.
2136 * Returns 0 in case of success.
2137 */
2138static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2139{
2140 struct http_txn *txn = s->txn;
2141 struct htx *htx = htxbuf(&s->req.buf);
2142 struct http_hdr_ctx ctx = { .blk = NULL };
2143
2144 unsigned int idx;
2145 const struct vary_hashing_information *info = NULL;
2146 unsigned int hash_length = 0;
2147 int retval = 0;
2148 int offset = 0;
2149
2150 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
2151 info = &vary_information[idx];
2152
2153 ctx.blk = NULL;
2154 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2155 http_find_header(htx, info->hdr_name, &ctx, 1)) {
2156 retval = info->norm_fn(ctx.value, &txn->cache_secondary_hash[offset], &hash_length);
2157 offset += hash_length;
2158 }
2159 else {
2160 /* Fill hash with 0s. */
2161 hash_length = info->hash_length;
2162 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2163 offset += hash_length;
2164 }
2165 }
2166
2167 return retval;
2168}
2169
2170/*
2171 * Build the actual secondary key of a given request out of the prebuilt key and
2172 * the actual vary signature (extracted from the response).
2173 * Returns 0 in case of success.
2174 */
2175static int http_request_reduce_secondary_key(unsigned int vary_signature,
2176 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2177{
2178 int offset = 0;
2179 int global_offset = 0;
2180 int vary_info_count = 0;
2181 int keep = 0;
2182 unsigned int vary_idx;
2183 const struct vary_hashing_information *vary_info;
2184
2185 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2186 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2187 vary_info = &vary_information[vary_idx];
2188 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2189
2190 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2191 prebuilt_key[global_offset] &= keep;
2192 }
2193 }
2194
2195 return 0;
2196}
2197
2198
Christopher Faulet99a17a22018-12-11 09:18:27 +01002199
2200static int
2201parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2202 struct flt_conf *fconf, char **err, void *private)
2203{
2204 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002205 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002206 char *name = NULL;
2207 int pos = *cur_arg;
2208
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002209 /* Get the cache filter name. <pos> point on "cache" keyword */
2210 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002211 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002212 goto error;
2213 }
2214 name = strdup(args[pos + 1]);
2215 if (!name) {
2216 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2217 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002218 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002219 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002220
2221 /* Check if an implicit filter with the same name already exists. If so,
2222 * we remove the implicit filter to use the explicit one. */
2223 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2224 if (f->id != cache_store_flt_id)
2225 continue;
2226
2227 cconf = f->conf;
2228 if (strcmp(name, cconf->c.name)) {
2229 cconf = NULL;
2230 continue;
2231 }
2232
2233 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2234 cconf = NULL;
2235 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2236 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002237 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002238 }
2239
2240 /* Remove the implicit filter. <cconf> is kept for the explicit one */
2241 LIST_DEL(&f->list);
2242 free(f);
2243 free(name);
2244 break;
2245 }
2246
2247 /* No implicit cache filter found, create configuration for the explicit one */
2248 if (!cconf) {
2249 cconf = calloc(1, sizeof(*cconf));
2250 if (!cconf) {
2251 memprintf(err, "%s: out of memory", args[*cur_arg]);
2252 goto error;
2253 }
2254 cconf->c.name = name;
2255 }
2256
2257 cconf->flags = 0;
2258 fconf->id = cache_store_flt_id;
2259 fconf->conf = cconf;
2260 fconf->ops = &cache_ops;
2261
2262 *cur_arg = pos;
2263 return 0;
2264
2265 error:
2266 free(name);
2267 free(cconf);
2268 return -1;
2269}
2270
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002271static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002272{
2273 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2274 return 1;
2275
2276 return 0;
2277}
2278
2279static int cli_io_handler_show_cache(struct appctx *appctx)
2280{
2281 struct cache* cache = appctx->ctx.cli.p0;
2282 struct stream_interface *si = appctx->owner;
2283
William Lallemand1f49a362017-11-21 20:01:26 +01002284 if (cache == NULL) {
2285 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
2286 }
2287
2288 list_for_each_entry_from(cache, &caches, list) {
2289 struct eb32_node *node = NULL;
2290 unsigned int next_key;
2291 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002292 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002293
William Lallemand1f49a362017-11-21 20:01:26 +01002294 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002295 if (!next_key) {
2296 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
2297 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002298 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002299 return 0;
2300 }
2301 }
William Lallemand1f49a362017-11-21 20:01:26 +01002302
2303 appctx->ctx.cli.p0 = cache;
2304
2305 while (1) {
2306
2307 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002308 if (!node || (node = eb32_next_dup(node)) == NULL)
2309 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002310 if (!node) {
2311 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02002312 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002313 break;
2314 }
2315
2316 entry = container_of(node, struct cache_entry, eb);
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002317 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2318 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2319 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2320 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 +01002321
2322 next_key = node->key + 1;
2323 appctx->ctx.cli.i0 = next_key;
2324
2325 shctx_unlock(shctx_ptr(cache));
2326
2327 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002328 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002329 return 0;
2330 }
2331 }
2332
2333 }
2334
2335 return 1;
2336
2337}
2338
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002339
2340/*
2341 * boolean, returns true if response was built out of a cache entry.
2342 */
2343static int
2344smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2345 const char *kw, void *private)
2346{
2347 smp->data.type = SMP_T_BOOL;
2348 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2349
2350 return 1;
2351}
2352
2353/*
2354 * string, returns cache name (if response came from a cache).
2355 */
2356static int
2357smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2358 const char *kw, void *private)
2359{
2360 struct appctx *appctx = NULL;
2361
2362 struct cache_flt_conf *cconf = NULL;
2363 struct cache *cache = NULL;
2364
2365 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2366 return 0;
2367
2368 /* Get appctx from the stream_interface. */
2369 appctx = si_appctx(&smp->strm->si[1]);
2370 if (appctx && appctx->rule) {
2371 cconf = appctx->rule->arg.act.p[0];
2372 if (cconf) {
2373 cache = cconf->c.cache;
2374
2375 smp->data.type = SMP_T_STR;
2376 smp->flags = SMP_F_CONST;
2377 smp->data.u.str.area = cache->id;
2378 smp->data.u.str.data = strlen(cache->id);
2379 return 1;
2380 }
2381 }
2382
2383 return 0;
2384}
2385
Christopher Faulet99a17a22018-12-11 09:18:27 +01002386/* Declare the filter parser for "cache" keyword */
2387static struct flt_kw_list filter_kws = { "CACHE", { }, {
2388 { "cache", parse_cache_flt, NULL },
2389 { NULL, NULL, NULL },
2390 }
2391};
2392
2393INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2394
William Lallemand1f49a362017-11-21 20:01:26 +01002395static struct cli_kw_list cli_kws = {{},{
William Lallemande899af82017-11-22 16:41:26 +01002396 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
2397 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002398}};
2399
Willy Tarreau0108d902018-11-25 19:14:37 +01002400INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002401
William Lallemand41db4602017-10-30 11:15:51 +01002402static struct action_kw_list http_res_actions = {
2403 .kw = {
2404 { "cache-store", parse_cache_store },
2405 { NULL, NULL }
2406 }
2407};
2408
Willy Tarreau0108d902018-11-25 19:14:37 +01002409INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2410
William Lallemand41db4602017-10-30 11:15:51 +01002411static struct action_kw_list http_req_actions = {
2412 .kw = {
2413 { "cache-use", parse_cache_use },
2414 { NULL, NULL }
2415 }
2416};
2417
Willy Tarreau0108d902018-11-25 19:14:37 +01002418INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2419
Willy Tarreau2231b632019-03-29 18:26:52 +01002420struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002421 .obj_type = OBJ_TYPE_APPLET,
2422 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002423 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002424 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002425};
2426
Willy Tarreaue6552512018-11-26 11:33:13 +01002427/* config parsers for this section */
2428REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002429REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002430
2431
2432/* Note: must not be declared <const> as its list will be overwritten */
2433static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2434 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2435 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2436 { /* END */ },
2437 }
2438};
2439
2440INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);