blob: ae133249759cb7b7a0cc5f6c905a7e206d8f4d2a [file] [log] [blame]
William Lallemand41db4602017-10-30 11:15:51 +01001/*
2 * Cache management
3 *
4 * Copyright 2017 HAProxy Technologies
5 * William Lallemand <wlallemand@haproxy.com>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 */
12
Willy Tarreaub2551052020-06-09 09:07:15 +020013#include <import/eb32tree.h>
14#include <import/sha1.h>
15
Willy Tarreau122eba92020-06-04 10:15:32 +020016#include <haproxy/action-t.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020017#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020018#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020019#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020020#include <haproxy/cli.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020021#include <haproxy/errors.h>
Willy Tarreauc7babd82020-06-04 21:29:29 +020022#include <haproxy/filters.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020023#include <haproxy/hash.h>
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +020024#include <haproxy/http.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020025#include <haproxy/http_ana.h>
Willy Tarreau87735332020-06-04 09:08:41 +020026#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020027#include <haproxy/http_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/htx.h>
29#include <haproxy/net_helper.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020030#include <haproxy/proxy.h>
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +010031#include <haproxy/sample.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020032#include <haproxy/shctx.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020033#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020034#include <haproxy/stream_interface.h>
Willy Tarreauce6700a2021-05-08 13:03:55 +020035#include <haproxy/tools.h>
William Lallemand41db4602017-10-30 11:15:51 +010036
Christopher Faulet27d93c32018-12-15 22:32:02 +010037#define CACHE_FLT_F_IMPLICIT_DECL 0x00000001 /* The cache filtre was implicitly declared (ie without
Christopher Faulet99a17a22018-12-11 09:18:27 +010038 * the filter keyword) */
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +020039#define CACHE_FLT_INIT 0x00000002 /* Whether the cache name was freed. */
Christopher Fauletafd819c2018-12-11 08:57:45 +010040
Christopher Fauletf4a4ef72018-12-07 17:39:53 +010041const char *cache_store_flt_id = "cache store filter";
William Lallemand41db4602017-10-30 11:15:51 +010042
Willy Tarreau2231b632019-03-29 18:26:52 +010043extern struct applet http_cache_applet;
William Lallemand41db4602017-10-30 11:15:51 +010044
45struct flt_ops cache_ops;
46
47struct cache {
Willy Tarreaufd5efb52017-11-26 08:54:31 +010048 struct list list; /* cache linked list */
William Lallemand41db4602017-10-30 11:15:51 +010049 struct eb_root entries; /* head of cache entries based on keys */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010050 unsigned int maxage; /* max-age */
51 unsigned int maxblocks;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +020052 unsigned int maxobjsz; /* max-object-size (in bytes) */
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +010053 unsigned int max_secondary_entries; /* maximum number of secondary entries with the same primary hash */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +010054 uint8_t vary_processing_enabled; /* boolean : manage Vary header (disabled by default) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010055 char id[33]; /* cache name */
William Lallemand41db4602017-10-30 11:15:51 +010056};
57
Christopher Faulet95220e22018-12-07 17:34:39 +010058/* cache config for filters */
59struct cache_flt_conf {
60 union {
61 struct cache *cache; /* cache used by the filter */
62 char *name; /* cache name used during conf parsing */
63 } c;
64 unsigned int flags; /* CACHE_FLT_F_* */
65};
66
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010067
68/*
69 * Vary-related structures and functions
70 */
71enum vary_header_bit {
72 VARY_ACCEPT_ENCODING = (1 << 0),
73 VARY_REFERER = (1 << 1),
74 VARY_LAST /* should always be last */
75};
76
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +010077/*
78 * Encoding list extracted from
79 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml
80 * and RFC7231#5.3.4.
81 */
82enum vary_encoding {
83 VARY_ENCODING_GZIP = (1 << 0),
84 VARY_ENCODING_DEFLATE = (1 << 1),
85 VARY_ENCODING_BR = (1 << 2),
86 VARY_ENCODING_COMPRESS = (1 << 3),
87 VARY_ENCODING_AES128GCM = (1 << 4),
88 VARY_ENCODING_EXI = (1 << 5),
89 VARY_ENCODING_PACK200_GZIP = (1 << 6),
90 VARY_ENCODING_ZSTD = (1 << 7),
91 VARY_ENCODING_IDENTITY = (1 << 8),
92 VARY_ENCODING_STAR = (1 << 9),
93 VARY_ENCODING_OTHER = (1 << 10)
94};
95
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010096struct vary_hashing_information {
97 struct ist hdr_name; /* Header name */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +050098 enum vary_header_bit value; /* Bit representing the header in a vary signature */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010099 unsigned int hash_length; /* Size of the sub hash for this header's value */
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100100 int(*norm_fn)(struct htx*,struct ist hdr_name,char* buf,unsigned int* buf_len); /* Normalization function */
Tim Duesterhused84d842021-01-18 13:41:17 +0100101 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 +0100102};
103
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100104static int http_request_prebuild_full_secondary_key(struct stream *s);
105static int http_request_build_secondary_key(struct stream *s, int vary_signature);
106static int http_request_reduce_secondary_key(unsigned int vary_signature,
107 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
108
109static int parse_encoding_value(struct ist value, unsigned int *encoding_value,
110 unsigned int *has_null_weight);
111
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +0100112static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
113 char *buf, unsigned int *buf_len);
114static int default_normalizer(struct htx *htx, struct ist hdr_name,
115 char *buf, unsigned int *buf_len);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100116
Tim Duesterhused84d842021-01-18 13:41:17 +0100117static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100118
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100119/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
120 * added to this array. */
121const struct vary_hashing_information vary_information[] = {
Tim Duesterhused84d842021-01-18 13:41:17 +0100122 { 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 +0100123 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer, NULL },
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100124};
125
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100126
William Lallemand41db4602017-10-30 11:15:51 +0100127/*
128 * cache ctx for filters
129 */
130struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100131 struct shared_block *first_block;
132};
133
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100134#define DEFAULT_MAX_SECONDARY_ENTRY 10
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100135
William Lallemand41db4602017-10-30 11:15:51 +0100136struct cache_entry {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100137 unsigned int complete; /* An entry won't be valid until complete is not null. */
William Lallemand41db4602017-10-30 11:15:51 +0100138 unsigned int latest_validation; /* latest validation date */
Willy Tarreau5e842192023-02-07 15:22:41 +0100139 unsigned int expire; /* expiration date (wall clock time) */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200140 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100141
William Lallemand41db4602017-10-30 11:15:51 +0100142 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100143 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200144
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100145 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
146 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
147 * to build secondary keys for this cache entry. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100148 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 +0100149 unsigned int last_clear_ts; /* Timestamp of the last call to clear_expired_duplicates. */
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100150
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200151 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
152 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
153
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200154 time_t last_modified; /* Origin server "Last-Modified" header value converted in
155 * seconds since epoch. If no "Last-Modified"
156 * header is found, use "Date" header value,
157 * otherwise use reception time. This field will
158 * be used in case of an "If-Modified-Since"-based
159 * conditional request. */
160
William Lallemand41db4602017-10-30 11:15:51 +0100161 unsigned char data[0];
162};
163
164#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100165#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100166
167static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200168static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100169static struct cache *tmp_cache_config = NULL;
170
Willy Tarreau8ceae722018-11-26 11:58:30 +0100171DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
172
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100173static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry);
174static void delete_entry(struct cache_entry *del_entry);
175
William Lallemandf528fff2017-11-23 19:43:17 +0100176struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100177{
178 struct eb32_node *node;
179 struct cache_entry *entry;
180
Willy Tarreau8b507582020-02-25 09:35:07 +0100181 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100182 if (!node)
183 return NULL;
184
185 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100186
187 /* if that's not the right node */
188 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
189 return NULL;
190
Willy Tarreau5e842192023-02-07 15:22:41 +0100191 if (entry->expire > date.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100192 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100193 } else {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100194 delete_entry(entry);
William Lallemand08727662017-11-21 20:01:27 +0100195 entry->eb.key = 0;
196 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100197 return NULL;
198
199}
200
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100201
202/*
203 * Compare a newly built secondary key to the one found in a cache_entry.
204 * Every sub-part of the key is compared to the reference through the dedicated
205 * comparison function of the sub-part (that might do more than a simple
206 * memcmp).
207 * Returns 0 if the keys are alike.
208 */
209static int secondary_key_cmp(const char *ref_key, const char *new_key)
210{
211 int retval = 0;
Tim Duesterhus5897cfe2021-01-18 13:41:18 +0100212 size_t idx = 0;
213 unsigned int offset = 0;
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100214 const struct vary_hashing_information *info;
215
216 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
217 info = &vary_information[idx];
218
219 if (info->cmp_fn)
220 retval = info->cmp_fn(&ref_key[offset], &new_key[offset], info->hash_length);
221 else
222 retval = memcmp(&ref_key[offset], &new_key[offset], info->hash_length);
223
224 offset += info->hash_length;
225 }
226
227 return retval;
228}
229
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100230/*
231 * There can be multiple entries with the same primary key in the ebtree so in
232 * order to get the proper one out of the list, we use a secondary_key.
233 * This function simply iterates over all the entries with the same primary_key
234 * until it finds the right one.
235 * Returns the cache_entry in case of success, NULL otherwise.
236 */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100237struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100238 const char *secondary_key)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100239{
240 struct eb32_node *node = &entry->eb;
241
242 if (!entry->secondary_key_signature)
243 return NULL;
244
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100245 while (entry && secondary_key_cmp(entry->secondary_key, secondary_key) != 0) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100246 node = eb32_next_dup(node);
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100247
248 /* Make the best use of this iteration and clear expired entries
249 * when we find them. Calling delete_entry would be too costly
250 * so we simply call eb32_delete. The secondary_entry count will
251 * be updated when we try to insert a new entry to this list. */
Willy Tarreau5e842192023-02-07 15:22:41 +0100252 if (entry->expire <= date.tv_sec) {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100253 eb32_delete(&entry->eb);
254 entry->eb.key = 0;
255 }
256
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100257 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
258 }
259
260 /* Expired entry */
Willy Tarreau5e842192023-02-07 15:22:41 +0100261 if (entry && entry->expire <= date.tv_sec) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100262 eb32_delete(&entry->eb);
263 entry->eb.key = 0;
264 entry = NULL;
265 }
266
267 return entry;
268}
269
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100270
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100271/*
272 * Remove all expired entries from a list of duplicates.
273 * Return the number of alive entries in the list and sets dup_tail to the
274 * current last item of the list.
275 */
276static unsigned int clear_expired_duplicates(struct eb32_node **dup_tail)
277{
278 unsigned int entry_count = 0;
279 struct cache_entry *entry = NULL;
280 struct eb32_node *prev = *dup_tail;
281 struct eb32_node *tail = NULL;
282
283 while (prev) {
284 entry = container_of(prev, struct cache_entry, eb);
285 prev = eb32_prev_dup(prev);
Willy Tarreau5e842192023-02-07 15:22:41 +0100286 if (entry->expire <= date.tv_sec) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100287 eb32_delete(&entry->eb);
288 entry->eb.key = 0;
289 }
290 else {
291 if (!tail)
292 tail = &entry->eb;
293 ++entry_count;
294 }
295 }
296
297 *dup_tail = tail;
298
299 return entry_count;
300}
301
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100302
303/*
304 * This function inserts a cache_entry in the cache's ebtree. In case of
305 * duplicate entries (vary), it then checks that the number of entries did not
306 * reach the max number of secondary entries. If this entry should not have been
307 * created, remove it.
308 * In the regular case (unique entries), this function does not do more than a
309 * simple insert. In case of secondary entries, it will at most cost an
310 * insertion+max_sec_entries time checks and entry deletion.
311 * Returns the newly inserted node in case of success, NULL otherwise.
312 */
313static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry)
314{
315 struct eb32_node *prev = NULL;
316 struct cache_entry *entry = NULL;
317 unsigned int entry_count = 0;
Willy Tarreau5e842192023-02-07 15:22:41 +0100318 unsigned int last_clear_ts = date.tv_sec;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100319
320 struct eb32_node *node = eb32_insert(&cache->entries, &new_entry->eb);
321
322 /* We should not have multiple entries with the same primary key unless
323 * the entry has a non null vary signature. */
324 if (!new_entry->secondary_key_signature)
325 return node;
326
327 prev = eb32_prev_dup(node);
328 if (prev != NULL) {
329 /* The last entry of a duplicate list should contain the current
330 * number of entries in the list. */
331 entry = container_of(prev, struct cache_entry, eb);
332 entry_count = entry->secondary_entries_count;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100333 last_clear_ts = entry->last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100334
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100335 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100336 /* Some entries of the duplicate list might be expired so
337 * we will iterate over all the items in order to free some
338 * space. In order to avoid going over the same list too
339 * often, we first check the timestamp of the last check
340 * performed. */
Willy Tarreau5e842192023-02-07 15:22:41 +0100341 if (last_clear_ts == date.tv_sec) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100342 /* Too many entries for this primary key, clear the
343 * one that was inserted. */
344 eb32_delete(node);
345 node->key = 0;
346 return NULL;
347 }
348
349 entry_count = clear_expired_duplicates(&prev);
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100350 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100351 /* Still too many entries for this primary key, delete
352 * the newly inserted one. */
353 entry = container_of(prev, struct cache_entry, eb);
Willy Tarreau5e842192023-02-07 15:22:41 +0100354 entry->last_clear_ts = date.tv_sec;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100355 eb32_delete(node);
356 node->key = 0;
357 return NULL;
358 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100359 }
360 }
361
362 new_entry->secondary_entries_count = entry_count + 1;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100363 new_entry->last_clear_ts = last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100364
365 return node;
366}
367
368
369/*
370 * This function removes an entry from the ebtree. If the entry was a duplicate
371 * (in case of Vary), it updates the secondary entry counter in another
372 * duplicate entry (the last entry of the dup list).
373 */
374static void delete_entry(struct cache_entry *del_entry)
375{
376 struct eb32_node *prev = NULL, *next = NULL;
377 struct cache_entry *entry = NULL;
378 struct eb32_node *last = NULL;
379
380 if (del_entry->secondary_key_signature) {
381 next = &del_entry->eb;
382
383 /* Look for last entry of the duplicates list. */
384 while ((next = eb32_next_dup(next))) {
385 last = next;
386 }
387
388 if (last) {
389 entry = container_of(last, struct cache_entry, eb);
390 --entry->secondary_entries_count;
391 }
392 else {
393 /* The current entry is the last one, look for the
394 * previous one to update its counter. */
395 prev = eb32_prev_dup(&del_entry->eb);
396 if (prev) {
397 entry = container_of(prev, struct cache_entry, eb);
398 entry->secondary_entries_count = del_entry->secondary_entries_count - 1;
399 }
400 }
401 }
402 eb32_delete(&del_entry->eb);
403 del_entry->eb.key = 0;
404}
405
406
William Lallemand4da3f8a2017-10-31 14:33:34 +0100407static inline struct shared_context *shctx_ptr(struct cache *cache)
408{
409 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
410}
411
William Lallemand77c11972017-10-31 20:43:01 +0100412static inline struct shared_block *block_ptr(struct cache_entry *entry)
413{
414 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
415}
416
417
418
William Lallemand41db4602017-10-30 11:15:51 +0100419static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100420cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100421{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100422 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100423 return 0;
424}
425
Christopher Faulet95220e22018-12-07 17:34:39 +0100426static void
427cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
428{
429 struct cache_flt_conf *cconf = fconf->conf;
430
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200431 if (!(cconf->flags & CACHE_FLT_INIT))
432 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100433 free(cconf);
434}
435
William Lallemand4da3f8a2017-10-31 14:33:34 +0100436static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100437cache_store_check(struct proxy *px, struct flt_conf *fconf)
438{
439 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100440 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100441 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100442 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100443
William Lallemandd1d1e222019-08-28 15:22:49 +0200444 /* Find the cache corresponding to the name in the filter config. The
445 * cache will not be referenced now in the filter config because it is
446 * not fully allocated. This step will be performed during the cache
447 * post_check.
448 */
449 list_for_each_entry(cache, &caches_config, list) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +0100450 if (strcmp(cache->id, cconf->c.name) == 0)
Christopher Faulet95220e22018-12-07 17:34:39 +0100451 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100452 }
453
454 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
455 proxy_type_str(px), px->id, (char *)cconf->c.name);
456 return 1;
457
458 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100459 /* Here <cache> points on the cache the filter must use and <cconf>
460 * points on the cache filter configuration. */
461
462 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100463 * enabled and if it is after the cache. When the compression is before
464 * the cache, an error is returned. Also check if the cache filter must
465 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100466 list_for_each_entry(f, &px->filter_configs, list) {
467 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100468 /* The compression filter must be evaluated after the cache. */
469 if (comp) {
470 ha_alert("config: %s '%s': unable to enable the compression filter before "
471 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
472 return 1;
473 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100474 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200475 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100476 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200477 else if (f->id == fcgi_flt_id)
478 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100479 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
480 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200481 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100482 * declaration is required. */
483 ha_alert("config: %s '%s': require an explicit filter declaration "
484 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
485 return 1;
486 }
487
Christopher Fauletafd819c2018-12-11 08:57:45 +0100488 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100489 return 0;
490}
491
492static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100493cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100494{
Christopher Faulet65554e12020-03-06 14:52:06 +0100495 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100496
Willy Tarreauacc5b012021-03-22 15:00:49 +0100497 st = pool_alloc(pool_head_cache_st);
Christopher Faulet65554e12020-03-06 14:52:06 +0100498 if (st == NULL)
499 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100500
Christopher Faulet65554e12020-03-06 14:52:06 +0100501 st->first_block = NULL;
502 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100503
Christopher Faulet65554e12020-03-06 14:52:06 +0100504 /* Register post-analyzer on AN_RES_WAIT_HTTP */
505 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100506 return 1;
507}
508
Christopher Faulet65554e12020-03-06 14:52:06 +0100509static void
510cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100511{
512 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100513 struct cache_flt_conf *cconf = FLT_CONF(filter);
514 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100515 struct shared_context *shctx = shctx_ptr(cache);
516
William Lallemand49dc0482017-11-24 14:33:54 +0100517 /* Everything should be released in the http_end filter, but we need to do it
518 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100519 if (st && st->first_block) {
Remi Tricot-Le Breton5c595362023-11-28 17:08:56 +0100520 struct cache_entry *object = (struct cache_entry *)st->first_block->data;
521
William Lallemand49dc0482017-11-24 14:33:54 +0100522 shctx_lock(shctx);
Remi Tricot-Le Breton5c595362023-11-28 17:08:56 +0100523 if (!object->complete) {
524 /* The stream was closed but the 'complete' flag was not
525 * set which means that cache_store_http_end was not
526 * called. The stream must have been closed before we
527 * could store the full answer in the cache.
528 */
529 delete_entry(object);
530 }
William Lallemand49dc0482017-11-24 14:33:54 +0100531 shctx_row_dec_hot(shctx, st->first_block);
532 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100533 }
534 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100535 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100536 filter->ctx = NULL;
537 }
William Lallemand49dc0482017-11-24 14:33:54 +0100538}
539
Christopher Faulet839791a2019-01-07 16:12:07 +0100540static int
541cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
542 unsigned an_bit)
543{
544 struct http_txn *txn = s->txn;
545 struct http_msg *msg = &txn->rsp;
546 struct cache_st *st = filter->ctx;
547
548 if (an_bit != AN_RES_WAIT_HTTP)
549 goto end;
550
551 /* Here we need to check if any compression filter precedes the cache
552 * filter. This is only possible when the compression is configured in
553 * the frontend while the cache filter is configured on the
554 * backend. This case cannot be detected during HAProxy startup. So in
555 * such cases, the cache is disabled.
556 */
557 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
558 pool_free(pool_head_cache_st, st);
559 filter->ctx = NULL;
560 }
561
562 end:
563 return 1;
564}
William Lallemand49dc0482017-11-24 14:33:54 +0100565
566static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100567cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
568{
569 struct cache_st *st = filter->ctx;
570
William Lallemand4da3f8a2017-10-31 14:33:34 +0100571 if (!(msg->chn->flags & CF_ISRESP) || !st)
572 return 1;
573
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200574 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100575 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100576 return 1;
577}
578
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200579static inline void disable_cache_entry(struct cache_st *st,
580 struct filter *filter, struct shared_context *shctx)
581{
582 struct cache_entry *object;
583
584 object = (struct cache_entry *)st->first_block->data;
585 filter->ctx = NULL; /* disable cache */
586 shctx_lock(shctx);
587 shctx_row_dec_hot(shctx, st->first_block);
Remi Tricot-Le Breton964caaf2020-12-15 14:30:12 +0100588 eb32_delete(&object->eb);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200589 object->eb.key = 0;
590 shctx_unlock(shctx);
591 pool_free(pool_head_cache_st, st);
592}
593
William Lallemand4da3f8a2017-10-31 14:33:34 +0100594static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100595cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
596 unsigned int offset, unsigned int len)
597{
Christopher Faulet95220e22018-12-07 17:34:39 +0100598 struct cache_flt_conf *cconf = FLT_CONF(filter);
599 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100600 struct cache_st *st = filter->ctx;
601 struct htx *htx = htxbuf(&msg->chn->buf);
602 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200603 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100604 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200605 unsigned int orig_len, to_forward;
606 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100607
608 if (!len)
609 return len;
610
611 if (!st->first_block) {
612 unregister_data_filter(s, msg->chn, filter);
613 return len;
614 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100615
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200616 chunk_reset(&trash);
617 orig_len = len;
618 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100619
620 htxret = htx_find_offset(htx, offset);
621 blk = htxret.blk;
622 offset = htxret.ret;
623 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100624 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200625 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100626 struct ist v;
627
628 switch (type) {
629 case HTX_BLK_UNUSED:
630 break;
631
632 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100633 v = htx_get_blk_value(htx, blk);
Tim Duesterhus154374c2021-03-02 18:57:27 +0100634 v = istadv(v, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100635 if (v.len > len)
636 v.len = len;
637
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200638 info = (type << 28) + v.len;
639 chunk_memcat(&trash, (char *)&info, sizeof(info));
640 chunk_memcat(&trash, v.ptr, v.len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100641 to_forward += v.len;
642 len -= v.len;
643 break;
644
645 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200646 /* Here offset must always be 0 because only
647 * DATA blocks can be partially transferred. */
648 if (offset)
649 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100650 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200651 goto end;
652
653 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
654 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100655 to_forward += sz;
656 len -= sz;
657 break;
658 }
659
660 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100661 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200662
663 end:
664 shctx_lock(shctx);
665 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
666 if (!fb) {
667 shctx_unlock(shctx);
668 goto no_cache;
669 }
670 shctx_unlock(shctx);
671
672 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
673 (unsigned char *)b_head(&trash), b_data(&trash));
674 if (ret < 0)
675 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100676
677 return to_forward;
678
679 no_cache:
680 disable_cache_entry(st, filter, shctx);
681 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200682 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100683}
684
685static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100686cache_store_http_end(struct stream *s, struct filter *filter,
687 struct http_msg *msg)
688{
689 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100690 struct cache_flt_conf *cconf = FLT_CONF(filter);
691 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100692 struct shared_context *shctx = shctx_ptr(cache);
693 struct cache_entry *object;
694
695 if (!(msg->chn->flags & CF_ISRESP))
696 return 1;
697
698 if (st && st->first_block) {
699
700 object = (struct cache_entry *)st->first_block->data;
701
William Lallemand4da3f8a2017-10-31 14:33:34 +0100702 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100703 /* The whole payload was cached, the entry can now be used. */
704 object->complete = 1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100705 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100706 shctx_row_dec_hot(shctx, st->first_block);
707 shctx_unlock(shctx);
708
709 }
710 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100711 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100712 filter->ctx = NULL;
713 }
714
715 return 1;
716}
717
718 /*
719 * This intends to be used when checking HTTP headers for some
720 * word=value directive. Return a pointer to the first character of value, if
Willy Tarreau94a01e12021-01-06 17:35:12 +0100721 * the word was not found or if there wasn't any value assigned to it return NULL
William Lallemand4da3f8a2017-10-31 14:33:34 +0100722 */
723char *directive_value(const char *sample, int slen, const char *word, int wlen)
724{
725 int st = 0;
726
727 if (slen < wlen)
728 return 0;
729
730 while (wlen) {
731 char c = *sample ^ *word;
732 if (c && c != ('A' ^ 'a'))
733 return NULL;
734 sample++;
735 word++;
736 slen--;
737 wlen--;
738 }
739
740 while (slen) {
741 if (st == 0) {
742 if (*sample != '=')
743 return NULL;
744 sample++;
745 slen--;
746 st = 1;
747 continue;
748 } else {
749 return (char *)sample;
750 }
751 }
752
753 return NULL;
754}
755
756/*
757 * Return the maxage in seconds of an HTTP response.
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100758 * The returned value will always take the cache's configuration into account
759 * (cache->maxage) but the actual max age of the response will be set in the
760 * true_maxage parameter. It will be used to determine if a response is already
761 * stale or not.
William Lallemand4da3f8a2017-10-31 14:33:34 +0100762 * Compute the maxage using either:
763 * - the assigned max-age of the cache
764 * - the s-maxage directive
765 * - the max-age directive
766 * - (Expires - Data) headers
767 * - the default-max-age of the cache
768 *
769 */
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100770int http_calc_maxage(struct stream *s, struct cache *cache, int *true_maxage)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100771{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200772 struct htx *htx = htxbuf(&s->res.buf);
773 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100774 long smaxage = -1;
775 long maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100776 int expires = -1;
777 struct tm tm = {};
778 time_t expires_val = 0;
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100779 char *endptr = NULL;
780 int offset = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100781
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100782 /* The Cache-Control max-age and s-maxage directives should be followed by
783 * a positive numerical value (see RFC 7234#5.2.1.1). According to the
784 * specs, a sender "should not" generate a quoted-string value but we will
785 * still accept this format since it isn't strictly forbidden. */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200786 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
787 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100788
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200789 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
790 if (value) {
791 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100792
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200793 chunk_strncat(chk, value, ctx.value.len - 8 + 1);
794 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100795 offset = (*chk->area == '"') ? 1 : 0;
796 smaxage = strtol(chk->area + offset, &endptr, 10);
Willy Tarreau79a63b12021-11-08 12:09:27 +0100797 if (unlikely(smaxage < 0 || endptr == chk->area + offset))
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100798 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100799 }
800
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200801 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
802 if (value) {
803 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200804
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200805 chunk_strncat(chk, value, ctx.value.len - 7 + 1);
806 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100807 offset = (*chk->area == '"') ? 1 : 0;
808 maxage = strtol(chk->area + offset, &endptr, 10);
Willy Tarreau79a63b12021-11-08 12:09:27 +0100809 if (unlikely(maxage < 0 || endptr == chk->area + offset))
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100810 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100811 }
812 }
813
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100814 /* Look for Expires header if no s-maxage or max-age Cache-Control data
815 * was found. */
816 if (maxage == -1 && smaxage == -1) {
817 ctx.blk = NULL;
818 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
819 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
820 expires_val = my_timegm(&tm);
821 /* A request having an expiring date earlier
822 * than the current date should be considered as
823 * stale. */
Willy Tarreau5e842192023-02-07 15:22:41 +0100824 expires = (expires_val >= date.tv_sec) ?
825 (expires_val - date.tv_sec) : 0;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100826 }
827 else {
828 /* Following RFC 7234#5.3, an invalid date
829 * format must be treated as a date in the past
830 * so the cache entry must be seen as already
831 * expired. */
832 expires = 0;
833 }
834 }
835 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100836
837
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100838 if (smaxage > 0) {
839 if (true_maxage)
840 *true_maxage = smaxage;
William Lallemand49b44532017-11-24 18:53:43 +0100841 return MIN(smaxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100842 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100843
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100844 if (maxage > 0) {
845 if (true_maxage)
846 *true_maxage = maxage;
William Lallemand49b44532017-11-24 18:53:43 +0100847 return MIN(maxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100848 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100849
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100850 if (expires >= 0) {
851 if (true_maxage)
852 *true_maxage = expires;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100853 return MIN(expires, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100854 }
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100855
William Lallemand49b44532017-11-24 18:53:43 +0100856 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100857
858}
859
860
William Lallemanda400a3a2017-11-20 19:13:12 +0100861static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
862{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200863 struct cache_entry *object = (struct cache_entry *)block->data;
864
865 if (first == block && object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100866 delete_entry(object);
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200867 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100868}
869
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200870
871/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
872 * date value should be compared to a date determined by in a previous response (for
873 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
874 * value of the response's reception time (by decreasing order of priority). */
875static time_t get_last_modified_time(struct htx *htx)
876{
877 time_t last_modified = 0;
878 struct http_hdr_ctx ctx = { .blk = NULL };
879 struct tm tm = {};
880
881 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
882 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
883 last_modified = my_timegm(&tm);
884 }
885 }
886
887 if (!last_modified) {
888 ctx.blk = NULL;
889 if (http_find_header(htx, ist("date"), &ctx, 1)) {
890 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
891 last_modified = my_timegm(&tm);
892 }
893 }
894 }
895
896 /* Fallback on the current time if no "Last-Modified" or "Date" header
897 * was found. */
898 if (!last_modified)
Willy Tarreau5e842192023-02-07 15:22:41 +0100899 last_modified = date.tv_sec;
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200900
901 return last_modified;
902}
903
William Lallemand41db4602017-10-30 11:15:51 +0100904/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100905 * Checks the vary header's value. The headers on which vary should be applied
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500906 * must be explicitly supported in the vary_information array (see cache.c). If
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100907 * any other header is mentioned, we won't store the response.
908 * Returns 1 if Vary-based storage can work, 0 otherwise.
909 */
910static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
911{
912 unsigned int vary_idx;
913 unsigned int vary_info_count;
914 const struct vary_hashing_information *vary_info;
915 struct http_hdr_ctx ctx = { .blk = NULL };
916
917 int retval = 1;
918
919 *vary_signature = 0;
920
921 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
922 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
923 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
924 vary_info = &vary_information[vary_idx];
925 if (isteqi(ctx.value, vary_info->hdr_name)) {
926 *vary_signature |= vary_info->value;
927 break;
928 }
929 }
930 retval = (vary_idx < vary_info_count);
931 }
932
933 return retval;
934}
935
936
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100937/*
938 * Look for the accept-encoding part of the secondary_key and replace the
939 * encoding bitmap part of the hash with the actual encoding of the response,
940 * extracted from the content-encoding header value.
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100941 * Responses that have an unknown encoding will not be cached if they also
942 * "vary" on the accept-encoding value.
943 * Returns 0 if we found a known encoding in the response, -1 otherwise.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100944 */
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100945static int set_secondary_key_encoding(struct htx *htx, char *secondary_key)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100946{
947 unsigned int resp_encoding_bitmap = 0;
948 const struct vary_hashing_information *info = vary_information;
949 unsigned int offset = 0;
950 unsigned int count = 0;
951 unsigned int hash_info_count = sizeof(vary_information)/sizeof(*vary_information);
952 unsigned int encoding_value;
953 struct http_hdr_ctx ctx = { .blk = NULL };
954
955 /* Look for the accept-encoding part of the secondary_key. */
956 while (count < hash_info_count && info->value != VARY_ACCEPT_ENCODING) {
957 offset += info->hash_length;
958 ++info;
959 ++count;
960 }
961
962 if (count == hash_info_count)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100963 return -1;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100964
965 while (http_find_header(htx, ist("content-encoding"), &ctx, 0)) {
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100966 if (parse_encoding_value(ctx.value, &encoding_value, NULL))
967 return -1; /* Do not store responses with an unknown encoding */
968 resp_encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100969 }
970
971 if (!resp_encoding_bitmap)
972 resp_encoding_bitmap |= VARY_ENCODING_IDENTITY;
973
974 /* Rewrite the bitmap part of the hash with the new bitmap that only
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +0500975 * corresponds the the response's encoding. */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100976 write_u32(secondary_key + offset, resp_encoding_bitmap);
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100977
978 return 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100979}
980
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100981
982/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500983 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100984 * register a filter to store the data
985 */
986enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200987 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100988{
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100989 int effective_maxage = 0;
990 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100991 struct http_txn *txn = s->txn;
992 struct http_msg *msg = &txn->rsp;
993 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100994 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100995 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100996 struct cache *cache = cconf->c.cache;
997 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100998 struct cache_st *cache_ctx = NULL;
999 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +01001000 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001001 struct htx *htx;
1002 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +02001003 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001004 int32_t pos;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001005 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001006
William Lallemand4da3f8a2017-10-31 14:33:34 +01001007 /* Don't cache if the response came from a cache */
1008 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
1009 s->target == &http_cache_applet.obj_type) {
1010 goto out;
1011 }
1012
1013 /* cache only HTTP/1.1 */
1014 if (!(txn->req.flags & HTTP_MSGF_VER_11))
1015 goto out;
1016
Willy Tarreau6905d182019-10-01 17:59:17 +02001017 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001018 if (txn->meth != HTTP_METH_GET) {
1019 /* In case of successful unsafe method on a stored resource, the
1020 * cached entry must be invalidated (see RFC7234#4.4).
1021 * A "non-error response" is one with a 2xx (Successful) or 3xx
1022 * (Redirection) status code. */
1023 if (txn->status >= 200 && txn->status < 400) {
1024 switch (txn->meth) {
1025 case HTTP_METH_OPTIONS:
1026 case HTTP_METH_GET:
1027 case HTTP_METH_HEAD:
1028 case HTTP_METH_TRACE:
1029 break;
1030
1031 default: /* Any unsafe method */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001032 /* Discard any corresponding entry in case of successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001033 * unsafe request (such as PUT, POST or DELETE). */
1034 shctx_lock(shctx);
1035
1036 old = entry_exist(cconf->c.cache, txn->cache_hash);
1037 if (old) {
1038 eb32_delete(&old->eb);
1039 old->eb.key = 0;
1040 }
1041 shctx_unlock(shctx);
1042 }
1043 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001044 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001045 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001046
Willy Tarreauc9036c02019-01-11 19:38:25 +01001047 /* cache key was not computed */
1048 if (!key)
1049 goto out;
1050
William Lallemand4da3f8a2017-10-31 14:33:34 +01001051 /* cache only 200 status code */
1052 if (txn->status != 200)
1053 goto out;
1054
Christopher Faulet839791a2019-01-07 16:12:07 +01001055 /* Find the corresponding filter instance for the current stream */
1056 list_for_each_entry(filter, &s->strm_flt.filters, list) {
1057 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
1058 /* No filter ctx, don't cache anything */
1059 if (!filter->ctx)
1060 goto out;
1061 cache_ctx = filter->ctx;
1062 break;
1063 }
1064 }
1065
1066 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001067 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001068
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001069 /* Do not cache too big objects. */
1070 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
1071 htx->data + htx->extra > shctx->max_obj_size)
1072 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001073
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001074 /* Only a subset of headers are supported in our Vary implementation. If
1075 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001076 * able to use the cache. Likewise, if Vary header support is disabled,
1077 * avoid caching responses that contain such a header. */
1078 ctx.blk = NULL;
1079 if (cache->vary_processing_enabled) {
1080 if (!http_check_vary_header(htx, &vary_signature))
1081 goto out;
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001082 if (vary_signature) {
1083 /* If something went wrong during the secondary key
1084 * building, do not store the response. */
1085 if (!(txn->flags & TX_CACHE_HAS_SEC_KEY))
1086 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001087 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001088 }
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001089 }
1090 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001091 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001092 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001093
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001094 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001095
Remi Tricot-Le Bretona59ce4f2023-02-21 11:47:17 +01001096 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK))
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001097 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001098
1099 shctx_lock(shctx);
1100 old = entry_exist(cache, txn->cache_hash);
1101 if (old) {
1102 if (vary_signature)
1103 old = secondary_entry_exist(cconf->c.cache, old,
1104 txn->cache_secondary_hash);
1105 if (old) {
1106 if (!old->complete) {
1107 /* An entry with the same primary key is already being
1108 * created, we should not try to store the current
1109 * response because it will waste space in the cache. */
1110 shctx_unlock(shctx);
1111 goto out;
1112 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001113 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001114 old->eb.key = 0;
1115 }
1116 }
1117 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1118 if (!first) {
1119 shctx_unlock(shctx);
1120 goto out;
1121 }
1122 /* the received memory is not initialized, we need at least to mark
1123 * the object as not indexed yet.
1124 */
1125 object = (struct cache_entry *)first->data;
1126 memset(object, 0, sizeof(*object));
1127 object->eb.key = key;
1128 object->secondary_key_signature = vary_signature;
1129 /* We need to temporarily set a valid expiring time until the actual one
1130 * is set by the end of this function (in case of concurrent accesses to
1131 * the same resource). This way the second access will find an existing
1132 * but not yet usable entry in the tree and will avoid storing its data. */
Willy Tarreau5e842192023-02-07 15:22:41 +01001133 object->expire = date.tv_sec + 2;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001134
1135 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1136 if (vary_signature)
1137 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1138
1139 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001140 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001141 object->eb.key = 0;
1142 shctx_unlock(shctx);
1143 goto out;
1144 }
1145 shctx_unlock(shctx);
1146
1147 /* reserve space for the cache_entry structure */
1148 first->len = sizeof(struct cache_entry);
1149 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001150
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001151 /* Determine the entry's maximum age (taking into account the cache's
1152 * configuration) as well as the response's explicit max age (extracted
1153 * from cache-control directives or the expires header). */
1154 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1155
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001156 ctx.blk = NULL;
1157 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
Tim Duesterhusc2942842021-01-02 22:47:17 +01001158 long long hdr_age;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001159 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1160 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1161 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001162 /* A response with an Age value greater than its
1163 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001164 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001165 if (unlikely(object->age > true_maxage))
1166 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001167 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001168 else
1169 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001170 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001171 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001172
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001173 /* Build a last-modified time that will be stored in the cache_entry and
1174 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001175 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001176
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001177 chunk_reset(&trash);
1178 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1179 struct htx_blk *blk = htx_get_blk(htx, pos);
1180 enum htx_blk_type type = htx_get_blk_type(blk);
1181 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001182
Christopher Fauletb0667472019-09-03 22:22:12 +02001183 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001184 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1185 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001186
1187 /* Look for optional ETag header.
1188 * We need to store the offset of the ETag value in order for
1189 * future conditional requests to be able to perform ETag
1190 * comparisons. */
1191 if (type == HTX_BLK_HDR) {
Tim Duesterhuse2fff102021-01-02 22:47:16 +01001192 struct ist header_name = htx_get_blk_name(htx, blk);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001193 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001194 object->etag_length = sz - istlen(header_name);
1195 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001196 }
1197 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001198 if (type == HTX_BLK_EOH)
1199 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001200 }
1201
Christopher Fauletb0667472019-09-03 22:22:12 +02001202 /* Do not cache objects if the headers are too big. */
1203 if (hdrs_len > htx->size - global.tune.maxrewrite)
1204 goto out;
1205
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001206 /* If the response has a secondary_key, fill its key part related to
1207 * encodings with the actual encoding of the response. This way any
1208 * subsequent request having the same primary key will have its accepted
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001209 * encodings tested upon the cached response's one.
1210 * We will not cache a response that has an unknown encoding (not
Ilya Shipitsin7704b0e2021-01-23 02:11:59 +05001211 * explicitly supported in parse_encoding_value function). */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001212 if (cache->vary_processing_enabled && vary_signature)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001213 if (set_secondary_key_encoding(htx, object->secondary_key))
1214 goto out;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001215
William Lallemand4da3f8a2017-10-31 14:33:34 +01001216 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001217 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001218 shctx_unlock(shctx);
1219 goto out;
1220 }
1221 shctx_unlock(shctx);
1222
William Lallemand4da3f8a2017-10-31 14:33:34 +01001223 /* cache the headers in a http action because it allows to chose what
1224 * to cache, for example you might want to cache a response before
1225 * modifying some HTTP headers, or on the contrary after modifying
1226 * those headers.
1227 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001228 /* does not need to be locked because it's in the "hot" list,
1229 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001230 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1231 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001232
1233 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001234 if (cache_ctx) {
1235 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001236 /* store latest value and expiration time */
Willy Tarreau5e842192023-02-07 15:22:41 +01001237 object->latest_validation = date.tv_sec;
1238 object->expire = date.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001239 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001240 }
1241
1242out:
1243 /* if does not cache */
1244 if (first) {
1245 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001246 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001247 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001248 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001249 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001250 shctx_row_dec_hot(shctx, first);
1251 shctx_unlock(shctx);
1252 }
1253
William Lallemand41db4602017-10-30 11:15:51 +01001254 return ACT_RET_CONT;
1255}
1256
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001257#define HTX_CACHE_INIT 0 /* Initial state. */
1258#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1259#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001260#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1261#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001262
William Lallemandecb73b12017-11-24 14:33:55 +01001263static void http_cache_applet_release(struct appctx *appctx)
1264{
Christopher Faulet95220e22018-12-07 17:34:39 +01001265 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +01001266 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001267 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001268 struct shared_block *first = block_ptr(cache_ptr);
1269
1270 shctx_lock(shctx_ptr(cache));
1271 shctx_row_dec_hot(shctx_ptr(cache), first);
1272 shctx_unlock(shctx_ptr(cache));
1273}
1274
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001275
1276static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1277 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001278{
Christopher Faulet95220e22018-12-07 17:34:39 +01001279 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1280 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001281 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001282 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001283 unsigned int max, total;
1284 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001285
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001286 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1287 if (!max)
1288 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001289 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001290 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1291 : info & 0xfffffff);
1292 if (blksz > max)
1293 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001294
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001295 blk = htx_add_blk(htx, type, blksz);
1296 if (!blk)
1297 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001298
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001299 blk->info = info;
1300 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001301 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001302 while (blksz) {
1303 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001304 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001305 offset += max;
1306 blksz -= max;
1307 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001308 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001309 if (blksz || offset == shctx->block_size) {
1310 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1311 offset = 0;
1312 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001313 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001314 appctx->ctx.cache.offset = offset;
1315 appctx->ctx.cache.next = shblk;
1316 appctx->ctx.cache.sent += total;
1317 return total;
1318}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001319
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001320static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1321 uint32_t info, struct shared_block *shblk, unsigned int offset)
1322{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001323
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001324 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1325 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1326 unsigned int max, total, rem_data;
1327 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001328
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001329 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1330 if (!max)
1331 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001332
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001333 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001334 if (appctx->ctx.cache.rem_data) {
1335 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001336 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001337 }
1338 else {
1339 blksz = (info & 0xfffffff);
1340 total = 4;
1341 }
1342 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001343 rem_data = blksz - max;
1344 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001345 }
1346
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001347 while (blksz) {
1348 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001349
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001350 max = MIN(blksz, shctx->block_size - offset);
1351 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1352 offset += sz;
1353 blksz -= sz;
1354 total += sz;
1355 if (sz < max)
1356 break;
1357 if (blksz || offset == shctx->block_size) {
1358 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1359 offset = 0;
1360 }
1361 }
1362
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001363 appctx->ctx.cache.offset = offset;
1364 appctx->ctx.cache.next = shblk;
1365 appctx->ctx.cache.sent += total;
1366 appctx->ctx.cache.rem_data = rem_data + blksz;
1367 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001368}
1369
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001370static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1371 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001372{
Christopher Faulet95220e22018-12-07 17:34:39 +01001373 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1374 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001375 struct shared_block *shblk;
1376 unsigned int offset, sz;
1377 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001378
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001379 while (len) {
1380 enum htx_blk_type type;
1381 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001382
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001383 shblk = appctx->ctx.cache.next;
1384 offset = appctx->ctx.cache.offset;
1385 if (appctx->ctx.cache.rem_data) {
1386 type = HTX_BLK_DATA;
1387 info = 0;
1388 goto add_data_blk;
1389 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001390
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001391 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001392 sz = MIN(4, shctx->block_size - offset);
1393 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1394 offset += sz;
1395 if (sz < 4) {
1396 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1397 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1398 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001399 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001400
1401 /* Get payload of the next HTX block and insert it. */
1402 type = (info >> 28);
1403 if (type != HTX_BLK_DATA)
1404 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1405 else {
1406 add_data_blk:
1407 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001408 }
1409
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001410 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001411 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001412 total += ret;
1413 len -= ret;
1414
1415 if (appctx->ctx.cache.rem_data || type == mark)
1416 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001417 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001418
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001419 return total;
1420}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001421
1422static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1423{
1424 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1425 unsigned int age;
1426 char *end;
1427
1428 chunk_reset(&trash);
Willy Tarreau5e842192023-02-07 15:22:41 +01001429 age = MAX(0, (int)(date.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001430 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1431 age = CACHE_ENTRY_MAX_AGE;
1432 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1433 b_set_data(&trash, end - b_head(&trash));
1434 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1435 return 0;
1436 return 1;
1437}
1438
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001439static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001440{
1441 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1442 struct shared_block *first = block_ptr(cache_ptr);
1443 struct stream_interface *si = appctx->owner;
1444 struct channel *req = si_oc(si);
1445 struct channel *res = si_ic(si);
1446 struct htx *req_htx, *res_htx;
1447 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001448 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001449 size_t ret, total = 0;
1450
Christopher Fauleta9169322022-03-07 16:44:30 +01001451 res_htx = htx_from_buf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001452 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001453
1454 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1455 goto out;
1456
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001457 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001458 if (!b_size(&res->buf)) {
1459 si_rx_room_blk(si);
1460 goto out;
1461 }
1462
Willy Tarreauefef3232018-12-16 00:37:45 +01001463 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001464 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001465
1466 if (appctx->st0 == HTX_CACHE_INIT) {
1467 appctx->ctx.cache.next = block_ptr(cache_ptr);
1468 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1469 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001470 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001471 appctx->st0 = HTX_CACHE_HEADER;
1472 }
1473
1474 if (appctx->st0 == HTX_CACHE_HEADER) {
1475 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001476 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1477 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1478 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1479 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001480 goto error;
1481
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001482 /* In case of a conditional request, we might want to send a
1483 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001484 if (appctx->ctx.cache.send_notmodified) {
1485 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1486 /* If replacing the status code fails we need to send the full response. */
1487 appctx->ctx.cache.send_notmodified = 0;
1488 }
1489 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001490
1491 /* Skip response body for HEAD requests or in case of "304 Not
1492 * Modified" response. */
1493 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001494 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001495 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001496 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001497 }
1498
1499 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001500 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1501 if (len) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001502 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_UNUSED);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001503 if (ret < len) {
1504 si_rx_room_blk(si);
1505 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001506 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001507 }
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001508 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001509 }
1510
1511 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001512 /* no more data are expected. */
1513 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletba476122022-03-07 15:53:57 +01001514 res->flags |= CF_EOI;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001515 appctx->st0 = HTX_CACHE_END;
1516 }
1517
1518 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001519 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001520 res->flags |= CF_READ_NULL;
1521 si_shutr(si);
1522 }
1523
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001524 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001525 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001526 if (total)
1527 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001528 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001529
1530 /* eat the whole request */
1531 if (co_data(req)) {
1532 req_htx = htx_from_buf(&req->buf);
1533 co_htx_skip(req, req_htx, co_data(req));
1534 htx_to_buf(req_htx, &req->buf);
1535 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001536 return;
1537
1538 error:
1539 /* Sent and HTTP error 500 */
1540 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001541 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001542 res->buf.data = b_data(errmsg);
1543 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1544 res_htx = htx_from_buf(&res->buf);
1545
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001546 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001547 appctx->st0 = HTX_CACHE_END;
1548 goto end;
1549}
1550
1551
Christopher Faulet95220e22018-12-07 17:34:39 +01001552static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001553{
1554 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001555 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001556
Christopher Faulet95220e22018-12-07 17:34:39 +01001557 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001558 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001559 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001560 }
1561
1562 /* check if a cache filter was already registered with this cache
1563 * name, if that's the case, must use it. */
1564 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001565 if (fconf->id == cache_store_flt_id) {
1566 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001567 if (cconf && strcmp((char *)cconf->c.name, name) == 0) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001568 rule->arg.act.p[0] = cconf;
1569 return 1;
1570 }
William Lallemand41db4602017-10-30 11:15:51 +01001571 }
1572 }
1573
Christopher Faulet95220e22018-12-07 17:34:39 +01001574 /* Create the filter cache config */
1575 cconf = calloc(1, sizeof(*cconf));
1576 if (!cconf) {
1577 memprintf(err, "out of memory\n");
1578 goto err;
1579 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001580 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001581 cconf->c.name = strdup(name);
1582 if (!cconf->c.name) {
1583 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001584 goto err;
1585 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001586
William Lallemand41db4602017-10-30 11:15:51 +01001587 /* register a filter to fill the cache buffer */
1588 fconf = calloc(1, sizeof(*fconf));
1589 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001590 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001591 goto err;
1592 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001593 fconf->id = cache_store_flt_id;
1594 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001595 fconf->ops = &cache_ops;
Willy Tarreau2b718102021-04-21 07:32:39 +02001596 LIST_APPEND(&proxy->filter_configs, &fconf->list);
William Lallemand41db4602017-10-30 11:15:51 +01001597
Christopher Faulet95220e22018-12-07 17:34:39 +01001598 rule->arg.act.p[0] = cconf;
1599 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001600
Christopher Faulet95220e22018-12-07 17:34:39 +01001601 err:
1602 free(cconf);
1603 return 0;
1604}
1605
1606enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1607 struct act_rule *rule, char **err)
1608{
1609 rule->action = ACT_CUSTOM;
1610 rule->action_ptr = http_action_store_cache;
1611
1612 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1613 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001614
Christopher Faulet95220e22018-12-07 17:34:39 +01001615 (*orig_arg)++;
1616 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001617}
1618
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001619/* This produces a sha1 hash of the concatenation of the HTTP method,
1620 * the first occurrence of the Host header followed by the path component
1621 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001622int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001623{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001624 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001625 struct htx *htx = htxbuf(&s->req.buf);
1626 struct htx_sl *sl;
1627 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001628 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001629 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001630 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001631
William Lallemandf528fff2017-11-23 19:43:17 +01001632 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001633 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001634
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001635 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001636 uri = htx_sl_req_uri(sl); // whole uri
1637 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001638 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001639
1640 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1641 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1642 * URIs are almost always sent in absolute form with their scheme. In
1643 * this case, the scheme is almost always "https". In order to support
1644 * sharing of cache objects between H1 and H2, we'll hash the absolute
1645 * URI whenever known, or prepend "https://" + the Host header for
1646 * relative URIs. The difference will only appear on absolute HTTP/1
1647 * requests sent to an origin server, which practically is never met in
1648 * the real world so we don't care about the ability to share the same
1649 * key here.URIs are normalized from the absolute URI to an origin form as
1650 * well.
1651 */
1652 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001653 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001654 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1655 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001656 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001657 }
1658
1659 chunk_memcat(trash, uri.ptr, uri.len);
William Lallemandf528fff2017-11-23 19:43:17 +01001660
1661 /* hash everything */
1662 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001663 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001664 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1665
1666 return 1;
1667}
1668
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001669/* Looks for "If-None-Match" headers in the request and compares their value
1670 * with the one that might have been stored in the cache_entry. If any of them
1671 * matches, a "304 Not Modified" response should be sent instead of the cached
1672 * data.
1673 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001674 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1675 *
1676 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1677 * header and compare its value (date) to the one stored in the cache_entry.
1678 * If the request's date is later than the cached one, we also send a
1679 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1680 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001681 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1682 */
1683static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1684 struct cache_entry *entry)
1685{
1686 int retval = 0;
1687
1688 struct http_hdr_ctx ctx = { .blk = NULL };
1689 struct ist cache_entry_etag = IST_NULL;
1690 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001691 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001692
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001693 struct tm tm = {};
1694 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001695
1696 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001697 * cache_entry's ETag in order to perform comparisons.
1698 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001699 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001700 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001701
1702 /* A '*' matches everything. */
1703 if (isteq(ctx.value, ist("*")) != 0) {
1704 retval = 1;
1705 break;
1706 }
1707
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001708 /* No need to rebuild an etag if none was stored in the cache. */
1709 if (entry->etag_length == 0)
1710 break;
1711
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001712 /* Rebuild the stored ETag. */
1713 if (etag_buffer == NULL) {
1714 etag_buffer = get_trash_chunk();
1715
1716 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1717 (unsigned char*)b_orig(etag_buffer),
1718 entry->etag_offset, entry->etag_length) == 0) {
1719 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1720 } else {
1721 /* We could not rebuild the ETag in one go, we
1722 * won't send a "304 Not Modified" response. */
1723 break;
1724 }
1725 }
1726
1727 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1728 retval = 1;
1729 break;
1730 }
1731 }
1732
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001733 /* If the request did not contain an "If-None-Match" header, we look for
1734 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1735 if (retval == 0 && if_none_match_found == 0) {
1736 ctx.blk = NULL;
1737 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1738 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1739 if_modified_since = my_timegm(&tm);
1740
1741 /* We send a "304 Not Modified" response if the
1742 * entry's last modified date is earlier than
1743 * the one found in the "If-Modified-Since"
1744 * header. */
1745 retval = (entry->last_modified <= if_modified_since);
1746 }
1747 }
1748 }
1749
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001750 return retval;
1751}
1752
William Lallemand41db4602017-10-30 11:15:51 +01001753enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1754 struct session *sess, struct stream *s, int flags)
1755{
William Lallemand77c11972017-10-31 20:43:01 +01001756
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001757 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001758 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001759 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1760 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001761 struct shared_block *entry_block;
1762
William Lallemand77c11972017-10-31 20:43:01 +01001763
Willy Tarreau6905d182019-10-01 17:59:17 +02001764 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1765 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001766 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001767 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001768 txn->flags |= TX_CACHE_IGNORE;
1769
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001770 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001771
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001772 /* The request's hash has to be calculated for all requests, even POSTs
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001773 * or PUTs for instance because RFC7234 specifies that a successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001774 * "unsafe" method on a stored resource must invalidate it
1775 * (see RFC7234#4.4). */
1776 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001777 return ACT_RET_CONT;
1778
Willy Tarreau504455c2017-12-22 17:47:35 +01001779 if (s->txn->flags & TX_CACHE_IGNORE)
1780 return ACT_RET_CONT;
1781
Willy Tarreaua1214a52018-12-14 14:00:25 +01001782 if (px == strm_fe(s))
Willy Tarreau4781b152021-04-06 13:53:36 +02001783 _HA_ATOMIC_INC(&px->fe_counters.p.http.cache_lookups);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001784 else
Willy Tarreau4781b152021-04-06 13:53:36 +02001785 _HA_ATOMIC_INC(&px->be_counters.p.http.cache_lookups);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001786
William Lallemanda400a3a2017-11-20 19:13:12 +01001787 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001788 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Bretona8ba4382023-02-21 17:42:04 +01001789 /* We must not use an entry that is not complete but the check will be
1790 * performed after we look for a potential secondary entry (in case of
1791 * Vary). */
1792 if (res) {
William Lallemand77c11972017-10-31 20:43:01 +01001793 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001794 entry_block = block_ptr(res);
1795 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001796 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001797
1798 /* In case of Vary, we could have multiple entries with the same
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001799 * primary hash. We need to calculate the secondary hash in order
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001800 * to find the actual entry we want (if it exists). */
1801 if (res->secondary_key_signature) {
1802 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1803 shctx_lock(shctx_ptr(cache));
1804 sec_entry = secondary_entry_exist(cache, res,
1805 s->txn->cache_secondary_hash);
1806 if (sec_entry && sec_entry != res) {
1807 /* The wrong row was added to the hot list. */
1808 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1809 entry_block = block_ptr(sec_entry);
1810 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1811 }
1812 res = sec_entry;
1813 shctx_unlock(shctx_ptr(cache));
1814 }
1815 else
1816 res = NULL;
1817 }
1818
Remi Tricot-Le Bretona8ba4382023-02-21 17:42:04 +01001819 /* We either looked for a valid secondary entry and could not
1820 * find one, or the entry we want to use is not complete. We
1821 * can't use the cache's entry and must forward the request to
1822 * the server. */
1823 if (!res || !res->complete) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001824 shctx_lock(shctx_ptr(cache));
1825 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1826 shctx_unlock(shctx_ptr(cache));
1827 return ACT_RET_CONT;
1828 }
1829
William Lallemand77c11972017-10-31 20:43:01 +01001830 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001831 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001832 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001833 appctx->rule = rule;
1834 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001835 appctx->ctx.cache.next = NULL;
1836 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001837 appctx->ctx.cache.send_notmodified =
1838 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001839
1840 if (px == strm_fe(s))
Willy Tarreau4781b152021-04-06 13:53:36 +02001841 _HA_ATOMIC_INC(&px->fe_counters.p.http.cache_hits);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001842 else
Willy Tarreau4781b152021-04-06 13:53:36 +02001843 _HA_ATOMIC_INC(&px->be_counters.p.http.cache_hits);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001844 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001845 } else {
Christopher Faulet95d7bc52022-04-21 11:30:43 +02001846 s->target = NULL;
William Lallemand55e76742017-11-21 20:01:28 +01001847 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001848 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001849 shctx_unlock(shctx_ptr(cache));
Christopher Faulet95d7bc52022-04-21 11:30:43 +02001850 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001851 }
1852 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001853 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001854
1855 /* Shared context does not need to be locked while we calculate the
1856 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001857 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001858 /* Build a complete secondary hash until the server response
1859 * tells us which fields should be kept (if any). */
1860 http_request_prebuild_full_secondary_key(s);
1861 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001862 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001863}
1864
1865
1866enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1867 struct act_rule *rule, char **err)
1868{
William Lallemand41db4602017-10-30 11:15:51 +01001869 rule->action = ACT_CUSTOM;
1870 rule->action_ptr = http_action_req_cache_use;
1871
Christopher Faulet95220e22018-12-07 17:34:39 +01001872 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001873 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001874
1875 (*orig_arg)++;
1876 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001877}
1878
1879int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1880{
1881 int err_code = 0;
1882
1883 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1884
1885 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001886 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001887 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001888 err_code |= ERR_ALERT | ERR_ABORT;
1889 goto out;
1890 }
1891
1892 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1893 err_code |= ERR_ABORT;
1894 goto out;
1895 }
1896
1897 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001898 struct cache *cache_config;
1899
William Lallemand41db4602017-10-30 11:15:51 +01001900 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1901 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001902 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001903 err_code |= ERR_ALERT | ERR_ABORT;
1904 goto out;
1905 }
1906
1907 strlcpy2(tmp_cache_config->id, args[1], 33);
1908 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001909 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001910 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001911 err_code |= ERR_WARN;
1912 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001913
1914 list_for_each_entry(cache_config, &caches_config, list) {
1915 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1916 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1917 file, linenum, tmp_cache_config->id);
1918 err_code |= ERR_ALERT | ERR_ABORT;
1919 goto out;
1920 }
1921 }
1922
William Lallemand49b44532017-11-24 18:53:43 +01001923 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001924 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001925 tmp_cache_config->maxobjsz = 0;
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001926 tmp_cache_config->max_secondary_entries = DEFAULT_MAX_SECONDARY_ENTRY;
William Lallemand41db4602017-10-30 11:15:51 +01001927 }
1928 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001929 unsigned long int maxsize;
1930 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001931
1932 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1933 err_code |= ERR_ABORT;
1934 goto out;
1935 }
1936
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001937 maxsize = strtoul(args[1], &err, 10);
1938 if (err == args[1] || *err != '\0') {
1939 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1940 file, linenum, args[1]);
1941 err_code |= ERR_ABORT;
1942 goto out;
1943 }
1944
1945 if (maxsize > (UINT_MAX >> 20)) {
1946 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1947 file, linenum, args[1], UINT_MAX >> 20);
1948 err_code |= ERR_ABORT;
1949 goto out;
1950 }
1951
William Lallemand41db4602017-10-30 11:15:51 +01001952 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001953 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001954 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001955 } else if (strcmp(args[0], "max-age") == 0) {
1956 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1957 err_code |= ERR_ABORT;
1958 goto out;
1959 }
1960
1961 if (!*args[1]) {
1962 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1963 file, linenum, args[0]);
1964 err_code |= ERR_WARN;
1965 }
1966
1967 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001968 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001969 unsigned int maxobjsz;
1970 char *err;
1971
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001972 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1973 err_code |= ERR_ABORT;
1974 goto out;
1975 }
1976
1977 if (!*args[1]) {
1978 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1979 file, linenum, args[0]);
1980 err_code |= ERR_WARN;
1981 }
1982
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001983 maxobjsz = strtoul(args[1], &err, 10);
1984 if (err == args[1] || *err != '\0') {
1985 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1986 file, linenum, args[1]);
1987 err_code |= ERR_ABORT;
1988 goto out;
1989 }
1990 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001991 } else if (strcmp(args[0], "process-vary") == 0) {
1992 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1993 err_code |= ERR_ABORT;
1994 goto out;
1995 }
1996
1997 if (!*args[1]) {
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001998 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 +01001999 file, linenum, args[0]);
2000 err_code |= ERR_WARN;
2001 }
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01002002 if (strcmp(args[1], "on") == 0)
2003 tmp_cache_config->vary_processing_enabled = 1;
2004 else if (strcmp(args[1], "off") == 0)
2005 tmp_cache_config->vary_processing_enabled = 0;
2006 else {
2007 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
2008 file, linenum, args[0]);
2009 err_code |= ERR_WARN;
2010 }
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01002011 } else if (strcmp(args[0], "max-secondary-entries") == 0) {
2012 unsigned int max_sec_entries;
2013 char *err;
2014
2015 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
2016 err_code |= ERR_ABORT;
2017 goto out;
2018 }
2019
2020 if (!*args[1]) {
2021 ha_warning("parsing [%s:%d]: '%s' expects a strictly positive number.\n",
2022 file, linenum, args[0]);
2023 err_code |= ERR_WARN;
2024 }
2025
2026 max_sec_entries = strtoul(args[1], &err, 10);
2027 if (err == args[1] || *err != '\0' || max_sec_entries == 0) {
2028 ha_warning("parsing [%s:%d]: max-secondary-entries wrong value '%s'\n",
2029 file, linenum, args[1]);
2030 err_code |= ERR_ABORT;
2031 goto out;
2032 }
2033 tmp_cache_config->max_secondary_entries = max_sec_entries;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002034 }
2035 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002036 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01002037 err_code |= ERR_ALERT | ERR_FATAL;
2038 goto out;
2039 }
2040out:
2041 return err_code;
2042}
2043
2044/* once the cache section is parsed */
2045
2046int cfg_post_parse_section_cache()
2047{
William Lallemand41db4602017-10-30 11:15:51 +01002048 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01002049
2050 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01002051
2052 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002053 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01002054 err_code |= ERR_FATAL | ERR_ALERT;
2055 goto out;
2056 }
2057
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002058 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002059 /* Default max. file size is a 256th of the cache size. */
2060 tmp_cache_config->maxobjsz =
2061 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002062 }
2063 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
2064 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
2065 err_code |= ERR_FATAL | ERR_ALERT;
2066 goto out;
2067 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002068
William Lallemandd1d1e222019-08-28 15:22:49 +02002069 /* add to the list of cache to init and reinit tmp_cache_config
2070 * for next cache section, if any.
2071 */
Willy Tarreau2b718102021-04-21 07:32:39 +02002072 LIST_APPEND(&caches_config, &tmp_cache_config->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002073 tmp_cache_config = NULL;
2074 return err_code;
2075 }
2076out:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002077 ha_free(&tmp_cache_config);
William Lallemandd1d1e222019-08-28 15:22:49 +02002078 return err_code;
2079
2080}
2081
2082int post_check_cache()
2083{
2084 struct proxy *px;
2085 struct cache *back, *cache_config, *cache;
2086 struct shared_context *shctx;
2087 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01002088 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02002089
2090 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
2091
2092 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
2093 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01002094
Frédéric Lécaillebc584492018-10-25 20:18:59 +02002095 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01002096 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01002097 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002098 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01002099 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002100
2101 err_code |= ERR_FATAL | ERR_ALERT;
2102 goto out;
2103 }
William Lallemanda400a3a2017-11-20 19:13:12 +01002104 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02002105 /* the cache structure is stored in the shctx and added to the
2106 * caches list, we can remove the entry from the caches_config
2107 * list */
2108 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01002109 cache = (struct cache *)shctx->data;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01002110 cache->entries = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +02002111 LIST_APPEND(&caches, &cache->list);
2112 LIST_DELETE(&cache_config->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002113 free(cache_config);
2114
2115 /* Find all references for this cache in the existing filters
2116 * (over all proxies) and reference it in matching filters.
2117 */
2118 for (px = proxies_list; px; px = px->next) {
2119 struct flt_conf *fconf;
2120 struct cache_flt_conf *cconf;
2121
2122 list_for_each_entry(fconf, &px->filter_configs, list) {
2123 if (fconf->id != cache_store_flt_id)
2124 continue;
2125
2126 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002127 if (strcmp(cache->id, cconf->c.name) == 0) {
William Lallemandd1d1e222019-08-28 15:22:49 +02002128 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02002129 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02002130 cconf->c.cache = cache;
2131 break;
2132 }
2133 }
2134 }
William Lallemand41db4602017-10-30 11:15:51 +01002135 }
William Lallemandd1d1e222019-08-28 15:22:49 +02002136
William Lallemand41db4602017-10-30 11:15:51 +01002137out:
William Lallemand41db4602017-10-30 11:15:51 +01002138 return err_code;
2139
William Lallemand41db4602017-10-30 11:15:51 +01002140}
2141
William Lallemand41db4602017-10-30 11:15:51 +01002142struct flt_ops cache_ops = {
2143 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01002144 .check = cache_store_check,
2145 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01002146
Christopher Faulet65554e12020-03-06 14:52:06 +01002147 /* Handle stream init/deinit */
2148 .attach = cache_store_strm_init,
2149 .detach = cache_store_strm_deinit,
2150
William Lallemand4da3f8a2017-10-31 14:33:34 +01002151 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01002152 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002153
2154 /* Filter HTTP requests and responses */
2155 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01002156 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002157 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01002158};
2159
Christopher Faulet99a17a22018-12-11 09:18:27 +01002160
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002161#define CHECK_ENCODING(str, encoding_name, encoding_value) \
2162 ({ \
2163 int retval = 0; \
2164 if (istmatch(str, (struct ist){ .ptr = encoding_name+1, .len = sizeof(encoding_name) - 2 })) { \
2165 retval = encoding_value; \
2166 encoding = istadv(encoding, sizeof(encoding_name) - 2); \
2167 } \
2168 (retval); \
2169 })
2170
2171/*
2172 * Parse the encoding <encoding> and try to match the encoding part upon an
2173 * encoding list of explicitly supported encodings (which all have a specific
2174 * bit in an encoding bitmap). If a weight is included in the value, find out if
2175 * it is null or not. The bit value will be set in the <encoding_value>
2176 * parameter and the <has_null_weight> will be set to 1 if the weight is strictly
2177 * 0, 1 otherwise.
2178 * The encodings list is extracted from
2179 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml.
2180 * Returns 0 in case of success and -1 in case of error.
2181 */
2182static int parse_encoding_value(struct ist encoding, unsigned int *encoding_value,
2183 unsigned int *has_null_weight)
2184{
2185 int retval = 0;
2186
2187 if (!encoding_value)
2188 return -1;
2189
2190 if (!istlen(encoding))
2191 return -1; /* Invalid encoding */
2192
2193 *encoding_value = 0;
2194 if (has_null_weight)
2195 *has_null_weight = 0;
2196
2197 switch (*encoding.ptr) {
2198 case 'a':
2199 encoding = istadv(encoding, 1);
2200 *encoding_value = CHECK_ENCODING(encoding, "aes128gcm", VARY_ENCODING_AES128GCM);
2201 break;
2202 case 'b':
2203 encoding = istadv(encoding, 1);
2204 *encoding_value = CHECK_ENCODING(encoding, "br", VARY_ENCODING_BR);
2205 break;
2206 case 'c':
2207 encoding = istadv(encoding, 1);
2208 *encoding_value = CHECK_ENCODING(encoding, "compress", VARY_ENCODING_COMPRESS);
2209 break;
2210 case 'd':
2211 encoding = istadv(encoding, 1);
2212 *encoding_value = CHECK_ENCODING(encoding, "deflate", VARY_ENCODING_DEFLATE);
2213 break;
2214 case 'e':
2215 encoding = istadv(encoding, 1);
2216 *encoding_value = CHECK_ENCODING(encoding, "exi", VARY_ENCODING_EXI);
2217 break;
2218 case 'g':
2219 encoding = istadv(encoding, 1);
2220 *encoding_value = CHECK_ENCODING(encoding, "gzip", VARY_ENCODING_GZIP);
2221 break;
2222 case 'i':
2223 encoding = istadv(encoding, 1);
2224 *encoding_value = CHECK_ENCODING(encoding, "identity", VARY_ENCODING_IDENTITY);
2225 break;
2226 case 'p':
2227 encoding = istadv(encoding, 1);
2228 *encoding_value = CHECK_ENCODING(encoding, "pack200-gzip", VARY_ENCODING_PACK200_GZIP);
2229 break;
2230 case 'x':
2231 encoding = istadv(encoding, 1);
2232 *encoding_value = CHECK_ENCODING(encoding, "x-gzip", VARY_ENCODING_GZIP);
2233 if (!*encoding_value)
2234 *encoding_value = CHECK_ENCODING(encoding, "x-compress", VARY_ENCODING_COMPRESS);
2235 break;
2236 case 'z':
2237 encoding = istadv(encoding, 1);
2238 *encoding_value = CHECK_ENCODING(encoding, "zstd", VARY_ENCODING_ZSTD);
2239 break;
2240 case '*':
2241 encoding = istadv(encoding, 1);
2242 *encoding_value = VARY_ENCODING_STAR;
2243 break;
2244 default:
2245 retval = -1; /* Unmanaged encoding */
2246 break;
2247 }
2248
2249 /* Process the optional weight part of the encoding. */
2250 if (*encoding_value) {
2251 encoding = http_trim_leading_spht(encoding);
2252 if (istlen(encoding)) {
2253 if (*encoding.ptr != ';')
2254 return -1;
2255
2256 if (has_null_weight) {
2257 encoding = istadv(encoding, 1);
2258
2259 encoding = http_trim_leading_spht(encoding);
2260
2261 *has_null_weight = isteq(encoding, ist("q=0"));
2262 }
2263 }
2264 }
2265
2266 return retval;
2267}
2268
Tim Duesterhus23b29452020-11-24 22:22:56 +01002269#define ACCEPT_ENCODING_MAX_ENTRIES 16
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002270/*
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002271 * Build a bitmap of the accept-encoding header.
2272 *
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002273 * The bitmap is built by matching every sub-part of the accept-encoding value
2274 * with a subset of explicitly supported encodings, which all have their own bit
2275 * in the bitmap. This bitmap will be used to determine if a response can be
2276 * served to a client (that is if it has an encoding that is accepted by the
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002277 * client). Any unknown encodings will be indicated by the VARY_ENCODING_OTHER
2278 * bit.
2279 *
2280 * Returns 0 in case of success and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002281 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002282static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
2283 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002284{
Tim Duesterhus23b29452020-11-24 22:22:56 +01002285 size_t count = 0;
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002286 uint32_t encoding_bitmap = 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002287 unsigned int encoding_bmp_bl = -1;
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002288 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002289 unsigned int encoding_value;
2290 unsigned int rejected_encoding;
2291
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002292 /* A user agent always accepts an unencoded value unless it explicitly
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002293 * refuses it through an "identity;q=0" accept-encoding value. */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002294 encoding_bitmap |= VARY_ENCODING_IDENTITY;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002295
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002296 /* Iterate over all the ACCEPT_ENCODING_MAX_ENTRIES first accept-encoding
2297 * values that might span acrosse multiple accept-encoding headers. */
2298 while (http_find_header(htx, hdr_name, &ctx, 0) && count < ACCEPT_ENCODING_MAX_ENTRIES) {
Tim Duesterhusbeec7ea2021-06-18 15:09:28 +02002299 count++;
2300
2301 /* As per RFC7231#5.3.4, "An Accept-Encoding header field with a
2302 * combined field-value that is empty implies that the user agent
2303 * does not want any content-coding in response."
2304 *
2305 * We must (and did) count the existence of this empty header to not
2306 * hit the `count == 0` case below, but must ignore the value to not
2307 * include VARY_ENCODING_OTHER into the final bitmap.
2308 */
2309 if (istlen(ctx.value) == 0)
2310 continue;
2311
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002312 /* Turn accept-encoding value to lower case */
2313 ist2bin_lc(istptr(ctx.value), ctx.value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002314
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002315 /* Try to identify a known encoding and to manage null weights. */
2316 if (!parse_encoding_value(ctx.value, &encoding_value, &rejected_encoding)) {
2317 if (rejected_encoding)
2318 encoding_bmp_bl &= ~encoding_value;
2319 else
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002320 encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002321 }
2322 else {
2323 /* Unknown encoding */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002324 encoding_bitmap |= VARY_ENCODING_OTHER;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002325 }
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002326 }
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002327
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002328 /* If a "*" was found in the accepted encodings (without a null weight),
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002329 * all the encoding are accepted except the ones explicitly rejected. */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002330 if (encoding_bitmap & VARY_ENCODING_STAR) {
2331 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002332 }
2333
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002334 /* Clear explicitly rejected encodings from the bitmap */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002335 encoding_bitmap &= encoding_bmp_bl;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002336
2337 /* As per RFC7231#5.3.4, "If no Accept-Encoding field is in the request,
2338 * any content-coding is considered acceptable by the user agent". */
2339 if (count == 0)
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002340 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002341
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002342 /* A request with more than ACCEPT_ENCODING_MAX_ENTRIES accepted
2343 * encodings might be illegitimate so we will not use it. */
2344 if (count == ACCEPT_ENCODING_MAX_ENTRIES)
2345 return -1;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002346
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002347 write_u32(buf, encoding_bitmap);
2348 *buf_len = sizeof(encoding_bitmap);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002349
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002350 /* This function fills the hash buffer correctly even if no header was
2351 * found, hence the 0 return value (success). */
Tim Duesterhus23b29452020-11-24 22:22:56 +01002352 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002353}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002354#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002355
2356/*
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002357 * Normalizer used by default for the Referer header. It only
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002358 * calculates a simple crc of the whole value.
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002359 * Only the first occurrence of the header will be taken into account in the
2360 * hash.
2361 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2362 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002363 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002364static int default_normalizer(struct htx *htx, struct ist hdr_name,
2365 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002366{
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002367 int retval = 1;
2368 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002369
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002370 if (http_find_header(htx, hdr_name, &ctx, 1)) {
2371 retval = 0;
2372 write_u32(buf, hash_crc32(istptr(ctx.value), istlen(ctx.value)));
2373 *buf_len = sizeof(int);
2374 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002375
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002376 return retval;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002377}
2378
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002379/*
Tim Duesterhused84d842021-01-18 13:41:17 +01002380 * Accept-Encoding bitmap comparison function.
2381 * Returns 0 if the bitmaps are compatible.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002382 */
Tim Duesterhused84d842021-01-18 13:41:17 +01002383static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002384{
Tim Duesterhused84d842021-01-18 13:41:17 +01002385 uint32_t ref_bitmap = read_u32(ref);
2386 uint32_t new_bitmap = read_u32(new);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002387
Tim Duesterhused84d842021-01-18 13:41:17 +01002388 if (!(ref_bitmap & VARY_ENCODING_OTHER)) {
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002389 /* All the bits set in the reference bitmap correspond to the
2390 * stored response' encoding and should all be set in the new
2391 * encoding bitmap in order for the client to be able to manage
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002392 * the response.
2393 *
2394 * If this is the case the cached response has encodings that
2395 * are accepted by the client. It can be served directly by
2396 * the cache (as far as the accept-encoding part is concerned).
2397 */
2398
Tim Duesterhused84d842021-01-18 13:41:17 +01002399 return (ref_bitmap & new_bitmap) != ref_bitmap;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002400 }
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002401 else {
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002402 return 1;
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002403 }
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002404}
2405
2406
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002407/*
2408 * Pre-calculate the hashes of all the supported headers (in our Vary
2409 * implementation) of a given request. We have to calculate all the hashes
2410 * in advance because the actual Vary signature won't be known until the first
2411 * response.
2412 * Only the first occurrence of every header will be taken into account in the
2413 * hash.
2414 * If the header is not present, the hash portion of the given header will be
2415 * filled with zeros.
2416 * Returns 0 in case of success.
2417 */
2418static int http_request_prebuild_full_secondary_key(struct stream *s)
2419{
Remi Tricot-Le Bretonbba29122020-12-23 18:13:44 +01002420 /* The fake signature (second parameter) will ensure that every part of the
2421 * secondary key is calculated. */
2422 return http_request_build_secondary_key(s, ~0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002423}
2424
2425
2426/*
2427 * Calculate the secondary key for a request for which we already have a known
2428 * vary signature. The key is made by aggregating hashes calculated for every
2429 * header mentioned in the vary signature.
2430 * Only the first occurrence of every header will be taken into account in the
2431 * hash.
2432 * If the header is not present, the hash portion of the given header will be
2433 * filled with zeros.
2434 * Returns 0 in case of success.
2435 */
2436static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2437{
2438 struct http_txn *txn = s->txn;
2439 struct htx *htx = htxbuf(&s->req.buf);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002440
2441 unsigned int idx;
2442 const struct vary_hashing_information *info = NULL;
2443 unsigned int hash_length = 0;
2444 int retval = 0;
2445 int offset = 0;
2446
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002447 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && retval >= 0; ++idx) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002448 info = &vary_information[idx];
2449
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002450 /* The normalizing functions will be in charge of getting the
2451 * header values from the htx. This way they can manage multiple
2452 * occurrences of their processed header. */
2453 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2454 !(retval = info->norm_fn(htx, info->hdr_name, &txn->cache_secondary_hash[offset], &hash_length))) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002455 offset += hash_length;
2456 }
2457 else {
2458 /* Fill hash with 0s. */
2459 hash_length = info->hash_length;
2460 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2461 offset += hash_length;
2462 }
2463 }
2464
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01002465 if (retval >= 0)
2466 txn->flags |= TX_CACHE_HAS_SEC_KEY;
2467
2468 return (retval < 0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002469}
2470
2471/*
2472 * Build the actual secondary key of a given request out of the prebuilt key and
2473 * the actual vary signature (extracted from the response).
2474 * Returns 0 in case of success.
2475 */
2476static int http_request_reduce_secondary_key(unsigned int vary_signature,
2477 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2478{
2479 int offset = 0;
2480 int global_offset = 0;
2481 int vary_info_count = 0;
2482 int keep = 0;
2483 unsigned int vary_idx;
2484 const struct vary_hashing_information *vary_info;
2485
2486 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2487 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2488 vary_info = &vary_information[vary_idx];
2489 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2490
2491 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2492 prebuilt_key[global_offset] &= keep;
2493 }
2494 }
2495
2496 return 0;
2497}
2498
2499
Christopher Faulet99a17a22018-12-11 09:18:27 +01002500
2501static int
2502parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2503 struct flt_conf *fconf, char **err, void *private)
2504{
2505 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002506 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002507 char *name = NULL;
2508 int pos = *cur_arg;
2509
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002510 /* Get the cache filter name. <pos> point on "cache" keyword */
2511 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002512 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002513 goto error;
2514 }
2515 name = strdup(args[pos + 1]);
2516 if (!name) {
2517 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2518 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002519 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002520 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002521
2522 /* Check if an implicit filter with the same name already exists. If so,
2523 * we remove the implicit filter to use the explicit one. */
2524 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2525 if (f->id != cache_store_flt_id)
2526 continue;
2527
2528 cconf = f->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002529 if (strcmp(name, cconf->c.name) != 0) {
Christopher Faulet99a17a22018-12-11 09:18:27 +01002530 cconf = NULL;
2531 continue;
2532 }
2533
2534 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2535 cconf = NULL;
2536 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2537 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002538 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002539 }
2540
2541 /* Remove the implicit filter. <cconf> is kept for the explicit one */
Willy Tarreau2b718102021-04-21 07:32:39 +02002542 LIST_DELETE(&f->list);
Christopher Faulet99a17a22018-12-11 09:18:27 +01002543 free(f);
2544 free(name);
2545 break;
2546 }
2547
2548 /* No implicit cache filter found, create configuration for the explicit one */
2549 if (!cconf) {
2550 cconf = calloc(1, sizeof(*cconf));
2551 if (!cconf) {
2552 memprintf(err, "%s: out of memory", args[*cur_arg]);
2553 goto error;
2554 }
2555 cconf->c.name = name;
2556 }
2557
2558 cconf->flags = 0;
2559 fconf->id = cache_store_flt_id;
2560 fconf->conf = cconf;
2561 fconf->ops = &cache_ops;
2562
2563 *cur_arg = pos;
2564 return 0;
2565
2566 error:
2567 free(name);
2568 free(cconf);
2569 return -1;
2570}
2571
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002572static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002573{
2574 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2575 return 1;
2576
2577 return 0;
2578}
2579
2580static int cli_io_handler_show_cache(struct appctx *appctx)
2581{
2582 struct cache* cache = appctx->ctx.cli.p0;
2583 struct stream_interface *si = appctx->owner;
2584
William Lallemand1f49a362017-11-21 20:01:26 +01002585 if (cache == NULL) {
2586 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
2587 }
2588
2589 list_for_each_entry_from(cache, &caches, list) {
2590 struct eb32_node *node = NULL;
2591 unsigned int next_key;
2592 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002593 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002594
William Lallemand1f49a362017-11-21 20:01:26 +01002595 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002596 if (!next_key) {
2597 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
2598 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002599 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002600 return 0;
2601 }
2602 }
William Lallemand1f49a362017-11-21 20:01:26 +01002603
2604 appctx->ctx.cli.p0 = cache;
2605
2606 while (1) {
2607
2608 shctx_lock(shctx_ptr(cache));
Christopher Fauleteba18d52021-11-23 16:03:05 +01002609 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002610 if (!node) {
2611 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02002612 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002613 break;
2614 }
2615
2616 entry = container_of(node, struct cache_entry, eb);
William Lallemand1f49a362017-11-21 20:01:26 +01002617 next_key = node->key + 1;
Willy Tarreaudcce27f2022-04-13 11:21:39 +02002618
Willy Tarreau5e842192023-02-07 15:22:41 +01002619 if (entry->expire > date.tv_sec) {
Willy Tarreaudcce27f2022-04-13 11:21:39 +02002620 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2621 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2622 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2623 chunk_appendf(&trash, " size:%u (%u blocks), refcount:%u, expire:%d\n",
2624 block_ptr(entry)->len, block_ptr(entry)->block_count,
Willy Tarreau5e842192023-02-07 15:22:41 +01002625 block_ptr(entry)->refcount, entry->expire - (int)date.tv_sec);
Willy Tarreaudcce27f2022-04-13 11:21:39 +02002626 } else {
2627 /* time to remove that one */
2628 delete_entry(entry);
2629 entry->eb.key = 0;
2630 }
2631
William Lallemand1f49a362017-11-21 20:01:26 +01002632 appctx->ctx.cli.i0 = next_key;
2633
2634 shctx_unlock(shctx_ptr(cache));
2635
2636 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002637 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002638 return 0;
2639 }
2640 }
2641
2642 }
2643
2644 return 1;
2645
2646}
2647
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002648
2649/*
2650 * boolean, returns true if response was built out of a cache entry.
2651 */
2652static int
2653smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2654 const char *kw, void *private)
2655{
2656 smp->data.type = SMP_T_BOOL;
2657 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2658
2659 return 1;
2660}
2661
2662/*
2663 * string, returns cache name (if response came from a cache).
2664 */
2665static int
2666smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2667 const char *kw, void *private)
2668{
2669 struct appctx *appctx = NULL;
2670
2671 struct cache_flt_conf *cconf = NULL;
2672 struct cache *cache = NULL;
2673
2674 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2675 return 0;
2676
2677 /* Get appctx from the stream_interface. */
2678 appctx = si_appctx(&smp->strm->si[1]);
2679 if (appctx && appctx->rule) {
2680 cconf = appctx->rule->arg.act.p[0];
2681 if (cconf) {
2682 cache = cconf->c.cache;
2683
2684 smp->data.type = SMP_T_STR;
2685 smp->flags = SMP_F_CONST;
2686 smp->data.u.str.area = cache->id;
2687 smp->data.u.str.data = strlen(cache->id);
2688 return 1;
2689 }
2690 }
2691
2692 return 0;
2693}
2694
Christopher Faulet99a17a22018-12-11 09:18:27 +01002695/* Declare the filter parser for "cache" keyword */
2696static struct flt_kw_list filter_kws = { "CACHE", { }, {
2697 { "cache", parse_cache_flt, NULL },
2698 { NULL, NULL, NULL },
2699 }
2700};
2701
2702INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2703
William Lallemand1f49a362017-11-21 20:01:26 +01002704static struct cli_kw_list cli_kws = {{},{
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002705 { { "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 +01002706 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002707}};
2708
Willy Tarreau0108d902018-11-25 19:14:37 +01002709INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002710
William Lallemand41db4602017-10-30 11:15:51 +01002711static struct action_kw_list http_res_actions = {
2712 .kw = {
2713 { "cache-store", parse_cache_store },
2714 { NULL, NULL }
2715 }
2716};
2717
Willy Tarreau0108d902018-11-25 19:14:37 +01002718INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2719
William Lallemand41db4602017-10-30 11:15:51 +01002720static struct action_kw_list http_req_actions = {
2721 .kw = {
2722 { "cache-use", parse_cache_use },
2723 { NULL, NULL }
2724 }
2725};
2726
Willy Tarreau0108d902018-11-25 19:14:37 +01002727INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2728
Willy Tarreau2231b632019-03-29 18:26:52 +01002729struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002730 .obj_type = OBJ_TYPE_APPLET,
2731 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002732 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002733 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002734};
2735
Willy Tarreaue6552512018-11-26 11:33:13 +01002736/* config parsers for this section */
2737REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002738REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002739
2740
2741/* Note: must not be declared <const> as its list will be overwritten */
2742static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2743 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2744 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2745 { /* END */ },
2746 }
2747};
2748
2749INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);