blob: 2e5c5a45bdf76caac17d32b7f3f868f28c44ee02 [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 Tarreauc6dfef72022-05-05 16:46:13 +020018#include <haproxy/applet.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020019#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020020#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020021#include <haproxy/cli.h>
Christopher Faulet908628c2022-03-25 16:43:49 +010022#include <haproxy/conn_stream.h>
23#include <haproxy/cs_utils.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020024#include <haproxy/errors.h>
Willy Tarreauc7babd82020-06-04 21:29:29 +020025#include <haproxy/filters.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020026#include <haproxy/hash.h>
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +020027#include <haproxy/http.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020028#include <haproxy/http_ana.h>
Willy Tarreau87735332020-06-04 09:08:41 +020029#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020030#include <haproxy/http_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020031#include <haproxy/htx.h>
32#include <haproxy/net_helper.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020033#include <haproxy/proxy.h>
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +010034#include <haproxy/sample.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020035#include <haproxy/shctx.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020036#include <haproxy/stream.h>
Willy Tarreauce6700a2021-05-08 13:03:55 +020037#include <haproxy/tools.h>
William Lallemand41db4602017-10-30 11:15:51 +010038
Christopher Faulet27d93c32018-12-15 22:32:02 +010039#define CACHE_FLT_F_IMPLICIT_DECL 0x00000001 /* The cache filtre was implicitly declared (ie without
Christopher Faulet99a17a22018-12-11 09:18:27 +010040 * the filter keyword) */
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +020041#define CACHE_FLT_INIT 0x00000002 /* Whether the cache name was freed. */
Christopher Fauletafd819c2018-12-11 08:57:45 +010042
Christopher Fauletf4a4ef72018-12-07 17:39:53 +010043const char *cache_store_flt_id = "cache store filter";
William Lallemand41db4602017-10-30 11:15:51 +010044
Willy Tarreau2231b632019-03-29 18:26:52 +010045extern struct applet http_cache_applet;
William Lallemand41db4602017-10-30 11:15:51 +010046
47struct flt_ops cache_ops;
48
49struct cache {
Willy Tarreaufd5efb52017-11-26 08:54:31 +010050 struct list list; /* cache linked list */
William Lallemand41db4602017-10-30 11:15:51 +010051 struct eb_root entries; /* head of cache entries based on keys */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010052 unsigned int maxage; /* max-age */
53 unsigned int maxblocks;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +020054 unsigned int maxobjsz; /* max-object-size (in bytes) */
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +010055 unsigned int max_secondary_entries; /* maximum number of secondary entries with the same primary hash */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +010056 uint8_t vary_processing_enabled; /* boolean : manage Vary header (disabled by default) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010057 char id[33]; /* cache name */
William Lallemand41db4602017-10-30 11:15:51 +010058};
59
Willy Tarreauf61494c2022-05-06 11:03:39 +020060/* the appctx context of a cache applet, stored in appctx->svcctx */
61struct cache_appctx {
62 struct cache_entry *entry; /* Entry to be sent from cache. */
63 unsigned int sent; /* The number of bytes already sent for this cache entry. */
64 unsigned int offset; /* start offset of remaining data relative to beginning of the next block */
65 unsigned int rem_data; /* Remaining bytes for the last data block (HTX only, 0 means process next block) */
66 unsigned int send_notmodified:1; /* In case of conditional request, we might want to send a "304 Not Modified" response instead of the stored data. */
67 unsigned int unused:31;
68 struct shared_block *next; /* The next block of data to be sent for this cache entry. */
69};
70
Christopher Faulet95220e22018-12-07 17:34:39 +010071/* cache config for filters */
72struct cache_flt_conf {
73 union {
74 struct cache *cache; /* cache used by the filter */
75 char *name; /* cache name used during conf parsing */
76 } c;
77 unsigned int flags; /* CACHE_FLT_F_* */
78};
79
Willy Tarreauc6dfef72022-05-05 16:46:13 +020080/* CLI context used during "show cache" */
81struct show_cache_ctx {
82 struct cache *cache;
83 uint next_key;
84};
85
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010086
87/*
88 * Vary-related structures and functions
89 */
90enum vary_header_bit {
91 VARY_ACCEPT_ENCODING = (1 << 0),
92 VARY_REFERER = (1 << 1),
93 VARY_LAST /* should always be last */
94};
95
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +010096/*
97 * Encoding list extracted from
98 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml
99 * and RFC7231#5.3.4.
100 */
101enum vary_encoding {
102 VARY_ENCODING_GZIP = (1 << 0),
103 VARY_ENCODING_DEFLATE = (1 << 1),
104 VARY_ENCODING_BR = (1 << 2),
105 VARY_ENCODING_COMPRESS = (1 << 3),
106 VARY_ENCODING_AES128GCM = (1 << 4),
107 VARY_ENCODING_EXI = (1 << 5),
108 VARY_ENCODING_PACK200_GZIP = (1 << 6),
109 VARY_ENCODING_ZSTD = (1 << 7),
110 VARY_ENCODING_IDENTITY = (1 << 8),
111 VARY_ENCODING_STAR = (1 << 9),
112 VARY_ENCODING_OTHER = (1 << 10)
113};
114
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100115struct vary_hashing_information {
116 struct ist hdr_name; /* Header name */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500117 enum vary_header_bit value; /* Bit representing the header in a vary signature */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100118 unsigned int hash_length; /* Size of the sub hash for this header's value */
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100119 int(*norm_fn)(struct htx*,struct ist hdr_name,char* buf,unsigned int* buf_len); /* Normalization function */
Tim Duesterhused84d842021-01-18 13:41:17 +0100120 int(*cmp_fn)(const void *ref, const void *new, unsigned int len); /* Comparison function, should return 0 if the hashes are alike */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100121};
122
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100123static int http_request_prebuild_full_secondary_key(struct stream *s);
124static int http_request_build_secondary_key(struct stream *s, int vary_signature);
125static int http_request_reduce_secondary_key(unsigned int vary_signature,
126 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
127
128static int parse_encoding_value(struct ist value, unsigned int *encoding_value,
129 unsigned int *has_null_weight);
130
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +0100131static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
132 char *buf, unsigned int *buf_len);
133static int default_normalizer(struct htx *htx, struct ist hdr_name,
134 char *buf, unsigned int *buf_len);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100135
Tim Duesterhused84d842021-01-18 13:41:17 +0100136static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100137
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100138/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
139 * added to this array. */
140const struct vary_hashing_information vary_information[] = {
Tim Duesterhused84d842021-01-18 13:41:17 +0100141 { IST("accept-encoding"), VARY_ACCEPT_ENCODING, sizeof(uint32_t), &accept_encoding_normalizer, &accept_encoding_bitmap_cmp },
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100142 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer, NULL },
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100143};
144
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100145
William Lallemand41db4602017-10-30 11:15:51 +0100146/*
147 * cache ctx for filters
148 */
149struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100150 struct shared_block *first_block;
151};
152
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100153#define DEFAULT_MAX_SECONDARY_ENTRY 10
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100154
William Lallemand41db4602017-10-30 11:15:51 +0100155struct cache_entry {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100156 unsigned int complete; /* An entry won't be valid until complete is not null. */
William Lallemand41db4602017-10-30 11:15:51 +0100157 unsigned int latest_validation; /* latest validation date */
158 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200159 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100160
William Lallemand41db4602017-10-30 11:15:51 +0100161 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100162 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200163
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100164 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
165 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
166 * to build secondary keys for this cache entry. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100167 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 +0100168 unsigned int last_clear_ts; /* Timestamp of the last call to clear_expired_duplicates. */
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100169
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200170 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
171 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
172
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200173 time_t last_modified; /* Origin server "Last-Modified" header value converted in
174 * seconds since epoch. If no "Last-Modified"
175 * header is found, use "Date" header value,
176 * otherwise use reception time. This field will
177 * be used in case of an "If-Modified-Since"-based
178 * conditional request. */
179
William Lallemand41db4602017-10-30 11:15:51 +0100180 unsigned char data[0];
181};
182
183#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100184#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100185
186static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200187static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100188static struct cache *tmp_cache_config = NULL;
189
Willy Tarreau8ceae722018-11-26 11:58:30 +0100190DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
191
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100192static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry);
193static void delete_entry(struct cache_entry *del_entry);
194
William Lallemandf528fff2017-11-23 19:43:17 +0100195struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100196{
197 struct eb32_node *node;
198 struct cache_entry *entry;
199
Willy Tarreau8b507582020-02-25 09:35:07 +0100200 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100201 if (!node)
202 return NULL;
203
204 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100205
206 /* if that's not the right node */
207 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
208 return NULL;
209
William Lallemand08727662017-11-21 20:01:27 +0100210 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100211 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100212 } else {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100213 delete_entry(entry);
William Lallemand08727662017-11-21 20:01:27 +0100214 entry->eb.key = 0;
215 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100216 return NULL;
217
218}
219
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100220
221/*
222 * Compare a newly built secondary key to the one found in a cache_entry.
223 * Every sub-part of the key is compared to the reference through the dedicated
224 * comparison function of the sub-part (that might do more than a simple
225 * memcmp).
226 * Returns 0 if the keys are alike.
227 */
228static int secondary_key_cmp(const char *ref_key, const char *new_key)
229{
230 int retval = 0;
Tim Duesterhus5897cfe2021-01-18 13:41:18 +0100231 size_t idx = 0;
232 unsigned int offset = 0;
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100233 const struct vary_hashing_information *info;
234
235 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
236 info = &vary_information[idx];
237
238 if (info->cmp_fn)
239 retval = info->cmp_fn(&ref_key[offset], &new_key[offset], info->hash_length);
240 else
241 retval = memcmp(&ref_key[offset], &new_key[offset], info->hash_length);
242
243 offset += info->hash_length;
244 }
245
246 return retval;
247}
248
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100249/*
250 * There can be multiple entries with the same primary key in the ebtree so in
251 * order to get the proper one out of the list, we use a secondary_key.
252 * This function simply iterates over all the entries with the same primary_key
253 * until it finds the right one.
254 * Returns the cache_entry in case of success, NULL otherwise.
255 */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100256struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100257 const char *secondary_key)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100258{
259 struct eb32_node *node = &entry->eb;
260
261 if (!entry->secondary_key_signature)
262 return NULL;
263
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100264 while (entry && secondary_key_cmp(entry->secondary_key, secondary_key) != 0) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100265 node = eb32_next_dup(node);
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100266
267 /* Make the best use of this iteration and clear expired entries
268 * when we find them. Calling delete_entry would be too costly
269 * so we simply call eb32_delete. The secondary_entry count will
270 * be updated when we try to insert a new entry to this list. */
271 if (entry->expire <= now.tv_sec) {
272 eb32_delete(&entry->eb);
273 entry->eb.key = 0;
274 }
275
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100276 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
277 }
278
279 /* Expired entry */
280 if (entry && entry->expire <= now.tv_sec) {
281 eb32_delete(&entry->eb);
282 entry->eb.key = 0;
283 entry = NULL;
284 }
285
286 return entry;
287}
288
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100289
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100290/*
291 * Remove all expired entries from a list of duplicates.
292 * Return the number of alive entries in the list and sets dup_tail to the
293 * current last item of the list.
294 */
295static unsigned int clear_expired_duplicates(struct eb32_node **dup_tail)
296{
297 unsigned int entry_count = 0;
298 struct cache_entry *entry = NULL;
299 struct eb32_node *prev = *dup_tail;
300 struct eb32_node *tail = NULL;
301
302 while (prev) {
303 entry = container_of(prev, struct cache_entry, eb);
304 prev = eb32_prev_dup(prev);
305 if (entry->expire <= now.tv_sec) {
306 eb32_delete(&entry->eb);
307 entry->eb.key = 0;
308 }
309 else {
310 if (!tail)
311 tail = &entry->eb;
312 ++entry_count;
313 }
314 }
315
316 *dup_tail = tail;
317
318 return entry_count;
319}
320
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100321
322/*
323 * This function inserts a cache_entry in the cache's ebtree. In case of
324 * duplicate entries (vary), it then checks that the number of entries did not
325 * reach the max number of secondary entries. If this entry should not have been
326 * created, remove it.
327 * In the regular case (unique entries), this function does not do more than a
328 * simple insert. In case of secondary entries, it will at most cost an
329 * insertion+max_sec_entries time checks and entry deletion.
330 * Returns the newly inserted node in case of success, NULL otherwise.
331 */
332static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry)
333{
334 struct eb32_node *prev = NULL;
335 struct cache_entry *entry = NULL;
336 unsigned int entry_count = 0;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100337 unsigned int last_clear_ts = now.tv_sec;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100338
339 struct eb32_node *node = eb32_insert(&cache->entries, &new_entry->eb);
340
341 /* We should not have multiple entries with the same primary key unless
342 * the entry has a non null vary signature. */
343 if (!new_entry->secondary_key_signature)
344 return node;
345
346 prev = eb32_prev_dup(node);
347 if (prev != NULL) {
348 /* The last entry of a duplicate list should contain the current
349 * number of entries in the list. */
350 entry = container_of(prev, struct cache_entry, eb);
351 entry_count = entry->secondary_entries_count;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100352 last_clear_ts = entry->last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100353
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100354 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100355 /* Some entries of the duplicate list might be expired so
356 * we will iterate over all the items in order to free some
357 * space. In order to avoid going over the same list too
358 * often, we first check the timestamp of the last check
359 * performed. */
360 if (last_clear_ts == now.tv_sec) {
361 /* Too many entries for this primary key, clear the
362 * one that was inserted. */
363 eb32_delete(node);
364 node->key = 0;
365 return NULL;
366 }
367
368 entry_count = clear_expired_duplicates(&prev);
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100369 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100370 /* Still too many entries for this primary key, delete
371 * the newly inserted one. */
372 entry = container_of(prev, struct cache_entry, eb);
373 entry->last_clear_ts = now.tv_sec;
374 eb32_delete(node);
375 node->key = 0;
376 return NULL;
377 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100378 }
379 }
380
381 new_entry->secondary_entries_count = entry_count + 1;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100382 new_entry->last_clear_ts = last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100383
384 return node;
385}
386
387
388/*
389 * This function removes an entry from the ebtree. If the entry was a duplicate
390 * (in case of Vary), it updates the secondary entry counter in another
391 * duplicate entry (the last entry of the dup list).
392 */
393static void delete_entry(struct cache_entry *del_entry)
394{
395 struct eb32_node *prev = NULL, *next = NULL;
396 struct cache_entry *entry = NULL;
397 struct eb32_node *last = NULL;
398
399 if (del_entry->secondary_key_signature) {
400 next = &del_entry->eb;
401
402 /* Look for last entry of the duplicates list. */
403 while ((next = eb32_next_dup(next))) {
404 last = next;
405 }
406
407 if (last) {
408 entry = container_of(last, struct cache_entry, eb);
409 --entry->secondary_entries_count;
410 }
411 else {
412 /* The current entry is the last one, look for the
413 * previous one to update its counter. */
414 prev = eb32_prev_dup(&del_entry->eb);
415 if (prev) {
416 entry = container_of(prev, struct cache_entry, eb);
417 entry->secondary_entries_count = del_entry->secondary_entries_count - 1;
418 }
419 }
420 }
421 eb32_delete(&del_entry->eb);
422 del_entry->eb.key = 0;
423}
424
425
William Lallemand4da3f8a2017-10-31 14:33:34 +0100426static inline struct shared_context *shctx_ptr(struct cache *cache)
427{
428 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
429}
430
William Lallemand77c11972017-10-31 20:43:01 +0100431static inline struct shared_block *block_ptr(struct cache_entry *entry)
432{
433 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
434}
435
436
437
William Lallemand41db4602017-10-30 11:15:51 +0100438static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100439cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100440{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100441 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100442 return 0;
443}
444
Christopher Faulet95220e22018-12-07 17:34:39 +0100445static void
446cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
447{
448 struct cache_flt_conf *cconf = fconf->conf;
449
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200450 if (!(cconf->flags & CACHE_FLT_INIT))
451 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100452 free(cconf);
453}
454
William Lallemand4da3f8a2017-10-31 14:33:34 +0100455static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100456cache_store_check(struct proxy *px, struct flt_conf *fconf)
457{
458 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100459 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100460 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100461 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100462
William Lallemandd1d1e222019-08-28 15:22:49 +0200463 /* Find the cache corresponding to the name in the filter config. The
464 * cache will not be referenced now in the filter config because it is
465 * not fully allocated. This step will be performed during the cache
466 * post_check.
467 */
468 list_for_each_entry(cache, &caches_config, list) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +0100469 if (strcmp(cache->id, cconf->c.name) == 0)
Christopher Faulet95220e22018-12-07 17:34:39 +0100470 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100471 }
472
473 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
474 proxy_type_str(px), px->id, (char *)cconf->c.name);
475 return 1;
476
477 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100478 /* Here <cache> points on the cache the filter must use and <cconf>
479 * points on the cache filter configuration. */
480
481 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100482 * enabled and if it is after the cache. When the compression is before
483 * the cache, an error is returned. Also check if the cache filter must
484 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100485 list_for_each_entry(f, &px->filter_configs, list) {
486 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100487 /* The compression filter must be evaluated after the cache. */
488 if (comp) {
489 ha_alert("config: %s '%s': unable to enable the compression filter before "
490 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
491 return 1;
492 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100493 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200494 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100495 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200496 else if (f->id == fcgi_flt_id)
497 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100498 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
499 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200500 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100501 * declaration is required. */
502 ha_alert("config: %s '%s': require an explicit filter declaration "
503 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
504 return 1;
505 }
506
Christopher Fauletafd819c2018-12-11 08:57:45 +0100507 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100508 return 0;
509}
510
511static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100512cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100513{
Christopher Faulet65554e12020-03-06 14:52:06 +0100514 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100515
Willy Tarreauacc5b012021-03-22 15:00:49 +0100516 st = pool_alloc(pool_head_cache_st);
Christopher Faulet65554e12020-03-06 14:52:06 +0100517 if (st == NULL)
518 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100519
Christopher Faulet65554e12020-03-06 14:52:06 +0100520 st->first_block = NULL;
521 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100522
Christopher Faulet65554e12020-03-06 14:52:06 +0100523 /* Register post-analyzer on AN_RES_WAIT_HTTP */
524 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100525 return 1;
526}
527
Christopher Faulet65554e12020-03-06 14:52:06 +0100528static void
529cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100530{
531 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100532 struct cache_flt_conf *cconf = FLT_CONF(filter);
533 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100534 struct shared_context *shctx = shctx_ptr(cache);
535
William Lallemand49dc0482017-11-24 14:33:54 +0100536 /* Everything should be released in the http_end filter, but we need to do it
537 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100538 if (st && st->first_block) {
William Lallemand49dc0482017-11-24 14:33:54 +0100539 shctx_lock(shctx);
540 shctx_row_dec_hot(shctx, st->first_block);
541 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100542 }
543 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100544 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100545 filter->ctx = NULL;
546 }
William Lallemand49dc0482017-11-24 14:33:54 +0100547}
548
Christopher Faulet839791a2019-01-07 16:12:07 +0100549static int
550cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
551 unsigned an_bit)
552{
553 struct http_txn *txn = s->txn;
554 struct http_msg *msg = &txn->rsp;
555 struct cache_st *st = filter->ctx;
556
557 if (an_bit != AN_RES_WAIT_HTTP)
558 goto end;
559
560 /* Here we need to check if any compression filter precedes the cache
561 * filter. This is only possible when the compression is configured in
562 * the frontend while the cache filter is configured on the
563 * backend. This case cannot be detected during HAProxy startup. So in
564 * such cases, the cache is disabled.
565 */
566 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
567 pool_free(pool_head_cache_st, st);
568 filter->ctx = NULL;
569 }
570
571 end:
572 return 1;
573}
William Lallemand49dc0482017-11-24 14:33:54 +0100574
575static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100576cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
577{
578 struct cache_st *st = filter->ctx;
579
William Lallemand4da3f8a2017-10-31 14:33:34 +0100580 if (!(msg->chn->flags & CF_ISRESP) || !st)
581 return 1;
582
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200583 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100584 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100585 return 1;
586}
587
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200588static inline void disable_cache_entry(struct cache_st *st,
589 struct filter *filter, struct shared_context *shctx)
590{
591 struct cache_entry *object;
592
593 object = (struct cache_entry *)st->first_block->data;
594 filter->ctx = NULL; /* disable cache */
595 shctx_lock(shctx);
596 shctx_row_dec_hot(shctx, st->first_block);
Remi Tricot-Le Breton964caaf2020-12-15 14:30:12 +0100597 eb32_delete(&object->eb);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200598 object->eb.key = 0;
599 shctx_unlock(shctx);
600 pool_free(pool_head_cache_st, st);
601}
602
William Lallemand4da3f8a2017-10-31 14:33:34 +0100603static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100604cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
605 unsigned int offset, unsigned int len)
606{
Christopher Faulet95220e22018-12-07 17:34:39 +0100607 struct cache_flt_conf *cconf = FLT_CONF(filter);
608 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100609 struct cache_st *st = filter->ctx;
610 struct htx *htx = htxbuf(&msg->chn->buf);
611 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200612 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100613 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200614 unsigned int orig_len, to_forward;
615 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100616
617 if (!len)
618 return len;
619
620 if (!st->first_block) {
621 unregister_data_filter(s, msg->chn, filter);
622 return len;
623 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100624
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200625 chunk_reset(&trash);
626 orig_len = len;
627 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100628
629 htxret = htx_find_offset(htx, offset);
630 blk = htxret.blk;
631 offset = htxret.ret;
632 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100633 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200634 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100635 struct ist v;
636
637 switch (type) {
638 case HTX_BLK_UNUSED:
639 break;
640
641 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100642 v = htx_get_blk_value(htx, blk);
Tim Duesterhus154374c2021-03-02 18:57:27 +0100643 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +0100644 v = isttrim(v, len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100645
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200646 info = (type << 28) + v.len;
647 chunk_memcat(&trash, (char *)&info, sizeof(info));
Tim Duesterhus77508502022-03-15 13:11:06 +0100648 chunk_istcat(&trash, v);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100649 to_forward += v.len;
650 len -= v.len;
651 break;
652
653 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200654 /* Here offset must always be 0 because only
655 * DATA blocks can be partially transferred. */
656 if (offset)
657 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100658 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200659 goto end;
660
661 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
662 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100663 to_forward += sz;
664 len -= sz;
665 break;
666 }
667
668 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100669 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200670
671 end:
672 shctx_lock(shctx);
673 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
674 if (!fb) {
675 shctx_unlock(shctx);
676 goto no_cache;
677 }
678 shctx_unlock(shctx);
679
680 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
681 (unsigned char *)b_head(&trash), b_data(&trash));
682 if (ret < 0)
683 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100684
685 return to_forward;
686
687 no_cache:
688 disable_cache_entry(st, filter, shctx);
689 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200690 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100691}
692
693static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100694cache_store_http_end(struct stream *s, struct filter *filter,
695 struct http_msg *msg)
696{
697 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100698 struct cache_flt_conf *cconf = FLT_CONF(filter);
699 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100700 struct shared_context *shctx = shctx_ptr(cache);
701 struct cache_entry *object;
702
703 if (!(msg->chn->flags & CF_ISRESP))
704 return 1;
705
706 if (st && st->first_block) {
707
708 object = (struct cache_entry *)st->first_block->data;
709
William Lallemand4da3f8a2017-10-31 14:33:34 +0100710 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100711 /* The whole payload was cached, the entry can now be used. */
712 object->complete = 1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100713 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100714 shctx_row_dec_hot(shctx, st->first_block);
715 shctx_unlock(shctx);
716
717 }
718 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100719 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100720 filter->ctx = NULL;
721 }
722
723 return 1;
724}
725
726 /*
727 * This intends to be used when checking HTTP headers for some
728 * word=value directive. Return a pointer to the first character of value, if
Willy Tarreau94a01e12021-01-06 17:35:12 +0100729 * the word was not found or if there wasn't any value assigned to it return NULL
William Lallemand4da3f8a2017-10-31 14:33:34 +0100730 */
731char *directive_value(const char *sample, int slen, const char *word, int wlen)
732{
733 int st = 0;
734
735 if (slen < wlen)
736 return 0;
737
738 while (wlen) {
739 char c = *sample ^ *word;
740 if (c && c != ('A' ^ 'a'))
741 return NULL;
742 sample++;
743 word++;
744 slen--;
745 wlen--;
746 }
747
748 while (slen) {
749 if (st == 0) {
750 if (*sample != '=')
751 return NULL;
752 sample++;
753 slen--;
754 st = 1;
755 continue;
756 } else {
757 return (char *)sample;
758 }
759 }
760
761 return NULL;
762}
763
764/*
765 * Return the maxage in seconds of an HTTP response.
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100766 * The returned value will always take the cache's configuration into account
767 * (cache->maxage) but the actual max age of the response will be set in the
768 * true_maxage parameter. It will be used to determine if a response is already
769 * stale or not.
William Lallemand4da3f8a2017-10-31 14:33:34 +0100770 * Compute the maxage using either:
771 * - the assigned max-age of the cache
772 * - the s-maxage directive
773 * - the max-age directive
774 * - (Expires - Data) headers
775 * - the default-max-age of the cache
776 *
777 */
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100778int http_calc_maxage(struct stream *s, struct cache *cache, int *true_maxage)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100779{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200780 struct htx *htx = htxbuf(&s->res.buf);
781 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100782 long smaxage = -1;
783 long maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100784 int expires = -1;
785 struct tm tm = {};
786 time_t expires_val = 0;
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100787 char *endptr = NULL;
788 int offset = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100789
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100790 /* The Cache-Control max-age and s-maxage directives should be followed by
791 * a positive numerical value (see RFC 7234#5.2.1.1). According to the
792 * specs, a sender "should not" generate a quoted-string value but we will
793 * still accept this format since it isn't strictly forbidden. */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200794 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
795 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100796
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200797 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
798 if (value) {
799 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100800
Willy Tarreau49b04822021-11-08 11:44:47 +0100801 chunk_memcat(chk, value, ctx.value.len - 8 + 1);
802 chunk_memcat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100803 offset = (*chk->area == '"') ? 1 : 0;
804 smaxage = strtol(chk->area + offset, &endptr, 10);
Willy Tarreau1f38bdb2021-11-08 12:09:27 +0100805 if (unlikely(smaxage < 0 || endptr == chk->area + offset))
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100806 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100807 }
808
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200809 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
810 if (value) {
811 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200812
Willy Tarreau49b04822021-11-08 11:44:47 +0100813 chunk_memcat(chk, value, ctx.value.len - 7 + 1);
814 chunk_memcat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100815 offset = (*chk->area == '"') ? 1 : 0;
816 maxage = strtol(chk->area + offset, &endptr, 10);
Willy Tarreau1f38bdb2021-11-08 12:09:27 +0100817 if (unlikely(maxage < 0 || endptr == chk->area + offset))
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100818 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100819 }
820 }
821
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100822 /* Look for Expires header if no s-maxage or max-age Cache-Control data
823 * was found. */
824 if (maxage == -1 && smaxage == -1) {
825 ctx.blk = NULL;
826 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
827 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
828 expires_val = my_timegm(&tm);
829 /* A request having an expiring date earlier
830 * than the current date should be considered as
831 * stale. */
832 expires = (expires_val >= now.tv_sec) ?
833 (expires_val - now.tv_sec) : 0;
834 }
835 else {
836 /* Following RFC 7234#5.3, an invalid date
837 * format must be treated as a date in the past
838 * so the cache entry must be seen as already
839 * expired. */
840 expires = 0;
841 }
842 }
843 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100844
845
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100846 if (smaxage > 0) {
847 if (true_maxage)
848 *true_maxage = smaxage;
William Lallemand49b44532017-11-24 18:53:43 +0100849 return MIN(smaxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100850 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100851
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100852 if (maxage > 0) {
853 if (true_maxage)
854 *true_maxage = maxage;
William Lallemand49b44532017-11-24 18:53:43 +0100855 return MIN(maxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100856 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100857
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100858 if (expires >= 0) {
859 if (true_maxage)
860 *true_maxage = expires;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100861 return MIN(expires, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100862 }
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100863
William Lallemand49b44532017-11-24 18:53:43 +0100864 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100865
866}
867
868
William Lallemanda400a3a2017-11-20 19:13:12 +0100869static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
870{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200871 struct cache_entry *object = (struct cache_entry *)block->data;
872
873 if (first == block && object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100874 delete_entry(object);
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200875 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100876}
877
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200878
879/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
880 * date value should be compared to a date determined by in a previous response (for
881 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
882 * value of the response's reception time (by decreasing order of priority). */
883static time_t get_last_modified_time(struct htx *htx)
884{
885 time_t last_modified = 0;
886 struct http_hdr_ctx ctx = { .blk = NULL };
887 struct tm tm = {};
888
889 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
890 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
891 last_modified = my_timegm(&tm);
892 }
893 }
894
895 if (!last_modified) {
896 ctx.blk = NULL;
897 if (http_find_header(htx, ist("date"), &ctx, 1)) {
898 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
899 last_modified = my_timegm(&tm);
900 }
901 }
902 }
903
904 /* Fallback on the current time if no "Last-Modified" or "Date" header
905 * was found. */
906 if (!last_modified)
907 last_modified = now.tv_sec;
908
909 return last_modified;
910}
911
William Lallemand41db4602017-10-30 11:15:51 +0100912/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100913 * Checks the vary header's value. The headers on which vary should be applied
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500914 * must be explicitly supported in the vary_information array (see cache.c). If
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100915 * any other header is mentioned, we won't store the response.
916 * Returns 1 if Vary-based storage can work, 0 otherwise.
917 */
918static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
919{
920 unsigned int vary_idx;
921 unsigned int vary_info_count;
922 const struct vary_hashing_information *vary_info;
923 struct http_hdr_ctx ctx = { .blk = NULL };
924
925 int retval = 1;
926
927 *vary_signature = 0;
928
929 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
930 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
931 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
932 vary_info = &vary_information[vary_idx];
933 if (isteqi(ctx.value, vary_info->hdr_name)) {
934 *vary_signature |= vary_info->value;
935 break;
936 }
937 }
938 retval = (vary_idx < vary_info_count);
939 }
940
941 return retval;
942}
943
944
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100945/*
946 * Look for the accept-encoding part of the secondary_key and replace the
947 * encoding bitmap part of the hash with the actual encoding of the response,
948 * extracted from the content-encoding header value.
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100949 * Responses that have an unknown encoding will not be cached if they also
950 * "vary" on the accept-encoding value.
951 * Returns 0 if we found a known encoding in the response, -1 otherwise.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100952 */
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100953static int set_secondary_key_encoding(struct htx *htx, char *secondary_key)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100954{
955 unsigned int resp_encoding_bitmap = 0;
956 const struct vary_hashing_information *info = vary_information;
957 unsigned int offset = 0;
958 unsigned int count = 0;
959 unsigned int hash_info_count = sizeof(vary_information)/sizeof(*vary_information);
960 unsigned int encoding_value;
961 struct http_hdr_ctx ctx = { .blk = NULL };
962
963 /* Look for the accept-encoding part of the secondary_key. */
964 while (count < hash_info_count && info->value != VARY_ACCEPT_ENCODING) {
965 offset += info->hash_length;
966 ++info;
967 ++count;
968 }
969
970 if (count == hash_info_count)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100971 return -1;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100972
973 while (http_find_header(htx, ist("content-encoding"), &ctx, 0)) {
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100974 if (parse_encoding_value(ctx.value, &encoding_value, NULL))
975 return -1; /* Do not store responses with an unknown encoding */
976 resp_encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100977 }
978
979 if (!resp_encoding_bitmap)
980 resp_encoding_bitmap |= VARY_ENCODING_IDENTITY;
981
982 /* Rewrite the bitmap part of the hash with the new bitmap that only
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +0500983 * corresponds the the response's encoding. */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100984 write_u32(secondary_key + offset, resp_encoding_bitmap);
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100985
986 return 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100987}
988
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100989
990/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500991 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100992 * register a filter to store the data
993 */
994enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200995 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100996{
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100997 int effective_maxage = 0;
998 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100999 struct http_txn *txn = s->txn;
1000 struct http_msg *msg = &txn->rsp;
1001 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001002 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001003 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001004 struct cache *cache = cconf->c.cache;
1005 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +01001006 struct cache_st *cache_ctx = NULL;
1007 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +01001008 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001009 struct htx *htx;
1010 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +02001011 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001012 int32_t pos;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001013 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001014
William Lallemand4da3f8a2017-10-31 14:33:34 +01001015 /* Don't cache if the response came from a cache */
1016 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
1017 s->target == &http_cache_applet.obj_type) {
1018 goto out;
1019 }
1020
1021 /* cache only HTTP/1.1 */
1022 if (!(txn->req.flags & HTTP_MSGF_VER_11))
1023 goto out;
1024
Willy Tarreau6905d182019-10-01 17:59:17 +02001025 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001026 if (txn->meth != HTTP_METH_GET) {
1027 /* In case of successful unsafe method on a stored resource, the
1028 * cached entry must be invalidated (see RFC7234#4.4).
1029 * A "non-error response" is one with a 2xx (Successful) or 3xx
1030 * (Redirection) status code. */
1031 if (txn->status >= 200 && txn->status < 400) {
1032 switch (txn->meth) {
1033 case HTTP_METH_OPTIONS:
1034 case HTTP_METH_GET:
1035 case HTTP_METH_HEAD:
1036 case HTTP_METH_TRACE:
1037 break;
1038
1039 default: /* Any unsafe method */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001040 /* Discard any corresponding entry in case of successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001041 * unsafe request (such as PUT, POST or DELETE). */
1042 shctx_lock(shctx);
1043
1044 old = entry_exist(cconf->c.cache, txn->cache_hash);
1045 if (old) {
1046 eb32_delete(&old->eb);
1047 old->eb.key = 0;
1048 }
1049 shctx_unlock(shctx);
1050 }
1051 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001052 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001053 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001054
Willy Tarreauc9036c02019-01-11 19:38:25 +01001055 /* cache key was not computed */
1056 if (!key)
1057 goto out;
1058
William Lallemand4da3f8a2017-10-31 14:33:34 +01001059 /* cache only 200 status code */
1060 if (txn->status != 200)
1061 goto out;
1062
Christopher Faulet839791a2019-01-07 16:12:07 +01001063 /* Find the corresponding filter instance for the current stream */
1064 list_for_each_entry(filter, &s->strm_flt.filters, list) {
1065 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
1066 /* No filter ctx, don't cache anything */
1067 if (!filter->ctx)
1068 goto out;
1069 cache_ctx = filter->ctx;
1070 break;
1071 }
1072 }
1073
1074 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001075 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001076
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001077 /* Do not cache too big objects. */
1078 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
1079 htx->data + htx->extra > shctx->max_obj_size)
1080 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001081
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001082 /* Only a subset of headers are supported in our Vary implementation. If
1083 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001084 * able to use the cache. Likewise, if Vary header support is disabled,
1085 * avoid caching responses that contain such a header. */
1086 ctx.blk = NULL;
1087 if (cache->vary_processing_enabled) {
1088 if (!http_check_vary_header(htx, &vary_signature))
1089 goto out;
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001090 if (vary_signature) {
1091 /* If something went wrong during the secondary key
1092 * building, do not store the response. */
1093 if (!(txn->flags & TX_CACHE_HAS_SEC_KEY))
1094 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001095 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001096 }
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001097 }
1098 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001099 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001100 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001101
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001102 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001103
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +01001104 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001105 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001106
1107 shctx_lock(shctx);
1108 old = entry_exist(cache, txn->cache_hash);
1109 if (old) {
1110 if (vary_signature)
1111 old = secondary_entry_exist(cconf->c.cache, old,
1112 txn->cache_secondary_hash);
1113 if (old) {
1114 if (!old->complete) {
1115 /* An entry with the same primary key is already being
1116 * created, we should not try to store the current
1117 * response because it will waste space in the cache. */
1118 shctx_unlock(shctx);
1119 goto out;
1120 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001121 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001122 old->eb.key = 0;
1123 }
1124 }
1125 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1126 if (!first) {
1127 shctx_unlock(shctx);
1128 goto out;
1129 }
1130 /* the received memory is not initialized, we need at least to mark
1131 * the object as not indexed yet.
1132 */
1133 object = (struct cache_entry *)first->data;
1134 memset(object, 0, sizeof(*object));
1135 object->eb.key = key;
1136 object->secondary_key_signature = vary_signature;
1137 /* We need to temporarily set a valid expiring time until the actual one
1138 * is set by the end of this function (in case of concurrent accesses to
1139 * the same resource). This way the second access will find an existing
1140 * but not yet usable entry in the tree and will avoid storing its data. */
1141 object->expire = now.tv_sec + 2;
1142
1143 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1144 if (vary_signature)
1145 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1146
1147 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001148 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001149 object->eb.key = 0;
1150 shctx_unlock(shctx);
1151 goto out;
1152 }
1153 shctx_unlock(shctx);
1154
1155 /* reserve space for the cache_entry structure */
1156 first->len = sizeof(struct cache_entry);
1157 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001158
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001159 /* Determine the entry's maximum age (taking into account the cache's
1160 * configuration) as well as the response's explicit max age (extracted
1161 * from cache-control directives or the expires header). */
1162 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1163
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001164 ctx.blk = NULL;
1165 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
Tim Duesterhusc2942842021-01-02 22:47:17 +01001166 long long hdr_age;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001167 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1168 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1169 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001170 /* A response with an Age value greater than its
1171 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001172 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001173 if (unlikely(object->age > true_maxage))
1174 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001175 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001176 else
1177 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001178 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001179 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001180
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001181 /* Build a last-modified time that will be stored in the cache_entry and
1182 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001183 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001184
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001185 chunk_reset(&trash);
1186 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1187 struct htx_blk *blk = htx_get_blk(htx, pos);
1188 enum htx_blk_type type = htx_get_blk_type(blk);
1189 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001190
Christopher Fauletb0667472019-09-03 22:22:12 +02001191 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001192 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1193 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001194
1195 /* Look for optional ETag header.
1196 * We need to store the offset of the ETag value in order for
1197 * future conditional requests to be able to perform ETag
1198 * comparisons. */
1199 if (type == HTX_BLK_HDR) {
Tim Duesterhuse2fff102021-01-02 22:47:16 +01001200 struct ist header_name = htx_get_blk_name(htx, blk);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001201 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001202 object->etag_length = sz - istlen(header_name);
1203 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001204 }
1205 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001206 if (type == HTX_BLK_EOH)
1207 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001208 }
1209
Christopher Fauletb0667472019-09-03 22:22:12 +02001210 /* Do not cache objects if the headers are too big. */
1211 if (hdrs_len > htx->size - global.tune.maxrewrite)
1212 goto out;
1213
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001214 /* If the response has a secondary_key, fill its key part related to
1215 * encodings with the actual encoding of the response. This way any
1216 * subsequent request having the same primary key will have its accepted
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001217 * encodings tested upon the cached response's one.
1218 * We will not cache a response that has an unknown encoding (not
Ilya Shipitsin7704b0e2021-01-23 02:11:59 +05001219 * explicitly supported in parse_encoding_value function). */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001220 if (cache->vary_processing_enabled && vary_signature)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001221 if (set_secondary_key_encoding(htx, object->secondary_key))
1222 goto out;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001223
William Lallemand4da3f8a2017-10-31 14:33:34 +01001224 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001225 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001226 shctx_unlock(shctx);
1227 goto out;
1228 }
1229 shctx_unlock(shctx);
1230
William Lallemand4da3f8a2017-10-31 14:33:34 +01001231 /* cache the headers in a http action because it allows to chose what
1232 * to cache, for example you might want to cache a response before
1233 * modifying some HTTP headers, or on the contrary after modifying
1234 * those headers.
1235 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001236 /* does not need to be locked because it's in the "hot" list,
1237 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001238 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1239 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001240
1241 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001242 if (cache_ctx) {
1243 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001244 /* store latest value and expiration time */
1245 object->latest_validation = now.tv_sec;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001246 object->expire = now.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001247 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001248 }
1249
1250out:
1251 /* if does not cache */
1252 if (first) {
1253 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001254 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001255 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001256 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001257 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001258 shctx_row_dec_hot(shctx, first);
1259 shctx_unlock(shctx);
1260 }
1261
William Lallemand41db4602017-10-30 11:15:51 +01001262 return ACT_RET_CONT;
1263}
1264
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001265#define HTX_CACHE_INIT 0 /* Initial state. */
1266#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1267#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001268#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1269#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001270
William Lallemandecb73b12017-11-24 14:33:55 +01001271static void http_cache_applet_release(struct appctx *appctx)
1272{
Willy Tarreauf61494c2022-05-06 11:03:39 +02001273 struct cache_appctx *ctx = appctx->svcctx;
Christopher Faulet95220e22018-12-07 17:34:39 +01001274 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
Willy Tarreauf61494c2022-05-06 11:03:39 +02001275 struct cache_entry *cache_ptr = ctx->entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001276 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001277 struct shared_block *first = block_ptr(cache_ptr);
1278
1279 shctx_lock(shctx_ptr(cache));
1280 shctx_row_dec_hot(shctx_ptr(cache), first);
1281 shctx_unlock(shctx_ptr(cache));
1282}
1283
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001284
1285static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1286 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001287{
Willy Tarreauf61494c2022-05-06 11:03:39 +02001288 struct cache_appctx *ctx = appctx->svcctx;
Christopher Faulet95220e22018-12-07 17:34:39 +01001289 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1290 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001291 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001292 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001293 unsigned int max, total;
1294 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001295
Christopher Faulet908628c2022-03-25 16:43:49 +01001296 max = htx_get_max_blksz(htx, channel_htx_recv_max(cs_ic(appctx->owner), htx));
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001297 if (!max)
1298 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001299 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001300 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1301 : info & 0xfffffff);
1302 if (blksz > max)
1303 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001304
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001305 blk = htx_add_blk(htx, type, blksz);
1306 if (!blk)
1307 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001308
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001309 blk->info = info;
1310 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001311 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001312 while (blksz) {
1313 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001314 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001315 offset += max;
1316 blksz -= max;
1317 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001318 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001319 if (blksz || offset == shctx->block_size) {
1320 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1321 offset = 0;
1322 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001323 }
Willy Tarreauf61494c2022-05-06 11:03:39 +02001324 ctx->offset = offset;
1325 ctx->next = shblk;
1326 ctx->sent += total;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001327 return total;
1328}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001329
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001330static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1331 uint32_t info, struct shared_block *shblk, unsigned int offset)
1332{
Willy Tarreauf61494c2022-05-06 11:03:39 +02001333 struct cache_appctx *ctx = appctx->svcctx;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001334 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1335 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1336 unsigned int max, total, rem_data;
1337 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001338
Christopher Faulet908628c2022-03-25 16:43:49 +01001339 max = htx_get_max_blksz(htx, channel_htx_recv_max(cs_ic(appctx->owner), htx));
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001340 if (!max)
1341 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001342
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001343 rem_data = 0;
Willy Tarreauf61494c2022-05-06 11:03:39 +02001344 if (ctx->rem_data) {
1345 blksz = ctx->rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001346 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001347 }
1348 else {
1349 blksz = (info & 0xfffffff);
1350 total = 4;
1351 }
1352 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001353 rem_data = blksz - max;
1354 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001355 }
1356
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001357 while (blksz) {
1358 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001359
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001360 max = MIN(blksz, shctx->block_size - offset);
1361 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1362 offset += sz;
1363 blksz -= sz;
1364 total += sz;
1365 if (sz < max)
1366 break;
1367 if (blksz || offset == shctx->block_size) {
1368 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1369 offset = 0;
1370 }
1371 }
1372
Willy Tarreauf61494c2022-05-06 11:03:39 +02001373 ctx->offset = offset;
1374 ctx->next = shblk;
1375 ctx->sent += total;
1376 ctx->rem_data = rem_data + blksz;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001377 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001378}
1379
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001380static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1381 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001382{
Willy Tarreauf61494c2022-05-06 11:03:39 +02001383 struct cache_appctx *ctx = appctx->svcctx;
Christopher Faulet95220e22018-12-07 17:34:39 +01001384 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1385 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001386 struct shared_block *shblk;
1387 unsigned int offset, sz;
1388 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001389
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001390 while (len) {
1391 enum htx_blk_type type;
1392 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001393
Willy Tarreauf61494c2022-05-06 11:03:39 +02001394 shblk = ctx->next;
1395 offset = ctx->offset;
1396 if (ctx->rem_data) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001397 type = HTX_BLK_DATA;
1398 info = 0;
1399 goto add_data_blk;
1400 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001401
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001402 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001403 sz = MIN(4, shctx->block_size - offset);
1404 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1405 offset += sz;
1406 if (sz < 4) {
1407 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1408 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1409 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001410 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001411
1412 /* Get payload of the next HTX block and insert it. */
1413 type = (info >> 28);
1414 if (type != HTX_BLK_DATA)
1415 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1416 else {
1417 add_data_blk:
1418 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001419 }
1420
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001421 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001422 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001423 total += ret;
1424 len -= ret;
1425
Willy Tarreauf61494c2022-05-06 11:03:39 +02001426 if (ctx->rem_data || type == mark)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001427 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001428 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001429
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001430 return total;
1431}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001432
1433static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1434{
Willy Tarreauf61494c2022-05-06 11:03:39 +02001435 struct cache_appctx *ctx = appctx->svcctx;
1436 struct cache_entry *cache_ptr = ctx->entry;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001437 unsigned int age;
1438 char *end;
1439
1440 chunk_reset(&trash);
1441 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1442 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1443 age = CACHE_ENTRY_MAX_AGE;
1444 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1445 b_set_data(&trash, end - b_head(&trash));
1446 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1447 return 0;
1448 return 1;
1449}
1450
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001451static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001452{
Willy Tarreauf61494c2022-05-06 11:03:39 +02001453 struct cache_appctx *ctx = appctx->svcctx;
1454 struct cache_entry *cache_ptr = ctx->entry;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001455 struct shared_block *first = block_ptr(cache_ptr);
Christopher Faulet908628c2022-03-25 16:43:49 +01001456 struct conn_stream *cs = appctx->owner;
1457 struct channel *req = cs_oc(cs);
1458 struct channel *res = cs_ic(cs);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001459 struct htx *req_htx, *res_htx;
1460 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001461 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001462 size_t ret, total = 0;
1463
Christopher Faulet8b1eed12022-03-07 16:44:30 +01001464 res_htx = htx_from_buf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001465 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001466
Christopher Faulet62e75742022-03-31 09:16:34 +02001467 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001468 goto out;
1469
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001470 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001471 if (!b_size(&res->buf)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001472 cs_rx_room_blk(cs);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001473 goto out;
1474 }
1475
Willy Tarreauefef3232018-12-16 00:37:45 +01001476 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001477 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001478
1479 if (appctx->st0 == HTX_CACHE_INIT) {
Willy Tarreauf61494c2022-05-06 11:03:39 +02001480 ctx->next = block_ptr(cache_ptr);
1481 ctx->offset = sizeof(*cache_ptr);
1482 ctx->sent = 0;
1483 ctx->rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001484 appctx->st0 = HTX_CACHE_HEADER;
1485 }
1486
1487 if (appctx->st0 == HTX_CACHE_HEADER) {
1488 /* Headers must be dump at once. Otherwise it is an error */
Willy Tarreauf61494c2022-05-06 11:03:39 +02001489 len = first->len - sizeof(*cache_ptr) - ctx->sent;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001490 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1491 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1492 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001493 goto error;
1494
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001495 /* In case of a conditional request, we might want to send a
1496 * "304 Not Modified" response instead of the stored data. */
Willy Tarreauf61494c2022-05-06 11:03:39 +02001497 if (ctx->send_notmodified) {
Tim Duesterhuse0142342020-10-22 21:15:06 +02001498 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1499 /* If replacing the status code fails we need to send the full response. */
Willy Tarreauf61494c2022-05-06 11:03:39 +02001500 ctx->send_notmodified = 0;
Tim Duesterhuse0142342020-10-22 21:15:06 +02001501 }
1502 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001503
1504 /* Skip response body for HEAD requests or in case of "304 Not
1505 * Modified" response. */
Willy Tarreauf61494c2022-05-06 11:03:39 +02001506 if (__cs_strm(cs)->txn->meth == HTTP_METH_HEAD || ctx->send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001507 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001508 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001509 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001510 }
1511
1512 if (appctx->st0 == HTX_CACHE_DATA) {
Willy Tarreauf61494c2022-05-06 11:03:39 +02001513 len = first->len - sizeof(*cache_ptr) - ctx->sent;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001514 if (len) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001515 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_UNUSED);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001516 if (ret < len) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001517 cs_rx_room_blk(cs);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001518 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001519 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001520 }
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001521 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001522 }
1523
1524 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001525 /* no more data are expected. */
1526 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletdbf1e882022-03-07 15:53:57 +01001527 res->flags |= CF_EOI;
Willy Tarreau66435e52022-05-10 11:32:31 +02001528 appctx->endp->flags |= CS_EP_EOI;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001529 appctx->st0 = HTX_CACHE_END;
1530 }
1531
1532 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001533 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001534 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02001535 cs_shutr(cs);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001536 }
1537
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001538 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001539 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001540 if (total)
1541 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001542 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001543
1544 /* eat the whole request */
1545 if (co_data(req)) {
1546 req_htx = htx_from_buf(&req->buf);
1547 co_htx_skip(req, req_htx, co_data(req));
1548 htx_to_buf(req_htx, &req->buf);
1549 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001550 return;
1551
1552 error:
1553 /* Sent and HTTP error 500 */
1554 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001555 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001556 res->buf.data = b_data(errmsg);
1557 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1558 res_htx = htx_from_buf(&res->buf);
1559
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001560 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001561 appctx->st0 = HTX_CACHE_END;
1562 goto end;
1563}
1564
1565
Christopher Faulet95220e22018-12-07 17:34:39 +01001566static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001567{
1568 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001569 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001570
Christopher Faulet95220e22018-12-07 17:34:39 +01001571 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001572 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001573 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001574 }
1575
1576 /* check if a cache filter was already registered with this cache
1577 * name, if that's the case, must use it. */
1578 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001579 if (fconf->id == cache_store_flt_id) {
1580 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001581 if (cconf && strcmp((char *)cconf->c.name, name) == 0) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001582 rule->arg.act.p[0] = cconf;
1583 return 1;
1584 }
William Lallemand41db4602017-10-30 11:15:51 +01001585 }
1586 }
1587
Christopher Faulet95220e22018-12-07 17:34:39 +01001588 /* Create the filter cache config */
1589 cconf = calloc(1, sizeof(*cconf));
1590 if (!cconf) {
1591 memprintf(err, "out of memory\n");
1592 goto err;
1593 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001594 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001595 cconf->c.name = strdup(name);
1596 if (!cconf->c.name) {
1597 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001598 goto err;
1599 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001600
William Lallemand41db4602017-10-30 11:15:51 +01001601 /* register a filter to fill the cache buffer */
1602 fconf = calloc(1, sizeof(*fconf));
1603 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001604 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001605 goto err;
1606 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001607 fconf->id = cache_store_flt_id;
1608 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001609 fconf->ops = &cache_ops;
Willy Tarreau2b718102021-04-21 07:32:39 +02001610 LIST_APPEND(&proxy->filter_configs, &fconf->list);
William Lallemand41db4602017-10-30 11:15:51 +01001611
Christopher Faulet95220e22018-12-07 17:34:39 +01001612 rule->arg.act.p[0] = cconf;
1613 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001614
Christopher Faulet95220e22018-12-07 17:34:39 +01001615 err:
1616 free(cconf);
1617 return 0;
1618}
1619
1620enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1621 struct act_rule *rule, char **err)
1622{
1623 rule->action = ACT_CUSTOM;
1624 rule->action_ptr = http_action_store_cache;
1625
1626 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1627 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001628
Christopher Faulet95220e22018-12-07 17:34:39 +01001629 (*orig_arg)++;
1630 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001631}
1632
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001633/* This produces a sha1 hash of the concatenation of the HTTP method,
1634 * the first occurrence of the Host header followed by the path component
1635 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001636int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001637{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001638 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001639 struct htx *htx = htxbuf(&s->req.buf);
1640 struct htx_sl *sl;
1641 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001642 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001643 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001644 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001645
William Lallemandf528fff2017-11-23 19:43:17 +01001646 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001647 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001648
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001649 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001650 uri = htx_sl_req_uri(sl); // whole uri
1651 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001652 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001653
1654 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1655 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1656 * URIs are almost always sent in absolute form with their scheme. In
1657 * this case, the scheme is almost always "https". In order to support
1658 * sharing of cache objects between H1 and H2, we'll hash the absolute
1659 * URI whenever known, or prepend "https://" + the Host header for
1660 * relative URIs. The difference will only appear on absolute HTTP/1
1661 * requests sent to an origin server, which practically is never met in
1662 * the real world so we don't care about the ability to share the same
1663 * key here.URIs are normalized from the absolute URI to an origin form as
1664 * well.
1665 */
1666 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001667 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001668 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1669 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001670 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001671 }
1672
Tim Duesterhus9f7ed8a2021-11-08 09:05:04 +01001673 chunk_istcat(trash, uri);
William Lallemandf528fff2017-11-23 19:43:17 +01001674
1675 /* hash everything */
1676 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001677 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001678 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1679
1680 return 1;
1681}
1682
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001683/* Looks for "If-None-Match" headers in the request and compares their value
1684 * with the one that might have been stored in the cache_entry. If any of them
1685 * matches, a "304 Not Modified" response should be sent instead of the cached
1686 * data.
1687 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001688 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1689 *
1690 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1691 * header and compare its value (date) to the one stored in the cache_entry.
1692 * If the request's date is later than the cached one, we also send a
1693 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1694 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001695 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1696 */
1697static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1698 struct cache_entry *entry)
1699{
1700 int retval = 0;
1701
1702 struct http_hdr_ctx ctx = { .blk = NULL };
1703 struct ist cache_entry_etag = IST_NULL;
1704 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001705 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001706
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001707 struct tm tm = {};
1708 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001709
1710 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001711 * cache_entry's ETag in order to perform comparisons.
1712 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001713 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001714 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001715
1716 /* A '*' matches everything. */
1717 if (isteq(ctx.value, ist("*")) != 0) {
1718 retval = 1;
1719 break;
1720 }
1721
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001722 /* No need to rebuild an etag if none was stored in the cache. */
1723 if (entry->etag_length == 0)
1724 break;
1725
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001726 /* Rebuild the stored ETag. */
1727 if (etag_buffer == NULL) {
1728 etag_buffer = get_trash_chunk();
1729
1730 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1731 (unsigned char*)b_orig(etag_buffer),
1732 entry->etag_offset, entry->etag_length) == 0) {
1733 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1734 } else {
1735 /* We could not rebuild the ETag in one go, we
1736 * won't send a "304 Not Modified" response. */
1737 break;
1738 }
1739 }
1740
1741 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1742 retval = 1;
1743 break;
1744 }
1745 }
1746
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001747 /* If the request did not contain an "If-None-Match" header, we look for
1748 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1749 if (retval == 0 && if_none_match_found == 0) {
1750 ctx.blk = NULL;
1751 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1752 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1753 if_modified_since = my_timegm(&tm);
1754
1755 /* We send a "304 Not Modified" response if the
1756 * entry's last modified date is earlier than
1757 * the one found in the "If-Modified-Since"
1758 * header. */
1759 retval = (entry->last_modified <= if_modified_since);
1760 }
1761 }
1762 }
1763
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001764 return retval;
1765}
1766
William Lallemand41db4602017-10-30 11:15:51 +01001767enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1768 struct session *sess, struct stream *s, int flags)
1769{
William Lallemand77c11972017-10-31 20:43:01 +01001770
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001771 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001772 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001773 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1774 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001775 struct shared_block *entry_block;
1776
William Lallemand77c11972017-10-31 20:43:01 +01001777
Willy Tarreau6905d182019-10-01 17:59:17 +02001778 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1779 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001780 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001781 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001782 txn->flags |= TX_CACHE_IGNORE;
1783
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001784 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001785
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001786 /* The request's hash has to be calculated for all requests, even POSTs
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001787 * or PUTs for instance because RFC7234 specifies that a successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001788 * "unsafe" method on a stored resource must invalidate it
1789 * (see RFC7234#4.4). */
1790 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001791 return ACT_RET_CONT;
1792
Willy Tarreau504455c2017-12-22 17:47:35 +01001793 if (s->txn->flags & TX_CACHE_IGNORE)
1794 return ACT_RET_CONT;
1795
Willy Tarreaua1214a52018-12-14 14:00:25 +01001796 if (px == strm_fe(s))
Willy Tarreau4781b152021-04-06 13:53:36 +02001797 _HA_ATOMIC_INC(&px->fe_counters.p.http.cache_lookups);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001798 else
Willy Tarreau4781b152021-04-06 13:53:36 +02001799 _HA_ATOMIC_INC(&px->be_counters.p.http.cache_lookups);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001800
William Lallemanda400a3a2017-11-20 19:13:12 +01001801 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001802 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001803 /* We must not use an entry that is not complete. */
1804 if (res && res->complete) {
William Lallemand77c11972017-10-31 20:43:01 +01001805 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001806 entry_block = block_ptr(res);
1807 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001808 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001809
1810 /* In case of Vary, we could have multiple entries with the same
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001811 * primary hash. We need to calculate the secondary hash in order
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001812 * to find the actual entry we want (if it exists). */
1813 if (res->secondary_key_signature) {
1814 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1815 shctx_lock(shctx_ptr(cache));
1816 sec_entry = secondary_entry_exist(cache, res,
1817 s->txn->cache_secondary_hash);
1818 if (sec_entry && sec_entry != res) {
1819 /* The wrong row was added to the hot list. */
1820 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1821 entry_block = block_ptr(sec_entry);
1822 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1823 }
1824 res = sec_entry;
1825 shctx_unlock(shctx_ptr(cache));
1826 }
1827 else
1828 res = NULL;
1829 }
1830
1831 /* We looked for a valid secondary entry and could not find one,
1832 * the request must be forwarded to the server. */
1833 if (!res) {
1834 shctx_lock(shctx_ptr(cache));
1835 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1836 shctx_unlock(shctx_ptr(cache));
1837 return ACT_RET_CONT;
1838 }
1839
William Lallemand77c11972017-10-31 20:43:01 +01001840 s->target = &http_cache_applet.obj_type;
Christopher Faulet1336ccf2022-04-12 18:15:16 +02001841 if ((appctx = cs_applet_create(s->csb, objt_applet(s->target)))) {
Willy Tarreauf61494c2022-05-06 11:03:39 +02001842 struct cache_appctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
1843
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001844 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001845 appctx->rule = rule;
Willy Tarreauf61494c2022-05-06 11:03:39 +02001846 ctx->entry = res;
1847 ctx->next = NULL;
1848 ctx->sent = 0;
1849 ctx->send_notmodified =
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001850 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001851
1852 if (px == strm_fe(s))
Willy Tarreau4781b152021-04-06 13:53:36 +02001853 _HA_ATOMIC_INC(&px->fe_counters.p.http.cache_hits);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001854 else
Willy Tarreau4781b152021-04-06 13:53:36 +02001855 _HA_ATOMIC_INC(&px->be_counters.p.http.cache_hits);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001856 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001857 } else {
Christopher Faulet1d216c72022-04-21 11:30:43 +02001858 s->target = NULL;
William Lallemand55e76742017-11-21 20:01:28 +01001859 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001860 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001861 shctx_unlock(shctx_ptr(cache));
Christopher Faulet1d216c72022-04-21 11:30:43 +02001862 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001863 }
1864 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001865 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001866
1867 /* Shared context does not need to be locked while we calculate the
1868 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001869 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001870 /* Build a complete secondary hash until the server response
1871 * tells us which fields should be kept (if any). */
1872 http_request_prebuild_full_secondary_key(s);
1873 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001874 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001875}
1876
1877
1878enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1879 struct act_rule *rule, char **err)
1880{
William Lallemand41db4602017-10-30 11:15:51 +01001881 rule->action = ACT_CUSTOM;
1882 rule->action_ptr = http_action_req_cache_use;
1883
Christopher Faulet95220e22018-12-07 17:34:39 +01001884 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001885 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001886
1887 (*orig_arg)++;
1888 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001889}
1890
1891int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1892{
1893 int err_code = 0;
1894
1895 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1896
1897 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001898 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001899 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001900 err_code |= ERR_ALERT | ERR_ABORT;
1901 goto out;
1902 }
1903
1904 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1905 err_code |= ERR_ABORT;
1906 goto out;
1907 }
1908
1909 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001910 struct cache *cache_config;
1911
William Lallemand41db4602017-10-30 11:15:51 +01001912 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1913 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001914 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001915 err_code |= ERR_ALERT | ERR_ABORT;
1916 goto out;
1917 }
1918
1919 strlcpy2(tmp_cache_config->id, args[1], 33);
1920 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001921 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001922 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001923 err_code |= ERR_WARN;
1924 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001925
1926 list_for_each_entry(cache_config, &caches_config, list) {
1927 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1928 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1929 file, linenum, tmp_cache_config->id);
1930 err_code |= ERR_ALERT | ERR_ABORT;
1931 goto out;
1932 }
1933 }
1934
William Lallemand49b44532017-11-24 18:53:43 +01001935 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001936 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001937 tmp_cache_config->maxobjsz = 0;
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001938 tmp_cache_config->max_secondary_entries = DEFAULT_MAX_SECONDARY_ENTRY;
William Lallemand41db4602017-10-30 11:15:51 +01001939 }
1940 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001941 unsigned long int maxsize;
1942 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001943
1944 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1945 err_code |= ERR_ABORT;
1946 goto out;
1947 }
1948
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001949 maxsize = strtoul(args[1], &err, 10);
1950 if (err == args[1] || *err != '\0') {
1951 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1952 file, linenum, args[1]);
1953 err_code |= ERR_ABORT;
1954 goto out;
1955 }
1956
1957 if (maxsize > (UINT_MAX >> 20)) {
1958 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1959 file, linenum, args[1], UINT_MAX >> 20);
1960 err_code |= ERR_ABORT;
1961 goto out;
1962 }
1963
William Lallemand41db4602017-10-30 11:15:51 +01001964 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001965 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001966 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001967 } else if (strcmp(args[0], "max-age") == 0) {
1968 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1969 err_code |= ERR_ABORT;
1970 goto out;
1971 }
1972
1973 if (!*args[1]) {
1974 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1975 file, linenum, args[0]);
1976 err_code |= ERR_WARN;
1977 }
1978
1979 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001980 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001981 unsigned int maxobjsz;
1982 char *err;
1983
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001984 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1985 err_code |= ERR_ABORT;
1986 goto out;
1987 }
1988
1989 if (!*args[1]) {
1990 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1991 file, linenum, args[0]);
1992 err_code |= ERR_WARN;
1993 }
1994
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001995 maxobjsz = strtoul(args[1], &err, 10);
1996 if (err == args[1] || *err != '\0') {
1997 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1998 file, linenum, args[1]);
1999 err_code |= ERR_ABORT;
2000 goto out;
2001 }
2002 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01002003 } else if (strcmp(args[0], "process-vary") == 0) {
2004 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
2005 err_code |= ERR_ABORT;
2006 goto out;
2007 }
2008
2009 if (!*args[1]) {
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01002010 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01002011 file, linenum, args[0]);
2012 err_code |= ERR_WARN;
2013 }
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01002014 if (strcmp(args[1], "on") == 0)
2015 tmp_cache_config->vary_processing_enabled = 1;
2016 else if (strcmp(args[1], "off") == 0)
2017 tmp_cache_config->vary_processing_enabled = 0;
2018 else {
2019 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
2020 file, linenum, args[0]);
2021 err_code |= ERR_WARN;
2022 }
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01002023 } else if (strcmp(args[0], "max-secondary-entries") == 0) {
2024 unsigned int max_sec_entries;
2025 char *err;
2026
2027 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
2028 err_code |= ERR_ABORT;
2029 goto out;
2030 }
2031
2032 if (!*args[1]) {
2033 ha_warning("parsing [%s:%d]: '%s' expects a strictly positive number.\n",
2034 file, linenum, args[0]);
2035 err_code |= ERR_WARN;
2036 }
2037
2038 max_sec_entries = strtoul(args[1], &err, 10);
2039 if (err == args[1] || *err != '\0' || max_sec_entries == 0) {
2040 ha_warning("parsing [%s:%d]: max-secondary-entries wrong value '%s'\n",
2041 file, linenum, args[1]);
2042 err_code |= ERR_ABORT;
2043 goto out;
2044 }
2045 tmp_cache_config->max_secondary_entries = max_sec_entries;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002046 }
2047 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002048 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01002049 err_code |= ERR_ALERT | ERR_FATAL;
2050 goto out;
2051 }
2052out:
2053 return err_code;
2054}
2055
2056/* once the cache section is parsed */
2057
2058int cfg_post_parse_section_cache()
2059{
William Lallemand41db4602017-10-30 11:15:51 +01002060 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01002061
2062 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01002063
2064 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002065 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01002066 err_code |= ERR_FATAL | ERR_ALERT;
2067 goto out;
2068 }
2069
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002070 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002071 /* Default max. file size is a 256th of the cache size. */
2072 tmp_cache_config->maxobjsz =
2073 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002074 }
2075 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
2076 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
2077 err_code |= ERR_FATAL | ERR_ALERT;
2078 goto out;
2079 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002080
William Lallemandd1d1e222019-08-28 15:22:49 +02002081 /* add to the list of cache to init and reinit tmp_cache_config
2082 * for next cache section, if any.
2083 */
Willy Tarreau2b718102021-04-21 07:32:39 +02002084 LIST_APPEND(&caches_config, &tmp_cache_config->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002085 tmp_cache_config = NULL;
2086 return err_code;
2087 }
2088out:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002089 ha_free(&tmp_cache_config);
William Lallemandd1d1e222019-08-28 15:22:49 +02002090 return err_code;
2091
2092}
2093
2094int post_check_cache()
2095{
2096 struct proxy *px;
2097 struct cache *back, *cache_config, *cache;
2098 struct shared_context *shctx;
2099 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01002100 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02002101
2102 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
2103
2104 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
2105 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01002106
Frédéric Lécaillebc584492018-10-25 20:18:59 +02002107 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01002108 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01002109 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002110 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01002111 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002112
2113 err_code |= ERR_FATAL | ERR_ALERT;
2114 goto out;
2115 }
William Lallemanda400a3a2017-11-20 19:13:12 +01002116 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02002117 /* the cache structure is stored in the shctx and added to the
2118 * caches list, we can remove the entry from the caches_config
2119 * list */
2120 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01002121 cache = (struct cache *)shctx->data;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01002122 cache->entries = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +02002123 LIST_APPEND(&caches, &cache->list);
2124 LIST_DELETE(&cache_config->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002125 free(cache_config);
2126
2127 /* Find all references for this cache in the existing filters
2128 * (over all proxies) and reference it in matching filters.
2129 */
2130 for (px = proxies_list; px; px = px->next) {
2131 struct flt_conf *fconf;
2132 struct cache_flt_conf *cconf;
2133
2134 list_for_each_entry(fconf, &px->filter_configs, list) {
2135 if (fconf->id != cache_store_flt_id)
2136 continue;
2137
2138 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002139 if (strcmp(cache->id, cconf->c.name) == 0) {
William Lallemandd1d1e222019-08-28 15:22:49 +02002140 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02002141 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02002142 cconf->c.cache = cache;
2143 break;
2144 }
2145 }
2146 }
William Lallemand41db4602017-10-30 11:15:51 +01002147 }
William Lallemandd1d1e222019-08-28 15:22:49 +02002148
William Lallemand41db4602017-10-30 11:15:51 +01002149out:
William Lallemand41db4602017-10-30 11:15:51 +01002150 return err_code;
2151
William Lallemand41db4602017-10-30 11:15:51 +01002152}
2153
William Lallemand41db4602017-10-30 11:15:51 +01002154struct flt_ops cache_ops = {
2155 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01002156 .check = cache_store_check,
2157 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01002158
Christopher Faulet65554e12020-03-06 14:52:06 +01002159 /* Handle stream init/deinit */
2160 .attach = cache_store_strm_init,
2161 .detach = cache_store_strm_deinit,
2162
William Lallemand4da3f8a2017-10-31 14:33:34 +01002163 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01002164 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002165
2166 /* Filter HTTP requests and responses */
2167 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01002168 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002169 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01002170};
2171
Christopher Faulet99a17a22018-12-11 09:18:27 +01002172
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002173#define CHECK_ENCODING(str, encoding_name, encoding_value) \
2174 ({ \
2175 int retval = 0; \
2176 if (istmatch(str, (struct ist){ .ptr = encoding_name+1, .len = sizeof(encoding_name) - 2 })) { \
2177 retval = encoding_value; \
2178 encoding = istadv(encoding, sizeof(encoding_name) - 2); \
2179 } \
2180 (retval); \
2181 })
2182
2183/*
2184 * Parse the encoding <encoding> and try to match the encoding part upon an
2185 * encoding list of explicitly supported encodings (which all have a specific
2186 * bit in an encoding bitmap). If a weight is included in the value, find out if
2187 * it is null or not. The bit value will be set in the <encoding_value>
2188 * parameter and the <has_null_weight> will be set to 1 if the weight is strictly
2189 * 0, 1 otherwise.
2190 * The encodings list is extracted from
2191 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml.
2192 * Returns 0 in case of success and -1 in case of error.
2193 */
2194static int parse_encoding_value(struct ist encoding, unsigned int *encoding_value,
2195 unsigned int *has_null_weight)
2196{
2197 int retval = 0;
2198
2199 if (!encoding_value)
2200 return -1;
2201
2202 if (!istlen(encoding))
2203 return -1; /* Invalid encoding */
2204
2205 *encoding_value = 0;
2206 if (has_null_weight)
2207 *has_null_weight = 0;
2208
2209 switch (*encoding.ptr) {
2210 case 'a':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002211 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002212 *encoding_value = CHECK_ENCODING(encoding, "aes128gcm", VARY_ENCODING_AES128GCM);
2213 break;
2214 case 'b':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002215 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002216 *encoding_value = CHECK_ENCODING(encoding, "br", VARY_ENCODING_BR);
2217 break;
2218 case 'c':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002219 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002220 *encoding_value = CHECK_ENCODING(encoding, "compress", VARY_ENCODING_COMPRESS);
2221 break;
2222 case 'd':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002223 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002224 *encoding_value = CHECK_ENCODING(encoding, "deflate", VARY_ENCODING_DEFLATE);
2225 break;
2226 case 'e':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002227 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002228 *encoding_value = CHECK_ENCODING(encoding, "exi", VARY_ENCODING_EXI);
2229 break;
2230 case 'g':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002231 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002232 *encoding_value = CHECK_ENCODING(encoding, "gzip", VARY_ENCODING_GZIP);
2233 break;
2234 case 'i':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002235 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002236 *encoding_value = CHECK_ENCODING(encoding, "identity", VARY_ENCODING_IDENTITY);
2237 break;
2238 case 'p':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002239 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002240 *encoding_value = CHECK_ENCODING(encoding, "pack200-gzip", VARY_ENCODING_PACK200_GZIP);
2241 break;
2242 case 'x':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002243 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002244 *encoding_value = CHECK_ENCODING(encoding, "x-gzip", VARY_ENCODING_GZIP);
2245 if (!*encoding_value)
2246 *encoding_value = CHECK_ENCODING(encoding, "x-compress", VARY_ENCODING_COMPRESS);
2247 break;
2248 case 'z':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002249 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002250 *encoding_value = CHECK_ENCODING(encoding, "zstd", VARY_ENCODING_ZSTD);
2251 break;
2252 case '*':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002253 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002254 *encoding_value = VARY_ENCODING_STAR;
2255 break;
2256 default:
2257 retval = -1; /* Unmanaged encoding */
2258 break;
2259 }
2260
2261 /* Process the optional weight part of the encoding. */
2262 if (*encoding_value) {
2263 encoding = http_trim_leading_spht(encoding);
2264 if (istlen(encoding)) {
2265 if (*encoding.ptr != ';')
2266 return -1;
2267
2268 if (has_null_weight) {
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002269 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002270
2271 encoding = http_trim_leading_spht(encoding);
2272
2273 *has_null_weight = isteq(encoding, ist("q=0"));
2274 }
2275 }
2276 }
2277
2278 return retval;
2279}
2280
Tim Duesterhus23b29452020-11-24 22:22:56 +01002281#define ACCEPT_ENCODING_MAX_ENTRIES 16
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002282/*
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002283 * Build a bitmap of the accept-encoding header.
2284 *
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002285 * The bitmap is built by matching every sub-part of the accept-encoding value
2286 * with a subset of explicitly supported encodings, which all have their own bit
2287 * in the bitmap. This bitmap will be used to determine if a response can be
2288 * served to a client (that is if it has an encoding that is accepted by the
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002289 * client). Any unknown encodings will be indicated by the VARY_ENCODING_OTHER
2290 * bit.
2291 *
2292 * Returns 0 in case of success and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002293 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002294static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
2295 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002296{
Tim Duesterhus23b29452020-11-24 22:22:56 +01002297 size_t count = 0;
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002298 uint32_t encoding_bitmap = 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002299 unsigned int encoding_bmp_bl = -1;
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002300 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002301 unsigned int encoding_value;
2302 unsigned int rejected_encoding;
2303
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002304 /* A user agent always accepts an unencoded value unless it explicitly
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002305 * refuses it through an "identity;q=0" accept-encoding value. */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002306 encoding_bitmap |= VARY_ENCODING_IDENTITY;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002307
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002308 /* Iterate over all the ACCEPT_ENCODING_MAX_ENTRIES first accept-encoding
2309 * values that might span acrosse multiple accept-encoding headers. */
2310 while (http_find_header(htx, hdr_name, &ctx, 0) && count < ACCEPT_ENCODING_MAX_ENTRIES) {
Tim Duesterhus3bc6af42021-06-18 15:09:28 +02002311 count++;
2312
2313 /* As per RFC7231#5.3.4, "An Accept-Encoding header field with a
2314 * combined field-value that is empty implies that the user agent
2315 * does not want any content-coding in response."
2316 *
2317 * We must (and did) count the existence of this empty header to not
2318 * hit the `count == 0` case below, but must ignore the value to not
2319 * include VARY_ENCODING_OTHER into the final bitmap.
2320 */
2321 if (istlen(ctx.value) == 0)
2322 continue;
2323
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002324 /* Turn accept-encoding value to lower case */
2325 ist2bin_lc(istptr(ctx.value), ctx.value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002326
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002327 /* Try to identify a known encoding and to manage null weights. */
2328 if (!parse_encoding_value(ctx.value, &encoding_value, &rejected_encoding)) {
2329 if (rejected_encoding)
2330 encoding_bmp_bl &= ~encoding_value;
2331 else
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002332 encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002333 }
2334 else {
2335 /* Unknown encoding */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002336 encoding_bitmap |= VARY_ENCODING_OTHER;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002337 }
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002338 }
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002339
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002340 /* If a "*" was found in the accepted encodings (without a null weight),
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002341 * all the encoding are accepted except the ones explicitly rejected. */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002342 if (encoding_bitmap & VARY_ENCODING_STAR) {
2343 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002344 }
2345
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002346 /* Clear explicitly rejected encodings from the bitmap */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002347 encoding_bitmap &= encoding_bmp_bl;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002348
2349 /* As per RFC7231#5.3.4, "If no Accept-Encoding field is in the request,
2350 * any content-coding is considered acceptable by the user agent". */
2351 if (count == 0)
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002352 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002353
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002354 /* A request with more than ACCEPT_ENCODING_MAX_ENTRIES accepted
2355 * encodings might be illegitimate so we will not use it. */
2356 if (count == ACCEPT_ENCODING_MAX_ENTRIES)
2357 return -1;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002358
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002359 write_u32(buf, encoding_bitmap);
2360 *buf_len = sizeof(encoding_bitmap);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002361
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002362 /* This function fills the hash buffer correctly even if no header was
2363 * found, hence the 0 return value (success). */
Tim Duesterhus23b29452020-11-24 22:22:56 +01002364 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002365}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002366#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002367
2368/*
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002369 * Normalizer used by default for the Referer header. It only
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002370 * calculates a simple crc of the whole value.
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002371 * Only the first occurrence of the header will be taken into account in the
2372 * hash.
2373 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2374 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002375 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002376static int default_normalizer(struct htx *htx, struct ist hdr_name,
2377 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002378{
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002379 int retval = 1;
2380 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002381
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002382 if (http_find_header(htx, hdr_name, &ctx, 1)) {
2383 retval = 0;
2384 write_u32(buf, hash_crc32(istptr(ctx.value), istlen(ctx.value)));
2385 *buf_len = sizeof(int);
2386 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002387
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002388 return retval;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002389}
2390
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002391/*
Tim Duesterhused84d842021-01-18 13:41:17 +01002392 * Accept-Encoding bitmap comparison function.
2393 * Returns 0 if the bitmaps are compatible.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002394 */
Tim Duesterhused84d842021-01-18 13:41:17 +01002395static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002396{
Tim Duesterhused84d842021-01-18 13:41:17 +01002397 uint32_t ref_bitmap = read_u32(ref);
2398 uint32_t new_bitmap = read_u32(new);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002399
Tim Duesterhused84d842021-01-18 13:41:17 +01002400 if (!(ref_bitmap & VARY_ENCODING_OTHER)) {
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002401 /* All the bits set in the reference bitmap correspond to the
2402 * stored response' encoding and should all be set in the new
2403 * encoding bitmap in order for the client to be able to manage
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002404 * the response.
2405 *
2406 * If this is the case the cached response has encodings that
2407 * are accepted by the client. It can be served directly by
2408 * the cache (as far as the accept-encoding part is concerned).
2409 */
2410
Tim Duesterhused84d842021-01-18 13:41:17 +01002411 return (ref_bitmap & new_bitmap) != ref_bitmap;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002412 }
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002413 else {
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002414 return 1;
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002415 }
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002416}
2417
2418
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002419/*
2420 * Pre-calculate the hashes of all the supported headers (in our Vary
2421 * implementation) of a given request. We have to calculate all the hashes
2422 * in advance because the actual Vary signature won't be known until the first
2423 * response.
2424 * Only the first occurrence of every header will be taken into account in the
2425 * hash.
2426 * If the header is not present, the hash portion of the given header will be
2427 * filled with zeros.
2428 * Returns 0 in case of success.
2429 */
2430static int http_request_prebuild_full_secondary_key(struct stream *s)
2431{
Remi Tricot-Le Bretonbba29122020-12-23 18:13:44 +01002432 /* The fake signature (second parameter) will ensure that every part of the
2433 * secondary key is calculated. */
2434 return http_request_build_secondary_key(s, ~0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002435}
2436
2437
2438/*
2439 * Calculate the secondary key for a request for which we already have a known
2440 * vary signature. The key is made by aggregating hashes calculated for every
2441 * header mentioned in the vary signature.
2442 * Only the first occurrence of every header will be taken into account in the
2443 * hash.
2444 * If the header is not present, the hash portion of the given header will be
2445 * filled with zeros.
2446 * Returns 0 in case of success.
2447 */
2448static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2449{
2450 struct http_txn *txn = s->txn;
2451 struct htx *htx = htxbuf(&s->req.buf);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002452
2453 unsigned int idx;
2454 const struct vary_hashing_information *info = NULL;
2455 unsigned int hash_length = 0;
2456 int retval = 0;
2457 int offset = 0;
2458
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002459 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && retval >= 0; ++idx) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002460 info = &vary_information[idx];
2461
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002462 /* The normalizing functions will be in charge of getting the
2463 * header values from the htx. This way they can manage multiple
2464 * occurrences of their processed header. */
2465 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2466 !(retval = info->norm_fn(htx, info->hdr_name, &txn->cache_secondary_hash[offset], &hash_length))) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002467 offset += hash_length;
2468 }
2469 else {
2470 /* Fill hash with 0s. */
2471 hash_length = info->hash_length;
2472 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2473 offset += hash_length;
2474 }
2475 }
2476
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01002477 if (retval >= 0)
2478 txn->flags |= TX_CACHE_HAS_SEC_KEY;
2479
2480 return (retval < 0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002481}
2482
2483/*
2484 * Build the actual secondary key of a given request out of the prebuilt key and
2485 * the actual vary signature (extracted from the response).
2486 * Returns 0 in case of success.
2487 */
2488static int http_request_reduce_secondary_key(unsigned int vary_signature,
2489 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2490{
2491 int offset = 0;
2492 int global_offset = 0;
2493 int vary_info_count = 0;
2494 int keep = 0;
2495 unsigned int vary_idx;
2496 const struct vary_hashing_information *vary_info;
2497
2498 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2499 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2500 vary_info = &vary_information[vary_idx];
2501 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2502
2503 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2504 prebuilt_key[global_offset] &= keep;
2505 }
2506 }
2507
2508 return 0;
2509}
2510
2511
Christopher Faulet99a17a22018-12-11 09:18:27 +01002512
2513static int
2514parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2515 struct flt_conf *fconf, char **err, void *private)
2516{
2517 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002518 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002519 char *name = NULL;
2520 int pos = *cur_arg;
2521
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002522 /* Get the cache filter name. <pos> point on "cache" keyword */
2523 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002524 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002525 goto error;
2526 }
2527 name = strdup(args[pos + 1]);
2528 if (!name) {
2529 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2530 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002531 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002532 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002533
2534 /* Check if an implicit filter with the same name already exists. If so,
2535 * we remove the implicit filter to use the explicit one. */
2536 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2537 if (f->id != cache_store_flt_id)
2538 continue;
2539
2540 cconf = f->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002541 if (strcmp(name, cconf->c.name) != 0) {
Christopher Faulet99a17a22018-12-11 09:18:27 +01002542 cconf = NULL;
2543 continue;
2544 }
2545
2546 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2547 cconf = NULL;
2548 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2549 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002550 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002551 }
2552
2553 /* Remove the implicit filter. <cconf> is kept for the explicit one */
Willy Tarreau2b718102021-04-21 07:32:39 +02002554 LIST_DELETE(&f->list);
Christopher Faulet99a17a22018-12-11 09:18:27 +01002555 free(f);
2556 free(name);
2557 break;
2558 }
2559
2560 /* No implicit cache filter found, create configuration for the explicit one */
2561 if (!cconf) {
2562 cconf = calloc(1, sizeof(*cconf));
2563 if (!cconf) {
2564 memprintf(err, "%s: out of memory", args[*cur_arg]);
2565 goto error;
2566 }
2567 cconf->c.name = name;
2568 }
2569
2570 cconf->flags = 0;
2571 fconf->id = cache_store_flt_id;
2572 fconf->conf = cconf;
2573 fconf->ops = &cache_ops;
2574
2575 *cur_arg = pos;
2576 return 0;
2577
2578 error:
2579 free(name);
2580 free(cconf);
2581 return -1;
2582}
2583
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002584/* It reserves a struct show_cache_ctx for the local variables */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002585static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002586{
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002587 struct show_cache_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
2588
William Lallemand1f49a362017-11-21 20:01:26 +01002589 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2590 return 1;
2591
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002592 ctx->cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
William Lallemand1f49a362017-11-21 20:01:26 +01002593 return 0;
2594}
2595
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002596/* It uses a struct show_cache_ctx for the local variables */
William Lallemand1f49a362017-11-21 20:01:26 +01002597static int cli_io_handler_show_cache(struct appctx *appctx)
2598{
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002599 struct show_cache_ctx *ctx = appctx->svcctx;
2600 struct cache* cache = ctx->cache;
Christopher Faulet908628c2022-03-25 16:43:49 +01002601 struct conn_stream *cs = appctx->owner;
William Lallemand1f49a362017-11-21 20:01:26 +01002602
William Lallemand1f49a362017-11-21 20:01:26 +01002603 list_for_each_entry_from(cache, &caches, list) {
2604 struct eb32_node *node = NULL;
2605 unsigned int next_key;
2606 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002607 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002608
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002609 next_key = ctx->next_key;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002610 if (!next_key) {
2611 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
Christopher Faulet908628c2022-03-25 16:43:49 +01002612 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002613 cs_rx_room_blk(cs);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002614 return 0;
2615 }
2616 }
William Lallemand1f49a362017-11-21 20:01:26 +01002617
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002618 ctx->cache = cache;
William Lallemand1f49a362017-11-21 20:01:26 +01002619
2620 while (1) {
2621
2622 shctx_lock(shctx_ptr(cache));
Christopher Faulet27f88a92021-11-23 16:03:05 +01002623 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002624 if (!node) {
2625 shctx_unlock(shctx_ptr(cache));
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002626 ctx->next_key = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002627 break;
2628 }
2629
2630 entry = container_of(node, struct cache_entry, eb);
William Lallemand1f49a362017-11-21 20:01:26 +01002631 next_key = node->key + 1;
Willy Tarreauf1de1b52022-04-13 11:21:39 +02002632
2633 if (entry->expire > now.tv_sec) {
2634 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2635 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2636 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2637 chunk_appendf(&trash, " size:%u (%u blocks), refcount:%u, expire:%d\n",
2638 block_ptr(entry)->len, block_ptr(entry)->block_count,
2639 block_ptr(entry)->refcount, entry->expire - (int)now.tv_sec);
2640 } else {
2641 /* time to remove that one */
2642 delete_entry(entry);
2643 entry->eb.key = 0;
2644 }
2645
Willy Tarreauc6dfef72022-05-05 16:46:13 +02002646 ctx->next_key = next_key;
William Lallemand1f49a362017-11-21 20:01:26 +01002647
2648 shctx_unlock(shctx_ptr(cache));
2649
Christopher Faulet908628c2022-03-25 16:43:49 +01002650 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002651 cs_rx_room_blk(cs);
William Lallemand1f49a362017-11-21 20:01:26 +01002652 return 0;
2653 }
2654 }
2655
2656 }
2657
2658 return 1;
2659
2660}
2661
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002662
2663/*
2664 * boolean, returns true if response was built out of a cache entry.
2665 */
2666static int
2667smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2668 const char *kw, void *private)
2669{
2670 smp->data.type = SMP_T_BOOL;
2671 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2672
2673 return 1;
2674}
2675
2676/*
2677 * string, returns cache name (if response came from a cache).
2678 */
2679static int
2680smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2681 const char *kw, void *private)
2682{
2683 struct appctx *appctx = NULL;
2684
2685 struct cache_flt_conf *cconf = NULL;
2686 struct cache *cache = NULL;
2687
2688 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2689 return 0;
2690
Christopher Faulet908628c2022-03-25 16:43:49 +01002691 /* Get appctx from the conn-stream. */
Christopher Faulet95a61e82021-12-22 14:22:03 +01002692 appctx = cs_appctx(smp->strm->csb);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002693 if (appctx && appctx->rule) {
2694 cconf = appctx->rule->arg.act.p[0];
2695 if (cconf) {
2696 cache = cconf->c.cache;
2697
2698 smp->data.type = SMP_T_STR;
2699 smp->flags = SMP_F_CONST;
2700 smp->data.u.str.area = cache->id;
2701 smp->data.u.str.data = strlen(cache->id);
2702 return 1;
2703 }
2704 }
2705
2706 return 0;
2707}
2708
Christopher Faulet99a17a22018-12-11 09:18:27 +01002709/* Declare the filter parser for "cache" keyword */
2710static struct flt_kw_list filter_kws = { "CACHE", { }, {
2711 { "cache", parse_cache_flt, NULL },
2712 { NULL, NULL, NULL },
2713 }
2714};
2715
2716INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2717
William Lallemand1f49a362017-11-21 20:01:26 +01002718static struct cli_kw_list cli_kws = {{},{
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002719 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
William Lallemande899af82017-11-22 16:41:26 +01002720 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002721}};
2722
Willy Tarreau0108d902018-11-25 19:14:37 +01002723INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002724
William Lallemand41db4602017-10-30 11:15:51 +01002725static struct action_kw_list http_res_actions = {
2726 .kw = {
2727 { "cache-store", parse_cache_store },
2728 { NULL, NULL }
2729 }
2730};
2731
Willy Tarreau0108d902018-11-25 19:14:37 +01002732INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2733
William Lallemand41db4602017-10-30 11:15:51 +01002734static struct action_kw_list http_req_actions = {
2735 .kw = {
2736 { "cache-use", parse_cache_use },
2737 { NULL, NULL }
2738 }
2739};
2740
Willy Tarreau0108d902018-11-25 19:14:37 +01002741INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2742
Willy Tarreau2231b632019-03-29 18:26:52 +01002743struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002744 .obj_type = OBJ_TYPE_APPLET,
2745 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002746 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002747 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002748};
2749
Willy Tarreaue6552512018-11-26 11:33:13 +01002750/* config parsers for this section */
2751REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002752REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002753
2754
2755/* Note: must not be declared <const> as its list will be overwritten */
2756static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2757 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2758 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2759 { /* END */ },
2760 }
2761};
2762
2763INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);