blob: a0b417e2ea4419c0af3b6a51baa7e12c3dfc7ab7 [file] [log] [blame]
William Lallemand41db4602017-10-30 11:15:51 +01001/*
2 * Cache management
3 *
4 * Copyright 2017 HAProxy Technologies
5 * William Lallemand <wlallemand@haproxy.com>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 */
12
Willy Tarreaub2551052020-06-09 09:07:15 +020013#include <import/eb32tree.h>
14#include <import/sha1.h>
15
Willy Tarreau122eba92020-06-04 10:15:32 +020016#include <haproxy/action-t.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020017#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020018#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020019#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020020#include <haproxy/cli.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020021#include <haproxy/errors.h>
Willy Tarreauc7babd82020-06-04 21:29:29 +020022#include <haproxy/filters.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020023#include <haproxy/hash.h>
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +020024#include <haproxy/http.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020025#include <haproxy/http_ana.h>
Willy Tarreau87735332020-06-04 09:08:41 +020026#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020027#include <haproxy/http_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/htx.h>
29#include <haproxy/net_helper.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020030#include <haproxy/proxy.h>
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +010031#include <haproxy/sample.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020032#include <haproxy/shctx.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020033#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020034#include <haproxy/stream_interface.h>
William Lallemand41db4602017-10-30 11:15:51 +010035
Christopher Faulet27d93c32018-12-15 22:32:02 +010036#define CACHE_FLT_F_IMPLICIT_DECL 0x00000001 /* The cache filtre was implicitly declared (ie without
Christopher Faulet99a17a22018-12-11 09:18:27 +010037 * the filter keyword) */
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +020038#define CACHE_FLT_INIT 0x00000002 /* Whether the cache name was freed. */
Christopher Fauletafd819c2018-12-11 08:57:45 +010039
Christopher Fauletf4a4ef72018-12-07 17:39:53 +010040const char *cache_store_flt_id = "cache store filter";
William Lallemand41db4602017-10-30 11:15:51 +010041
Willy Tarreau2231b632019-03-29 18:26:52 +010042extern struct applet http_cache_applet;
William Lallemand41db4602017-10-30 11:15:51 +010043
44struct flt_ops cache_ops;
45
46struct cache {
Willy Tarreaufd5efb52017-11-26 08:54:31 +010047 struct list list; /* cache linked list */
William Lallemand41db4602017-10-30 11:15:51 +010048 struct eb_root entries; /* head of cache entries based on keys */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010049 unsigned int maxage; /* max-age */
50 unsigned int maxblocks;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +020051 unsigned int maxobjsz; /* max-object-size (in bytes) */
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +010052 unsigned int max_secondary_entries; /* maximum number of secondary entries with the same primary hash */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +010053 uint8_t vary_processing_enabled; /* boolean : manage Vary header (disabled by default) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010054 char id[33]; /* cache name */
William Lallemand41db4602017-10-30 11:15:51 +010055};
56
Christopher Faulet95220e22018-12-07 17:34:39 +010057/* cache config for filters */
58struct cache_flt_conf {
59 union {
60 struct cache *cache; /* cache used by the filter */
61 char *name; /* cache name used during conf parsing */
62 } c;
63 unsigned int flags; /* CACHE_FLT_F_* */
64};
65
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010066
67/*
68 * Vary-related structures and functions
69 */
70enum vary_header_bit {
71 VARY_ACCEPT_ENCODING = (1 << 0),
72 VARY_REFERER = (1 << 1),
73 VARY_LAST /* should always be last */
74};
75
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +010076/*
77 * Encoding list extracted from
78 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml
79 * and RFC7231#5.3.4.
80 */
81enum vary_encoding {
82 VARY_ENCODING_GZIP = (1 << 0),
83 VARY_ENCODING_DEFLATE = (1 << 1),
84 VARY_ENCODING_BR = (1 << 2),
85 VARY_ENCODING_COMPRESS = (1 << 3),
86 VARY_ENCODING_AES128GCM = (1 << 4),
87 VARY_ENCODING_EXI = (1 << 5),
88 VARY_ENCODING_PACK200_GZIP = (1 << 6),
89 VARY_ENCODING_ZSTD = (1 << 7),
90 VARY_ENCODING_IDENTITY = (1 << 8),
91 VARY_ENCODING_STAR = (1 << 9),
92 VARY_ENCODING_OTHER = (1 << 10)
93};
94
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010095struct vary_hashing_information {
96 struct ist hdr_name; /* Header name */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +050097 enum vary_header_bit value; /* Bit representing the header in a vary signature */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010098 unsigned int hash_length; /* Size of the sub hash for this header's value */
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +010099 int(*norm_fn)(struct htx*,struct ist hdr_name,char* buf,unsigned int* buf_len); /* Normalization function */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100100 int(*cmp_fn)(const void *ref_hash, const void *new_hash, unsigned int hash_len); /* Comparison function, should return 0 if the hashes are alike */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100101};
102
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100103struct accept_encoding_hash {
104 unsigned int encoding_bitmap;
105 unsigned int hash;
106} __attribute__((packed));
107
108static int http_request_prebuild_full_secondary_key(struct stream *s);
109static int http_request_build_secondary_key(struct stream *s, int vary_signature);
110static int http_request_reduce_secondary_key(unsigned int vary_signature,
111 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
112
113static int parse_encoding_value(struct ist value, unsigned int *encoding_value,
114 unsigned int *has_null_weight);
115
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +0100116static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
117 char *buf, unsigned int *buf_len);
118static int default_normalizer(struct htx *htx, struct ist hdr_name,
119 char *buf, unsigned int *buf_len);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100120
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100121static int accept_encoding_hash_cmp(const void *ref_hash, const void *new_hash, unsigned int hash_len);
122
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100123/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
124 * added to this array. */
125const struct vary_hashing_information vary_information[] = {
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100126 { IST("accept-encoding"), VARY_ACCEPT_ENCODING, sizeof(struct accept_encoding_hash), &accept_encoding_normalizer, &accept_encoding_hash_cmp },
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100127 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer, NULL },
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100128};
129
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100130
William Lallemand41db4602017-10-30 11:15:51 +0100131/*
132 * cache ctx for filters
133 */
134struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100135 struct shared_block *first_block;
136};
137
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100138#define DEFAULT_MAX_SECONDARY_ENTRY 10
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100139
William Lallemand41db4602017-10-30 11:15:51 +0100140struct cache_entry {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100141 unsigned int complete; /* An entry won't be valid until complete is not null. */
William Lallemand41db4602017-10-30 11:15:51 +0100142 unsigned int latest_validation; /* latest validation date */
143 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200144 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100145
William Lallemand41db4602017-10-30 11:15:51 +0100146 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100147 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200148
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100149 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
150 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
151 * to build secondary keys for this cache entry. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100152 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 +0100153 unsigned int last_clear_ts; /* Timestamp of the last call to clear_expired_duplicates. */
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100154
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200155 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
156 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
157
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200158 time_t last_modified; /* Origin server "Last-Modified" header value converted in
159 * seconds since epoch. If no "Last-Modified"
160 * header is found, use "Date" header value,
161 * otherwise use reception time. This field will
162 * be used in case of an "If-Modified-Since"-based
163 * conditional request. */
164
William Lallemand41db4602017-10-30 11:15:51 +0100165 unsigned char data[0];
166};
167
168#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100169#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100170
171static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200172static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100173static struct cache *tmp_cache_config = NULL;
174
Willy Tarreau8ceae722018-11-26 11:58:30 +0100175DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
176
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100177static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry);
178static void delete_entry(struct cache_entry *del_entry);
179
William Lallemandf528fff2017-11-23 19:43:17 +0100180struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100181{
182 struct eb32_node *node;
183 struct cache_entry *entry;
184
Willy Tarreau8b507582020-02-25 09:35:07 +0100185 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100186 if (!node)
187 return NULL;
188
189 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100190
191 /* if that's not the right node */
192 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
193 return NULL;
194
William Lallemand08727662017-11-21 20:01:27 +0100195 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100196 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100197 } else {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100198 delete_entry(entry);
William Lallemand08727662017-11-21 20:01:27 +0100199 entry->eb.key = 0;
200 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100201 return NULL;
202
203}
204
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100205
206/*
207 * Compare a newly built secondary key to the one found in a cache_entry.
208 * Every sub-part of the key is compared to the reference through the dedicated
209 * comparison function of the sub-part (that might do more than a simple
210 * memcmp).
211 * Returns 0 if the keys are alike.
212 */
213static int secondary_key_cmp(const char *ref_key, const char *new_key)
214{
215 int retval = 0;
216 int idx = 0;
217 int offset = 0;
218 const struct vary_hashing_information *info;
219
220 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
221 info = &vary_information[idx];
222
223 if (info->cmp_fn)
224 retval = info->cmp_fn(&ref_key[offset], &new_key[offset], info->hash_length);
225 else
226 retval = memcmp(&ref_key[offset], &new_key[offset], info->hash_length);
227
228 offset += info->hash_length;
229 }
230
231 return retval;
232}
233
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100234/*
235 * There can be multiple entries with the same primary key in the ebtree so in
236 * order to get the proper one out of the list, we use a secondary_key.
237 * This function simply iterates over all the entries with the same primary_key
238 * until it finds the right one.
239 * Returns the cache_entry in case of success, NULL otherwise.
240 */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100241struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100242 const char *secondary_key)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100243{
244 struct eb32_node *node = &entry->eb;
245
246 if (!entry->secondary_key_signature)
247 return NULL;
248
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100249 while (entry && secondary_key_cmp(entry->secondary_key, secondary_key) != 0) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100250 node = eb32_next_dup(node);
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100251
252 /* Make the best use of this iteration and clear expired entries
253 * when we find them. Calling delete_entry would be too costly
254 * so we simply call eb32_delete. The secondary_entry count will
255 * be updated when we try to insert a new entry to this list. */
256 if (entry->expire <= now.tv_sec) {
257 eb32_delete(&entry->eb);
258 entry->eb.key = 0;
259 }
260
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100261 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
262 }
263
264 /* Expired entry */
265 if (entry && entry->expire <= now.tv_sec) {
266 eb32_delete(&entry->eb);
267 entry->eb.key = 0;
268 entry = NULL;
269 }
270
271 return entry;
272}
273
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100274
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100275/*
276 * Remove all expired entries from a list of duplicates.
277 * Return the number of alive entries in the list and sets dup_tail to the
278 * current last item of the list.
279 */
280static unsigned int clear_expired_duplicates(struct eb32_node **dup_tail)
281{
282 unsigned int entry_count = 0;
283 struct cache_entry *entry = NULL;
284 struct eb32_node *prev = *dup_tail;
285 struct eb32_node *tail = NULL;
286
287 while (prev) {
288 entry = container_of(prev, struct cache_entry, eb);
289 prev = eb32_prev_dup(prev);
290 if (entry->expire <= now.tv_sec) {
291 eb32_delete(&entry->eb);
292 entry->eb.key = 0;
293 }
294 else {
295 if (!tail)
296 tail = &entry->eb;
297 ++entry_count;
298 }
299 }
300
301 *dup_tail = tail;
302
303 return entry_count;
304}
305
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100306
307/*
308 * This function inserts a cache_entry in the cache's ebtree. In case of
309 * duplicate entries (vary), it then checks that the number of entries did not
310 * reach the max number of secondary entries. If this entry should not have been
311 * created, remove it.
312 * In the regular case (unique entries), this function does not do more than a
313 * simple insert. In case of secondary entries, it will at most cost an
314 * insertion+max_sec_entries time checks and entry deletion.
315 * Returns the newly inserted node in case of success, NULL otherwise.
316 */
317static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry)
318{
319 struct eb32_node *prev = NULL;
320 struct cache_entry *entry = NULL;
321 unsigned int entry_count = 0;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100322 unsigned int last_clear_ts = now.tv_sec;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100323
324 struct eb32_node *node = eb32_insert(&cache->entries, &new_entry->eb);
325
326 /* We should not have multiple entries with the same primary key unless
327 * the entry has a non null vary signature. */
328 if (!new_entry->secondary_key_signature)
329 return node;
330
331 prev = eb32_prev_dup(node);
332 if (prev != NULL) {
333 /* The last entry of a duplicate list should contain the current
334 * number of entries in the list. */
335 entry = container_of(prev, struct cache_entry, eb);
336 entry_count = entry->secondary_entries_count;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100337 last_clear_ts = entry->last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100338
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100339 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100340 /* Some entries of the duplicate list might be expired so
341 * we will iterate over all the items in order to free some
342 * space. In order to avoid going over the same list too
343 * often, we first check the timestamp of the last check
344 * performed. */
345 if (last_clear_ts == now.tv_sec) {
346 /* Too many entries for this primary key, clear the
347 * one that was inserted. */
348 eb32_delete(node);
349 node->key = 0;
350 return NULL;
351 }
352
353 entry_count = clear_expired_duplicates(&prev);
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100354 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100355 /* Still too many entries for this primary key, delete
356 * the newly inserted one. */
357 entry = container_of(prev, struct cache_entry, eb);
358 entry->last_clear_ts = now.tv_sec;
359 eb32_delete(node);
360 node->key = 0;
361 return NULL;
362 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100363 }
364 }
365
366 new_entry->secondary_entries_count = entry_count + 1;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100367 new_entry->last_clear_ts = last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100368
369 return node;
370}
371
372
373/*
374 * This function removes an entry from the ebtree. If the entry was a duplicate
375 * (in case of Vary), it updates the secondary entry counter in another
376 * duplicate entry (the last entry of the dup list).
377 */
378static void delete_entry(struct cache_entry *del_entry)
379{
380 struct eb32_node *prev = NULL, *next = NULL;
381 struct cache_entry *entry = NULL;
382 struct eb32_node *last = NULL;
383
384 if (del_entry->secondary_key_signature) {
385 next = &del_entry->eb;
386
387 /* Look for last entry of the duplicates list. */
388 while ((next = eb32_next_dup(next))) {
389 last = next;
390 }
391
392 if (last) {
393 entry = container_of(last, struct cache_entry, eb);
394 --entry->secondary_entries_count;
395 }
396 else {
397 /* The current entry is the last one, look for the
398 * previous one to update its counter. */
399 prev = eb32_prev_dup(&del_entry->eb);
400 if (prev) {
401 entry = container_of(prev, struct cache_entry, eb);
402 entry->secondary_entries_count = del_entry->secondary_entries_count - 1;
403 }
404 }
405 }
406 eb32_delete(&del_entry->eb);
407 del_entry->eb.key = 0;
408}
409
410
William Lallemand4da3f8a2017-10-31 14:33:34 +0100411static inline struct shared_context *shctx_ptr(struct cache *cache)
412{
413 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
414}
415
William Lallemand77c11972017-10-31 20:43:01 +0100416static inline struct shared_block *block_ptr(struct cache_entry *entry)
417{
418 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
419}
420
421
422
William Lallemand41db4602017-10-30 11:15:51 +0100423static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100424cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100425{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100426 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100427 return 0;
428}
429
Christopher Faulet95220e22018-12-07 17:34:39 +0100430static void
431cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
432{
433 struct cache_flt_conf *cconf = fconf->conf;
434
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200435 if (!(cconf->flags & CACHE_FLT_INIT))
436 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100437 free(cconf);
438}
439
William Lallemand4da3f8a2017-10-31 14:33:34 +0100440static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100441cache_store_check(struct proxy *px, struct flt_conf *fconf)
442{
443 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100444 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100445 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100446 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100447
William Lallemandd1d1e222019-08-28 15:22:49 +0200448 /* Find the cache corresponding to the name in the filter config. The
449 * cache will not be referenced now in the filter config because it is
450 * not fully allocated. This step will be performed during the cache
451 * post_check.
452 */
453 list_for_each_entry(cache, &caches_config, list) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +0100454 if (strcmp(cache->id, cconf->c.name) == 0)
Christopher Faulet95220e22018-12-07 17:34:39 +0100455 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100456 }
457
458 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
459 proxy_type_str(px), px->id, (char *)cconf->c.name);
460 return 1;
461
462 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100463 /* Here <cache> points on the cache the filter must use and <cconf>
464 * points on the cache filter configuration. */
465
466 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100467 * enabled and if it is after the cache. When the compression is before
468 * the cache, an error is returned. Also check if the cache filter must
469 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100470 list_for_each_entry(f, &px->filter_configs, list) {
471 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100472 /* The compression filter must be evaluated after the cache. */
473 if (comp) {
474 ha_alert("config: %s '%s': unable to enable the compression filter before "
475 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
476 return 1;
477 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100478 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200479 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100480 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200481 else if (f->id == fcgi_flt_id)
482 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100483 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
484 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200485 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100486 * declaration is required. */
487 ha_alert("config: %s '%s': require an explicit filter declaration "
488 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
489 return 1;
490 }
491
Christopher Fauletafd819c2018-12-11 08:57:45 +0100492 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100493 return 0;
494}
495
496static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100497cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100498{
Christopher Faulet65554e12020-03-06 14:52:06 +0100499 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100500
Christopher Faulet65554e12020-03-06 14:52:06 +0100501 st = pool_alloc_dirty(pool_head_cache_st);
502 if (st == NULL)
503 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100504
Christopher Faulet65554e12020-03-06 14:52:06 +0100505 st->first_block = NULL;
506 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100507
Christopher Faulet65554e12020-03-06 14:52:06 +0100508 /* Register post-analyzer on AN_RES_WAIT_HTTP */
509 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100510 return 1;
511}
512
Christopher Faulet65554e12020-03-06 14:52:06 +0100513static void
514cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100515{
516 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100517 struct cache_flt_conf *cconf = FLT_CONF(filter);
518 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100519 struct shared_context *shctx = shctx_ptr(cache);
520
William Lallemand49dc0482017-11-24 14:33:54 +0100521 /* Everything should be released in the http_end filter, but we need to do it
522 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100523 if (st && st->first_block) {
William Lallemand49dc0482017-11-24 14:33:54 +0100524 shctx_lock(shctx);
525 shctx_row_dec_hot(shctx, st->first_block);
526 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100527 }
528 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100529 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100530 filter->ctx = NULL;
531 }
William Lallemand49dc0482017-11-24 14:33:54 +0100532}
533
Christopher Faulet839791a2019-01-07 16:12:07 +0100534static int
535cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
536 unsigned an_bit)
537{
538 struct http_txn *txn = s->txn;
539 struct http_msg *msg = &txn->rsp;
540 struct cache_st *st = filter->ctx;
541
542 if (an_bit != AN_RES_WAIT_HTTP)
543 goto end;
544
545 /* Here we need to check if any compression filter precedes the cache
546 * filter. This is only possible when the compression is configured in
547 * the frontend while the cache filter is configured on the
548 * backend. This case cannot be detected during HAProxy startup. So in
549 * such cases, the cache is disabled.
550 */
551 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
552 pool_free(pool_head_cache_st, st);
553 filter->ctx = NULL;
554 }
555
556 end:
557 return 1;
558}
William Lallemand49dc0482017-11-24 14:33:54 +0100559
560static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100561cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
562{
563 struct cache_st *st = filter->ctx;
564
William Lallemand4da3f8a2017-10-31 14:33:34 +0100565 if (!(msg->chn->flags & CF_ISRESP) || !st)
566 return 1;
567
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200568 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100569 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100570 return 1;
571}
572
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200573static inline void disable_cache_entry(struct cache_st *st,
574 struct filter *filter, struct shared_context *shctx)
575{
576 struct cache_entry *object;
577
578 object = (struct cache_entry *)st->first_block->data;
579 filter->ctx = NULL; /* disable cache */
580 shctx_lock(shctx);
581 shctx_row_dec_hot(shctx, st->first_block);
Remi Tricot-Le Breton964caaf2020-12-15 14:30:12 +0100582 eb32_delete(&object->eb);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200583 object->eb.key = 0;
584 shctx_unlock(shctx);
585 pool_free(pool_head_cache_st, st);
586}
587
William Lallemand4da3f8a2017-10-31 14:33:34 +0100588static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100589cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
590 unsigned int offset, unsigned int len)
591{
Christopher Faulet95220e22018-12-07 17:34:39 +0100592 struct cache_flt_conf *cconf = FLT_CONF(filter);
593 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100594 struct cache_st *st = filter->ctx;
595 struct htx *htx = htxbuf(&msg->chn->buf);
596 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200597 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100598 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200599 unsigned int orig_len, to_forward;
600 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100601
602 if (!len)
603 return len;
604
605 if (!st->first_block) {
606 unregister_data_filter(s, msg->chn, filter);
607 return len;
608 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100609
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200610 chunk_reset(&trash);
611 orig_len = len;
612 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100613
614 htxret = htx_find_offset(htx, offset);
615 blk = htxret.blk;
616 offset = htxret.ret;
617 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100618 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200619 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100620 struct ist v;
621
622 switch (type) {
623 case HTX_BLK_UNUSED:
624 break;
625
626 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100627 v = htx_get_blk_value(htx, blk);
628 v.ptr += offset;
629 v.len -= offset;
630 if (v.len > len)
631 v.len = len;
632
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200633 info = (type << 28) + v.len;
634 chunk_memcat(&trash, (char *)&info, sizeof(info));
635 chunk_memcat(&trash, v.ptr, v.len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100636 to_forward += v.len;
637 len -= v.len;
638 break;
639
640 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200641 /* Here offset must always be 0 because only
642 * DATA blocks can be partially transferred. */
643 if (offset)
644 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100645 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200646 goto end;
647
648 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
649 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100650 to_forward += sz;
651 len -= sz;
652 break;
653 }
654
655 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100656 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200657
658 end:
659 shctx_lock(shctx);
660 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
661 if (!fb) {
662 shctx_unlock(shctx);
663 goto no_cache;
664 }
665 shctx_unlock(shctx);
666
667 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
668 (unsigned char *)b_head(&trash), b_data(&trash));
669 if (ret < 0)
670 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100671
672 return to_forward;
673
674 no_cache:
675 disable_cache_entry(st, filter, shctx);
676 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200677 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100678}
679
680static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100681cache_store_http_end(struct stream *s, struct filter *filter,
682 struct http_msg *msg)
683{
684 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100685 struct cache_flt_conf *cconf = FLT_CONF(filter);
686 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100687 struct shared_context *shctx = shctx_ptr(cache);
688 struct cache_entry *object;
689
690 if (!(msg->chn->flags & CF_ISRESP))
691 return 1;
692
693 if (st && st->first_block) {
694
695 object = (struct cache_entry *)st->first_block->data;
696
William Lallemand4da3f8a2017-10-31 14:33:34 +0100697 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100698 /* The whole payload was cached, the entry can now be used. */
699 object->complete = 1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100700 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100701 shctx_row_dec_hot(shctx, st->first_block);
702 shctx_unlock(shctx);
703
704 }
705 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100706 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100707 filter->ctx = NULL;
708 }
709
710 return 1;
711}
712
713 /*
714 * This intends to be used when checking HTTP headers for some
715 * word=value directive. Return a pointer to the first character of value, if
716 * the word was not found or if there wasn't any value assigned ot it return NULL
717 */
718char *directive_value(const char *sample, int slen, const char *word, int wlen)
719{
720 int st = 0;
721
722 if (slen < wlen)
723 return 0;
724
725 while (wlen) {
726 char c = *sample ^ *word;
727 if (c && c != ('A' ^ 'a'))
728 return NULL;
729 sample++;
730 word++;
731 slen--;
732 wlen--;
733 }
734
735 while (slen) {
736 if (st == 0) {
737 if (*sample != '=')
738 return NULL;
739 sample++;
740 slen--;
741 st = 1;
742 continue;
743 } else {
744 return (char *)sample;
745 }
746 }
747
748 return NULL;
749}
750
751/*
752 * Return the maxage in seconds of an HTTP response.
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100753 * The returned value will always take the cache's configuration into account
754 * (cache->maxage) but the actual max age of the response will be set in the
755 * true_maxage parameter. It will be used to determine if a response is already
756 * stale or not.
William Lallemand4da3f8a2017-10-31 14:33:34 +0100757 * Compute the maxage using either:
758 * - the assigned max-age of the cache
759 * - the s-maxage directive
760 * - the max-age directive
761 * - (Expires - Data) headers
762 * - the default-max-age of the cache
763 *
764 */
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100765int http_calc_maxage(struct stream *s, struct cache *cache, int *true_maxage)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100766{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200767 struct htx *htx = htxbuf(&s->res.buf);
768 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100769 long smaxage = -1;
770 long maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100771 int expires = -1;
772 struct tm tm = {};
773 time_t expires_val = 0;
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100774 char *endptr = NULL;
775 int offset = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100776
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100777 /* The Cache-Control max-age and s-maxage directives should be followed by
778 * a positive numerical value (see RFC 7234#5.2.1.1). According to the
779 * specs, a sender "should not" generate a quoted-string value but we will
780 * still accept this format since it isn't strictly forbidden. */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200781 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
782 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100783
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200784 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
785 if (value) {
786 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100787
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200788 chunk_strncat(chk, value, ctx.value.len - 8 + 1);
789 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100790 offset = (*chk->area == '"') ? 1 : 0;
791 smaxage = strtol(chk->area + offset, &endptr, 10);
792 if (unlikely(smaxage < 0 || endptr == chk->area))
793 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100794 }
795
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200796 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
797 if (value) {
798 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200799
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200800 chunk_strncat(chk, value, ctx.value.len - 7 + 1);
801 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100802 offset = (*chk->area == '"') ? 1 : 0;
803 maxage = strtol(chk->area + offset, &endptr, 10);
804 if (unlikely(maxage < 0 || endptr == chk->area))
805 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100806 }
807 }
808
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100809 /* Look for Expires header if no s-maxage or max-age Cache-Control data
810 * was found. */
811 if (maxage == -1 && smaxage == -1) {
812 ctx.blk = NULL;
813 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
814 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
815 expires_val = my_timegm(&tm);
816 /* A request having an expiring date earlier
817 * than the current date should be considered as
818 * stale. */
819 expires = (expires_val >= now.tv_sec) ?
820 (expires_val - now.tv_sec) : 0;
821 }
822 else {
823 /* Following RFC 7234#5.3, an invalid date
824 * format must be treated as a date in the past
825 * so the cache entry must be seen as already
826 * expired. */
827 expires = 0;
828 }
829 }
830 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100831
832
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100833 if (smaxage > 0) {
834 if (true_maxage)
835 *true_maxage = smaxage;
William Lallemand49b44532017-11-24 18:53:43 +0100836 return MIN(smaxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100837 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100838
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100839 if (maxage > 0) {
840 if (true_maxage)
841 *true_maxage = maxage;
William Lallemand49b44532017-11-24 18:53:43 +0100842 return MIN(maxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100843 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100844
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100845 if (expires >= 0) {
846 if (true_maxage)
847 *true_maxage = expires;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100848 return MIN(expires, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100849 }
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100850
William Lallemand49b44532017-11-24 18:53:43 +0100851 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100852
853}
854
855
William Lallemanda400a3a2017-11-20 19:13:12 +0100856static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
857{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200858 struct cache_entry *object = (struct cache_entry *)block->data;
859
860 if (first == block && object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100861 delete_entry(object);
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200862 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100863}
864
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200865
866/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
867 * date value should be compared to a date determined by in a previous response (for
868 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
869 * value of the response's reception time (by decreasing order of priority). */
870static time_t get_last_modified_time(struct htx *htx)
871{
872 time_t last_modified = 0;
873 struct http_hdr_ctx ctx = { .blk = NULL };
874 struct tm tm = {};
875
876 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
877 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
878 last_modified = my_timegm(&tm);
879 }
880 }
881
882 if (!last_modified) {
883 ctx.blk = NULL;
884 if (http_find_header(htx, ist("date"), &ctx, 1)) {
885 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
886 last_modified = my_timegm(&tm);
887 }
888 }
889 }
890
891 /* Fallback on the current time if no "Last-Modified" or "Date" header
892 * was found. */
893 if (!last_modified)
894 last_modified = now.tv_sec;
895
896 return last_modified;
897}
898
William Lallemand41db4602017-10-30 11:15:51 +0100899/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100900 * Checks the vary header's value. The headers on which vary should be applied
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500901 * must be explicitly supported in the vary_information array (see cache.c). If
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100902 * any other header is mentioned, we won't store the response.
903 * Returns 1 if Vary-based storage can work, 0 otherwise.
904 */
905static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
906{
907 unsigned int vary_idx;
908 unsigned int vary_info_count;
909 const struct vary_hashing_information *vary_info;
910 struct http_hdr_ctx ctx = { .blk = NULL };
911
912 int retval = 1;
913
914 *vary_signature = 0;
915
916 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
917 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
918 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
919 vary_info = &vary_information[vary_idx];
920 if (isteqi(ctx.value, vary_info->hdr_name)) {
921 *vary_signature |= vary_info->value;
922 break;
923 }
924 }
925 retval = (vary_idx < vary_info_count);
926 }
927
928 return retval;
929}
930
931
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100932/*
933 * Look for the accept-encoding part of the secondary_key and replace the
934 * encoding bitmap part of the hash with the actual encoding of the response,
935 * extracted from the content-encoding header value.
936 */
937static void set_secondary_key_encoding(struct htx *htx, char *secondary_key)
938{
939 unsigned int resp_encoding_bitmap = 0;
940 const struct vary_hashing_information *info = vary_information;
941 unsigned int offset = 0;
942 unsigned int count = 0;
943 unsigned int hash_info_count = sizeof(vary_information)/sizeof(*vary_information);
944 unsigned int encoding_value;
945 struct http_hdr_ctx ctx = { .blk = NULL };
946
947 /* Look for the accept-encoding part of the secondary_key. */
948 while (count < hash_info_count && info->value != VARY_ACCEPT_ENCODING) {
949 offset += info->hash_length;
950 ++info;
951 ++count;
952 }
953
954 if (count == hash_info_count)
955 return;
956
957 while (http_find_header(htx, ist("content-encoding"), &ctx, 0)) {
958 if (!parse_encoding_value(ctx.value, &encoding_value, NULL))
959 resp_encoding_bitmap |= encoding_value;
960 else
961 resp_encoding_bitmap |= VARY_ENCODING_OTHER;
962 }
963
964 if (!resp_encoding_bitmap)
965 resp_encoding_bitmap |= VARY_ENCODING_IDENTITY;
966
967 /* Rewrite the bitmap part of the hash with the new bitmap that only
968 * correponds the the response's encoding. */
969 write_u32(secondary_key + offset, resp_encoding_bitmap);
970}
971
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100972
973/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500974 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100975 * register a filter to store the data
976 */
977enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200978 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100979{
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200980 long long hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100981 int effective_maxage = 0;
982 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100983 struct http_txn *txn = s->txn;
984 struct http_msg *msg = &txn->rsp;
985 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100986 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100987 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100988 struct cache *cache = cconf->c.cache;
989 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100990 struct cache_st *cache_ctx = NULL;
991 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +0100992 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200993 struct htx *htx;
994 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +0200995 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200996 int32_t pos;
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200997 struct ist header_name = IST_NULL;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100998 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100999
William Lallemand4da3f8a2017-10-31 14:33:34 +01001000 /* Don't cache if the response came from a cache */
1001 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
1002 s->target == &http_cache_applet.obj_type) {
1003 goto out;
1004 }
1005
1006 /* cache only HTTP/1.1 */
1007 if (!(txn->req.flags & HTTP_MSGF_VER_11))
1008 goto out;
1009
Willy Tarreau6905d182019-10-01 17:59:17 +02001010 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001011 if (txn->meth != HTTP_METH_GET) {
1012 /* In case of successful unsafe method on a stored resource, the
1013 * cached entry must be invalidated (see RFC7234#4.4).
1014 * A "non-error response" is one with a 2xx (Successful) or 3xx
1015 * (Redirection) status code. */
1016 if (txn->status >= 200 && txn->status < 400) {
1017 switch (txn->meth) {
1018 case HTTP_METH_OPTIONS:
1019 case HTTP_METH_GET:
1020 case HTTP_METH_HEAD:
1021 case HTTP_METH_TRACE:
1022 break;
1023
1024 default: /* Any unsafe method */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001025 /* Discard any corresponding entry in case of successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001026 * unsafe request (such as PUT, POST or DELETE). */
1027 shctx_lock(shctx);
1028
1029 old = entry_exist(cconf->c.cache, txn->cache_hash);
1030 if (old) {
1031 eb32_delete(&old->eb);
1032 old->eb.key = 0;
1033 }
1034 shctx_unlock(shctx);
1035 }
1036 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001037 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001038 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001039
Willy Tarreauc9036c02019-01-11 19:38:25 +01001040 /* cache key was not computed */
1041 if (!key)
1042 goto out;
1043
William Lallemand4da3f8a2017-10-31 14:33:34 +01001044 /* cache only 200 status code */
1045 if (txn->status != 200)
1046 goto out;
1047
Christopher Faulet839791a2019-01-07 16:12:07 +01001048 /* Find the corresponding filter instance for the current stream */
1049 list_for_each_entry(filter, &s->strm_flt.filters, list) {
1050 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
1051 /* No filter ctx, don't cache anything */
1052 if (!filter->ctx)
1053 goto out;
1054 cache_ctx = filter->ctx;
1055 break;
1056 }
1057 }
1058
1059 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001060 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001061
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001062 /* Do not cache too big objects. */
1063 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
1064 htx->data + htx->extra > shctx->max_obj_size)
1065 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001066
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001067 /* Only a subset of headers are supported in our Vary implementation. If
1068 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001069 * able to use the cache. Likewise, if Vary header support is disabled,
1070 * avoid caching responses that contain such a header. */
1071 ctx.blk = NULL;
1072 if (cache->vary_processing_enabled) {
1073 if (!http_check_vary_header(htx, &vary_signature))
1074 goto out;
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001075 if (vary_signature) {
1076 /* If something went wrong during the secondary key
1077 * building, do not store the response. */
1078 if (!(txn->flags & TX_CACHE_HAS_SEC_KEY))
1079 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001080 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001081 }
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001082 }
1083 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001084 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001085 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001086
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001087 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001088
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +01001089 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001090 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001091
1092 shctx_lock(shctx);
1093 old = entry_exist(cache, txn->cache_hash);
1094 if (old) {
1095 if (vary_signature)
1096 old = secondary_entry_exist(cconf->c.cache, old,
1097 txn->cache_secondary_hash);
1098 if (old) {
1099 if (!old->complete) {
1100 /* An entry with the same primary key is already being
1101 * created, we should not try to store the current
1102 * response because it will waste space in the cache. */
1103 shctx_unlock(shctx);
1104 goto out;
1105 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001106 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001107 old->eb.key = 0;
1108 }
1109 }
1110 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1111 if (!first) {
1112 shctx_unlock(shctx);
1113 goto out;
1114 }
1115 /* the received memory is not initialized, we need at least to mark
1116 * the object as not indexed yet.
1117 */
1118 object = (struct cache_entry *)first->data;
1119 memset(object, 0, sizeof(*object));
1120 object->eb.key = key;
1121 object->secondary_key_signature = vary_signature;
1122 /* We need to temporarily set a valid expiring time until the actual one
1123 * is set by the end of this function (in case of concurrent accesses to
1124 * the same resource). This way the second access will find an existing
1125 * but not yet usable entry in the tree and will avoid storing its data. */
1126 object->expire = now.tv_sec + 2;
1127
1128 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1129 if (vary_signature)
1130 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1131
1132 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001133 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001134 object->eb.key = 0;
1135 shctx_unlock(shctx);
1136 goto out;
1137 }
1138 shctx_unlock(shctx);
1139
1140 /* reserve space for the cache_entry structure */
1141 first->len = sizeof(struct cache_entry);
1142 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001143
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001144 /* Determine the entry's maximum age (taking into account the cache's
1145 * configuration) as well as the response's explicit max age (extracted
1146 * from cache-control directives or the expires header). */
1147 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1148
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001149 ctx.blk = NULL;
1150 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
1151 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1152 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1153 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001154 /* A response with an Age value greater than its
1155 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001156 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001157 if (unlikely(object->age > true_maxage))
1158 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001159 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001160 else
1161 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001162 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001163 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001164
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001165 /* Build a last-modified time that will be stored in the cache_entry and
1166 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001167 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001168
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001169 chunk_reset(&trash);
1170 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1171 struct htx_blk *blk = htx_get_blk(htx, pos);
1172 enum htx_blk_type type = htx_get_blk_type(blk);
1173 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001174
Christopher Fauletb0667472019-09-03 22:22:12 +02001175 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001176 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1177 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001178
1179 /* Look for optional ETag header.
1180 * We need to store the offset of the ETag value in order for
1181 * future conditional requests to be able to perform ETag
1182 * comparisons. */
1183 if (type == HTX_BLK_HDR) {
1184 header_name = htx_get_blk_name(htx, blk);
1185 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001186 object->etag_length = sz - istlen(header_name);
1187 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001188 }
1189 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001190 if (type == HTX_BLK_EOH)
1191 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001192 }
1193
Christopher Fauletb0667472019-09-03 22:22:12 +02001194 /* Do not cache objects if the headers are too big. */
1195 if (hdrs_len > htx->size - global.tune.maxrewrite)
1196 goto out;
1197
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001198 /* If the response has a secondary_key, fill its key part related to
1199 * encodings with the actual encoding of the response. This way any
1200 * subsequent request having the same primary key will have its accepted
1201 * encodings tested upon the cached response's one. */
1202 if (cache->vary_processing_enabled && vary_signature)
1203 set_secondary_key_encoding(htx, object->secondary_key);
1204
William Lallemand4da3f8a2017-10-31 14:33:34 +01001205 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001206 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001207 shctx_unlock(shctx);
1208 goto out;
1209 }
1210 shctx_unlock(shctx);
1211
William Lallemand4da3f8a2017-10-31 14:33:34 +01001212 /* cache the headers in a http action because it allows to chose what
1213 * to cache, for example you might want to cache a response before
1214 * modifying some HTTP headers, or on the contrary after modifying
1215 * those headers.
1216 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001217 /* does not need to be locked because it's in the "hot" list,
1218 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001219 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1220 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001221
1222 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001223 if (cache_ctx) {
1224 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001225 /* store latest value and expiration time */
1226 object->latest_validation = now.tv_sec;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001227 object->expire = now.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001228 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001229 }
1230
1231out:
1232 /* if does not cache */
1233 if (first) {
1234 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001235 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001236 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001237 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001238 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001239 shctx_row_dec_hot(shctx, first);
1240 shctx_unlock(shctx);
1241 }
1242
William Lallemand41db4602017-10-30 11:15:51 +01001243 return ACT_RET_CONT;
1244}
1245
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001246#define HTX_CACHE_INIT 0 /* Initial state. */
1247#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1248#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001249#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1250#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001251
William Lallemandecb73b12017-11-24 14:33:55 +01001252static void http_cache_applet_release(struct appctx *appctx)
1253{
Christopher Faulet95220e22018-12-07 17:34:39 +01001254 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +01001255 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001256 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001257 struct shared_block *first = block_ptr(cache_ptr);
1258
1259 shctx_lock(shctx_ptr(cache));
1260 shctx_row_dec_hot(shctx_ptr(cache), first);
1261 shctx_unlock(shctx_ptr(cache));
1262}
1263
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001264
1265static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1266 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001267{
Christopher Faulet95220e22018-12-07 17:34:39 +01001268 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1269 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001270 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001271 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001272 unsigned int max, total;
1273 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001274
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001275 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1276 if (!max)
1277 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001278 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001279 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1280 : info & 0xfffffff);
1281 if (blksz > max)
1282 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001283
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001284 blk = htx_add_blk(htx, type, blksz);
1285 if (!blk)
1286 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001287
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001288 blk->info = info;
1289 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001290 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001291 while (blksz) {
1292 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001293 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001294 offset += max;
1295 blksz -= max;
1296 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001297 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001298 if (blksz || offset == shctx->block_size) {
1299 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1300 offset = 0;
1301 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001302 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001303 appctx->ctx.cache.offset = offset;
1304 appctx->ctx.cache.next = shblk;
1305 appctx->ctx.cache.sent += total;
1306 return total;
1307}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001308
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001309static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1310 uint32_t info, struct shared_block *shblk, unsigned int offset)
1311{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001312
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001313 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1314 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1315 unsigned int max, total, rem_data;
1316 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001317
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001318 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1319 if (!max)
1320 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001321
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001322 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001323 if (appctx->ctx.cache.rem_data) {
1324 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001325 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001326 }
1327 else {
1328 blksz = (info & 0xfffffff);
1329 total = 4;
1330 }
1331 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001332 rem_data = blksz - max;
1333 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001334 }
1335
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001336 while (blksz) {
1337 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001338
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001339 max = MIN(blksz, shctx->block_size - offset);
1340 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1341 offset += sz;
1342 blksz -= sz;
1343 total += sz;
1344 if (sz < max)
1345 break;
1346 if (blksz || offset == shctx->block_size) {
1347 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1348 offset = 0;
1349 }
1350 }
1351
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001352 appctx->ctx.cache.offset = offset;
1353 appctx->ctx.cache.next = shblk;
1354 appctx->ctx.cache.sent += total;
1355 appctx->ctx.cache.rem_data = rem_data + blksz;
1356 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001357}
1358
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001359static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1360 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001361{
Christopher Faulet95220e22018-12-07 17:34:39 +01001362 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1363 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001364 struct shared_block *shblk;
1365 unsigned int offset, sz;
1366 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001367
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001368 while (len) {
1369 enum htx_blk_type type;
1370 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001371
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001372 shblk = appctx->ctx.cache.next;
1373 offset = appctx->ctx.cache.offset;
1374 if (appctx->ctx.cache.rem_data) {
1375 type = HTX_BLK_DATA;
1376 info = 0;
1377 goto add_data_blk;
1378 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001379
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001380 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001381 sz = MIN(4, shctx->block_size - offset);
1382 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1383 offset += sz;
1384 if (sz < 4) {
1385 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1386 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1387 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001388 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001389
1390 /* Get payload of the next HTX block and insert it. */
1391 type = (info >> 28);
1392 if (type != HTX_BLK_DATA)
1393 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1394 else {
1395 add_data_blk:
1396 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001397 }
1398
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001399 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001400 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001401 total += ret;
1402 len -= ret;
1403
1404 if (appctx->ctx.cache.rem_data || type == mark)
1405 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001406 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001407
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001408 return total;
1409}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001410
1411static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1412{
1413 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1414 unsigned int age;
1415 char *end;
1416
1417 chunk_reset(&trash);
1418 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1419 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1420 age = CACHE_ENTRY_MAX_AGE;
1421 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1422 b_set_data(&trash, end - b_head(&trash));
1423 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1424 return 0;
1425 return 1;
1426}
1427
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001428static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001429{
1430 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1431 struct shared_block *first = block_ptr(cache_ptr);
1432 struct stream_interface *si = appctx->owner;
1433 struct channel *req = si_oc(si);
1434 struct channel *res = si_ic(si);
1435 struct htx *req_htx, *res_htx;
1436 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001437 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001438 size_t ret, total = 0;
1439
1440 res_htx = htxbuf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001441 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001442
1443 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1444 goto out;
1445
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001446 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001447 if (!b_size(&res->buf)) {
1448 si_rx_room_blk(si);
1449 goto out;
1450 }
1451
Willy Tarreauefef3232018-12-16 00:37:45 +01001452 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001453 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001454
1455 if (appctx->st0 == HTX_CACHE_INIT) {
1456 appctx->ctx.cache.next = block_ptr(cache_ptr);
1457 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1458 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001459 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001460 appctx->st0 = HTX_CACHE_HEADER;
1461 }
1462
1463 if (appctx->st0 == HTX_CACHE_HEADER) {
1464 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001465 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1466 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1467 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1468 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001469 goto error;
1470
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001471 /* In case of a conditional request, we might want to send a
1472 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001473 if (appctx->ctx.cache.send_notmodified) {
1474 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1475 /* If replacing the status code fails we need to send the full response. */
1476 appctx->ctx.cache.send_notmodified = 0;
1477 }
1478 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001479
1480 /* Skip response body for HEAD requests or in case of "304 Not
1481 * Modified" response. */
1482 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001483 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001484 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001485 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001486 }
1487
1488 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001489 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1490 if (len) {
1491 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOM);
1492 if (ret < len) {
1493 si_rx_room_blk(si);
1494 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001495 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001496 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001497 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001498 }
1499
1500 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Faulet810df062020-07-22 16:20:34 +02001501 res_htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001502 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
1503 si_rx_room_blk(si);
1504 goto out;
1505 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001506 appctx->st0 = HTX_CACHE_END;
1507 }
1508
1509 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001510 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001511 res->flags |= CF_READ_NULL;
1512 si_shutr(si);
1513 }
1514
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001515 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001516 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001517 if (total)
1518 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001519 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001520
1521 /* eat the whole request */
1522 if (co_data(req)) {
1523 req_htx = htx_from_buf(&req->buf);
1524 co_htx_skip(req, req_htx, co_data(req));
1525 htx_to_buf(req_htx, &req->buf);
1526 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001527 return;
1528
1529 error:
1530 /* Sent and HTTP error 500 */
1531 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001532 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001533 res->buf.data = b_data(errmsg);
1534 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1535 res_htx = htx_from_buf(&res->buf);
1536
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001537 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001538 appctx->st0 = HTX_CACHE_END;
1539 goto end;
1540}
1541
1542
Christopher Faulet95220e22018-12-07 17:34:39 +01001543static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001544{
1545 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001546 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001547
Christopher Faulet95220e22018-12-07 17:34:39 +01001548 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001549 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001550 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001551 }
1552
1553 /* check if a cache filter was already registered with this cache
1554 * name, if that's the case, must use it. */
1555 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001556 if (fconf->id == cache_store_flt_id) {
1557 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001558 if (cconf && strcmp((char *)cconf->c.name, name) == 0) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001559 rule->arg.act.p[0] = cconf;
1560 return 1;
1561 }
William Lallemand41db4602017-10-30 11:15:51 +01001562 }
1563 }
1564
Christopher Faulet95220e22018-12-07 17:34:39 +01001565 /* Create the filter cache config */
1566 cconf = calloc(1, sizeof(*cconf));
1567 if (!cconf) {
1568 memprintf(err, "out of memory\n");
1569 goto err;
1570 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001571 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001572 cconf->c.name = strdup(name);
1573 if (!cconf->c.name) {
1574 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001575 goto err;
1576 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001577
William Lallemand41db4602017-10-30 11:15:51 +01001578 /* register a filter to fill the cache buffer */
1579 fconf = calloc(1, sizeof(*fconf));
1580 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001581 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001582 goto err;
1583 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001584 fconf->id = cache_store_flt_id;
1585 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001586 fconf->ops = &cache_ops;
1587 LIST_ADDQ(&proxy->filter_configs, &fconf->list);
1588
Christopher Faulet95220e22018-12-07 17:34:39 +01001589 rule->arg.act.p[0] = cconf;
1590 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001591
Christopher Faulet95220e22018-12-07 17:34:39 +01001592 err:
1593 free(cconf);
1594 return 0;
1595}
1596
1597enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1598 struct act_rule *rule, char **err)
1599{
1600 rule->action = ACT_CUSTOM;
1601 rule->action_ptr = http_action_store_cache;
1602
1603 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1604 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001605
Christopher Faulet95220e22018-12-07 17:34:39 +01001606 (*orig_arg)++;
1607 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001608}
1609
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001610/* This produces a sha1 hash of the concatenation of the HTTP method,
1611 * the first occurrence of the Host header followed by the path component
1612 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001613int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001614{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001615 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001616 struct htx *htx = htxbuf(&s->req.buf);
1617 struct htx_sl *sl;
1618 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001619 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001620 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001621 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001622
William Lallemandf528fff2017-11-23 19:43:17 +01001623 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001624 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001625
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001626 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001627 uri = htx_sl_req_uri(sl); // whole uri
1628 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001629 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001630
1631 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1632 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1633 * URIs are almost always sent in absolute form with their scheme. In
1634 * this case, the scheme is almost always "https". In order to support
1635 * sharing of cache objects between H1 and H2, we'll hash the absolute
1636 * URI whenever known, or prepend "https://" + the Host header for
1637 * relative URIs. The difference will only appear on absolute HTTP/1
1638 * requests sent to an origin server, which practically is never met in
1639 * the real world so we don't care about the ability to share the same
1640 * key here.URIs are normalized from the absolute URI to an origin form as
1641 * well.
1642 */
1643 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001644 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001645 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1646 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001647 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001648 }
1649
1650 chunk_memcat(trash, uri.ptr, uri.len);
William Lallemandf528fff2017-11-23 19:43:17 +01001651
1652 /* hash everything */
1653 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001654 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001655 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1656
1657 return 1;
1658}
1659
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001660/* Looks for "If-None-Match" headers in the request and compares their value
1661 * with the one that might have been stored in the cache_entry. If any of them
1662 * matches, a "304 Not Modified" response should be sent instead of the cached
1663 * data.
1664 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001665 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1666 *
1667 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1668 * header and compare its value (date) to the one stored in the cache_entry.
1669 * If the request's date is later than the cached one, we also send a
1670 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1671 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001672 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1673 */
1674static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1675 struct cache_entry *entry)
1676{
1677 int retval = 0;
1678
1679 struct http_hdr_ctx ctx = { .blk = NULL };
1680 struct ist cache_entry_etag = IST_NULL;
1681 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001682 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001683
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001684 struct tm tm = {};
1685 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001686
1687 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001688 * cache_entry's ETag in order to perform comparisons.
1689 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001690 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001691 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001692
1693 /* A '*' matches everything. */
1694 if (isteq(ctx.value, ist("*")) != 0) {
1695 retval = 1;
1696 break;
1697 }
1698
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001699 /* No need to rebuild an etag if none was stored in the cache. */
1700 if (entry->etag_length == 0)
1701 break;
1702
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001703 /* Rebuild the stored ETag. */
1704 if (etag_buffer == NULL) {
1705 etag_buffer = get_trash_chunk();
1706
1707 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1708 (unsigned char*)b_orig(etag_buffer),
1709 entry->etag_offset, entry->etag_length) == 0) {
1710 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1711 } else {
1712 /* We could not rebuild the ETag in one go, we
1713 * won't send a "304 Not Modified" response. */
1714 break;
1715 }
1716 }
1717
1718 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1719 retval = 1;
1720 break;
1721 }
1722 }
1723
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001724 /* If the request did not contain an "If-None-Match" header, we look for
1725 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1726 if (retval == 0 && if_none_match_found == 0) {
1727 ctx.blk = NULL;
1728 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1729 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1730 if_modified_since = my_timegm(&tm);
1731
1732 /* We send a "304 Not Modified" response if the
1733 * entry's last modified date is earlier than
1734 * the one found in the "If-Modified-Since"
1735 * header. */
1736 retval = (entry->last_modified <= if_modified_since);
1737 }
1738 }
1739 }
1740
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001741 return retval;
1742}
1743
William Lallemand41db4602017-10-30 11:15:51 +01001744enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1745 struct session *sess, struct stream *s, int flags)
1746{
William Lallemand77c11972017-10-31 20:43:01 +01001747
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001748 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001749 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001750 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1751 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001752 struct shared_block *entry_block;
1753
William Lallemand77c11972017-10-31 20:43:01 +01001754
Willy Tarreau6905d182019-10-01 17:59:17 +02001755 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1756 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001757 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001758 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001759 txn->flags |= TX_CACHE_IGNORE;
1760
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001761 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001762
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001763 /* The request's hash has to be calculated for all requests, even POSTs
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001764 * or PUTs for instance because RFC7234 specifies that a successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001765 * "unsafe" method on a stored resource must invalidate it
1766 * (see RFC7234#4.4). */
1767 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001768 return ACT_RET_CONT;
1769
Willy Tarreau504455c2017-12-22 17:47:35 +01001770 if (s->txn->flags & TX_CACHE_IGNORE)
1771 return ACT_RET_CONT;
1772
Willy Tarreaua1214a52018-12-14 14:00:25 +01001773 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001774 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001775 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001776 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001777
William Lallemanda400a3a2017-11-20 19:13:12 +01001778 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001779 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001780 /* We must not use an entry that is not complete. */
1781 if (res && res->complete) {
William Lallemand77c11972017-10-31 20:43:01 +01001782 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001783 entry_block = block_ptr(res);
1784 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001785 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001786
1787 /* In case of Vary, we could have multiple entries with the same
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001788 * primary hash. We need to calculate the secondary hash in order
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001789 * to find the actual entry we want (if it exists). */
1790 if (res->secondary_key_signature) {
1791 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1792 shctx_lock(shctx_ptr(cache));
1793 sec_entry = secondary_entry_exist(cache, res,
1794 s->txn->cache_secondary_hash);
1795 if (sec_entry && sec_entry != res) {
1796 /* The wrong row was added to the hot list. */
1797 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1798 entry_block = block_ptr(sec_entry);
1799 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1800 }
1801 res = sec_entry;
1802 shctx_unlock(shctx_ptr(cache));
1803 }
1804 else
1805 res = NULL;
1806 }
1807
1808 /* We looked for a valid secondary entry and could not find one,
1809 * the request must be forwarded to the server. */
1810 if (!res) {
1811 shctx_lock(shctx_ptr(cache));
1812 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1813 shctx_unlock(shctx_ptr(cache));
1814 return ACT_RET_CONT;
1815 }
1816
William Lallemand77c11972017-10-31 20:43:01 +01001817 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001818 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001819 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001820 appctx->rule = rule;
1821 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001822 appctx->ctx.cache.next = NULL;
1823 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001824 appctx->ctx.cache.send_notmodified =
1825 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001826
1827 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001828 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_hits, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001829 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001830 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_hits, 1);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001831 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001832 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001833 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001834 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001835 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001836 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001837 }
1838 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001839 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001840
1841 /* Shared context does not need to be locked while we calculate the
1842 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001843 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001844 /* Build a complete secondary hash until the server response
1845 * tells us which fields should be kept (if any). */
1846 http_request_prebuild_full_secondary_key(s);
1847 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001848 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001849}
1850
1851
1852enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1853 struct act_rule *rule, char **err)
1854{
William Lallemand41db4602017-10-30 11:15:51 +01001855 rule->action = ACT_CUSTOM;
1856 rule->action_ptr = http_action_req_cache_use;
1857
Christopher Faulet95220e22018-12-07 17:34:39 +01001858 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001859 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001860
1861 (*orig_arg)++;
1862 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001863}
1864
1865int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1866{
1867 int err_code = 0;
1868
1869 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1870
1871 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001872 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001873 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001874 err_code |= ERR_ALERT | ERR_ABORT;
1875 goto out;
1876 }
1877
1878 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1879 err_code |= ERR_ABORT;
1880 goto out;
1881 }
1882
1883 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001884 struct cache *cache_config;
1885
William Lallemand41db4602017-10-30 11:15:51 +01001886 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1887 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001888 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001889 err_code |= ERR_ALERT | ERR_ABORT;
1890 goto out;
1891 }
1892
1893 strlcpy2(tmp_cache_config->id, args[1], 33);
1894 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001895 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001896 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001897 err_code |= ERR_WARN;
1898 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001899
1900 list_for_each_entry(cache_config, &caches_config, list) {
1901 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1902 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1903 file, linenum, tmp_cache_config->id);
1904 err_code |= ERR_ALERT | ERR_ABORT;
1905 goto out;
1906 }
1907 }
1908
William Lallemand49b44532017-11-24 18:53:43 +01001909 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001910 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001911 tmp_cache_config->maxobjsz = 0;
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001912 tmp_cache_config->max_secondary_entries = DEFAULT_MAX_SECONDARY_ENTRY;
William Lallemand41db4602017-10-30 11:15:51 +01001913 }
1914 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001915 unsigned long int maxsize;
1916 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001917
1918 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1919 err_code |= ERR_ABORT;
1920 goto out;
1921 }
1922
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001923 maxsize = strtoul(args[1], &err, 10);
1924 if (err == args[1] || *err != '\0') {
1925 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1926 file, linenum, args[1]);
1927 err_code |= ERR_ABORT;
1928 goto out;
1929 }
1930
1931 if (maxsize > (UINT_MAX >> 20)) {
1932 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1933 file, linenum, args[1], UINT_MAX >> 20);
1934 err_code |= ERR_ABORT;
1935 goto out;
1936 }
1937
William Lallemand41db4602017-10-30 11:15:51 +01001938 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001939 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001940 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001941 } else if (strcmp(args[0], "max-age") == 0) {
1942 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1943 err_code |= ERR_ABORT;
1944 goto out;
1945 }
1946
1947 if (!*args[1]) {
1948 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1949 file, linenum, args[0]);
1950 err_code |= ERR_WARN;
1951 }
1952
1953 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001954 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001955 unsigned int maxobjsz;
1956 char *err;
1957
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001958 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1959 err_code |= ERR_ABORT;
1960 goto out;
1961 }
1962
1963 if (!*args[1]) {
1964 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1965 file, linenum, args[0]);
1966 err_code |= ERR_WARN;
1967 }
1968
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001969 maxobjsz = strtoul(args[1], &err, 10);
1970 if (err == args[1] || *err != '\0') {
1971 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1972 file, linenum, args[1]);
1973 err_code |= ERR_ABORT;
1974 goto out;
1975 }
1976 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001977 } else if (strcmp(args[0], "process-vary") == 0) {
1978 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1979 err_code |= ERR_ABORT;
1980 goto out;
1981 }
1982
1983 if (!*args[1]) {
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001984 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 +01001985 file, linenum, args[0]);
1986 err_code |= ERR_WARN;
1987 }
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001988 if (strcmp(args[1], "on") == 0)
1989 tmp_cache_config->vary_processing_enabled = 1;
1990 else if (strcmp(args[1], "off") == 0)
1991 tmp_cache_config->vary_processing_enabled = 0;
1992 else {
1993 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
1994 file, linenum, args[0]);
1995 err_code |= ERR_WARN;
1996 }
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001997 } else if (strcmp(args[0], "max-secondary-entries") == 0) {
1998 unsigned int max_sec_entries;
1999 char *err;
2000
2001 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
2002 err_code |= ERR_ABORT;
2003 goto out;
2004 }
2005
2006 if (!*args[1]) {
2007 ha_warning("parsing [%s:%d]: '%s' expects a strictly positive number.\n",
2008 file, linenum, args[0]);
2009 err_code |= ERR_WARN;
2010 }
2011
2012 max_sec_entries = strtoul(args[1], &err, 10);
2013 if (err == args[1] || *err != '\0' || max_sec_entries == 0) {
2014 ha_warning("parsing [%s:%d]: max-secondary-entries wrong value '%s'\n",
2015 file, linenum, args[1]);
2016 err_code |= ERR_ABORT;
2017 goto out;
2018 }
2019 tmp_cache_config->max_secondary_entries = max_sec_entries;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002020 }
2021 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002022 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01002023 err_code |= ERR_ALERT | ERR_FATAL;
2024 goto out;
2025 }
2026out:
2027 return err_code;
2028}
2029
2030/* once the cache section is parsed */
2031
2032int cfg_post_parse_section_cache()
2033{
William Lallemand41db4602017-10-30 11:15:51 +01002034 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01002035
2036 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01002037
2038 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002039 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01002040 err_code |= ERR_FATAL | ERR_ALERT;
2041 goto out;
2042 }
2043
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002044 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002045 /* Default max. file size is a 256th of the cache size. */
2046 tmp_cache_config->maxobjsz =
2047 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002048 }
2049 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
2050 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
2051 err_code |= ERR_FATAL | ERR_ALERT;
2052 goto out;
2053 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002054
William Lallemandd1d1e222019-08-28 15:22:49 +02002055 /* add to the list of cache to init and reinit tmp_cache_config
2056 * for next cache section, if any.
2057 */
2058 LIST_ADDQ(&caches_config, &tmp_cache_config->list);
2059 tmp_cache_config = NULL;
2060 return err_code;
2061 }
2062out:
2063 free(tmp_cache_config);
2064 tmp_cache_config = NULL;
2065 return err_code;
2066
2067}
2068
2069int post_check_cache()
2070{
2071 struct proxy *px;
2072 struct cache *back, *cache_config, *cache;
2073 struct shared_context *shctx;
2074 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01002075 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02002076
2077 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
2078
2079 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
2080 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01002081
Frédéric Lécaillebc584492018-10-25 20:18:59 +02002082 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01002083 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01002084 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002085 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01002086 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002087
2088 err_code |= ERR_FATAL | ERR_ALERT;
2089 goto out;
2090 }
William Lallemanda400a3a2017-11-20 19:13:12 +01002091 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02002092 /* the cache structure is stored in the shctx and added to the
2093 * caches list, we can remove the entry from the caches_config
2094 * list */
2095 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01002096 cache = (struct cache *)shctx->data;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01002097 cache->entries = EB_ROOT;
William Lallemand41db4602017-10-30 11:15:51 +01002098 LIST_ADDQ(&caches, &cache->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002099 LIST_DEL(&cache_config->list);
2100 free(cache_config);
2101
2102 /* Find all references for this cache in the existing filters
2103 * (over all proxies) and reference it in matching filters.
2104 */
2105 for (px = proxies_list; px; px = px->next) {
2106 struct flt_conf *fconf;
2107 struct cache_flt_conf *cconf;
2108
2109 list_for_each_entry(fconf, &px->filter_configs, list) {
2110 if (fconf->id != cache_store_flt_id)
2111 continue;
2112
2113 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002114 if (strcmp(cache->id, cconf->c.name) == 0) {
William Lallemandd1d1e222019-08-28 15:22:49 +02002115 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02002116 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02002117 cconf->c.cache = cache;
2118 break;
2119 }
2120 }
2121 }
William Lallemand41db4602017-10-30 11:15:51 +01002122 }
William Lallemandd1d1e222019-08-28 15:22:49 +02002123
William Lallemand41db4602017-10-30 11:15:51 +01002124out:
William Lallemand41db4602017-10-30 11:15:51 +01002125 return err_code;
2126
William Lallemand41db4602017-10-30 11:15:51 +01002127}
2128
William Lallemand41db4602017-10-30 11:15:51 +01002129struct flt_ops cache_ops = {
2130 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01002131 .check = cache_store_check,
2132 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01002133
Christopher Faulet65554e12020-03-06 14:52:06 +01002134 /* Handle stream init/deinit */
2135 .attach = cache_store_strm_init,
2136 .detach = cache_store_strm_deinit,
2137
William Lallemand4da3f8a2017-10-31 14:33:34 +01002138 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01002139 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002140
2141 /* Filter HTTP requests and responses */
2142 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01002143 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002144 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01002145};
2146
Christopher Faulet99a17a22018-12-11 09:18:27 +01002147
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002148int accept_encoding_cmp(const void *a, const void *b)
2149{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002150 unsigned int int_a = *(unsigned int*)a;
2151 unsigned int int_b = *(unsigned int*)b;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002152
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002153 if (int_a < int_b)
2154 return -1;
2155 if (int_a > int_b)
2156 return 1;
2157 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002158}
2159
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002160
2161#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/*
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002271 * Build a hash of the accept-encoding header. The hash is split into an
2272 * encoding bitmap and an actual hash of the different encodings.
2273 * 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
2277 * client).
2278 * The hash part is built out of all the sub-parts of the value, which are
2279 * converted to lower case, hashed, sorted and then all the unique sub-hashes
2280 * are XORed into a single hash.
2281 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2282 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002283 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002284static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
2285 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002286{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002287 unsigned int values[ACCEPT_ENCODING_MAX_ENTRIES] = {};
Tim Duesterhus23b29452020-11-24 22:22:56 +01002288 size_t count = 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002289 struct accept_encoding_hash hash = {};
2290 unsigned int encoding_bmp_bl = -1;
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002291 unsigned int prev = 0, curr = 0;
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002292 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002293 unsigned int encoding_value;
2294 unsigned int rejected_encoding;
2295
2296 /* A user agent always accepts an unencoded value unless it explicitely
2297 * refuses it through an "identity;q=0" accept-encoding value. */
2298 hash.encoding_bitmap |= VARY_ENCODING_IDENTITY;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002299
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002300 /* Iterate over all the ACCEPT_ENCODING_MAX_ENTRIES first accept-encoding
2301 * values that might span acrosse multiple accept-encoding headers. */
2302 while (http_find_header(htx, hdr_name, &ctx, 0) && count < ACCEPT_ENCODING_MAX_ENTRIES) {
2303 /* Turn accept-encoding value to lower case */
2304 ist2bin_lc(istptr(ctx.value), ctx.value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002305
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002306 /* Try to identify a known encoding and to manage null weights. */
2307 if (!parse_encoding_value(ctx.value, &encoding_value, &rejected_encoding)) {
2308 if (rejected_encoding)
2309 encoding_bmp_bl &= ~encoding_value;
2310 else
2311 hash.encoding_bitmap |= encoding_value;
2312 }
2313 else {
2314 /* Unknown encoding */
2315 hash.encoding_bitmap |= VARY_ENCODING_OTHER;
2316 }
2317
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002318 values[count++] = hash_crc32(istptr(ctx.value), istlen(ctx.value));
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002319 }
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002320
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002321 /* If a "*" was found in the accepted encodings (without a null weight),
2322 * all the encoding are accepted except the ones explicitely rejected. */
2323 if (hash.encoding_bitmap & VARY_ENCODING_STAR) {
2324 hash.encoding_bitmap = ~0;
2325 }
2326
2327 /* Clear explicitely rejected encodings from the bitmap */
2328 hash.encoding_bitmap &= encoding_bmp_bl;
2329
2330 /* As per RFC7231#5.3.4, "If no Accept-Encoding field is in the request,
2331 * any content-coding is considered acceptable by the user agent". */
2332 if (count == 0)
2333 hash.encoding_bitmap = ~0;
2334
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002335 /* A request with more than ACCEPT_ENCODING_MAX_ENTRIES accepted
2336 * encodings might be illegitimate so we will not use it. */
2337 if (count == ACCEPT_ENCODING_MAX_ENTRIES)
2338 return -1;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002339
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002340 /* Sort the values alphabetically. */
2341 qsort(values, count, sizeof(*values), &accept_encoding_cmp);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002342
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002343 while (count) {
2344 curr = values[--count];
2345 if (curr != prev) {
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002346 hash.hash ^= curr;
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002347 }
2348 prev = curr;
2349 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002350
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002351 write_u32(buf, hash.encoding_bitmap);
2352 *buf_len = sizeof(hash.encoding_bitmap);
2353 write_u32(buf+*buf_len, hash.hash);
2354 *buf_len += sizeof(hash.hash);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002355
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002356 /* This function fills the hash buffer correctly even if no header was
2357 * found, hence the 0 return value (success). */
Tim Duesterhus23b29452020-11-24 22:22:56 +01002358 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002359}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002360#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002361
2362/*
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002363 * Normalizer used by default for the Referer header. It only
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002364 * calculates a simple crc of the whole value.
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002365 * Only the first occurrence of the header will be taken into account in the
2366 * hash.
2367 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2368 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002369 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002370static int default_normalizer(struct htx *htx, struct ist hdr_name,
2371 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002372{
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002373 int retval = 1;
2374 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002375
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002376 if (http_find_header(htx, hdr_name, &ctx, 1)) {
2377 retval = 0;
2378 write_u32(buf, hash_crc32(istptr(ctx.value), istlen(ctx.value)));
2379 *buf_len = sizeof(int);
2380 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002381
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002382 return retval;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002383}
2384
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002385/*
2386 * Accept-Encoding sub-hash comparison function.
2387 * Returns 0 if the hashes are alike.
2388 */
2389static int accept_encoding_hash_cmp(const void *ref_hash, const void *new_hash, unsigned int hash_len)
2390{
2391 struct accept_encoding_hash ref = {};
2392 struct accept_encoding_hash new = {};
2393
2394 ref.encoding_bitmap = read_u32(ref_hash);
2395 new.encoding_bitmap = read_u32(new_hash);
2396
2397 if (!(ref.encoding_bitmap & VARY_ENCODING_OTHER)) {
2398 /* All the bits set in the reference bitmap correspond to the
2399 * stored response' encoding and should all be set in the new
2400 * encoding bitmap in order for the client to be able to manage
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002401 * the response.
2402 *
2403 * If this is the case the cached response has encodings that
2404 * are accepted by the client. It can be served directly by
2405 * the cache (as far as the accept-encoding part is concerned).
2406 */
2407
2408 return (ref.encoding_bitmap & new.encoding_bitmap) != ref.encoding_bitmap;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002409 }
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002410 else {
2411 /* We must compare hashes only when the the response contains
2412 * unknown encodings.
2413 * Otherwise we might serve unacceptable responses if the hash
2414 * of a client's `accept-encoding` header collides with a
2415 * known encoding.
2416 */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002417
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002418 ref.hash = read_u32(ref_hash+sizeof(ref.encoding_bitmap));
2419 new.hash = read_u32(new_hash+sizeof(new.encoding_bitmap));
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002420
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002421 return ref.hash != new.hash;
2422 }
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002423}
2424
2425
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002426/*
2427 * Pre-calculate the hashes of all the supported headers (in our Vary
2428 * implementation) of a given request. We have to calculate all the hashes
2429 * in advance because the actual Vary signature won't be known until the first
2430 * response.
2431 * Only the first occurrence of every header will be taken into account in the
2432 * hash.
2433 * If the header is not present, the hash portion of the given header will be
2434 * filled with zeros.
2435 * Returns 0 in case of success.
2436 */
2437static int http_request_prebuild_full_secondary_key(struct stream *s)
2438{
Remi Tricot-Le Bretonbba29122020-12-23 18:13:44 +01002439 /* The fake signature (second parameter) will ensure that every part of the
2440 * secondary key is calculated. */
2441 return http_request_build_secondary_key(s, ~0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002442}
2443
2444
2445/*
2446 * Calculate the secondary key for a request for which we already have a known
2447 * vary signature. The key is made by aggregating hashes calculated for every
2448 * header mentioned in the vary signature.
2449 * Only the first occurrence of every header will be taken into account in the
2450 * hash.
2451 * If the header is not present, the hash portion of the given header will be
2452 * filled with zeros.
2453 * Returns 0 in case of success.
2454 */
2455static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2456{
2457 struct http_txn *txn = s->txn;
2458 struct htx *htx = htxbuf(&s->req.buf);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002459
2460 unsigned int idx;
2461 const struct vary_hashing_information *info = NULL;
2462 unsigned int hash_length = 0;
2463 int retval = 0;
2464 int offset = 0;
2465
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002466 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && retval >= 0; ++idx) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002467 info = &vary_information[idx];
2468
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002469 /* The normalizing functions will be in charge of getting the
2470 * header values from the htx. This way they can manage multiple
2471 * occurrences of their processed header. */
2472 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2473 !(retval = info->norm_fn(htx, info->hdr_name, &txn->cache_secondary_hash[offset], &hash_length))) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002474 offset += hash_length;
2475 }
2476 else {
2477 /* Fill hash with 0s. */
2478 hash_length = info->hash_length;
2479 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2480 offset += hash_length;
2481 }
2482 }
2483
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01002484 if (retval >= 0)
2485 txn->flags |= TX_CACHE_HAS_SEC_KEY;
2486
2487 return (retval < 0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002488}
2489
2490/*
2491 * Build the actual secondary key of a given request out of the prebuilt key and
2492 * the actual vary signature (extracted from the response).
2493 * Returns 0 in case of success.
2494 */
2495static int http_request_reduce_secondary_key(unsigned int vary_signature,
2496 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2497{
2498 int offset = 0;
2499 int global_offset = 0;
2500 int vary_info_count = 0;
2501 int keep = 0;
2502 unsigned int vary_idx;
2503 const struct vary_hashing_information *vary_info;
2504
2505 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2506 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2507 vary_info = &vary_information[vary_idx];
2508 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2509
2510 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2511 prebuilt_key[global_offset] &= keep;
2512 }
2513 }
2514
2515 return 0;
2516}
2517
2518
Christopher Faulet99a17a22018-12-11 09:18:27 +01002519
2520static int
2521parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2522 struct flt_conf *fconf, char **err, void *private)
2523{
2524 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002525 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002526 char *name = NULL;
2527 int pos = *cur_arg;
2528
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002529 /* Get the cache filter name. <pos> point on "cache" keyword */
2530 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002531 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002532 goto error;
2533 }
2534 name = strdup(args[pos + 1]);
2535 if (!name) {
2536 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2537 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002538 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002539 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002540
2541 /* Check if an implicit filter with the same name already exists. If so,
2542 * we remove the implicit filter to use the explicit one. */
2543 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2544 if (f->id != cache_store_flt_id)
2545 continue;
2546
2547 cconf = f->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002548 if (strcmp(name, cconf->c.name) != 0) {
Christopher Faulet99a17a22018-12-11 09:18:27 +01002549 cconf = NULL;
2550 continue;
2551 }
2552
2553 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2554 cconf = NULL;
2555 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2556 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002557 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002558 }
2559
2560 /* Remove the implicit filter. <cconf> is kept for the explicit one */
2561 LIST_DEL(&f->list);
2562 free(f);
2563 free(name);
2564 break;
2565 }
2566
2567 /* No implicit cache filter found, create configuration for the explicit one */
2568 if (!cconf) {
2569 cconf = calloc(1, sizeof(*cconf));
2570 if (!cconf) {
2571 memprintf(err, "%s: out of memory", args[*cur_arg]);
2572 goto error;
2573 }
2574 cconf->c.name = name;
2575 }
2576
2577 cconf->flags = 0;
2578 fconf->id = cache_store_flt_id;
2579 fconf->conf = cconf;
2580 fconf->ops = &cache_ops;
2581
2582 *cur_arg = pos;
2583 return 0;
2584
2585 error:
2586 free(name);
2587 free(cconf);
2588 return -1;
2589}
2590
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002591static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002592{
2593 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2594 return 1;
2595
2596 return 0;
2597}
2598
2599static int cli_io_handler_show_cache(struct appctx *appctx)
2600{
2601 struct cache* cache = appctx->ctx.cli.p0;
2602 struct stream_interface *si = appctx->owner;
2603
William Lallemand1f49a362017-11-21 20:01:26 +01002604 if (cache == NULL) {
2605 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
2606 }
2607
2608 list_for_each_entry_from(cache, &caches, list) {
2609 struct eb32_node *node = NULL;
2610 unsigned int next_key;
2611 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002612 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002613
William Lallemand1f49a362017-11-21 20:01:26 +01002614 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002615 if (!next_key) {
2616 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
2617 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002618 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002619 return 0;
2620 }
2621 }
William Lallemand1f49a362017-11-21 20:01:26 +01002622
2623 appctx->ctx.cli.p0 = cache;
2624
2625 while (1) {
2626
2627 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002628 if (!node || (node = eb32_next_dup(node)) == NULL)
2629 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002630 if (!node) {
2631 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02002632 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002633 break;
2634 }
2635
2636 entry = container_of(node, struct cache_entry, eb);
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002637 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2638 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2639 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2640 chunk_appendf(&trash, " size:%u (%u blocks), refcount:%u, expire:%d\n", block_ptr(entry)->len, block_ptr(entry)->block_count, block_ptr(entry)->refcount, entry->expire - (int)now.tv_sec);
William Lallemand1f49a362017-11-21 20:01:26 +01002641
2642 next_key = node->key + 1;
2643 appctx->ctx.cli.i0 = next_key;
2644
2645 shctx_unlock(shctx_ptr(cache));
2646
2647 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002648 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002649 return 0;
2650 }
2651 }
2652
2653 }
2654
2655 return 1;
2656
2657}
2658
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002659
2660/*
2661 * boolean, returns true if response was built out of a cache entry.
2662 */
2663static int
2664smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2665 const char *kw, void *private)
2666{
2667 smp->data.type = SMP_T_BOOL;
2668 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2669
2670 return 1;
2671}
2672
2673/*
2674 * string, returns cache name (if response came from a cache).
2675 */
2676static int
2677smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2678 const char *kw, void *private)
2679{
2680 struct appctx *appctx = NULL;
2681
2682 struct cache_flt_conf *cconf = NULL;
2683 struct cache *cache = NULL;
2684
2685 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2686 return 0;
2687
2688 /* Get appctx from the stream_interface. */
2689 appctx = si_appctx(&smp->strm->si[1]);
2690 if (appctx && appctx->rule) {
2691 cconf = appctx->rule->arg.act.p[0];
2692 if (cconf) {
2693 cache = cconf->c.cache;
2694
2695 smp->data.type = SMP_T_STR;
2696 smp->flags = SMP_F_CONST;
2697 smp->data.u.str.area = cache->id;
2698 smp->data.u.str.data = strlen(cache->id);
2699 return 1;
2700 }
2701 }
2702
2703 return 0;
2704}
2705
Christopher Faulet99a17a22018-12-11 09:18:27 +01002706/* Declare the filter parser for "cache" keyword */
2707static struct flt_kw_list filter_kws = { "CACHE", { }, {
2708 { "cache", parse_cache_flt, NULL },
2709 { NULL, NULL, NULL },
2710 }
2711};
2712
2713INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2714
William Lallemand1f49a362017-11-21 20:01:26 +01002715static struct cli_kw_list cli_kws = {{},{
William Lallemande899af82017-11-22 16:41:26 +01002716 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
2717 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002718}};
2719
Willy Tarreau0108d902018-11-25 19:14:37 +01002720INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002721
William Lallemand41db4602017-10-30 11:15:51 +01002722static struct action_kw_list http_res_actions = {
2723 .kw = {
2724 { "cache-store", parse_cache_store },
2725 { NULL, NULL }
2726 }
2727};
2728
Willy Tarreau0108d902018-11-25 19:14:37 +01002729INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2730
William Lallemand41db4602017-10-30 11:15:51 +01002731static struct action_kw_list http_req_actions = {
2732 .kw = {
2733 { "cache-use", parse_cache_use },
2734 { NULL, NULL }
2735 }
2736};
2737
Willy Tarreau0108d902018-11-25 19:14:37 +01002738INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2739
Willy Tarreau2231b632019-03-29 18:26:52 +01002740struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002741 .obj_type = OBJ_TYPE_APPLET,
2742 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002743 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002744 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002745};
2746
Willy Tarreaue6552512018-11-26 11:33:13 +01002747/* config parsers for this section */
2748REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002749REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002750
2751
2752/* Note: must not be declared <const> as its list will be overwritten */
2753static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2754 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2755 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2756 { /* END */ },
2757 }
2758};
2759
2760INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);