blob: 9485caa00584f87dfd04695baa2c8259601c2393 [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{
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100980 int effective_maxage = 0;
981 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100982 struct http_txn *txn = s->txn;
983 struct http_msg *msg = &txn->rsp;
984 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100985 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100986 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100987 struct cache *cache = cconf->c.cache;
988 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100989 struct cache_st *cache_ctx = NULL;
990 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +0100991 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200992 struct htx *htx;
993 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +0200994 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200995 int32_t pos;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100996 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100997
William Lallemand4da3f8a2017-10-31 14:33:34 +0100998 /* Don't cache if the response came from a cache */
999 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
1000 s->target == &http_cache_applet.obj_type) {
1001 goto out;
1002 }
1003
1004 /* cache only HTTP/1.1 */
1005 if (!(txn->req.flags & HTTP_MSGF_VER_11))
1006 goto out;
1007
Willy Tarreau6905d182019-10-01 17:59:17 +02001008 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001009 if (txn->meth != HTTP_METH_GET) {
1010 /* In case of successful unsafe method on a stored resource, the
1011 * cached entry must be invalidated (see RFC7234#4.4).
1012 * A "non-error response" is one with a 2xx (Successful) or 3xx
1013 * (Redirection) status code. */
1014 if (txn->status >= 200 && txn->status < 400) {
1015 switch (txn->meth) {
1016 case HTTP_METH_OPTIONS:
1017 case HTTP_METH_GET:
1018 case HTTP_METH_HEAD:
1019 case HTTP_METH_TRACE:
1020 break;
1021
1022 default: /* Any unsafe method */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001023 /* Discard any corresponding entry in case of successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001024 * unsafe request (such as PUT, POST or DELETE). */
1025 shctx_lock(shctx);
1026
1027 old = entry_exist(cconf->c.cache, txn->cache_hash);
1028 if (old) {
1029 eb32_delete(&old->eb);
1030 old->eb.key = 0;
1031 }
1032 shctx_unlock(shctx);
1033 }
1034 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001035 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001036 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001037
Willy Tarreauc9036c02019-01-11 19:38:25 +01001038 /* cache key was not computed */
1039 if (!key)
1040 goto out;
1041
William Lallemand4da3f8a2017-10-31 14:33:34 +01001042 /* cache only 200 status code */
1043 if (txn->status != 200)
1044 goto out;
1045
Christopher Faulet839791a2019-01-07 16:12:07 +01001046 /* Find the corresponding filter instance for the current stream */
1047 list_for_each_entry(filter, &s->strm_flt.filters, list) {
1048 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
1049 /* No filter ctx, don't cache anything */
1050 if (!filter->ctx)
1051 goto out;
1052 cache_ctx = filter->ctx;
1053 break;
1054 }
1055 }
1056
1057 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001058 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001059
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001060 /* Do not cache too big objects. */
1061 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
1062 htx->data + htx->extra > shctx->max_obj_size)
1063 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001064
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001065 /* Only a subset of headers are supported in our Vary implementation. If
1066 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001067 * able to use the cache. Likewise, if Vary header support is disabled,
1068 * avoid caching responses that contain such a header. */
1069 ctx.blk = NULL;
1070 if (cache->vary_processing_enabled) {
1071 if (!http_check_vary_header(htx, &vary_signature))
1072 goto out;
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001073 if (vary_signature) {
1074 /* If something went wrong during the secondary key
1075 * building, do not store the response. */
1076 if (!(txn->flags & TX_CACHE_HAS_SEC_KEY))
1077 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001078 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001079 }
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001080 }
1081 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001082 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001083 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001084
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001085 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001086
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +01001087 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001088 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001089
1090 shctx_lock(shctx);
1091 old = entry_exist(cache, txn->cache_hash);
1092 if (old) {
1093 if (vary_signature)
1094 old = secondary_entry_exist(cconf->c.cache, old,
1095 txn->cache_secondary_hash);
1096 if (old) {
1097 if (!old->complete) {
1098 /* An entry with the same primary key is already being
1099 * created, we should not try to store the current
1100 * response because it will waste space in the cache. */
1101 shctx_unlock(shctx);
1102 goto out;
1103 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001104 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001105 old->eb.key = 0;
1106 }
1107 }
1108 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1109 if (!first) {
1110 shctx_unlock(shctx);
1111 goto out;
1112 }
1113 /* the received memory is not initialized, we need at least to mark
1114 * the object as not indexed yet.
1115 */
1116 object = (struct cache_entry *)first->data;
1117 memset(object, 0, sizeof(*object));
1118 object->eb.key = key;
1119 object->secondary_key_signature = vary_signature;
1120 /* We need to temporarily set a valid expiring time until the actual one
1121 * is set by the end of this function (in case of concurrent accesses to
1122 * the same resource). This way the second access will find an existing
1123 * but not yet usable entry in the tree and will avoid storing its data. */
1124 object->expire = now.tv_sec + 2;
1125
1126 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1127 if (vary_signature)
1128 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1129
1130 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001131 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001132 object->eb.key = 0;
1133 shctx_unlock(shctx);
1134 goto out;
1135 }
1136 shctx_unlock(shctx);
1137
1138 /* reserve space for the cache_entry structure */
1139 first->len = sizeof(struct cache_entry);
1140 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001141
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001142 /* Determine the entry's maximum age (taking into account the cache's
1143 * configuration) as well as the response's explicit max age (extracted
1144 * from cache-control directives or the expires header). */
1145 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1146
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001147 ctx.blk = NULL;
1148 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
Tim Duesterhusc2942842021-01-02 22:47:17 +01001149 long long hdr_age;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001150 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1151 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1152 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001153 /* A response with an Age value greater than its
1154 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001155 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001156 if (unlikely(object->age > true_maxage))
1157 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001158 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001159 else
1160 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001161 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001162 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001163
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001164 /* Build a last-modified time that will be stored in the cache_entry and
1165 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001166 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001167
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001168 chunk_reset(&trash);
1169 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1170 struct htx_blk *blk = htx_get_blk(htx, pos);
1171 enum htx_blk_type type = htx_get_blk_type(blk);
1172 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001173
Christopher Fauletb0667472019-09-03 22:22:12 +02001174 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001175 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1176 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001177
1178 /* Look for optional ETag header.
1179 * We need to store the offset of the ETag value in order for
1180 * future conditional requests to be able to perform ETag
1181 * comparisons. */
1182 if (type == HTX_BLK_HDR) {
Tim Duesterhuse2fff102021-01-02 22:47:16 +01001183 struct ist header_name = htx_get_blk_name(htx, blk);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001184 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001185 object->etag_length = sz - istlen(header_name);
1186 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001187 }
1188 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001189 if (type == HTX_BLK_EOH)
1190 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001191 }
1192
Christopher Fauletb0667472019-09-03 22:22:12 +02001193 /* Do not cache objects if the headers are too big. */
1194 if (hdrs_len > htx->size - global.tune.maxrewrite)
1195 goto out;
1196
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001197 /* If the response has a secondary_key, fill its key part related to
1198 * encodings with the actual encoding of the response. This way any
1199 * subsequent request having the same primary key will have its accepted
1200 * encodings tested upon the cached response's one. */
1201 if (cache->vary_processing_enabled && vary_signature)
1202 set_secondary_key_encoding(htx, object->secondary_key);
1203
William Lallemand4da3f8a2017-10-31 14:33:34 +01001204 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001205 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001206 shctx_unlock(shctx);
1207 goto out;
1208 }
1209 shctx_unlock(shctx);
1210
William Lallemand4da3f8a2017-10-31 14:33:34 +01001211 /* cache the headers in a http action because it allows to chose what
1212 * to cache, for example you might want to cache a response before
1213 * modifying some HTTP headers, or on the contrary after modifying
1214 * those headers.
1215 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001216 /* does not need to be locked because it's in the "hot" list,
1217 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001218 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1219 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001220
1221 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001222 if (cache_ctx) {
1223 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001224 /* store latest value and expiration time */
1225 object->latest_validation = now.tv_sec;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001226 object->expire = now.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001227 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001228 }
1229
1230out:
1231 /* if does not cache */
1232 if (first) {
1233 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001234 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001235 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001236 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001237 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001238 shctx_row_dec_hot(shctx, first);
1239 shctx_unlock(shctx);
1240 }
1241
William Lallemand41db4602017-10-30 11:15:51 +01001242 return ACT_RET_CONT;
1243}
1244
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001245#define HTX_CACHE_INIT 0 /* Initial state. */
1246#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1247#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001248#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1249#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001250
William Lallemandecb73b12017-11-24 14:33:55 +01001251static void http_cache_applet_release(struct appctx *appctx)
1252{
Christopher Faulet95220e22018-12-07 17:34:39 +01001253 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +01001254 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001255 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001256 struct shared_block *first = block_ptr(cache_ptr);
1257
1258 shctx_lock(shctx_ptr(cache));
1259 shctx_row_dec_hot(shctx_ptr(cache), first);
1260 shctx_unlock(shctx_ptr(cache));
1261}
1262
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001263
1264static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1265 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001266{
Christopher Faulet95220e22018-12-07 17:34:39 +01001267 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1268 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001269 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001270 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001271 unsigned int max, total;
1272 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001273
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001274 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1275 if (!max)
1276 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001277 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001278 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1279 : info & 0xfffffff);
1280 if (blksz > max)
1281 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001282
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001283 blk = htx_add_blk(htx, type, blksz);
1284 if (!blk)
1285 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001286
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001287 blk->info = info;
1288 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001289 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001290 while (blksz) {
1291 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001292 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001293 offset += max;
1294 blksz -= max;
1295 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001296 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001297 if (blksz || offset == shctx->block_size) {
1298 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1299 offset = 0;
1300 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001301 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001302 appctx->ctx.cache.offset = offset;
1303 appctx->ctx.cache.next = shblk;
1304 appctx->ctx.cache.sent += total;
1305 return total;
1306}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001307
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001308static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1309 uint32_t info, struct shared_block *shblk, unsigned int offset)
1310{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001311
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001312 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1313 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1314 unsigned int max, total, rem_data;
1315 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001316
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001317 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1318 if (!max)
1319 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001320
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001321 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001322 if (appctx->ctx.cache.rem_data) {
1323 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001324 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001325 }
1326 else {
1327 blksz = (info & 0xfffffff);
1328 total = 4;
1329 }
1330 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001331 rem_data = blksz - max;
1332 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001333 }
1334
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001335 while (blksz) {
1336 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001337
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001338 max = MIN(blksz, shctx->block_size - offset);
1339 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1340 offset += sz;
1341 blksz -= sz;
1342 total += sz;
1343 if (sz < max)
1344 break;
1345 if (blksz || offset == shctx->block_size) {
1346 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1347 offset = 0;
1348 }
1349 }
1350
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001351 appctx->ctx.cache.offset = offset;
1352 appctx->ctx.cache.next = shblk;
1353 appctx->ctx.cache.sent += total;
1354 appctx->ctx.cache.rem_data = rem_data + blksz;
1355 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001356}
1357
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001358static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1359 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001360{
Christopher Faulet95220e22018-12-07 17:34:39 +01001361 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1362 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001363 struct shared_block *shblk;
1364 unsigned int offset, sz;
1365 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001366
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001367 while (len) {
1368 enum htx_blk_type type;
1369 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001370
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001371 shblk = appctx->ctx.cache.next;
1372 offset = appctx->ctx.cache.offset;
1373 if (appctx->ctx.cache.rem_data) {
1374 type = HTX_BLK_DATA;
1375 info = 0;
1376 goto add_data_blk;
1377 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001378
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001379 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001380 sz = MIN(4, shctx->block_size - offset);
1381 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1382 offset += sz;
1383 if (sz < 4) {
1384 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1385 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1386 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001387 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001388
1389 /* Get payload of the next HTX block and insert it. */
1390 type = (info >> 28);
1391 if (type != HTX_BLK_DATA)
1392 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1393 else {
1394 add_data_blk:
1395 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001396 }
1397
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001398 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001399 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001400 total += ret;
1401 len -= ret;
1402
1403 if (appctx->ctx.cache.rem_data || type == mark)
1404 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001405 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001406
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001407 return total;
1408}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001409
1410static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1411{
1412 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1413 unsigned int age;
1414 char *end;
1415
1416 chunk_reset(&trash);
1417 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1418 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1419 age = CACHE_ENTRY_MAX_AGE;
1420 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1421 b_set_data(&trash, end - b_head(&trash));
1422 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1423 return 0;
1424 return 1;
1425}
1426
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001427static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001428{
1429 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1430 struct shared_block *first = block_ptr(cache_ptr);
1431 struct stream_interface *si = appctx->owner;
1432 struct channel *req = si_oc(si);
1433 struct channel *res = si_ic(si);
1434 struct htx *req_htx, *res_htx;
1435 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001436 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001437 size_t ret, total = 0;
1438
1439 res_htx = htxbuf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001440 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001441
1442 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1443 goto out;
1444
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001445 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001446 if (!b_size(&res->buf)) {
1447 si_rx_room_blk(si);
1448 goto out;
1449 }
1450
Willy Tarreauefef3232018-12-16 00:37:45 +01001451 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001452 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001453
1454 if (appctx->st0 == HTX_CACHE_INIT) {
1455 appctx->ctx.cache.next = block_ptr(cache_ptr);
1456 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1457 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001458 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001459 appctx->st0 = HTX_CACHE_HEADER;
1460 }
1461
1462 if (appctx->st0 == HTX_CACHE_HEADER) {
1463 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001464 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1465 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1466 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1467 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001468 goto error;
1469
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001470 /* In case of a conditional request, we might want to send a
1471 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001472 if (appctx->ctx.cache.send_notmodified) {
1473 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1474 /* If replacing the status code fails we need to send the full response. */
1475 appctx->ctx.cache.send_notmodified = 0;
1476 }
1477 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001478
1479 /* Skip response body for HEAD requests or in case of "304 Not
1480 * Modified" response. */
1481 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001482 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001483 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001484 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001485 }
1486
1487 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001488 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1489 if (len) {
1490 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOM);
1491 if (ret < len) {
1492 si_rx_room_blk(si);
1493 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001494 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001495 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001496 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001497 }
1498
1499 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Faulet810df062020-07-22 16:20:34 +02001500 res_htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001501 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
1502 si_rx_room_blk(si);
1503 goto out;
1504 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001505 appctx->st0 = HTX_CACHE_END;
1506 }
1507
1508 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001509 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001510 res->flags |= CF_READ_NULL;
1511 si_shutr(si);
1512 }
1513
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001514 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001515 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001516 if (total)
1517 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001518 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001519
1520 /* eat the whole request */
1521 if (co_data(req)) {
1522 req_htx = htx_from_buf(&req->buf);
1523 co_htx_skip(req, req_htx, co_data(req));
1524 htx_to_buf(req_htx, &req->buf);
1525 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001526 return;
1527
1528 error:
1529 /* Sent and HTTP error 500 */
1530 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001531 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001532 res->buf.data = b_data(errmsg);
1533 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1534 res_htx = htx_from_buf(&res->buf);
1535
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001536 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001537 appctx->st0 = HTX_CACHE_END;
1538 goto end;
1539}
1540
1541
Christopher Faulet95220e22018-12-07 17:34:39 +01001542static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001543{
1544 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001545 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001546
Christopher Faulet95220e22018-12-07 17:34:39 +01001547 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001548 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001549 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001550 }
1551
1552 /* check if a cache filter was already registered with this cache
1553 * name, if that's the case, must use it. */
1554 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001555 if (fconf->id == cache_store_flt_id) {
1556 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001557 if (cconf && strcmp((char *)cconf->c.name, name) == 0) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001558 rule->arg.act.p[0] = cconf;
1559 return 1;
1560 }
William Lallemand41db4602017-10-30 11:15:51 +01001561 }
1562 }
1563
Christopher Faulet95220e22018-12-07 17:34:39 +01001564 /* Create the filter cache config */
1565 cconf = calloc(1, sizeof(*cconf));
1566 if (!cconf) {
1567 memprintf(err, "out of memory\n");
1568 goto err;
1569 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001570 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001571 cconf->c.name = strdup(name);
1572 if (!cconf->c.name) {
1573 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001574 goto err;
1575 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001576
William Lallemand41db4602017-10-30 11:15:51 +01001577 /* register a filter to fill the cache buffer */
1578 fconf = calloc(1, sizeof(*fconf));
1579 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001580 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001581 goto err;
1582 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001583 fconf->id = cache_store_flt_id;
1584 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001585 fconf->ops = &cache_ops;
1586 LIST_ADDQ(&proxy->filter_configs, &fconf->list);
1587
Christopher Faulet95220e22018-12-07 17:34:39 +01001588 rule->arg.act.p[0] = cconf;
1589 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001590
Christopher Faulet95220e22018-12-07 17:34:39 +01001591 err:
1592 free(cconf);
1593 return 0;
1594}
1595
1596enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1597 struct act_rule *rule, char **err)
1598{
1599 rule->action = ACT_CUSTOM;
1600 rule->action_ptr = http_action_store_cache;
1601
1602 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1603 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001604
Christopher Faulet95220e22018-12-07 17:34:39 +01001605 (*orig_arg)++;
1606 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001607}
1608
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001609/* This produces a sha1 hash of the concatenation of the HTTP method,
1610 * the first occurrence of the Host header followed by the path component
1611 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001612int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001613{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001614 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001615 struct htx *htx = htxbuf(&s->req.buf);
1616 struct htx_sl *sl;
1617 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001618 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001619 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001620 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001621
William Lallemandf528fff2017-11-23 19:43:17 +01001622 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001623 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001624
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001625 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001626 uri = htx_sl_req_uri(sl); // whole uri
1627 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001628 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001629
1630 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1631 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1632 * URIs are almost always sent in absolute form with their scheme. In
1633 * this case, the scheme is almost always "https". In order to support
1634 * sharing of cache objects between H1 and H2, we'll hash the absolute
1635 * URI whenever known, or prepend "https://" + the Host header for
1636 * relative URIs. The difference will only appear on absolute HTTP/1
1637 * requests sent to an origin server, which practically is never met in
1638 * the real world so we don't care about the ability to share the same
1639 * key here.URIs are normalized from the absolute URI to an origin form as
1640 * well.
1641 */
1642 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001643 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001644 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1645 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001646 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001647 }
1648
1649 chunk_memcat(trash, uri.ptr, uri.len);
William Lallemandf528fff2017-11-23 19:43:17 +01001650
1651 /* hash everything */
1652 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001653 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001654 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1655
1656 return 1;
1657}
1658
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001659/* Looks for "If-None-Match" headers in the request and compares their value
1660 * with the one that might have been stored in the cache_entry. If any of them
1661 * matches, a "304 Not Modified" response should be sent instead of the cached
1662 * data.
1663 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001664 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1665 *
1666 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1667 * header and compare its value (date) to the one stored in the cache_entry.
1668 * If the request's date is later than the cached one, we also send a
1669 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1670 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001671 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1672 */
1673static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1674 struct cache_entry *entry)
1675{
1676 int retval = 0;
1677
1678 struct http_hdr_ctx ctx = { .blk = NULL };
1679 struct ist cache_entry_etag = IST_NULL;
1680 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001681 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001682
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001683 struct tm tm = {};
1684 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001685
1686 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001687 * cache_entry's ETag in order to perform comparisons.
1688 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001689 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001690 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001691
1692 /* A '*' matches everything. */
1693 if (isteq(ctx.value, ist("*")) != 0) {
1694 retval = 1;
1695 break;
1696 }
1697
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001698 /* No need to rebuild an etag if none was stored in the cache. */
1699 if (entry->etag_length == 0)
1700 break;
1701
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001702 /* Rebuild the stored ETag. */
1703 if (etag_buffer == NULL) {
1704 etag_buffer = get_trash_chunk();
1705
1706 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1707 (unsigned char*)b_orig(etag_buffer),
1708 entry->etag_offset, entry->etag_length) == 0) {
1709 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1710 } else {
1711 /* We could not rebuild the ETag in one go, we
1712 * won't send a "304 Not Modified" response. */
1713 break;
1714 }
1715 }
1716
1717 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1718 retval = 1;
1719 break;
1720 }
1721 }
1722
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001723 /* If the request did not contain an "If-None-Match" header, we look for
1724 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1725 if (retval == 0 && if_none_match_found == 0) {
1726 ctx.blk = NULL;
1727 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1728 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1729 if_modified_since = my_timegm(&tm);
1730
1731 /* We send a "304 Not Modified" response if the
1732 * entry's last modified date is earlier than
1733 * the one found in the "If-Modified-Since"
1734 * header. */
1735 retval = (entry->last_modified <= if_modified_since);
1736 }
1737 }
1738 }
1739
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001740 return retval;
1741}
1742
William Lallemand41db4602017-10-30 11:15:51 +01001743enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1744 struct session *sess, struct stream *s, int flags)
1745{
William Lallemand77c11972017-10-31 20:43:01 +01001746
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001747 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001748 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001749 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1750 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001751 struct shared_block *entry_block;
1752
William Lallemand77c11972017-10-31 20:43:01 +01001753
Willy Tarreau6905d182019-10-01 17:59:17 +02001754 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1755 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001756 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001757 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001758 txn->flags |= TX_CACHE_IGNORE;
1759
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001760 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001761
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001762 /* The request's hash has to be calculated for all requests, even POSTs
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001763 * or PUTs for instance because RFC7234 specifies that a successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001764 * "unsafe" method on a stored resource must invalidate it
1765 * (see RFC7234#4.4). */
1766 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001767 return ACT_RET_CONT;
1768
Willy Tarreau504455c2017-12-22 17:47:35 +01001769 if (s->txn->flags & TX_CACHE_IGNORE)
1770 return ACT_RET_CONT;
1771
Willy Tarreaua1214a52018-12-14 14:00:25 +01001772 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001773 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001774 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001775 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001776
William Lallemanda400a3a2017-11-20 19:13:12 +01001777 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001778 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001779 /* We must not use an entry that is not complete. */
1780 if (res && res->complete) {
William Lallemand77c11972017-10-31 20:43:01 +01001781 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001782 entry_block = block_ptr(res);
1783 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001784 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001785
1786 /* In case of Vary, we could have multiple entries with the same
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001787 * primary hash. We need to calculate the secondary hash in order
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001788 * to find the actual entry we want (if it exists). */
1789 if (res->secondary_key_signature) {
1790 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1791 shctx_lock(shctx_ptr(cache));
1792 sec_entry = secondary_entry_exist(cache, res,
1793 s->txn->cache_secondary_hash);
1794 if (sec_entry && sec_entry != res) {
1795 /* The wrong row was added to the hot list. */
1796 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1797 entry_block = block_ptr(sec_entry);
1798 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1799 }
1800 res = sec_entry;
1801 shctx_unlock(shctx_ptr(cache));
1802 }
1803 else
1804 res = NULL;
1805 }
1806
1807 /* We looked for a valid secondary entry and could not find one,
1808 * the request must be forwarded to the server. */
1809 if (!res) {
1810 shctx_lock(shctx_ptr(cache));
1811 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1812 shctx_unlock(shctx_ptr(cache));
1813 return ACT_RET_CONT;
1814 }
1815
William Lallemand77c11972017-10-31 20:43:01 +01001816 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001817 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001818 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001819 appctx->rule = rule;
1820 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001821 appctx->ctx.cache.next = NULL;
1822 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001823 appctx->ctx.cache.send_notmodified =
1824 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001825
1826 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001827 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_hits, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001828 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001829 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_hits, 1);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001830 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001831 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001832 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001833 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001834 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001835 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001836 }
1837 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001838 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001839
1840 /* Shared context does not need to be locked while we calculate the
1841 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001842 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001843 /* Build a complete secondary hash until the server response
1844 * tells us which fields should be kept (if any). */
1845 http_request_prebuild_full_secondary_key(s);
1846 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001847 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001848}
1849
1850
1851enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1852 struct act_rule *rule, char **err)
1853{
William Lallemand41db4602017-10-30 11:15:51 +01001854 rule->action = ACT_CUSTOM;
1855 rule->action_ptr = http_action_req_cache_use;
1856
Christopher Faulet95220e22018-12-07 17:34:39 +01001857 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001858 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001859
1860 (*orig_arg)++;
1861 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001862}
1863
1864int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1865{
1866 int err_code = 0;
1867
1868 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1869
1870 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001871 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001872 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001873 err_code |= ERR_ALERT | ERR_ABORT;
1874 goto out;
1875 }
1876
1877 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1878 err_code |= ERR_ABORT;
1879 goto out;
1880 }
1881
1882 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001883 struct cache *cache_config;
1884
William Lallemand41db4602017-10-30 11:15:51 +01001885 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1886 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001887 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001888 err_code |= ERR_ALERT | ERR_ABORT;
1889 goto out;
1890 }
1891
1892 strlcpy2(tmp_cache_config->id, args[1], 33);
1893 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001894 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001895 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001896 err_code |= ERR_WARN;
1897 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001898
1899 list_for_each_entry(cache_config, &caches_config, list) {
1900 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1901 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1902 file, linenum, tmp_cache_config->id);
1903 err_code |= ERR_ALERT | ERR_ABORT;
1904 goto out;
1905 }
1906 }
1907
William Lallemand49b44532017-11-24 18:53:43 +01001908 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001909 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001910 tmp_cache_config->maxobjsz = 0;
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001911 tmp_cache_config->max_secondary_entries = DEFAULT_MAX_SECONDARY_ENTRY;
William Lallemand41db4602017-10-30 11:15:51 +01001912 }
1913 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001914 unsigned long int maxsize;
1915 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001916
1917 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1918 err_code |= ERR_ABORT;
1919 goto out;
1920 }
1921
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001922 maxsize = strtoul(args[1], &err, 10);
1923 if (err == args[1] || *err != '\0') {
1924 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1925 file, linenum, args[1]);
1926 err_code |= ERR_ABORT;
1927 goto out;
1928 }
1929
1930 if (maxsize > (UINT_MAX >> 20)) {
1931 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1932 file, linenum, args[1], UINT_MAX >> 20);
1933 err_code |= ERR_ABORT;
1934 goto out;
1935 }
1936
William Lallemand41db4602017-10-30 11:15:51 +01001937 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001938 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001939 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001940 } else if (strcmp(args[0], "max-age") == 0) {
1941 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1942 err_code |= ERR_ABORT;
1943 goto out;
1944 }
1945
1946 if (!*args[1]) {
1947 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1948 file, linenum, args[0]);
1949 err_code |= ERR_WARN;
1950 }
1951
1952 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001953 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001954 unsigned int maxobjsz;
1955 char *err;
1956
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001957 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1958 err_code |= ERR_ABORT;
1959 goto out;
1960 }
1961
1962 if (!*args[1]) {
1963 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1964 file, linenum, args[0]);
1965 err_code |= ERR_WARN;
1966 }
1967
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001968 maxobjsz = strtoul(args[1], &err, 10);
1969 if (err == args[1] || *err != '\0') {
1970 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1971 file, linenum, args[1]);
1972 err_code |= ERR_ABORT;
1973 goto out;
1974 }
1975 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001976 } else if (strcmp(args[0], "process-vary") == 0) {
1977 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1978 err_code |= ERR_ABORT;
1979 goto out;
1980 }
1981
1982 if (!*args[1]) {
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001983 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 +01001984 file, linenum, args[0]);
1985 err_code |= ERR_WARN;
1986 }
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001987 if (strcmp(args[1], "on") == 0)
1988 tmp_cache_config->vary_processing_enabled = 1;
1989 else if (strcmp(args[1], "off") == 0)
1990 tmp_cache_config->vary_processing_enabled = 0;
1991 else {
1992 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
1993 file, linenum, args[0]);
1994 err_code |= ERR_WARN;
1995 }
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001996 } else if (strcmp(args[0], "max-secondary-entries") == 0) {
1997 unsigned int max_sec_entries;
1998 char *err;
1999
2000 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
2001 err_code |= ERR_ABORT;
2002 goto out;
2003 }
2004
2005 if (!*args[1]) {
2006 ha_warning("parsing [%s:%d]: '%s' expects a strictly positive number.\n",
2007 file, linenum, args[0]);
2008 err_code |= ERR_WARN;
2009 }
2010
2011 max_sec_entries = strtoul(args[1], &err, 10);
2012 if (err == args[1] || *err != '\0' || max_sec_entries == 0) {
2013 ha_warning("parsing [%s:%d]: max-secondary-entries wrong value '%s'\n",
2014 file, linenum, args[1]);
2015 err_code |= ERR_ABORT;
2016 goto out;
2017 }
2018 tmp_cache_config->max_secondary_entries = max_sec_entries;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002019 }
2020 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002021 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01002022 err_code |= ERR_ALERT | ERR_FATAL;
2023 goto out;
2024 }
2025out:
2026 return err_code;
2027}
2028
2029/* once the cache section is parsed */
2030
2031int cfg_post_parse_section_cache()
2032{
William Lallemand41db4602017-10-30 11:15:51 +01002033 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01002034
2035 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01002036
2037 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002038 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01002039 err_code |= ERR_FATAL | ERR_ALERT;
2040 goto out;
2041 }
2042
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002043 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002044 /* Default max. file size is a 256th of the cache size. */
2045 tmp_cache_config->maxobjsz =
2046 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002047 }
2048 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
2049 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
2050 err_code |= ERR_FATAL | ERR_ALERT;
2051 goto out;
2052 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002053
William Lallemandd1d1e222019-08-28 15:22:49 +02002054 /* add to the list of cache to init and reinit tmp_cache_config
2055 * for next cache section, if any.
2056 */
2057 LIST_ADDQ(&caches_config, &tmp_cache_config->list);
2058 tmp_cache_config = NULL;
2059 return err_code;
2060 }
2061out:
2062 free(tmp_cache_config);
2063 tmp_cache_config = NULL;
2064 return err_code;
2065
2066}
2067
2068int post_check_cache()
2069{
2070 struct proxy *px;
2071 struct cache *back, *cache_config, *cache;
2072 struct shared_context *shctx;
2073 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01002074 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02002075
2076 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
2077
2078 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
2079 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01002080
Frédéric Lécaillebc584492018-10-25 20:18:59 +02002081 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01002082 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01002083 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002084 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01002085 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002086
2087 err_code |= ERR_FATAL | ERR_ALERT;
2088 goto out;
2089 }
William Lallemanda400a3a2017-11-20 19:13:12 +01002090 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02002091 /* the cache structure is stored in the shctx and added to the
2092 * caches list, we can remove the entry from the caches_config
2093 * list */
2094 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01002095 cache = (struct cache *)shctx->data;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01002096 cache->entries = EB_ROOT;
William Lallemand41db4602017-10-30 11:15:51 +01002097 LIST_ADDQ(&caches, &cache->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002098 LIST_DEL(&cache_config->list);
2099 free(cache_config);
2100
2101 /* Find all references for this cache in the existing filters
2102 * (over all proxies) and reference it in matching filters.
2103 */
2104 for (px = proxies_list; px; px = px->next) {
2105 struct flt_conf *fconf;
2106 struct cache_flt_conf *cconf;
2107
2108 list_for_each_entry(fconf, &px->filter_configs, list) {
2109 if (fconf->id != cache_store_flt_id)
2110 continue;
2111
2112 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002113 if (strcmp(cache->id, cconf->c.name) == 0) {
William Lallemandd1d1e222019-08-28 15:22:49 +02002114 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02002115 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02002116 cconf->c.cache = cache;
2117 break;
2118 }
2119 }
2120 }
William Lallemand41db4602017-10-30 11:15:51 +01002121 }
William Lallemandd1d1e222019-08-28 15:22:49 +02002122
William Lallemand41db4602017-10-30 11:15:51 +01002123out:
William Lallemand41db4602017-10-30 11:15:51 +01002124 return err_code;
2125
William Lallemand41db4602017-10-30 11:15:51 +01002126}
2127
William Lallemand41db4602017-10-30 11:15:51 +01002128struct flt_ops cache_ops = {
2129 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01002130 .check = cache_store_check,
2131 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01002132
Christopher Faulet65554e12020-03-06 14:52:06 +01002133 /* Handle stream init/deinit */
2134 .attach = cache_store_strm_init,
2135 .detach = cache_store_strm_deinit,
2136
William Lallemand4da3f8a2017-10-31 14:33:34 +01002137 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01002138 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002139
2140 /* Filter HTTP requests and responses */
2141 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01002142 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002143 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01002144};
2145
Christopher Faulet99a17a22018-12-11 09:18:27 +01002146
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002147int accept_encoding_cmp(const void *a, const void *b)
2148{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002149 unsigned int int_a = *(unsigned int*)a;
2150 unsigned int int_b = *(unsigned int*)b;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002151
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002152 if (int_a < int_b)
2153 return -1;
2154 if (int_a > int_b)
2155 return 1;
2156 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002157}
2158
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002159
2160#define CHECK_ENCODING(str, encoding_name, encoding_value) \
2161 ({ \
2162 int retval = 0; \
2163 if (istmatch(str, (struct ist){ .ptr = encoding_name+1, .len = sizeof(encoding_name) - 2 })) { \
2164 retval = encoding_value; \
2165 encoding = istadv(encoding, sizeof(encoding_name) - 2); \
2166 } \
2167 (retval); \
2168 })
2169
2170/*
2171 * Parse the encoding <encoding> and try to match the encoding part upon an
2172 * encoding list of explicitly supported encodings (which all have a specific
2173 * bit in an encoding bitmap). If a weight is included in the value, find out if
2174 * it is null or not. The bit value will be set in the <encoding_value>
2175 * parameter and the <has_null_weight> will be set to 1 if the weight is strictly
2176 * 0, 1 otherwise.
2177 * The encodings list is extracted from
2178 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml.
2179 * Returns 0 in case of success and -1 in case of error.
2180 */
2181static int parse_encoding_value(struct ist encoding, unsigned int *encoding_value,
2182 unsigned int *has_null_weight)
2183{
2184 int retval = 0;
2185
2186 if (!encoding_value)
2187 return -1;
2188
2189 if (!istlen(encoding))
2190 return -1; /* Invalid encoding */
2191
2192 *encoding_value = 0;
2193 if (has_null_weight)
2194 *has_null_weight = 0;
2195
2196 switch (*encoding.ptr) {
2197 case 'a':
2198 encoding = istadv(encoding, 1);
2199 *encoding_value = CHECK_ENCODING(encoding, "aes128gcm", VARY_ENCODING_AES128GCM);
2200 break;
2201 case 'b':
2202 encoding = istadv(encoding, 1);
2203 *encoding_value = CHECK_ENCODING(encoding, "br", VARY_ENCODING_BR);
2204 break;
2205 case 'c':
2206 encoding = istadv(encoding, 1);
2207 *encoding_value = CHECK_ENCODING(encoding, "compress", VARY_ENCODING_COMPRESS);
2208 break;
2209 case 'd':
2210 encoding = istadv(encoding, 1);
2211 *encoding_value = CHECK_ENCODING(encoding, "deflate", VARY_ENCODING_DEFLATE);
2212 break;
2213 case 'e':
2214 encoding = istadv(encoding, 1);
2215 *encoding_value = CHECK_ENCODING(encoding, "exi", VARY_ENCODING_EXI);
2216 break;
2217 case 'g':
2218 encoding = istadv(encoding, 1);
2219 *encoding_value = CHECK_ENCODING(encoding, "gzip", VARY_ENCODING_GZIP);
2220 break;
2221 case 'i':
2222 encoding = istadv(encoding, 1);
2223 *encoding_value = CHECK_ENCODING(encoding, "identity", VARY_ENCODING_IDENTITY);
2224 break;
2225 case 'p':
2226 encoding = istadv(encoding, 1);
2227 *encoding_value = CHECK_ENCODING(encoding, "pack200-gzip", VARY_ENCODING_PACK200_GZIP);
2228 break;
2229 case 'x':
2230 encoding = istadv(encoding, 1);
2231 *encoding_value = CHECK_ENCODING(encoding, "x-gzip", VARY_ENCODING_GZIP);
2232 if (!*encoding_value)
2233 *encoding_value = CHECK_ENCODING(encoding, "x-compress", VARY_ENCODING_COMPRESS);
2234 break;
2235 case 'z':
2236 encoding = istadv(encoding, 1);
2237 *encoding_value = CHECK_ENCODING(encoding, "zstd", VARY_ENCODING_ZSTD);
2238 break;
2239 case '*':
2240 encoding = istadv(encoding, 1);
2241 *encoding_value = VARY_ENCODING_STAR;
2242 break;
2243 default:
2244 retval = -1; /* Unmanaged encoding */
2245 break;
2246 }
2247
2248 /* Process the optional weight part of the encoding. */
2249 if (*encoding_value) {
2250 encoding = http_trim_leading_spht(encoding);
2251 if (istlen(encoding)) {
2252 if (*encoding.ptr != ';')
2253 return -1;
2254
2255 if (has_null_weight) {
2256 encoding = istadv(encoding, 1);
2257
2258 encoding = http_trim_leading_spht(encoding);
2259
2260 *has_null_weight = isteq(encoding, ist("q=0"));
2261 }
2262 }
2263 }
2264
2265 return retval;
2266}
2267
Tim Duesterhus23b29452020-11-24 22:22:56 +01002268#define ACCEPT_ENCODING_MAX_ENTRIES 16
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002269/*
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002270 * Build a hash of the accept-encoding header. The hash is split into an
2271 * encoding bitmap and an actual hash of the different encodings.
2272 * The bitmap is built by matching every sub-part of the accept-encoding value
2273 * with a subset of explicitly supported encodings, which all have their own bit
2274 * in the bitmap. This bitmap will be used to determine if a response can be
2275 * served to a client (that is if it has an encoding that is accepted by the
2276 * client).
2277 * The hash part is built out of all the sub-parts of the value, which are
2278 * converted to lower case, hashed, sorted and then all the unique sub-hashes
2279 * are XORed into a single hash.
2280 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2281 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002282 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002283static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
2284 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002285{
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002286 unsigned int values[ACCEPT_ENCODING_MAX_ENTRIES] = {};
Tim Duesterhus23b29452020-11-24 22:22:56 +01002287 size_t count = 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002288 struct accept_encoding_hash hash = {};
2289 unsigned int encoding_bmp_bl = -1;
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002290 unsigned int prev = 0, curr = 0;
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002291 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002292 unsigned int encoding_value;
2293 unsigned int rejected_encoding;
2294
2295 /* A user agent always accepts an unencoded value unless it explicitely
2296 * refuses it through an "identity;q=0" accept-encoding value. */
2297 hash.encoding_bitmap |= VARY_ENCODING_IDENTITY;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002298
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002299 /* Iterate over all the ACCEPT_ENCODING_MAX_ENTRIES first accept-encoding
2300 * values that might span acrosse multiple accept-encoding headers. */
2301 while (http_find_header(htx, hdr_name, &ctx, 0) && count < ACCEPT_ENCODING_MAX_ENTRIES) {
2302 /* Turn accept-encoding value to lower case */
2303 ist2bin_lc(istptr(ctx.value), ctx.value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002304
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002305 /* Try to identify a known encoding and to manage null weights. */
2306 if (!parse_encoding_value(ctx.value, &encoding_value, &rejected_encoding)) {
2307 if (rejected_encoding)
2308 encoding_bmp_bl &= ~encoding_value;
2309 else
2310 hash.encoding_bitmap |= encoding_value;
2311 }
2312 else {
2313 /* Unknown encoding */
2314 hash.encoding_bitmap |= VARY_ENCODING_OTHER;
2315 }
2316
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002317 values[count++] = hash_crc32(istptr(ctx.value), istlen(ctx.value));
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002318 }
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002319
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002320 /* If a "*" was found in the accepted encodings (without a null weight),
2321 * all the encoding are accepted except the ones explicitely rejected. */
2322 if (hash.encoding_bitmap & VARY_ENCODING_STAR) {
2323 hash.encoding_bitmap = ~0;
2324 }
2325
2326 /* Clear explicitely rejected encodings from the bitmap */
2327 hash.encoding_bitmap &= encoding_bmp_bl;
2328
2329 /* As per RFC7231#5.3.4, "If no Accept-Encoding field is in the request,
2330 * any content-coding is considered acceptable by the user agent". */
2331 if (count == 0)
2332 hash.encoding_bitmap = ~0;
2333
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002334 /* A request with more than ACCEPT_ENCODING_MAX_ENTRIES accepted
2335 * encodings might be illegitimate so we will not use it. */
2336 if (count == ACCEPT_ENCODING_MAX_ENTRIES)
2337 return -1;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002338
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002339 /* Sort the values alphabetically. */
2340 qsort(values, count, sizeof(*values), &accept_encoding_cmp);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002341
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002342 while (count) {
2343 curr = values[--count];
2344 if (curr != prev) {
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002345 hash.hash ^= curr;
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002346 }
2347 prev = curr;
2348 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002349
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002350 write_u32(buf, hash.encoding_bitmap);
2351 *buf_len = sizeof(hash.encoding_bitmap);
2352 write_u32(buf+*buf_len, hash.hash);
2353 *buf_len += sizeof(hash.hash);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002354
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002355 /* This function fills the hash buffer correctly even if no header was
2356 * found, hence the 0 return value (success). */
Tim Duesterhus23b29452020-11-24 22:22:56 +01002357 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002358}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002359#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002360
2361/*
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002362 * Normalizer used by default for the Referer header. It only
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002363 * calculates a simple crc of the whole value.
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002364 * Only the first occurrence of the header will be taken into account in the
2365 * hash.
2366 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2367 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002368 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002369static int default_normalizer(struct htx *htx, struct ist hdr_name,
2370 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002371{
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002372 int retval = 1;
2373 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002374
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002375 if (http_find_header(htx, hdr_name, &ctx, 1)) {
2376 retval = 0;
2377 write_u32(buf, hash_crc32(istptr(ctx.value), istlen(ctx.value)));
2378 *buf_len = sizeof(int);
2379 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002380
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002381 return retval;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002382}
2383
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002384/*
2385 * Accept-Encoding sub-hash comparison function.
2386 * Returns 0 if the hashes are alike.
2387 */
2388static int accept_encoding_hash_cmp(const void *ref_hash, const void *new_hash, unsigned int hash_len)
2389{
2390 struct accept_encoding_hash ref = {};
2391 struct accept_encoding_hash new = {};
2392
2393 ref.encoding_bitmap = read_u32(ref_hash);
2394 new.encoding_bitmap = read_u32(new_hash);
2395
2396 if (!(ref.encoding_bitmap & VARY_ENCODING_OTHER)) {
2397 /* All the bits set in the reference bitmap correspond to the
2398 * stored response' encoding and should all be set in the new
2399 * encoding bitmap in order for the client to be able to manage
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002400 * the response.
2401 *
2402 * If this is the case the cached response has encodings that
2403 * are accepted by the client. It can be served directly by
2404 * the cache (as far as the accept-encoding part is concerned).
2405 */
2406
2407 return (ref.encoding_bitmap & new.encoding_bitmap) != ref.encoding_bitmap;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002408 }
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002409 else {
2410 /* We must compare hashes only when the the response contains
2411 * unknown encodings.
2412 * Otherwise we might serve unacceptable responses if the hash
2413 * of a client's `accept-encoding` header collides with a
2414 * known encoding.
2415 */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002416
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002417 ref.hash = read_u32(ref_hash+sizeof(ref.encoding_bitmap));
2418 new.hash = read_u32(new_hash+sizeof(new.encoding_bitmap));
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002419
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002420 return ref.hash != new.hash;
2421 }
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002422}
2423
2424
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002425/*
2426 * Pre-calculate the hashes of all the supported headers (in our Vary
2427 * implementation) of a given request. We have to calculate all the hashes
2428 * in advance because the actual Vary signature won't be known until the first
2429 * response.
2430 * Only the first occurrence of every header will be taken into account in the
2431 * hash.
2432 * If the header is not present, the hash portion of the given header will be
2433 * filled with zeros.
2434 * Returns 0 in case of success.
2435 */
2436static int http_request_prebuild_full_secondary_key(struct stream *s)
2437{
Remi Tricot-Le Bretonbba29122020-12-23 18:13:44 +01002438 /* The fake signature (second parameter) will ensure that every part of the
2439 * secondary key is calculated. */
2440 return http_request_build_secondary_key(s, ~0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002441}
2442
2443
2444/*
2445 * Calculate the secondary key for a request for which we already have a known
2446 * vary signature. The key is made by aggregating hashes calculated for every
2447 * header mentioned in the vary signature.
2448 * Only the first occurrence of every header will be taken into account in the
2449 * hash.
2450 * If the header is not present, the hash portion of the given header will be
2451 * filled with zeros.
2452 * Returns 0 in case of success.
2453 */
2454static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2455{
2456 struct http_txn *txn = s->txn;
2457 struct htx *htx = htxbuf(&s->req.buf);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002458
2459 unsigned int idx;
2460 const struct vary_hashing_information *info = NULL;
2461 unsigned int hash_length = 0;
2462 int retval = 0;
2463 int offset = 0;
2464
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002465 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && retval >= 0; ++idx) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002466 info = &vary_information[idx];
2467
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002468 /* The normalizing functions will be in charge of getting the
2469 * header values from the htx. This way they can manage multiple
2470 * occurrences of their processed header. */
2471 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2472 !(retval = info->norm_fn(htx, info->hdr_name, &txn->cache_secondary_hash[offset], &hash_length))) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002473 offset += hash_length;
2474 }
2475 else {
2476 /* Fill hash with 0s. */
2477 hash_length = info->hash_length;
2478 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2479 offset += hash_length;
2480 }
2481 }
2482
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01002483 if (retval >= 0)
2484 txn->flags |= TX_CACHE_HAS_SEC_KEY;
2485
2486 return (retval < 0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002487}
2488
2489/*
2490 * Build the actual secondary key of a given request out of the prebuilt key and
2491 * the actual vary signature (extracted from the response).
2492 * Returns 0 in case of success.
2493 */
2494static int http_request_reduce_secondary_key(unsigned int vary_signature,
2495 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2496{
2497 int offset = 0;
2498 int global_offset = 0;
2499 int vary_info_count = 0;
2500 int keep = 0;
2501 unsigned int vary_idx;
2502 const struct vary_hashing_information *vary_info;
2503
2504 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2505 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2506 vary_info = &vary_information[vary_idx];
2507 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2508
2509 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2510 prebuilt_key[global_offset] &= keep;
2511 }
2512 }
2513
2514 return 0;
2515}
2516
2517
Christopher Faulet99a17a22018-12-11 09:18:27 +01002518
2519static int
2520parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2521 struct flt_conf *fconf, char **err, void *private)
2522{
2523 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002524 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002525 char *name = NULL;
2526 int pos = *cur_arg;
2527
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002528 /* Get the cache filter name. <pos> point on "cache" keyword */
2529 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002530 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002531 goto error;
2532 }
2533 name = strdup(args[pos + 1]);
2534 if (!name) {
2535 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2536 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002537 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002538 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002539
2540 /* Check if an implicit filter with the same name already exists. If so,
2541 * we remove the implicit filter to use the explicit one. */
2542 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2543 if (f->id != cache_store_flt_id)
2544 continue;
2545
2546 cconf = f->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002547 if (strcmp(name, cconf->c.name) != 0) {
Christopher Faulet99a17a22018-12-11 09:18:27 +01002548 cconf = NULL;
2549 continue;
2550 }
2551
2552 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2553 cconf = NULL;
2554 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2555 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002556 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002557 }
2558
2559 /* Remove the implicit filter. <cconf> is kept for the explicit one */
2560 LIST_DEL(&f->list);
2561 free(f);
2562 free(name);
2563 break;
2564 }
2565
2566 /* No implicit cache filter found, create configuration for the explicit one */
2567 if (!cconf) {
2568 cconf = calloc(1, sizeof(*cconf));
2569 if (!cconf) {
2570 memprintf(err, "%s: out of memory", args[*cur_arg]);
2571 goto error;
2572 }
2573 cconf->c.name = name;
2574 }
2575
2576 cconf->flags = 0;
2577 fconf->id = cache_store_flt_id;
2578 fconf->conf = cconf;
2579 fconf->ops = &cache_ops;
2580
2581 *cur_arg = pos;
2582 return 0;
2583
2584 error:
2585 free(name);
2586 free(cconf);
2587 return -1;
2588}
2589
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002590static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002591{
2592 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2593 return 1;
2594
2595 return 0;
2596}
2597
2598static int cli_io_handler_show_cache(struct appctx *appctx)
2599{
2600 struct cache* cache = appctx->ctx.cli.p0;
2601 struct stream_interface *si = appctx->owner;
2602
William Lallemand1f49a362017-11-21 20:01:26 +01002603 if (cache == NULL) {
2604 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
2605 }
2606
2607 list_for_each_entry_from(cache, &caches, list) {
2608 struct eb32_node *node = NULL;
2609 unsigned int next_key;
2610 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002611 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002612
William Lallemand1f49a362017-11-21 20:01:26 +01002613 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002614 if (!next_key) {
2615 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
2616 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002617 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002618 return 0;
2619 }
2620 }
William Lallemand1f49a362017-11-21 20:01:26 +01002621
2622 appctx->ctx.cli.p0 = cache;
2623
2624 while (1) {
2625
2626 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002627 if (!node || (node = eb32_next_dup(node)) == NULL)
2628 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002629 if (!node) {
2630 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02002631 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002632 break;
2633 }
2634
2635 entry = container_of(node, struct cache_entry, eb);
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002636 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2637 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2638 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2639 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 +01002640
2641 next_key = node->key + 1;
2642 appctx->ctx.cli.i0 = next_key;
2643
2644 shctx_unlock(shctx_ptr(cache));
2645
2646 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002647 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002648 return 0;
2649 }
2650 }
2651
2652 }
2653
2654 return 1;
2655
2656}
2657
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002658
2659/*
2660 * boolean, returns true if response was built out of a cache entry.
2661 */
2662static int
2663smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2664 const char *kw, void *private)
2665{
2666 smp->data.type = SMP_T_BOOL;
2667 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2668
2669 return 1;
2670}
2671
2672/*
2673 * string, returns cache name (if response came from a cache).
2674 */
2675static int
2676smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2677 const char *kw, void *private)
2678{
2679 struct appctx *appctx = NULL;
2680
2681 struct cache_flt_conf *cconf = NULL;
2682 struct cache *cache = NULL;
2683
2684 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2685 return 0;
2686
2687 /* Get appctx from the stream_interface. */
2688 appctx = si_appctx(&smp->strm->si[1]);
2689 if (appctx && appctx->rule) {
2690 cconf = appctx->rule->arg.act.p[0];
2691 if (cconf) {
2692 cache = cconf->c.cache;
2693
2694 smp->data.type = SMP_T_STR;
2695 smp->flags = SMP_F_CONST;
2696 smp->data.u.str.area = cache->id;
2697 smp->data.u.str.data = strlen(cache->id);
2698 return 1;
2699 }
2700 }
2701
2702 return 0;
2703}
2704
Christopher Faulet99a17a22018-12-11 09:18:27 +01002705/* Declare the filter parser for "cache" keyword */
2706static struct flt_kw_list filter_kws = { "CACHE", { }, {
2707 { "cache", parse_cache_flt, NULL },
2708 { NULL, NULL, NULL },
2709 }
2710};
2711
2712INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2713
William Lallemand1f49a362017-11-21 20:01:26 +01002714static struct cli_kw_list cli_kws = {{},{
William Lallemande899af82017-11-22 16:41:26 +01002715 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
2716 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002717}};
2718
Willy Tarreau0108d902018-11-25 19:14:37 +01002719INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002720
William Lallemand41db4602017-10-30 11:15:51 +01002721static struct action_kw_list http_res_actions = {
2722 .kw = {
2723 { "cache-store", parse_cache_store },
2724 { NULL, NULL }
2725 }
2726};
2727
Willy Tarreau0108d902018-11-25 19:14:37 +01002728INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2729
William Lallemand41db4602017-10-30 11:15:51 +01002730static struct action_kw_list http_req_actions = {
2731 .kw = {
2732 { "cache-use", parse_cache_use },
2733 { NULL, NULL }
2734 }
2735};
2736
Willy Tarreau0108d902018-11-25 19:14:37 +01002737INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2738
Willy Tarreau2231b632019-03-29 18:26:52 +01002739struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002740 .obj_type = OBJ_TYPE_APPLET,
2741 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002742 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002743 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002744};
2745
Willy Tarreaue6552512018-11-26 11:33:13 +01002746/* config parsers for this section */
2747REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002748REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002749
2750
2751/* Note: must not be declared <const> as its list will be overwritten */
2752static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2753 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2754 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2755 { /* END */ },
2756 }
2757};
2758
2759INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);