blob: 0e2e3f9a83ab1a7992441c1ebbf1414ccdcce7f8 [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 */
Tim Duesterhused84d842021-01-18 13:41:17 +0100100 int(*cmp_fn)(const void *ref, const void *new, unsigned int len); /* Comparison function, should return 0 if the hashes are alike */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100101};
102
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100103static int http_request_prebuild_full_secondary_key(struct stream *s);
104static int http_request_build_secondary_key(struct stream *s, int vary_signature);
105static int http_request_reduce_secondary_key(unsigned int vary_signature,
106 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
107
108static int parse_encoding_value(struct ist value, unsigned int *encoding_value,
109 unsigned int *has_null_weight);
110
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +0100111static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
112 char *buf, unsigned int *buf_len);
113static int default_normalizer(struct htx *htx, struct ist hdr_name,
114 char *buf, unsigned int *buf_len);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100115
Tim Duesterhused84d842021-01-18 13:41:17 +0100116static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100117
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100118/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
119 * added to this array. */
120const struct vary_hashing_information vary_information[] = {
Tim Duesterhused84d842021-01-18 13:41:17 +0100121 { IST("accept-encoding"), VARY_ACCEPT_ENCODING, sizeof(uint32_t), &accept_encoding_normalizer, &accept_encoding_bitmap_cmp },
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100122 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer, NULL },
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100123};
124
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100125
William Lallemand41db4602017-10-30 11:15:51 +0100126/*
127 * cache ctx for filters
128 */
129struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100130 struct shared_block *first_block;
131};
132
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100133#define DEFAULT_MAX_SECONDARY_ENTRY 10
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100134
William Lallemand41db4602017-10-30 11:15:51 +0100135struct cache_entry {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100136 unsigned int complete; /* An entry won't be valid until complete is not null. */
William Lallemand41db4602017-10-30 11:15:51 +0100137 unsigned int latest_validation; /* latest validation date */
138 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200139 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100140
William Lallemand41db4602017-10-30 11:15:51 +0100141 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100142 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200143
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100144 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
145 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
146 * to build secondary keys for this cache entry. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100147 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 +0100148 unsigned int last_clear_ts; /* Timestamp of the last call to clear_expired_duplicates. */
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100149
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200150 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
151 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
152
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200153 time_t last_modified; /* Origin server "Last-Modified" header value converted in
154 * seconds since epoch. If no "Last-Modified"
155 * header is found, use "Date" header value,
156 * otherwise use reception time. This field will
157 * be used in case of an "If-Modified-Since"-based
158 * conditional request. */
159
William Lallemand41db4602017-10-30 11:15:51 +0100160 unsigned char data[0];
161};
162
163#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100164#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100165
166static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200167static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100168static struct cache *tmp_cache_config = NULL;
169
Willy Tarreau8ceae722018-11-26 11:58:30 +0100170DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
171
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100172static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry);
173static void delete_entry(struct cache_entry *del_entry);
174
William Lallemandf528fff2017-11-23 19:43:17 +0100175struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100176{
177 struct eb32_node *node;
178 struct cache_entry *entry;
179
Willy Tarreau8b507582020-02-25 09:35:07 +0100180 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100181 if (!node)
182 return NULL;
183
184 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100185
186 /* if that's not the right node */
187 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
188 return NULL;
189
William Lallemand08727662017-11-21 20:01:27 +0100190 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100191 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100192 } else {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100193 delete_entry(entry);
William Lallemand08727662017-11-21 20:01:27 +0100194 entry->eb.key = 0;
195 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100196 return NULL;
197
198}
199
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100200
201/*
202 * Compare a newly built secondary key to the one found in a cache_entry.
203 * Every sub-part of the key is compared to the reference through the dedicated
204 * comparison function of the sub-part (that might do more than a simple
205 * memcmp).
206 * Returns 0 if the keys are alike.
207 */
208static int secondary_key_cmp(const char *ref_key, const char *new_key)
209{
210 int retval = 0;
Tim Duesterhus5897cfe2021-01-18 13:41:18 +0100211 size_t idx = 0;
212 unsigned int offset = 0;
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100213 const struct vary_hashing_information *info;
214
215 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
216 info = &vary_information[idx];
217
218 if (info->cmp_fn)
219 retval = info->cmp_fn(&ref_key[offset], &new_key[offset], info->hash_length);
220 else
221 retval = memcmp(&ref_key[offset], &new_key[offset], info->hash_length);
222
223 offset += info->hash_length;
224 }
225
226 return retval;
227}
228
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100229/*
230 * There can be multiple entries with the same primary key in the ebtree so in
231 * order to get the proper one out of the list, we use a secondary_key.
232 * This function simply iterates over all the entries with the same primary_key
233 * until it finds the right one.
234 * Returns the cache_entry in case of success, NULL otherwise.
235 */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100236struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100237 const char *secondary_key)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100238{
239 struct eb32_node *node = &entry->eb;
240
241 if (!entry->secondary_key_signature)
242 return NULL;
243
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100244 while (entry && secondary_key_cmp(entry->secondary_key, secondary_key) != 0) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100245 node = eb32_next_dup(node);
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100246
247 /* Make the best use of this iteration and clear expired entries
248 * when we find them. Calling delete_entry would be too costly
249 * so we simply call eb32_delete. The secondary_entry count will
250 * be updated when we try to insert a new entry to this list. */
251 if (entry->expire <= now.tv_sec) {
252 eb32_delete(&entry->eb);
253 entry->eb.key = 0;
254 }
255
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100256 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
257 }
258
259 /* Expired entry */
260 if (entry && entry->expire <= now.tv_sec) {
261 eb32_delete(&entry->eb);
262 entry->eb.key = 0;
263 entry = NULL;
264 }
265
266 return entry;
267}
268
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100269
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100270/*
271 * Remove all expired entries from a list of duplicates.
272 * Return the number of alive entries in the list and sets dup_tail to the
273 * current last item of the list.
274 */
275static unsigned int clear_expired_duplicates(struct eb32_node **dup_tail)
276{
277 unsigned int entry_count = 0;
278 struct cache_entry *entry = NULL;
279 struct eb32_node *prev = *dup_tail;
280 struct eb32_node *tail = NULL;
281
282 while (prev) {
283 entry = container_of(prev, struct cache_entry, eb);
284 prev = eb32_prev_dup(prev);
285 if (entry->expire <= now.tv_sec) {
286 eb32_delete(&entry->eb);
287 entry->eb.key = 0;
288 }
289 else {
290 if (!tail)
291 tail = &entry->eb;
292 ++entry_count;
293 }
294 }
295
296 *dup_tail = tail;
297
298 return entry_count;
299}
300
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100301
302/*
303 * This function inserts a cache_entry in the cache's ebtree. In case of
304 * duplicate entries (vary), it then checks that the number of entries did not
305 * reach the max number of secondary entries. If this entry should not have been
306 * created, remove it.
307 * In the regular case (unique entries), this function does not do more than a
308 * simple insert. In case of secondary entries, it will at most cost an
309 * insertion+max_sec_entries time checks and entry deletion.
310 * Returns the newly inserted node in case of success, NULL otherwise.
311 */
312static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry)
313{
314 struct eb32_node *prev = NULL;
315 struct cache_entry *entry = NULL;
316 unsigned int entry_count = 0;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100317 unsigned int last_clear_ts = now.tv_sec;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100318
319 struct eb32_node *node = eb32_insert(&cache->entries, &new_entry->eb);
320
321 /* We should not have multiple entries with the same primary key unless
322 * the entry has a non null vary signature. */
323 if (!new_entry->secondary_key_signature)
324 return node;
325
326 prev = eb32_prev_dup(node);
327 if (prev != NULL) {
328 /* The last entry of a duplicate list should contain the current
329 * number of entries in the list. */
330 entry = container_of(prev, struct cache_entry, eb);
331 entry_count = entry->secondary_entries_count;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100332 last_clear_ts = entry->last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100333
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100334 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100335 /* Some entries of the duplicate list might be expired so
336 * we will iterate over all the items in order to free some
337 * space. In order to avoid going over the same list too
338 * often, we first check the timestamp of the last check
339 * performed. */
340 if (last_clear_ts == now.tv_sec) {
341 /* Too many entries for this primary key, clear the
342 * one that was inserted. */
343 eb32_delete(node);
344 node->key = 0;
345 return NULL;
346 }
347
348 entry_count = clear_expired_duplicates(&prev);
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100349 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100350 /* Still too many entries for this primary key, delete
351 * the newly inserted one. */
352 entry = container_of(prev, struct cache_entry, eb);
353 entry->last_clear_ts = now.tv_sec;
354 eb32_delete(node);
355 node->key = 0;
356 return NULL;
357 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100358 }
359 }
360
361 new_entry->secondary_entries_count = entry_count + 1;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100362 new_entry->last_clear_ts = last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100363
364 return node;
365}
366
367
368/*
369 * This function removes an entry from the ebtree. If the entry was a duplicate
370 * (in case of Vary), it updates the secondary entry counter in another
371 * duplicate entry (the last entry of the dup list).
372 */
373static void delete_entry(struct cache_entry *del_entry)
374{
375 struct eb32_node *prev = NULL, *next = NULL;
376 struct cache_entry *entry = NULL;
377 struct eb32_node *last = NULL;
378
379 if (del_entry->secondary_key_signature) {
380 next = &del_entry->eb;
381
382 /* Look for last entry of the duplicates list. */
383 while ((next = eb32_next_dup(next))) {
384 last = next;
385 }
386
387 if (last) {
388 entry = container_of(last, struct cache_entry, eb);
389 --entry->secondary_entries_count;
390 }
391 else {
392 /* The current entry is the last one, look for the
393 * previous one to update its counter. */
394 prev = eb32_prev_dup(&del_entry->eb);
395 if (prev) {
396 entry = container_of(prev, struct cache_entry, eb);
397 entry->secondary_entries_count = del_entry->secondary_entries_count - 1;
398 }
399 }
400 }
401 eb32_delete(&del_entry->eb);
402 del_entry->eb.key = 0;
403}
404
405
William Lallemand4da3f8a2017-10-31 14:33:34 +0100406static inline struct shared_context *shctx_ptr(struct cache *cache)
407{
408 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
409}
410
William Lallemand77c11972017-10-31 20:43:01 +0100411static inline struct shared_block *block_ptr(struct cache_entry *entry)
412{
413 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
414}
415
416
417
William Lallemand41db4602017-10-30 11:15:51 +0100418static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100419cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100420{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100421 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100422 return 0;
423}
424
Christopher Faulet95220e22018-12-07 17:34:39 +0100425static void
426cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
427{
428 struct cache_flt_conf *cconf = fconf->conf;
429
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200430 if (!(cconf->flags & CACHE_FLT_INIT))
431 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100432 free(cconf);
433}
434
William Lallemand4da3f8a2017-10-31 14:33:34 +0100435static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100436cache_store_check(struct proxy *px, struct flt_conf *fconf)
437{
438 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100439 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100440 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100441 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100442
William Lallemandd1d1e222019-08-28 15:22:49 +0200443 /* Find the cache corresponding to the name in the filter config. The
444 * cache will not be referenced now in the filter config because it is
445 * not fully allocated. This step will be performed during the cache
446 * post_check.
447 */
448 list_for_each_entry(cache, &caches_config, list) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +0100449 if (strcmp(cache->id, cconf->c.name) == 0)
Christopher Faulet95220e22018-12-07 17:34:39 +0100450 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100451 }
452
453 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
454 proxy_type_str(px), px->id, (char *)cconf->c.name);
455 return 1;
456
457 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100458 /* Here <cache> points on the cache the filter must use and <cconf>
459 * points on the cache filter configuration. */
460
461 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100462 * enabled and if it is after the cache. When the compression is before
463 * the cache, an error is returned. Also check if the cache filter must
464 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100465 list_for_each_entry(f, &px->filter_configs, list) {
466 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100467 /* The compression filter must be evaluated after the cache. */
468 if (comp) {
469 ha_alert("config: %s '%s': unable to enable the compression filter before "
470 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
471 return 1;
472 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100473 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200474 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100475 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200476 else if (f->id == fcgi_flt_id)
477 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100478 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
479 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200480 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100481 * declaration is required. */
482 ha_alert("config: %s '%s': require an explicit filter declaration "
483 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
484 return 1;
485 }
486
Christopher Fauletafd819c2018-12-11 08:57:45 +0100487 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100488 return 0;
489}
490
491static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100492cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100493{
Christopher Faulet65554e12020-03-06 14:52:06 +0100494 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100495
Christopher Faulet65554e12020-03-06 14:52:06 +0100496 st = pool_alloc_dirty(pool_head_cache_st);
497 if (st == NULL)
498 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100499
Christopher Faulet65554e12020-03-06 14:52:06 +0100500 st->first_block = NULL;
501 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100502
Christopher Faulet65554e12020-03-06 14:52:06 +0100503 /* Register post-analyzer on AN_RES_WAIT_HTTP */
504 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100505 return 1;
506}
507
Christopher Faulet65554e12020-03-06 14:52:06 +0100508static void
509cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100510{
511 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100512 struct cache_flt_conf *cconf = FLT_CONF(filter);
513 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100514 struct shared_context *shctx = shctx_ptr(cache);
515
William Lallemand49dc0482017-11-24 14:33:54 +0100516 /* Everything should be released in the http_end filter, but we need to do it
517 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100518 if (st && st->first_block) {
William Lallemand49dc0482017-11-24 14:33:54 +0100519 shctx_lock(shctx);
520 shctx_row_dec_hot(shctx, st->first_block);
521 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100522 }
523 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100524 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100525 filter->ctx = NULL;
526 }
William Lallemand49dc0482017-11-24 14:33:54 +0100527}
528
Christopher Faulet839791a2019-01-07 16:12:07 +0100529static int
530cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
531 unsigned an_bit)
532{
533 struct http_txn *txn = s->txn;
534 struct http_msg *msg = &txn->rsp;
535 struct cache_st *st = filter->ctx;
536
537 if (an_bit != AN_RES_WAIT_HTTP)
538 goto end;
539
540 /* Here we need to check if any compression filter precedes the cache
541 * filter. This is only possible when the compression is configured in
542 * the frontend while the cache filter is configured on the
543 * backend. This case cannot be detected during HAProxy startup. So in
544 * such cases, the cache is disabled.
545 */
546 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
547 pool_free(pool_head_cache_st, st);
548 filter->ctx = NULL;
549 }
550
551 end:
552 return 1;
553}
William Lallemand49dc0482017-11-24 14:33:54 +0100554
555static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100556cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
557{
558 struct cache_st *st = filter->ctx;
559
William Lallemand4da3f8a2017-10-31 14:33:34 +0100560 if (!(msg->chn->flags & CF_ISRESP) || !st)
561 return 1;
562
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200563 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100564 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100565 return 1;
566}
567
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200568static inline void disable_cache_entry(struct cache_st *st,
569 struct filter *filter, struct shared_context *shctx)
570{
571 struct cache_entry *object;
572
573 object = (struct cache_entry *)st->first_block->data;
574 filter->ctx = NULL; /* disable cache */
575 shctx_lock(shctx);
576 shctx_row_dec_hot(shctx, st->first_block);
Remi Tricot-Le Breton964caaf2020-12-15 14:30:12 +0100577 eb32_delete(&object->eb);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200578 object->eb.key = 0;
579 shctx_unlock(shctx);
580 pool_free(pool_head_cache_st, st);
581}
582
William Lallemand4da3f8a2017-10-31 14:33:34 +0100583static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100584cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
585 unsigned int offset, unsigned int len)
586{
Christopher Faulet95220e22018-12-07 17:34:39 +0100587 struct cache_flt_conf *cconf = FLT_CONF(filter);
588 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100589 struct cache_st *st = filter->ctx;
590 struct htx *htx = htxbuf(&msg->chn->buf);
591 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200592 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100593 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200594 unsigned int orig_len, to_forward;
595 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100596
597 if (!len)
598 return len;
599
600 if (!st->first_block) {
601 unregister_data_filter(s, msg->chn, filter);
602 return len;
603 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100604
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200605 chunk_reset(&trash);
606 orig_len = len;
607 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100608
609 htxret = htx_find_offset(htx, offset);
610 blk = htxret.blk;
611 offset = htxret.ret;
612 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100613 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200614 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100615 struct ist v;
616
617 switch (type) {
618 case HTX_BLK_UNUSED:
619 break;
620
621 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100622 v = htx_get_blk_value(htx, blk);
623 v.ptr += offset;
624 v.len -= offset;
625 if (v.len > len)
626 v.len = len;
627
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200628 info = (type << 28) + v.len;
629 chunk_memcat(&trash, (char *)&info, sizeof(info));
630 chunk_memcat(&trash, v.ptr, v.len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100631 to_forward += v.len;
632 len -= v.len;
633 break;
634
635 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200636 /* Here offset must always be 0 because only
637 * DATA blocks can be partially transferred. */
638 if (offset)
639 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100640 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200641 goto end;
642
643 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
644 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100645 to_forward += sz;
646 len -= sz;
647 break;
648 }
649
650 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100651 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200652
653 end:
654 shctx_lock(shctx);
655 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
656 if (!fb) {
657 shctx_unlock(shctx);
658 goto no_cache;
659 }
660 shctx_unlock(shctx);
661
662 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
663 (unsigned char *)b_head(&trash), b_data(&trash));
664 if (ret < 0)
665 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100666
667 return to_forward;
668
669 no_cache:
670 disable_cache_entry(st, filter, shctx);
671 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200672 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100673}
674
675static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100676cache_store_http_end(struct stream *s, struct filter *filter,
677 struct http_msg *msg)
678{
679 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100680 struct cache_flt_conf *cconf = FLT_CONF(filter);
681 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100682 struct shared_context *shctx = shctx_ptr(cache);
683 struct cache_entry *object;
684
685 if (!(msg->chn->flags & CF_ISRESP))
686 return 1;
687
688 if (st && st->first_block) {
689
690 object = (struct cache_entry *)st->first_block->data;
691
William Lallemand4da3f8a2017-10-31 14:33:34 +0100692 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100693 /* The whole payload was cached, the entry can now be used. */
694 object->complete = 1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100695 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100696 shctx_row_dec_hot(shctx, st->first_block);
697 shctx_unlock(shctx);
698
699 }
700 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100701 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100702 filter->ctx = NULL;
703 }
704
705 return 1;
706}
707
708 /*
709 * This intends to be used when checking HTTP headers for some
710 * word=value directive. Return a pointer to the first character of value, if
Willy Tarreau94a01e12021-01-06 17:35:12 +0100711 * the word was not found or if there wasn't any value assigned to it return NULL
William Lallemand4da3f8a2017-10-31 14:33:34 +0100712 */
713char *directive_value(const char *sample, int slen, const char *word, int wlen)
714{
715 int st = 0;
716
717 if (slen < wlen)
718 return 0;
719
720 while (wlen) {
721 char c = *sample ^ *word;
722 if (c && c != ('A' ^ 'a'))
723 return NULL;
724 sample++;
725 word++;
726 slen--;
727 wlen--;
728 }
729
730 while (slen) {
731 if (st == 0) {
732 if (*sample != '=')
733 return NULL;
734 sample++;
735 slen--;
736 st = 1;
737 continue;
738 } else {
739 return (char *)sample;
740 }
741 }
742
743 return NULL;
744}
745
746/*
747 * Return the maxage in seconds of an HTTP response.
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100748 * The returned value will always take the cache's configuration into account
749 * (cache->maxage) but the actual max age of the response will be set in the
750 * true_maxage parameter. It will be used to determine if a response is already
751 * stale or not.
William Lallemand4da3f8a2017-10-31 14:33:34 +0100752 * Compute the maxage using either:
753 * - the assigned max-age of the cache
754 * - the s-maxage directive
755 * - the max-age directive
756 * - (Expires - Data) headers
757 * - the default-max-age of the cache
758 *
759 */
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100760int http_calc_maxage(struct stream *s, struct cache *cache, int *true_maxage)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100761{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200762 struct htx *htx = htxbuf(&s->res.buf);
763 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100764 long smaxage = -1;
765 long maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100766 int expires = -1;
767 struct tm tm = {};
768 time_t expires_val = 0;
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100769 char *endptr = NULL;
770 int offset = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100771
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100772 /* The Cache-Control max-age and s-maxage directives should be followed by
773 * a positive numerical value (see RFC 7234#5.2.1.1). According to the
774 * specs, a sender "should not" generate a quoted-string value but we will
775 * still accept this format since it isn't strictly forbidden. */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200776 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
777 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100778
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200779 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
780 if (value) {
781 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100782
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200783 chunk_strncat(chk, value, ctx.value.len - 8 + 1);
784 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100785 offset = (*chk->area == '"') ? 1 : 0;
786 smaxage = strtol(chk->area + offset, &endptr, 10);
787 if (unlikely(smaxage < 0 || endptr == chk->area))
788 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100789 }
790
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200791 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
792 if (value) {
793 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200794
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200795 chunk_strncat(chk, value, ctx.value.len - 7 + 1);
796 chunk_strncat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100797 offset = (*chk->area == '"') ? 1 : 0;
798 maxage = strtol(chk->area + offset, &endptr, 10);
799 if (unlikely(maxage < 0 || endptr == chk->area))
800 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100801 }
802 }
803
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100804 /* Look for Expires header if no s-maxage or max-age Cache-Control data
805 * was found. */
806 if (maxage == -1 && smaxage == -1) {
807 ctx.blk = NULL;
808 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
809 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
810 expires_val = my_timegm(&tm);
811 /* A request having an expiring date earlier
812 * than the current date should be considered as
813 * stale. */
814 expires = (expires_val >= now.tv_sec) ?
815 (expires_val - now.tv_sec) : 0;
816 }
817 else {
818 /* Following RFC 7234#5.3, an invalid date
819 * format must be treated as a date in the past
820 * so the cache entry must be seen as already
821 * expired. */
822 expires = 0;
823 }
824 }
825 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100826
827
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100828 if (smaxage > 0) {
829 if (true_maxage)
830 *true_maxage = smaxage;
William Lallemand49b44532017-11-24 18:53:43 +0100831 return MIN(smaxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100832 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100833
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100834 if (maxage > 0) {
835 if (true_maxage)
836 *true_maxage = maxage;
William Lallemand49b44532017-11-24 18:53:43 +0100837 return MIN(maxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100838 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100839
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100840 if (expires >= 0) {
841 if (true_maxage)
842 *true_maxage = expires;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100843 return MIN(expires, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100844 }
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100845
William Lallemand49b44532017-11-24 18:53:43 +0100846 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100847
848}
849
850
William Lallemanda400a3a2017-11-20 19:13:12 +0100851static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
852{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200853 struct cache_entry *object = (struct cache_entry *)block->data;
854
855 if (first == block && object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100856 delete_entry(object);
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200857 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100858}
859
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200860
861/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
862 * date value should be compared to a date determined by in a previous response (for
863 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
864 * value of the response's reception time (by decreasing order of priority). */
865static time_t get_last_modified_time(struct htx *htx)
866{
867 time_t last_modified = 0;
868 struct http_hdr_ctx ctx = { .blk = NULL };
869 struct tm tm = {};
870
871 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
872 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
873 last_modified = my_timegm(&tm);
874 }
875 }
876
877 if (!last_modified) {
878 ctx.blk = NULL;
879 if (http_find_header(htx, ist("date"), &ctx, 1)) {
880 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
881 last_modified = my_timegm(&tm);
882 }
883 }
884 }
885
886 /* Fallback on the current time if no "Last-Modified" or "Date" header
887 * was found. */
888 if (!last_modified)
889 last_modified = now.tv_sec;
890
891 return last_modified;
892}
893
William Lallemand41db4602017-10-30 11:15:51 +0100894/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100895 * Checks the vary header's value. The headers on which vary should be applied
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500896 * must be explicitly supported in the vary_information array (see cache.c). If
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100897 * any other header is mentioned, we won't store the response.
898 * Returns 1 if Vary-based storage can work, 0 otherwise.
899 */
900static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
901{
902 unsigned int vary_idx;
903 unsigned int vary_info_count;
904 const struct vary_hashing_information *vary_info;
905 struct http_hdr_ctx ctx = { .blk = NULL };
906
907 int retval = 1;
908
909 *vary_signature = 0;
910
911 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
912 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
913 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
914 vary_info = &vary_information[vary_idx];
915 if (isteqi(ctx.value, vary_info->hdr_name)) {
916 *vary_signature |= vary_info->value;
917 break;
918 }
919 }
920 retval = (vary_idx < vary_info_count);
921 }
922
923 return retval;
924}
925
926
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100927/*
928 * Look for the accept-encoding part of the secondary_key and replace the
929 * encoding bitmap part of the hash with the actual encoding of the response,
930 * extracted from the content-encoding header value.
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100931 * Responses that have an unknown encoding will not be cached if they also
932 * "vary" on the accept-encoding value.
933 * Returns 0 if we found a known encoding in the response, -1 otherwise.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100934 */
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100935static int set_secondary_key_encoding(struct htx *htx, char *secondary_key)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100936{
937 unsigned int resp_encoding_bitmap = 0;
938 const struct vary_hashing_information *info = vary_information;
939 unsigned int offset = 0;
940 unsigned int count = 0;
941 unsigned int hash_info_count = sizeof(vary_information)/sizeof(*vary_information);
942 unsigned int encoding_value;
943 struct http_hdr_ctx ctx = { .blk = NULL };
944
945 /* Look for the accept-encoding part of the secondary_key. */
946 while (count < hash_info_count && info->value != VARY_ACCEPT_ENCODING) {
947 offset += info->hash_length;
948 ++info;
949 ++count;
950 }
951
952 if (count == hash_info_count)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100953 return -1;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100954
955 while (http_find_header(htx, ist("content-encoding"), &ctx, 0)) {
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100956 if (parse_encoding_value(ctx.value, &encoding_value, NULL))
957 return -1; /* Do not store responses with an unknown encoding */
958 resp_encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100959 }
960
961 if (!resp_encoding_bitmap)
962 resp_encoding_bitmap |= VARY_ENCODING_IDENTITY;
963
964 /* Rewrite the bitmap part of the hash with the new bitmap that only
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +0500965 * corresponds the the response's encoding. */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100966 write_u32(secondary_key + offset, resp_encoding_bitmap);
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100967
968 return 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100969}
970
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100971
972/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500973 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100974 * register a filter to store the data
975 */
976enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200977 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100978{
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100979 int effective_maxage = 0;
980 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100981 struct http_txn *txn = s->txn;
982 struct http_msg *msg = &txn->rsp;
983 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100984 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100985 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100986 struct cache *cache = cconf->c.cache;
987 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100988 struct cache_st *cache_ctx = NULL;
989 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +0100990 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200991 struct htx *htx;
992 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +0200993 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200994 int32_t pos;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100995 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100996
William Lallemand4da3f8a2017-10-31 14:33:34 +0100997 /* Don't cache if the response came from a cache */
998 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
999 s->target == &http_cache_applet.obj_type) {
1000 goto out;
1001 }
1002
1003 /* cache only HTTP/1.1 */
1004 if (!(txn->req.flags & HTTP_MSGF_VER_11))
1005 goto out;
1006
Willy Tarreau6905d182019-10-01 17:59:17 +02001007 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001008 if (txn->meth != HTTP_METH_GET) {
1009 /* In case of successful unsafe method on a stored resource, the
1010 * cached entry must be invalidated (see RFC7234#4.4).
1011 * A "non-error response" is one with a 2xx (Successful) or 3xx
1012 * (Redirection) status code. */
1013 if (txn->status >= 200 && txn->status < 400) {
1014 switch (txn->meth) {
1015 case HTTP_METH_OPTIONS:
1016 case HTTP_METH_GET:
1017 case HTTP_METH_HEAD:
1018 case HTTP_METH_TRACE:
1019 break;
1020
1021 default: /* Any unsafe method */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001022 /* Discard any corresponding entry in case of successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001023 * unsafe request (such as PUT, POST or DELETE). */
1024 shctx_lock(shctx);
1025
1026 old = entry_exist(cconf->c.cache, txn->cache_hash);
1027 if (old) {
1028 eb32_delete(&old->eb);
1029 old->eb.key = 0;
1030 }
1031 shctx_unlock(shctx);
1032 }
1033 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001034 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001035 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001036
Willy Tarreauc9036c02019-01-11 19:38:25 +01001037 /* cache key was not computed */
1038 if (!key)
1039 goto out;
1040
William Lallemand4da3f8a2017-10-31 14:33:34 +01001041 /* cache only 200 status code */
1042 if (txn->status != 200)
1043 goto out;
1044
Christopher Faulet839791a2019-01-07 16:12:07 +01001045 /* Find the corresponding filter instance for the current stream */
1046 list_for_each_entry(filter, &s->strm_flt.filters, list) {
1047 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
1048 /* No filter ctx, don't cache anything */
1049 if (!filter->ctx)
1050 goto out;
1051 cache_ctx = filter->ctx;
1052 break;
1053 }
1054 }
1055
1056 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001057 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001058
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001059 /* Do not cache too big objects. */
1060 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
1061 htx->data + htx->extra > shctx->max_obj_size)
1062 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001063
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001064 /* Only a subset of headers are supported in our Vary implementation. If
1065 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001066 * able to use the cache. Likewise, if Vary header support is disabled,
1067 * avoid caching responses that contain such a header. */
1068 ctx.blk = NULL;
1069 if (cache->vary_processing_enabled) {
1070 if (!http_check_vary_header(htx, &vary_signature))
1071 goto out;
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001072 if (vary_signature) {
1073 /* If something went wrong during the secondary key
1074 * building, do not store the response. */
1075 if (!(txn->flags & TX_CACHE_HAS_SEC_KEY))
1076 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001077 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001078 }
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001079 }
1080 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001081 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001082 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001083
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001084 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001085
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +01001086 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001087 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001088
1089 shctx_lock(shctx);
1090 old = entry_exist(cache, txn->cache_hash);
1091 if (old) {
1092 if (vary_signature)
1093 old = secondary_entry_exist(cconf->c.cache, old,
1094 txn->cache_secondary_hash);
1095 if (old) {
1096 if (!old->complete) {
1097 /* An entry with the same primary key is already being
1098 * created, we should not try to store the current
1099 * response because it will waste space in the cache. */
1100 shctx_unlock(shctx);
1101 goto out;
1102 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001103 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001104 old->eb.key = 0;
1105 }
1106 }
1107 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1108 if (!first) {
1109 shctx_unlock(shctx);
1110 goto out;
1111 }
1112 /* the received memory is not initialized, we need at least to mark
1113 * the object as not indexed yet.
1114 */
1115 object = (struct cache_entry *)first->data;
1116 memset(object, 0, sizeof(*object));
1117 object->eb.key = key;
1118 object->secondary_key_signature = vary_signature;
1119 /* We need to temporarily set a valid expiring time until the actual one
1120 * is set by the end of this function (in case of concurrent accesses to
1121 * the same resource). This way the second access will find an existing
1122 * but not yet usable entry in the tree and will avoid storing its data. */
1123 object->expire = now.tv_sec + 2;
1124
1125 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1126 if (vary_signature)
1127 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1128
1129 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001130 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001131 object->eb.key = 0;
1132 shctx_unlock(shctx);
1133 goto out;
1134 }
1135 shctx_unlock(shctx);
1136
1137 /* reserve space for the cache_entry structure */
1138 first->len = sizeof(struct cache_entry);
1139 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001140
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001141 /* Determine the entry's maximum age (taking into account the cache's
1142 * configuration) as well as the response's explicit max age (extracted
1143 * from cache-control directives or the expires header). */
1144 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1145
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001146 ctx.blk = NULL;
1147 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
Tim Duesterhusc2942842021-01-02 22:47:17 +01001148 long long hdr_age;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001149 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1150 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1151 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001152 /* A response with an Age value greater than its
1153 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001154 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001155 if (unlikely(object->age > true_maxage))
1156 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001157 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001158 else
1159 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001160 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001161 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001162
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001163 /* Build a last-modified time that will be stored in the cache_entry and
1164 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001165 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001166
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001167 chunk_reset(&trash);
1168 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1169 struct htx_blk *blk = htx_get_blk(htx, pos);
1170 enum htx_blk_type type = htx_get_blk_type(blk);
1171 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001172
Christopher Fauletb0667472019-09-03 22:22:12 +02001173 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001174 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1175 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001176
1177 /* Look for optional ETag header.
1178 * We need to store the offset of the ETag value in order for
1179 * future conditional requests to be able to perform ETag
1180 * comparisons. */
1181 if (type == HTX_BLK_HDR) {
Tim Duesterhuse2fff102021-01-02 22:47:16 +01001182 struct ist header_name = htx_get_blk_name(htx, blk);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001183 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001184 object->etag_length = sz - istlen(header_name);
1185 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001186 }
1187 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001188 if (type == HTX_BLK_EOH)
1189 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001190 }
1191
Christopher Fauletb0667472019-09-03 22:22:12 +02001192 /* Do not cache objects if the headers are too big. */
1193 if (hdrs_len > htx->size - global.tune.maxrewrite)
1194 goto out;
1195
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001196 /* If the response has a secondary_key, fill its key part related to
1197 * encodings with the actual encoding of the response. This way any
1198 * subsequent request having the same primary key will have its accepted
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001199 * encodings tested upon the cached response's one.
1200 * We will not cache a response that has an unknown encoding (not
Ilya Shipitsin7704b0e2021-01-23 02:11:59 +05001201 * explicitly supported in parse_encoding_value function). */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001202 if (cache->vary_processing_enabled && vary_signature)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001203 if (set_secondary_key_encoding(htx, object->secondary_key))
1204 goto out;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001205
William Lallemand4da3f8a2017-10-31 14:33:34 +01001206 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001207 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001208 shctx_unlock(shctx);
1209 goto out;
1210 }
1211 shctx_unlock(shctx);
1212
William Lallemand4da3f8a2017-10-31 14:33:34 +01001213 /* cache the headers in a http action because it allows to chose what
1214 * to cache, for example you might want to cache a response before
1215 * modifying some HTTP headers, or on the contrary after modifying
1216 * those headers.
1217 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001218 /* does not need to be locked because it's in the "hot" list,
1219 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001220 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1221 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001222
1223 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001224 if (cache_ctx) {
1225 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001226 /* store latest value and expiration time */
1227 object->latest_validation = now.tv_sec;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001228 object->expire = now.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001229 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001230 }
1231
1232out:
1233 /* if does not cache */
1234 if (first) {
1235 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001236 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001237 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001238 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001239 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001240 shctx_row_dec_hot(shctx, first);
1241 shctx_unlock(shctx);
1242 }
1243
William Lallemand41db4602017-10-30 11:15:51 +01001244 return ACT_RET_CONT;
1245}
1246
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001247#define HTX_CACHE_INIT 0 /* Initial state. */
1248#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1249#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001250#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1251#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001252
William Lallemandecb73b12017-11-24 14:33:55 +01001253static void http_cache_applet_release(struct appctx *appctx)
1254{
Christopher Faulet95220e22018-12-07 17:34:39 +01001255 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +01001256 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001257 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001258 struct shared_block *first = block_ptr(cache_ptr);
1259
1260 shctx_lock(shctx_ptr(cache));
1261 shctx_row_dec_hot(shctx_ptr(cache), first);
1262 shctx_unlock(shctx_ptr(cache));
1263}
1264
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001265
1266static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1267 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001268{
Christopher Faulet95220e22018-12-07 17:34:39 +01001269 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1270 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001271 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001272 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001273 unsigned int max, total;
1274 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001275
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001276 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1277 if (!max)
1278 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001279 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001280 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1281 : info & 0xfffffff);
1282 if (blksz > max)
1283 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001284
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001285 blk = htx_add_blk(htx, type, blksz);
1286 if (!blk)
1287 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001288
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001289 blk->info = info;
1290 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001291 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001292 while (blksz) {
1293 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001294 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001295 offset += max;
1296 blksz -= max;
1297 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001298 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001299 if (blksz || offset == shctx->block_size) {
1300 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1301 offset = 0;
1302 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001303 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001304 appctx->ctx.cache.offset = offset;
1305 appctx->ctx.cache.next = shblk;
1306 appctx->ctx.cache.sent += total;
1307 return total;
1308}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001309
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001310static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1311 uint32_t info, struct shared_block *shblk, unsigned int offset)
1312{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001313
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001314 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1315 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1316 unsigned int max, total, rem_data;
1317 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001318
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001319 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(appctx->owner), htx));
1320 if (!max)
1321 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001322
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001323 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001324 if (appctx->ctx.cache.rem_data) {
1325 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001326 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001327 }
1328 else {
1329 blksz = (info & 0xfffffff);
1330 total = 4;
1331 }
1332 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001333 rem_data = blksz - max;
1334 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001335 }
1336
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001337 while (blksz) {
1338 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001339
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001340 max = MIN(blksz, shctx->block_size - offset);
1341 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1342 offset += sz;
1343 blksz -= sz;
1344 total += sz;
1345 if (sz < max)
1346 break;
1347 if (blksz || offset == shctx->block_size) {
1348 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1349 offset = 0;
1350 }
1351 }
1352
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001353 appctx->ctx.cache.offset = offset;
1354 appctx->ctx.cache.next = shblk;
1355 appctx->ctx.cache.sent += total;
1356 appctx->ctx.cache.rem_data = rem_data + blksz;
1357 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001358}
1359
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001360static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1361 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001362{
Christopher Faulet95220e22018-12-07 17:34:39 +01001363 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1364 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001365 struct shared_block *shblk;
1366 unsigned int offset, sz;
1367 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001368
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001369 while (len) {
1370 enum htx_blk_type type;
1371 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001372
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001373 shblk = appctx->ctx.cache.next;
1374 offset = appctx->ctx.cache.offset;
1375 if (appctx->ctx.cache.rem_data) {
1376 type = HTX_BLK_DATA;
1377 info = 0;
1378 goto add_data_blk;
1379 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001380
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001381 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001382 sz = MIN(4, shctx->block_size - offset);
1383 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1384 offset += sz;
1385 if (sz < 4) {
1386 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1387 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1388 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001389 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001390
1391 /* Get payload of the next HTX block and insert it. */
1392 type = (info >> 28);
1393 if (type != HTX_BLK_DATA)
1394 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1395 else {
1396 add_data_blk:
1397 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001398 }
1399
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001400 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001401 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001402 total += ret;
1403 len -= ret;
1404
1405 if (appctx->ctx.cache.rem_data || type == mark)
1406 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001407 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001408
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001409 return total;
1410}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001411
1412static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1413{
1414 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1415 unsigned int age;
1416 char *end;
1417
1418 chunk_reset(&trash);
1419 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1420 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1421 age = CACHE_ENTRY_MAX_AGE;
1422 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1423 b_set_data(&trash, end - b_head(&trash));
1424 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1425 return 0;
1426 return 1;
1427}
1428
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001429static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001430{
1431 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1432 struct shared_block *first = block_ptr(cache_ptr);
1433 struct stream_interface *si = appctx->owner;
1434 struct channel *req = si_oc(si);
1435 struct channel *res = si_ic(si);
1436 struct htx *req_htx, *res_htx;
1437 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001438 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001439 size_t ret, total = 0;
1440
1441 res_htx = htxbuf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001442 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001443
1444 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1445 goto out;
1446
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001447 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001448 if (!b_size(&res->buf)) {
1449 si_rx_room_blk(si);
1450 goto out;
1451 }
1452
Willy Tarreauefef3232018-12-16 00:37:45 +01001453 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001454 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001455
1456 if (appctx->st0 == HTX_CACHE_INIT) {
1457 appctx->ctx.cache.next = block_ptr(cache_ptr);
1458 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1459 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001460 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001461 appctx->st0 = HTX_CACHE_HEADER;
1462 }
1463
1464 if (appctx->st0 == HTX_CACHE_HEADER) {
1465 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001466 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1467 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1468 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1469 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001470 goto error;
1471
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001472 /* In case of a conditional request, we might want to send a
1473 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001474 if (appctx->ctx.cache.send_notmodified) {
1475 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1476 /* If replacing the status code fails we need to send the full response. */
1477 appctx->ctx.cache.send_notmodified = 0;
1478 }
1479 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001480
1481 /* Skip response body for HEAD requests or in case of "304 Not
1482 * Modified" response. */
1483 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001484 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001485 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001486 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001487 }
1488
1489 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001490 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1491 if (len) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001492 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_UNUSED);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001493 if (ret < len) {
1494 si_rx_room_blk(si);
1495 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001496 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001497 }
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001498 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001499 }
1500
1501 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001502 /* no more data are expected. */
1503 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001504 appctx->st0 = HTX_CACHE_END;
1505 }
1506
1507 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001508 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001509 res->flags |= CF_READ_NULL;
1510 si_shutr(si);
1511 }
1512
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001513 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001514 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001515 if (total)
1516 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001517 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001518
1519 /* eat the whole request */
1520 if (co_data(req)) {
1521 req_htx = htx_from_buf(&req->buf);
1522 co_htx_skip(req, req_htx, co_data(req));
1523 htx_to_buf(req_htx, &req->buf);
1524 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001525 return;
1526
1527 error:
1528 /* Sent and HTTP error 500 */
1529 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001530 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001531 res->buf.data = b_data(errmsg);
1532 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1533 res_htx = htx_from_buf(&res->buf);
1534
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001535 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001536 appctx->st0 = HTX_CACHE_END;
1537 goto end;
1538}
1539
1540
Christopher Faulet95220e22018-12-07 17:34:39 +01001541static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001542{
1543 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001544 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001545
Christopher Faulet95220e22018-12-07 17:34:39 +01001546 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001547 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001548 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001549 }
1550
1551 /* check if a cache filter was already registered with this cache
1552 * name, if that's the case, must use it. */
1553 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001554 if (fconf->id == cache_store_flt_id) {
1555 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001556 if (cconf && strcmp((char *)cconf->c.name, name) == 0) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001557 rule->arg.act.p[0] = cconf;
1558 return 1;
1559 }
William Lallemand41db4602017-10-30 11:15:51 +01001560 }
1561 }
1562
Christopher Faulet95220e22018-12-07 17:34:39 +01001563 /* Create the filter cache config */
1564 cconf = calloc(1, sizeof(*cconf));
1565 if (!cconf) {
1566 memprintf(err, "out of memory\n");
1567 goto err;
1568 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001569 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001570 cconf->c.name = strdup(name);
1571 if (!cconf->c.name) {
1572 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001573 goto err;
1574 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001575
William Lallemand41db4602017-10-30 11:15:51 +01001576 /* register a filter to fill the cache buffer */
1577 fconf = calloc(1, sizeof(*fconf));
1578 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001579 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001580 goto err;
1581 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001582 fconf->id = cache_store_flt_id;
1583 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001584 fconf->ops = &cache_ops;
1585 LIST_ADDQ(&proxy->filter_configs, &fconf->list);
1586
Christopher Faulet95220e22018-12-07 17:34:39 +01001587 rule->arg.act.p[0] = cconf;
1588 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001589
Christopher Faulet95220e22018-12-07 17:34:39 +01001590 err:
1591 free(cconf);
1592 return 0;
1593}
1594
1595enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1596 struct act_rule *rule, char **err)
1597{
1598 rule->action = ACT_CUSTOM;
1599 rule->action_ptr = http_action_store_cache;
1600
1601 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1602 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001603
Christopher Faulet95220e22018-12-07 17:34:39 +01001604 (*orig_arg)++;
1605 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001606}
1607
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001608/* This produces a sha1 hash of the concatenation of the HTTP method,
1609 * the first occurrence of the Host header followed by the path component
1610 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001611int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001612{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001613 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001614 struct htx *htx = htxbuf(&s->req.buf);
1615 struct htx_sl *sl;
1616 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001617 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001618 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001619 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001620
William Lallemandf528fff2017-11-23 19:43:17 +01001621 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001622 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001623
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001624 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001625 uri = htx_sl_req_uri(sl); // whole uri
1626 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001627 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001628
1629 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1630 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1631 * URIs are almost always sent in absolute form with their scheme. In
1632 * this case, the scheme is almost always "https". In order to support
1633 * sharing of cache objects between H1 and H2, we'll hash the absolute
1634 * URI whenever known, or prepend "https://" + the Host header for
1635 * relative URIs. The difference will only appear on absolute HTTP/1
1636 * requests sent to an origin server, which practically is never met in
1637 * the real world so we don't care about the ability to share the same
1638 * key here.URIs are normalized from the absolute URI to an origin form as
1639 * well.
1640 */
1641 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001642 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001643 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1644 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001645 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001646 }
1647
1648 chunk_memcat(trash, uri.ptr, uri.len);
William Lallemandf528fff2017-11-23 19:43:17 +01001649
1650 /* hash everything */
1651 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001652 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001653 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1654
1655 return 1;
1656}
1657
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001658/* Looks for "If-None-Match" headers in the request and compares their value
1659 * with the one that might have been stored in the cache_entry. If any of them
1660 * matches, a "304 Not Modified" response should be sent instead of the cached
1661 * data.
1662 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001663 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1664 *
1665 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1666 * header and compare its value (date) to the one stored in the cache_entry.
1667 * If the request's date is later than the cached one, we also send a
1668 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1669 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001670 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1671 */
1672static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1673 struct cache_entry *entry)
1674{
1675 int retval = 0;
1676
1677 struct http_hdr_ctx ctx = { .blk = NULL };
1678 struct ist cache_entry_etag = IST_NULL;
1679 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001680 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001681
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001682 struct tm tm = {};
1683 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001684
1685 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001686 * cache_entry's ETag in order to perform comparisons.
1687 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001688 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001689 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001690
1691 /* A '*' matches everything. */
1692 if (isteq(ctx.value, ist("*")) != 0) {
1693 retval = 1;
1694 break;
1695 }
1696
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001697 /* No need to rebuild an etag if none was stored in the cache. */
1698 if (entry->etag_length == 0)
1699 break;
1700
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001701 /* Rebuild the stored ETag. */
1702 if (etag_buffer == NULL) {
1703 etag_buffer = get_trash_chunk();
1704
1705 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1706 (unsigned char*)b_orig(etag_buffer),
1707 entry->etag_offset, entry->etag_length) == 0) {
1708 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1709 } else {
1710 /* We could not rebuild the ETag in one go, we
1711 * won't send a "304 Not Modified" response. */
1712 break;
1713 }
1714 }
1715
1716 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1717 retval = 1;
1718 break;
1719 }
1720 }
1721
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001722 /* If the request did not contain an "If-None-Match" header, we look for
1723 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1724 if (retval == 0 && if_none_match_found == 0) {
1725 ctx.blk = NULL;
1726 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1727 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1728 if_modified_since = my_timegm(&tm);
1729
1730 /* We send a "304 Not Modified" response if the
1731 * entry's last modified date is earlier than
1732 * the one found in the "If-Modified-Since"
1733 * header. */
1734 retval = (entry->last_modified <= if_modified_since);
1735 }
1736 }
1737 }
1738
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001739 return retval;
1740}
1741
William Lallemand41db4602017-10-30 11:15:51 +01001742enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1743 struct session *sess, struct stream *s, int flags)
1744{
William Lallemand77c11972017-10-31 20:43:01 +01001745
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001746 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001747 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001748 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1749 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001750 struct shared_block *entry_block;
1751
William Lallemand77c11972017-10-31 20:43:01 +01001752
Willy Tarreau6905d182019-10-01 17:59:17 +02001753 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1754 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001755 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001756 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001757 txn->flags |= TX_CACHE_IGNORE;
1758
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001759 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001760
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001761 /* The request's hash has to be calculated for all requests, even POSTs
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001762 * or PUTs for instance because RFC7234 specifies that a successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001763 * "unsafe" method on a stored resource must invalidate it
1764 * (see RFC7234#4.4). */
1765 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001766 return ACT_RET_CONT;
1767
Willy Tarreau504455c2017-12-22 17:47:35 +01001768 if (s->txn->flags & TX_CACHE_IGNORE)
1769 return ACT_RET_CONT;
1770
Willy Tarreaua1214a52018-12-14 14:00:25 +01001771 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001772 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001773 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001774 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_lookups, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001775
William Lallemanda400a3a2017-11-20 19:13:12 +01001776 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001777 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001778 /* We must not use an entry that is not complete. */
1779 if (res && res->complete) {
William Lallemand77c11972017-10-31 20:43:01 +01001780 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001781 entry_block = block_ptr(res);
1782 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001783 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001784
1785 /* In case of Vary, we could have multiple entries with the same
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001786 * primary hash. We need to calculate the secondary hash in order
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001787 * to find the actual entry we want (if it exists). */
1788 if (res->secondary_key_signature) {
1789 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1790 shctx_lock(shctx_ptr(cache));
1791 sec_entry = secondary_entry_exist(cache, res,
1792 s->txn->cache_secondary_hash);
1793 if (sec_entry && sec_entry != res) {
1794 /* The wrong row was added to the hot list. */
1795 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1796 entry_block = block_ptr(sec_entry);
1797 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1798 }
1799 res = sec_entry;
1800 shctx_unlock(shctx_ptr(cache));
1801 }
1802 else
1803 res = NULL;
1804 }
1805
1806 /* We looked for a valid secondary entry and could not find one,
1807 * the request must be forwarded to the server. */
1808 if (!res) {
1809 shctx_lock(shctx_ptr(cache));
1810 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1811 shctx_unlock(shctx_ptr(cache));
1812 return ACT_RET_CONT;
1813 }
1814
William Lallemand77c11972017-10-31 20:43:01 +01001815 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001816 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001817 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001818 appctx->rule = rule;
1819 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001820 appctx->ctx.cache.next = NULL;
1821 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001822 appctx->ctx.cache.send_notmodified =
1823 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001824
1825 if (px == strm_fe(s))
Olivier Houchardaa090d42019-03-08 18:49:24 +01001826 _HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_hits, 1);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001827 else
Olivier Houchardaa090d42019-03-08 18:49:24 +01001828 _HA_ATOMIC_ADD(&px->be_counters.p.http.cache_hits, 1);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001829 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001830 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001831 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001832 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001833 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001834 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001835 }
1836 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001837 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001838
1839 /* Shared context does not need to be locked while we calculate the
1840 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001841 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001842 /* Build a complete secondary hash until the server response
1843 * tells us which fields should be kept (if any). */
1844 http_request_prebuild_full_secondary_key(s);
1845 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001846 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001847}
1848
1849
1850enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1851 struct act_rule *rule, char **err)
1852{
William Lallemand41db4602017-10-30 11:15:51 +01001853 rule->action = ACT_CUSTOM;
1854 rule->action_ptr = http_action_req_cache_use;
1855
Christopher Faulet95220e22018-12-07 17:34:39 +01001856 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001857 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001858
1859 (*orig_arg)++;
1860 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001861}
1862
1863int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1864{
1865 int err_code = 0;
1866
1867 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1868
1869 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001870 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001871 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001872 err_code |= ERR_ALERT | ERR_ABORT;
1873 goto out;
1874 }
1875
1876 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1877 err_code |= ERR_ABORT;
1878 goto out;
1879 }
1880
1881 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001882 struct cache *cache_config;
1883
William Lallemand41db4602017-10-30 11:15:51 +01001884 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1885 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001886 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001887 err_code |= ERR_ALERT | ERR_ABORT;
1888 goto out;
1889 }
1890
1891 strlcpy2(tmp_cache_config->id, args[1], 33);
1892 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001893 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001894 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001895 err_code |= ERR_WARN;
1896 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001897
1898 list_for_each_entry(cache_config, &caches_config, list) {
1899 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1900 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1901 file, linenum, tmp_cache_config->id);
1902 err_code |= ERR_ALERT | ERR_ABORT;
1903 goto out;
1904 }
1905 }
1906
William Lallemand49b44532017-11-24 18:53:43 +01001907 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001908 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001909 tmp_cache_config->maxobjsz = 0;
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001910 tmp_cache_config->max_secondary_entries = DEFAULT_MAX_SECONDARY_ENTRY;
William Lallemand41db4602017-10-30 11:15:51 +01001911 }
1912 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001913 unsigned long int maxsize;
1914 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001915
1916 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1917 err_code |= ERR_ABORT;
1918 goto out;
1919 }
1920
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001921 maxsize = strtoul(args[1], &err, 10);
1922 if (err == args[1] || *err != '\0') {
1923 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1924 file, linenum, args[1]);
1925 err_code |= ERR_ABORT;
1926 goto out;
1927 }
1928
1929 if (maxsize > (UINT_MAX >> 20)) {
1930 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1931 file, linenum, args[1], UINT_MAX >> 20);
1932 err_code |= ERR_ABORT;
1933 goto out;
1934 }
1935
William Lallemand41db4602017-10-30 11:15:51 +01001936 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001937 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001938 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001939 } else if (strcmp(args[0], "max-age") == 0) {
1940 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1941 err_code |= ERR_ABORT;
1942 goto out;
1943 }
1944
1945 if (!*args[1]) {
1946 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1947 file, linenum, args[0]);
1948 err_code |= ERR_WARN;
1949 }
1950
1951 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001952 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001953 unsigned int maxobjsz;
1954 char *err;
1955
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001956 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1957 err_code |= ERR_ABORT;
1958 goto out;
1959 }
1960
1961 if (!*args[1]) {
1962 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1963 file, linenum, args[0]);
1964 err_code |= ERR_WARN;
1965 }
1966
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001967 maxobjsz = strtoul(args[1], &err, 10);
1968 if (err == args[1] || *err != '\0') {
1969 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1970 file, linenum, args[1]);
1971 err_code |= ERR_ABORT;
1972 goto out;
1973 }
1974 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001975 } else if (strcmp(args[0], "process-vary") == 0) {
1976 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1977 err_code |= ERR_ABORT;
1978 goto out;
1979 }
1980
1981 if (!*args[1]) {
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001982 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 +01001983 file, linenum, args[0]);
1984 err_code |= ERR_WARN;
1985 }
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001986 if (strcmp(args[1], "on") == 0)
1987 tmp_cache_config->vary_processing_enabled = 1;
1988 else if (strcmp(args[1], "off") == 0)
1989 tmp_cache_config->vary_processing_enabled = 0;
1990 else {
1991 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
1992 file, linenum, args[0]);
1993 err_code |= ERR_WARN;
1994 }
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001995 } else if (strcmp(args[0], "max-secondary-entries") == 0) {
1996 unsigned int max_sec_entries;
1997 char *err;
1998
1999 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
2000 err_code |= ERR_ABORT;
2001 goto out;
2002 }
2003
2004 if (!*args[1]) {
2005 ha_warning("parsing [%s:%d]: '%s' expects a strictly positive number.\n",
2006 file, linenum, args[0]);
2007 err_code |= ERR_WARN;
2008 }
2009
2010 max_sec_entries = strtoul(args[1], &err, 10);
2011 if (err == args[1] || *err != '\0' || max_sec_entries == 0) {
2012 ha_warning("parsing [%s:%d]: max-secondary-entries wrong value '%s'\n",
2013 file, linenum, args[1]);
2014 err_code |= ERR_ABORT;
2015 goto out;
2016 }
2017 tmp_cache_config->max_secondary_entries = max_sec_entries;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002018 }
2019 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002020 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01002021 err_code |= ERR_ALERT | ERR_FATAL;
2022 goto out;
2023 }
2024out:
2025 return err_code;
2026}
2027
2028/* once the cache section is parsed */
2029
2030int cfg_post_parse_section_cache()
2031{
William Lallemand41db4602017-10-30 11:15:51 +01002032 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01002033
2034 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01002035
2036 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002037 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01002038 err_code |= ERR_FATAL | ERR_ALERT;
2039 goto out;
2040 }
2041
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002042 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002043 /* Default max. file size is a 256th of the cache size. */
2044 tmp_cache_config->maxobjsz =
2045 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002046 }
2047 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
2048 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
2049 err_code |= ERR_FATAL | ERR_ALERT;
2050 goto out;
2051 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002052
William Lallemandd1d1e222019-08-28 15:22:49 +02002053 /* add to the list of cache to init and reinit tmp_cache_config
2054 * for next cache section, if any.
2055 */
2056 LIST_ADDQ(&caches_config, &tmp_cache_config->list);
2057 tmp_cache_config = NULL;
2058 return err_code;
2059 }
2060out:
2061 free(tmp_cache_config);
2062 tmp_cache_config = NULL;
2063 return err_code;
2064
2065}
2066
2067int post_check_cache()
2068{
2069 struct proxy *px;
2070 struct cache *back, *cache_config, *cache;
2071 struct shared_context *shctx;
2072 int ret_shctx;
Christopher Fauletfc633b62020-11-06 15:24:23 +01002073 int err_code = ERR_NONE;
William Lallemandd1d1e222019-08-28 15:22:49 +02002074
2075 list_for_each_entry_safe(cache_config, back, &caches_config, list) {
2076
2077 ret_shctx = shctx_init(&shctx, cache_config->maxblocks, CACHE_BLOCKSIZE,
2078 cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01002079
Frédéric Lécaillebc584492018-10-25 20:18:59 +02002080 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01002081 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01002082 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002083 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01002084 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01002085
2086 err_code |= ERR_FATAL | ERR_ALERT;
2087 goto out;
2088 }
William Lallemanda400a3a2017-11-20 19:13:12 +01002089 shctx->free_block = cache_free_blocks;
William Lallemandd1d1e222019-08-28 15:22:49 +02002090 /* the cache structure is stored in the shctx and added to the
2091 * caches list, we can remove the entry from the caches_config
2092 * list */
2093 memcpy(shctx->data, cache_config, sizeof(struct cache));
William Lallemand41db4602017-10-30 11:15:51 +01002094 cache = (struct cache *)shctx->data;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01002095 cache->entries = EB_ROOT;
William Lallemand41db4602017-10-30 11:15:51 +01002096 LIST_ADDQ(&caches, &cache->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002097 LIST_DEL(&cache_config->list);
2098 free(cache_config);
2099
2100 /* Find all references for this cache in the existing filters
2101 * (over all proxies) and reference it in matching filters.
2102 */
2103 for (px = proxies_list; px; px = px->next) {
2104 struct flt_conf *fconf;
2105 struct cache_flt_conf *cconf;
2106
2107 list_for_each_entry(fconf, &px->filter_configs, list) {
2108 if (fconf->id != cache_store_flt_id)
2109 continue;
2110
2111 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002112 if (strcmp(cache->id, cconf->c.name) == 0) {
William Lallemandd1d1e222019-08-28 15:22:49 +02002113 free(cconf->c.name);
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +02002114 cconf->flags |= CACHE_FLT_INIT;
William Lallemandd1d1e222019-08-28 15:22:49 +02002115 cconf->c.cache = cache;
2116 break;
2117 }
2118 }
2119 }
William Lallemand41db4602017-10-30 11:15:51 +01002120 }
William Lallemandd1d1e222019-08-28 15:22:49 +02002121
William Lallemand41db4602017-10-30 11:15:51 +01002122out:
William Lallemand41db4602017-10-30 11:15:51 +01002123 return err_code;
2124
William Lallemand41db4602017-10-30 11:15:51 +01002125}
2126
William Lallemand41db4602017-10-30 11:15:51 +01002127struct flt_ops cache_ops = {
2128 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01002129 .check = cache_store_check,
2130 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01002131
Christopher Faulet65554e12020-03-06 14:52:06 +01002132 /* Handle stream init/deinit */
2133 .attach = cache_store_strm_init,
2134 .detach = cache_store_strm_deinit,
2135
William Lallemand4da3f8a2017-10-31 14:33:34 +01002136 /* Handle channels activity */
Christopher Faulet839791a2019-01-07 16:12:07 +01002137 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002138
2139 /* Filter HTTP requests and responses */
2140 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01002141 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01002142 .http_end = cache_store_http_end,
William Lallemand41db4602017-10-30 11:15:51 +01002143};
2144
Christopher Faulet99a17a22018-12-11 09:18:27 +01002145
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002146#define CHECK_ENCODING(str, encoding_name, encoding_value) \
2147 ({ \
2148 int retval = 0; \
2149 if (istmatch(str, (struct ist){ .ptr = encoding_name+1, .len = sizeof(encoding_name) - 2 })) { \
2150 retval = encoding_value; \
2151 encoding = istadv(encoding, sizeof(encoding_name) - 2); \
2152 } \
2153 (retval); \
2154 })
2155
2156/*
2157 * Parse the encoding <encoding> and try to match the encoding part upon an
2158 * encoding list of explicitly supported encodings (which all have a specific
2159 * bit in an encoding bitmap). If a weight is included in the value, find out if
2160 * it is null or not. The bit value will be set in the <encoding_value>
2161 * parameter and the <has_null_weight> will be set to 1 if the weight is strictly
2162 * 0, 1 otherwise.
2163 * The encodings list is extracted from
2164 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml.
2165 * Returns 0 in case of success and -1 in case of error.
2166 */
2167static int parse_encoding_value(struct ist encoding, unsigned int *encoding_value,
2168 unsigned int *has_null_weight)
2169{
2170 int retval = 0;
2171
2172 if (!encoding_value)
2173 return -1;
2174
2175 if (!istlen(encoding))
2176 return -1; /* Invalid encoding */
2177
2178 *encoding_value = 0;
2179 if (has_null_weight)
2180 *has_null_weight = 0;
2181
2182 switch (*encoding.ptr) {
2183 case 'a':
2184 encoding = istadv(encoding, 1);
2185 *encoding_value = CHECK_ENCODING(encoding, "aes128gcm", VARY_ENCODING_AES128GCM);
2186 break;
2187 case 'b':
2188 encoding = istadv(encoding, 1);
2189 *encoding_value = CHECK_ENCODING(encoding, "br", VARY_ENCODING_BR);
2190 break;
2191 case 'c':
2192 encoding = istadv(encoding, 1);
2193 *encoding_value = CHECK_ENCODING(encoding, "compress", VARY_ENCODING_COMPRESS);
2194 break;
2195 case 'd':
2196 encoding = istadv(encoding, 1);
2197 *encoding_value = CHECK_ENCODING(encoding, "deflate", VARY_ENCODING_DEFLATE);
2198 break;
2199 case 'e':
2200 encoding = istadv(encoding, 1);
2201 *encoding_value = CHECK_ENCODING(encoding, "exi", VARY_ENCODING_EXI);
2202 break;
2203 case 'g':
2204 encoding = istadv(encoding, 1);
2205 *encoding_value = CHECK_ENCODING(encoding, "gzip", VARY_ENCODING_GZIP);
2206 break;
2207 case 'i':
2208 encoding = istadv(encoding, 1);
2209 *encoding_value = CHECK_ENCODING(encoding, "identity", VARY_ENCODING_IDENTITY);
2210 break;
2211 case 'p':
2212 encoding = istadv(encoding, 1);
2213 *encoding_value = CHECK_ENCODING(encoding, "pack200-gzip", VARY_ENCODING_PACK200_GZIP);
2214 break;
2215 case 'x':
2216 encoding = istadv(encoding, 1);
2217 *encoding_value = CHECK_ENCODING(encoding, "x-gzip", VARY_ENCODING_GZIP);
2218 if (!*encoding_value)
2219 *encoding_value = CHECK_ENCODING(encoding, "x-compress", VARY_ENCODING_COMPRESS);
2220 break;
2221 case 'z':
2222 encoding = istadv(encoding, 1);
2223 *encoding_value = CHECK_ENCODING(encoding, "zstd", VARY_ENCODING_ZSTD);
2224 break;
2225 case '*':
2226 encoding = istadv(encoding, 1);
2227 *encoding_value = VARY_ENCODING_STAR;
2228 break;
2229 default:
2230 retval = -1; /* Unmanaged encoding */
2231 break;
2232 }
2233
2234 /* Process the optional weight part of the encoding. */
2235 if (*encoding_value) {
2236 encoding = http_trim_leading_spht(encoding);
2237 if (istlen(encoding)) {
2238 if (*encoding.ptr != ';')
2239 return -1;
2240
2241 if (has_null_weight) {
2242 encoding = istadv(encoding, 1);
2243
2244 encoding = http_trim_leading_spht(encoding);
2245
2246 *has_null_weight = isteq(encoding, ist("q=0"));
2247 }
2248 }
2249 }
2250
2251 return retval;
2252}
2253
Tim Duesterhus23b29452020-11-24 22:22:56 +01002254#define ACCEPT_ENCODING_MAX_ENTRIES 16
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002255/*
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002256 * Build a bitmap of the accept-encoding header.
2257 *
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002258 * The bitmap is built by matching every sub-part of the accept-encoding value
2259 * with a subset of explicitly supported encodings, which all have their own bit
2260 * in the bitmap. This bitmap will be used to determine if a response can be
2261 * served to a client (that is if it has an encoding that is accepted by the
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002262 * client). Any unknown encodings will be indicated by the VARY_ENCODING_OTHER
2263 * bit.
2264 *
2265 * Returns 0 in case of success and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002266 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002267static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
2268 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002269{
Tim Duesterhus23b29452020-11-24 22:22:56 +01002270 size_t count = 0;
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002271 uint32_t encoding_bitmap = 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002272 unsigned int encoding_bmp_bl = -1;
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002273 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002274 unsigned int encoding_value;
2275 unsigned int rejected_encoding;
2276
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002277 /* A user agent always accepts an unencoded value unless it explicitly
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002278 * refuses it through an "identity;q=0" accept-encoding value. */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002279 encoding_bitmap |= VARY_ENCODING_IDENTITY;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002280
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002281 /* Iterate over all the ACCEPT_ENCODING_MAX_ENTRIES first accept-encoding
2282 * values that might span acrosse multiple accept-encoding headers. */
2283 while (http_find_header(htx, hdr_name, &ctx, 0) && count < ACCEPT_ENCODING_MAX_ENTRIES) {
2284 /* Turn accept-encoding value to lower case */
2285 ist2bin_lc(istptr(ctx.value), ctx.value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002286
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002287 /* Try to identify a known encoding and to manage null weights. */
2288 if (!parse_encoding_value(ctx.value, &encoding_value, &rejected_encoding)) {
2289 if (rejected_encoding)
2290 encoding_bmp_bl &= ~encoding_value;
2291 else
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002292 encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002293 }
2294 else {
2295 /* Unknown encoding */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002296 encoding_bitmap |= VARY_ENCODING_OTHER;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002297 }
2298
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002299 count++;
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002300 }
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002301
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002302 /* If a "*" was found in the accepted encodings (without a null weight),
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002303 * all the encoding are accepted except the ones explicitly rejected. */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002304 if (encoding_bitmap & VARY_ENCODING_STAR) {
2305 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002306 }
2307
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002308 /* Clear explicitly rejected encodings from the bitmap */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002309 encoding_bitmap &= encoding_bmp_bl;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002310
2311 /* As per RFC7231#5.3.4, "If no Accept-Encoding field is in the request,
2312 * any content-coding is considered acceptable by the user agent". */
2313 if (count == 0)
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002314 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002315
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002316 /* A request with more than ACCEPT_ENCODING_MAX_ENTRIES accepted
2317 * encodings might be illegitimate so we will not use it. */
2318 if (count == ACCEPT_ENCODING_MAX_ENTRIES)
2319 return -1;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002320
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002321 write_u32(buf, encoding_bitmap);
2322 *buf_len = sizeof(encoding_bitmap);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002323
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002324 /* This function fills the hash buffer correctly even if no header was
2325 * found, hence the 0 return value (success). */
Tim Duesterhus23b29452020-11-24 22:22:56 +01002326 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002327}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002328#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002329
2330/*
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002331 * Normalizer used by default for the Referer header. It only
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002332 * calculates a simple crc of the whole value.
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002333 * Only the first occurrence of the header will be taken into account in the
2334 * hash.
2335 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2336 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002337 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002338static int default_normalizer(struct htx *htx, struct ist hdr_name,
2339 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002340{
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002341 int retval = 1;
2342 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002343
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002344 if (http_find_header(htx, hdr_name, &ctx, 1)) {
2345 retval = 0;
2346 write_u32(buf, hash_crc32(istptr(ctx.value), istlen(ctx.value)));
2347 *buf_len = sizeof(int);
2348 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002349
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002350 return retval;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002351}
2352
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002353/*
Tim Duesterhused84d842021-01-18 13:41:17 +01002354 * Accept-Encoding bitmap comparison function.
2355 * Returns 0 if the bitmaps are compatible.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002356 */
Tim Duesterhused84d842021-01-18 13:41:17 +01002357static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002358{
Tim Duesterhused84d842021-01-18 13:41:17 +01002359 uint32_t ref_bitmap = read_u32(ref);
2360 uint32_t new_bitmap = read_u32(new);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002361
Tim Duesterhused84d842021-01-18 13:41:17 +01002362 if (!(ref_bitmap & VARY_ENCODING_OTHER)) {
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002363 /* All the bits set in the reference bitmap correspond to the
2364 * stored response' encoding and should all be set in the new
2365 * encoding bitmap in order for the client to be able to manage
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002366 * the response.
2367 *
2368 * If this is the case the cached response has encodings that
2369 * are accepted by the client. It can be served directly by
2370 * the cache (as far as the accept-encoding part is concerned).
2371 */
2372
Tim Duesterhused84d842021-01-18 13:41:17 +01002373 return (ref_bitmap & new_bitmap) != ref_bitmap;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002374 }
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002375 else {
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002376 return 1;
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002377 }
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002378}
2379
2380
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002381/*
2382 * Pre-calculate the hashes of all the supported headers (in our Vary
2383 * implementation) of a given request. We have to calculate all the hashes
2384 * in advance because the actual Vary signature won't be known until the first
2385 * response.
2386 * Only the first occurrence of every header will be taken into account in the
2387 * hash.
2388 * If the header is not present, the hash portion of the given header will be
2389 * filled with zeros.
2390 * Returns 0 in case of success.
2391 */
2392static int http_request_prebuild_full_secondary_key(struct stream *s)
2393{
Remi Tricot-Le Bretonbba29122020-12-23 18:13:44 +01002394 /* The fake signature (second parameter) will ensure that every part of the
2395 * secondary key is calculated. */
2396 return http_request_build_secondary_key(s, ~0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002397}
2398
2399
2400/*
2401 * Calculate the secondary key for a request for which we already have a known
2402 * vary signature. The key is made by aggregating hashes calculated for every
2403 * header mentioned in the vary signature.
2404 * Only the first occurrence of every header will be taken into account in the
2405 * hash.
2406 * If the header is not present, the hash portion of the given header will be
2407 * filled with zeros.
2408 * Returns 0 in case of success.
2409 */
2410static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2411{
2412 struct http_txn *txn = s->txn;
2413 struct htx *htx = htxbuf(&s->req.buf);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002414
2415 unsigned int idx;
2416 const struct vary_hashing_information *info = NULL;
2417 unsigned int hash_length = 0;
2418 int retval = 0;
2419 int offset = 0;
2420
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002421 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && retval >= 0; ++idx) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002422 info = &vary_information[idx];
2423
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002424 /* The normalizing functions will be in charge of getting the
2425 * header values from the htx. This way they can manage multiple
2426 * occurrences of their processed header. */
2427 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2428 !(retval = info->norm_fn(htx, info->hdr_name, &txn->cache_secondary_hash[offset], &hash_length))) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002429 offset += hash_length;
2430 }
2431 else {
2432 /* Fill hash with 0s. */
2433 hash_length = info->hash_length;
2434 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2435 offset += hash_length;
2436 }
2437 }
2438
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01002439 if (retval >= 0)
2440 txn->flags |= TX_CACHE_HAS_SEC_KEY;
2441
2442 return (retval < 0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002443}
2444
2445/*
2446 * Build the actual secondary key of a given request out of the prebuilt key and
2447 * the actual vary signature (extracted from the response).
2448 * Returns 0 in case of success.
2449 */
2450static int http_request_reduce_secondary_key(unsigned int vary_signature,
2451 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2452{
2453 int offset = 0;
2454 int global_offset = 0;
2455 int vary_info_count = 0;
2456 int keep = 0;
2457 unsigned int vary_idx;
2458 const struct vary_hashing_information *vary_info;
2459
2460 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2461 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2462 vary_info = &vary_information[vary_idx];
2463 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2464
2465 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2466 prebuilt_key[global_offset] &= keep;
2467 }
2468 }
2469
2470 return 0;
2471}
2472
2473
Christopher Faulet99a17a22018-12-11 09:18:27 +01002474
2475static int
2476parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2477 struct flt_conf *fconf, char **err, void *private)
2478{
2479 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002480 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002481 char *name = NULL;
2482 int pos = *cur_arg;
2483
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002484 /* Get the cache filter name. <pos> point on "cache" keyword */
2485 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002486 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002487 goto error;
2488 }
2489 name = strdup(args[pos + 1]);
2490 if (!name) {
2491 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2492 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002493 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002494 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002495
2496 /* Check if an implicit filter with the same name already exists. If so,
2497 * we remove the implicit filter to use the explicit one. */
2498 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2499 if (f->id != cache_store_flt_id)
2500 continue;
2501
2502 cconf = f->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002503 if (strcmp(name, cconf->c.name) != 0) {
Christopher Faulet99a17a22018-12-11 09:18:27 +01002504 cconf = NULL;
2505 continue;
2506 }
2507
2508 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2509 cconf = NULL;
2510 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2511 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002512 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002513 }
2514
2515 /* Remove the implicit filter. <cconf> is kept for the explicit one */
2516 LIST_DEL(&f->list);
2517 free(f);
2518 free(name);
2519 break;
2520 }
2521
2522 /* No implicit cache filter found, create configuration for the explicit one */
2523 if (!cconf) {
2524 cconf = calloc(1, sizeof(*cconf));
2525 if (!cconf) {
2526 memprintf(err, "%s: out of memory", args[*cur_arg]);
2527 goto error;
2528 }
2529 cconf->c.name = name;
2530 }
2531
2532 cconf->flags = 0;
2533 fconf->id = cache_store_flt_id;
2534 fconf->conf = cconf;
2535 fconf->ops = &cache_ops;
2536
2537 *cur_arg = pos;
2538 return 0;
2539
2540 error:
2541 free(name);
2542 free(cconf);
2543 return -1;
2544}
2545
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002546static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002547{
2548 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2549 return 1;
2550
2551 return 0;
2552}
2553
2554static int cli_io_handler_show_cache(struct appctx *appctx)
2555{
2556 struct cache* cache = appctx->ctx.cli.p0;
2557 struct stream_interface *si = appctx->owner;
2558
William Lallemand1f49a362017-11-21 20:01:26 +01002559 if (cache == NULL) {
2560 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
2561 }
2562
2563 list_for_each_entry_from(cache, &caches, list) {
2564 struct eb32_node *node = NULL;
2565 unsigned int next_key;
2566 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002567 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002568
William Lallemand1f49a362017-11-21 20:01:26 +01002569 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002570 if (!next_key) {
2571 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
2572 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002573 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002574 return 0;
2575 }
2576 }
William Lallemand1f49a362017-11-21 20:01:26 +01002577
2578 appctx->ctx.cli.p0 = cache;
2579
2580 while (1) {
2581
2582 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002583 if (!node || (node = eb32_next_dup(node)) == NULL)
2584 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002585 if (!node) {
2586 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02002587 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002588 break;
2589 }
2590
2591 entry = container_of(node, struct cache_entry, eb);
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002592 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2593 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2594 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2595 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 +01002596
2597 next_key = node->key + 1;
2598 appctx->ctx.cli.i0 = next_key;
2599
2600 shctx_unlock(shctx_ptr(cache));
2601
2602 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002603 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002604 return 0;
2605 }
2606 }
2607
2608 }
2609
2610 return 1;
2611
2612}
2613
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002614
2615/*
2616 * boolean, returns true if response was built out of a cache entry.
2617 */
2618static int
2619smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2620 const char *kw, void *private)
2621{
2622 smp->data.type = SMP_T_BOOL;
2623 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2624
2625 return 1;
2626}
2627
2628/*
2629 * string, returns cache name (if response came from a cache).
2630 */
2631static int
2632smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2633 const char *kw, void *private)
2634{
2635 struct appctx *appctx = NULL;
2636
2637 struct cache_flt_conf *cconf = NULL;
2638 struct cache *cache = NULL;
2639
2640 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2641 return 0;
2642
2643 /* Get appctx from the stream_interface. */
2644 appctx = si_appctx(&smp->strm->si[1]);
2645 if (appctx && appctx->rule) {
2646 cconf = appctx->rule->arg.act.p[0];
2647 if (cconf) {
2648 cache = cconf->c.cache;
2649
2650 smp->data.type = SMP_T_STR;
2651 smp->flags = SMP_F_CONST;
2652 smp->data.u.str.area = cache->id;
2653 smp->data.u.str.data = strlen(cache->id);
2654 return 1;
2655 }
2656 }
2657
2658 return 0;
2659}
2660
Christopher Faulet99a17a22018-12-11 09:18:27 +01002661/* Declare the filter parser for "cache" keyword */
2662static struct flt_kw_list filter_kws = { "CACHE", { }, {
2663 { "cache", parse_cache_flt, NULL },
2664 { NULL, NULL, NULL },
2665 }
2666};
2667
2668INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2669
William Lallemand1f49a362017-11-21 20:01:26 +01002670static struct cli_kw_list cli_kws = {{},{
William Lallemande899af82017-11-22 16:41:26 +01002671 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
2672 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002673}};
2674
Willy Tarreau0108d902018-11-25 19:14:37 +01002675INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002676
William Lallemand41db4602017-10-30 11:15:51 +01002677static struct action_kw_list http_res_actions = {
2678 .kw = {
2679 { "cache-store", parse_cache_store },
2680 { NULL, NULL }
2681 }
2682};
2683
Willy Tarreau0108d902018-11-25 19:14:37 +01002684INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2685
William Lallemand41db4602017-10-30 11:15:51 +01002686static struct action_kw_list http_req_actions = {
2687 .kw = {
2688 { "cache-use", parse_cache_use },
2689 { NULL, NULL }
2690 }
2691};
2692
Willy Tarreau0108d902018-11-25 19:14:37 +01002693INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2694
Willy Tarreau2231b632019-03-29 18:26:52 +01002695struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002696 .obj_type = OBJ_TYPE_APPLET,
2697 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002698 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002699 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002700};
2701
Willy Tarreaue6552512018-11-26 11:33:13 +01002702/* config parsers for this section */
2703REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002704REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002705
2706
2707/* Note: must not be declared <const> as its list will be overwritten */
2708static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2709 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2710 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2711 { /* END */ },
2712 }
2713};
2714
2715INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);