blob: 1aa1103a6b707a854e80db1b386095ff2df09913 [file] [log] [blame]
William Lallemand41db4602017-10-30 11:15:51 +01001/*
2 * Cache management
3 *
4 * Copyright 2017 HAProxy Technologies
5 * William Lallemand <wlallemand@haproxy.com>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 */
12
Willy Tarreaub2551052020-06-09 09:07:15 +020013#include <import/eb32tree.h>
14#include <import/sha1.h>
15
Willy Tarreau122eba92020-06-04 10:15:32 +020016#include <haproxy/action-t.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020017#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020018#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020019#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020020#include <haproxy/cli.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020021#include <haproxy/errors.h>
Willy Tarreauc7babd82020-06-04 21:29:29 +020022#include <haproxy/filters.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020023#include <haproxy/hash.h>
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +020024#include <haproxy/http.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020025#include <haproxy/http_ana.h>
Willy Tarreau87735332020-06-04 09:08:41 +020026#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020027#include <haproxy/http_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/htx.h>
29#include <haproxy/net_helper.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020030#include <haproxy/proxy.h>
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +010031#include <haproxy/sample.h>
Willy Tarreau334099c2020-06-03 18:38:48 +020032#include <haproxy/shctx.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020033#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020034#include <haproxy/stream_interface.h>
Willy Tarreauce6700a2021-05-08 13:03:55 +020035#include <haproxy/tools.h>
William Lallemand41db4602017-10-30 11:15:51 +010036
Christopher Faulet27d93c32018-12-15 22:32:02 +010037#define CACHE_FLT_F_IMPLICIT_DECL 0x00000001 /* The cache filtre was implicitly declared (ie without
Christopher Faulet99a17a22018-12-11 09:18:27 +010038 * the filter keyword) */
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +020039#define CACHE_FLT_INIT 0x00000002 /* Whether the cache name was freed. */
Christopher Fauletafd819c2018-12-11 08:57:45 +010040
Christopher Fauletf4a4ef72018-12-07 17:39:53 +010041const char *cache_store_flt_id = "cache store filter";
William Lallemand41db4602017-10-30 11:15:51 +010042
Willy Tarreau2231b632019-03-29 18:26:52 +010043extern struct applet http_cache_applet;
William Lallemand41db4602017-10-30 11:15:51 +010044
45struct flt_ops cache_ops;
46
47struct cache {
Willy Tarreaufd5efb52017-11-26 08:54:31 +010048 struct list list; /* cache linked list */
William Lallemand41db4602017-10-30 11:15:51 +010049 struct eb_root entries; /* head of cache entries based on keys */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010050 unsigned int maxage; /* max-age */
51 unsigned int maxblocks;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +020052 unsigned int maxobjsz; /* max-object-size (in bytes) */
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +010053 unsigned int max_secondary_entries; /* maximum number of secondary entries with the same primary hash */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +010054 uint8_t vary_processing_enabled; /* boolean : manage Vary header (disabled by default) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010055 char id[33]; /* cache name */
William Lallemand41db4602017-10-30 11:15:51 +010056};
57
Christopher Faulet95220e22018-12-07 17:34:39 +010058/* cache config for filters */
59struct cache_flt_conf {
60 union {
61 struct cache *cache; /* cache used by the filter */
62 char *name; /* cache name used during conf parsing */
63 } c;
64 unsigned int flags; /* CACHE_FLT_F_* */
65};
66
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010067
68/*
69 * Vary-related structures and functions
70 */
71enum vary_header_bit {
72 VARY_ACCEPT_ENCODING = (1 << 0),
73 VARY_REFERER = (1 << 1),
74 VARY_LAST /* should always be last */
75};
76
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +010077/*
78 * Encoding list extracted from
79 * https://www.iana.org/assignments/http-parameters/http-parameters.xhtml
80 * and RFC7231#5.3.4.
81 */
82enum vary_encoding {
83 VARY_ENCODING_GZIP = (1 << 0),
84 VARY_ENCODING_DEFLATE = (1 << 1),
85 VARY_ENCODING_BR = (1 << 2),
86 VARY_ENCODING_COMPRESS = (1 << 3),
87 VARY_ENCODING_AES128GCM = (1 << 4),
88 VARY_ENCODING_EXI = (1 << 5),
89 VARY_ENCODING_PACK200_GZIP = (1 << 6),
90 VARY_ENCODING_ZSTD = (1 << 7),
91 VARY_ENCODING_IDENTITY = (1 << 8),
92 VARY_ENCODING_STAR = (1 << 9),
93 VARY_ENCODING_OTHER = (1 << 10)
94};
95
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010096struct vary_hashing_information {
97 struct ist hdr_name; /* Header name */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +050098 enum vary_header_bit value; /* Bit representing the header in a vary signature */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +010099 unsigned int hash_length; /* Size of the sub hash for this header's value */
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100100 int(*norm_fn)(struct htx*,struct ist hdr_name,char* buf,unsigned int* buf_len); /* Normalization function */
Tim Duesterhused84d842021-01-18 13:41:17 +0100101 int(*cmp_fn)(const void *ref, const void *new, unsigned int len); /* Comparison function, should return 0 if the hashes are alike */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100102};
103
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100104static int http_request_prebuild_full_secondary_key(struct stream *s);
105static int http_request_build_secondary_key(struct stream *s, int vary_signature);
106static int http_request_reduce_secondary_key(unsigned int vary_signature,
107 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN]);
108
109static int parse_encoding_value(struct ist value, unsigned int *encoding_value,
110 unsigned int *has_null_weight);
111
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +0100112static int accept_encoding_normalizer(struct htx *htx, struct ist hdr_name,
113 char *buf, unsigned int *buf_len);
114static int default_normalizer(struct htx *htx, struct ist hdr_name,
115 char *buf, unsigned int *buf_len);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100116
Tim Duesterhused84d842021-01-18 13:41:17 +0100117static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100118
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100119/* Warning : do not forget to update HTTP_CACHE_SEC_KEY_LEN when new items are
120 * added to this array. */
121const struct vary_hashing_information vary_information[] = {
Tim Duesterhused84d842021-01-18 13:41:17 +0100122 { IST("accept-encoding"), VARY_ACCEPT_ENCODING, sizeof(uint32_t), &accept_encoding_normalizer, &accept_encoding_bitmap_cmp },
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100123 { IST("referer"), VARY_REFERER, sizeof(int), &default_normalizer, NULL },
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100124};
125
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100126
William Lallemand41db4602017-10-30 11:15:51 +0100127/*
128 * cache ctx for filters
129 */
130struct cache_st {
William Lallemand41db4602017-10-30 11:15:51 +0100131 struct shared_block *first_block;
132};
133
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100134#define DEFAULT_MAX_SECONDARY_ENTRY 10
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100135
William Lallemand41db4602017-10-30 11:15:51 +0100136struct cache_entry {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100137 unsigned int complete; /* An entry won't be valid until complete is not null. */
William Lallemand41db4602017-10-30 11:15:51 +0100138 unsigned int latest_validation; /* latest validation date */
139 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200140 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100141
William Lallemand41db4602017-10-30 11:15:51 +0100142 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +0100143 char hash[20];
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200144
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100145 char secondary_key[HTTP_CACHE_SEC_KEY_LEN]; /* Optional secondary key. */
146 unsigned int secondary_key_signature; /* Bitfield of the HTTP headers that should be used
147 * to build secondary keys for this cache entry. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100148 unsigned int secondary_entries_count; /* Should only be filled in the last entry of a list of dup entries */
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100149 unsigned int last_clear_ts; /* Timestamp of the last call to clear_expired_duplicates. */
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100150
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +0200151 unsigned int etag_length; /* Length of the ETag value (if one was found in the response). */
152 unsigned int etag_offset; /* Offset of the ETag value in the data buffer. */
153
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200154 time_t last_modified; /* Origin server "Last-Modified" header value converted in
155 * seconds since epoch. If no "Last-Modified"
156 * header is found, use "Date" header value,
157 * otherwise use reception time. This field will
158 * be used in case of an "If-Modified-Since"-based
159 * conditional request. */
160
William Lallemand41db4602017-10-30 11:15:51 +0100161 unsigned char data[0];
162};
163
164#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +0100165#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +0100166
167static struct list caches = LIST_HEAD_INIT(caches);
William Lallemandd1d1e222019-08-28 15:22:49 +0200168static struct list caches_config = LIST_HEAD_INIT(caches_config); /* cache config to init */
William Lallemand41db4602017-10-30 11:15:51 +0100169static struct cache *tmp_cache_config = NULL;
170
Willy Tarreau8ceae722018-11-26 11:58:30 +0100171DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
172
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100173static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry);
174static void delete_entry(struct cache_entry *del_entry);
175
William Lallemandf528fff2017-11-23 19:43:17 +0100176struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100177{
178 struct eb32_node *node;
179 struct cache_entry *entry;
180
Willy Tarreau8b507582020-02-25 09:35:07 +0100181 node = eb32_lookup(&cache->entries, read_u32(hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100182 if (!node)
183 return NULL;
184
185 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100186
187 /* if that's not the right node */
188 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
189 return NULL;
190
William Lallemand08727662017-11-21 20:01:27 +0100191 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100192 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100193 } else {
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100194 delete_entry(entry);
William Lallemand08727662017-11-21 20:01:27 +0100195 entry->eb.key = 0;
196 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100197 return NULL;
198
199}
200
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100201
202/*
203 * Compare a newly built secondary key to the one found in a cache_entry.
204 * Every sub-part of the key is compared to the reference through the dedicated
205 * comparison function of the sub-part (that might do more than a simple
206 * memcmp).
207 * Returns 0 if the keys are alike.
208 */
209static int secondary_key_cmp(const char *ref_key, const char *new_key)
210{
211 int retval = 0;
Tim Duesterhus5897cfe2021-01-18 13:41:18 +0100212 size_t idx = 0;
213 unsigned int offset = 0;
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100214 const struct vary_hashing_information *info;
215
216 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && !retval; ++idx) {
217 info = &vary_information[idx];
218
219 if (info->cmp_fn)
220 retval = info->cmp_fn(&ref_key[offset], &new_key[offset], info->hash_length);
221 else
222 retval = memcmp(&ref_key[offset], &new_key[offset], info->hash_length);
223
224 offset += info->hash_length;
225 }
226
227 return retval;
228}
229
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100230/*
231 * There can be multiple entries with the same primary key in the ebtree so in
232 * order to get the proper one out of the list, we use a secondary_key.
233 * This function simply iterates over all the entries with the same primary_key
234 * until it finds the right one.
235 * Returns the cache_entry in case of success, NULL otherwise.
236 */
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100237struct cache_entry *secondary_entry_exist(struct cache *cache, struct cache_entry *entry,
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100238 const char *secondary_key)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100239{
240 struct eb32_node *node = &entry->eb;
241
242 if (!entry->secondary_key_signature)
243 return NULL;
244
Remi Tricot-Le Breton6a34b2b2020-12-23 18:13:47 +0100245 while (entry && secondary_key_cmp(entry->secondary_key, secondary_key) != 0) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100246 node = eb32_next_dup(node);
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100247
248 /* Make the best use of this iteration and clear expired entries
249 * when we find them. Calling delete_entry would be too costly
250 * so we simply call eb32_delete. The secondary_entry count will
251 * be updated when we try to insert a new entry to this list. */
252 if (entry->expire <= now.tv_sec) {
253 eb32_delete(&entry->eb);
254 entry->eb.key = 0;
255 }
256
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100257 entry = node ? eb32_entry(node, struct cache_entry, eb) : NULL;
258 }
259
260 /* Expired entry */
261 if (entry && entry->expire <= now.tv_sec) {
262 eb32_delete(&entry->eb);
263 entry->eb.key = 0;
264 entry = NULL;
265 }
266
267 return entry;
268}
269
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100270
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100271/*
272 * Remove all expired entries from a list of duplicates.
273 * Return the number of alive entries in the list and sets dup_tail to the
274 * current last item of the list.
275 */
276static unsigned int clear_expired_duplicates(struct eb32_node **dup_tail)
277{
278 unsigned int entry_count = 0;
279 struct cache_entry *entry = NULL;
280 struct eb32_node *prev = *dup_tail;
281 struct eb32_node *tail = NULL;
282
283 while (prev) {
284 entry = container_of(prev, struct cache_entry, eb);
285 prev = eb32_prev_dup(prev);
286 if (entry->expire <= now.tv_sec) {
287 eb32_delete(&entry->eb);
288 entry->eb.key = 0;
289 }
290 else {
291 if (!tail)
292 tail = &entry->eb;
293 ++entry_count;
294 }
295 }
296
297 *dup_tail = tail;
298
299 return entry_count;
300}
301
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100302
303/*
304 * This function inserts a cache_entry in the cache's ebtree. In case of
305 * duplicate entries (vary), it then checks that the number of entries did not
306 * reach the max number of secondary entries. If this entry should not have been
307 * created, remove it.
308 * In the regular case (unique entries), this function does not do more than a
309 * simple insert. In case of secondary entries, it will at most cost an
310 * insertion+max_sec_entries time checks and entry deletion.
311 * Returns the newly inserted node in case of success, NULL otherwise.
312 */
313static struct eb32_node *insert_entry(struct cache *cache, struct cache_entry *new_entry)
314{
315 struct eb32_node *prev = NULL;
316 struct cache_entry *entry = NULL;
317 unsigned int entry_count = 0;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100318 unsigned int last_clear_ts = now.tv_sec;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100319
320 struct eb32_node *node = eb32_insert(&cache->entries, &new_entry->eb);
321
322 /* We should not have multiple entries with the same primary key unless
323 * the entry has a non null vary signature. */
324 if (!new_entry->secondary_key_signature)
325 return node;
326
327 prev = eb32_prev_dup(node);
328 if (prev != NULL) {
329 /* The last entry of a duplicate list should contain the current
330 * number of entries in the list. */
331 entry = container_of(prev, struct cache_entry, eb);
332 entry_count = entry->secondary_entries_count;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100333 last_clear_ts = entry->last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100334
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100335 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100336 /* Some entries of the duplicate list might be expired so
337 * we will iterate over all the items in order to free some
338 * space. In order to avoid going over the same list too
339 * often, we first check the timestamp of the last check
340 * performed. */
341 if (last_clear_ts == now.tv_sec) {
342 /* Too many entries for this primary key, clear the
343 * one that was inserted. */
344 eb32_delete(node);
345 node->key = 0;
346 return NULL;
347 }
348
349 entry_count = clear_expired_duplicates(&prev);
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +0100350 if (entry_count >= cache->max_secondary_entries) {
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100351 /* Still too many entries for this primary key, delete
352 * the newly inserted one. */
353 entry = container_of(prev, struct cache_entry, eb);
354 entry->last_clear_ts = now.tv_sec;
355 eb32_delete(node);
356 node->key = 0;
357 return NULL;
358 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100359 }
360 }
361
362 new_entry->secondary_entries_count = entry_count + 1;
Remi Tricot-Le Breton73be7962020-12-10 17:58:42 +0100363 new_entry->last_clear_ts = last_clear_ts;
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100364
365 return node;
366}
367
368
369/*
370 * This function removes an entry from the ebtree. If the entry was a duplicate
371 * (in case of Vary), it updates the secondary entry counter in another
372 * duplicate entry (the last entry of the dup list).
373 */
374static void delete_entry(struct cache_entry *del_entry)
375{
376 struct eb32_node *prev = NULL, *next = NULL;
377 struct cache_entry *entry = NULL;
378 struct eb32_node *last = NULL;
379
380 if (del_entry->secondary_key_signature) {
381 next = &del_entry->eb;
382
383 /* Look for last entry of the duplicates list. */
384 while ((next = eb32_next_dup(next))) {
385 last = next;
386 }
387
388 if (last) {
389 entry = container_of(last, struct cache_entry, eb);
390 --entry->secondary_entries_count;
391 }
392 else {
393 /* The current entry is the last one, look for the
394 * previous one to update its counter. */
395 prev = eb32_prev_dup(&del_entry->eb);
396 if (prev) {
397 entry = container_of(prev, struct cache_entry, eb);
398 entry->secondary_entries_count = del_entry->secondary_entries_count - 1;
399 }
400 }
401 }
402 eb32_delete(&del_entry->eb);
403 del_entry->eb.key = 0;
404}
405
406
William Lallemand4da3f8a2017-10-31 14:33:34 +0100407static inline struct shared_context *shctx_ptr(struct cache *cache)
408{
409 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
410}
411
William Lallemand77c11972017-10-31 20:43:01 +0100412static inline struct shared_block *block_ptr(struct cache_entry *entry)
413{
414 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
415}
416
417
418
William Lallemand41db4602017-10-30 11:15:51 +0100419static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100420cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100421{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100422 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100423 return 0;
424}
425
Christopher Faulet95220e22018-12-07 17:34:39 +0100426static void
427cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
428{
429 struct cache_flt_conf *cconf = fconf->conf;
430
Tim Duesterhusd7c6e6a2020-09-14 18:01:33 +0200431 if (!(cconf->flags & CACHE_FLT_INIT))
432 free(cconf->c.name);
Christopher Faulet95220e22018-12-07 17:34:39 +0100433 free(cconf);
434}
435
William Lallemand4da3f8a2017-10-31 14:33:34 +0100436static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100437cache_store_check(struct proxy *px, struct flt_conf *fconf)
438{
439 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100440 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100441 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100442 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100443
William Lallemandd1d1e222019-08-28 15:22:49 +0200444 /* Find the cache corresponding to the name in the filter config. The
445 * cache will not be referenced now in the filter config because it is
446 * not fully allocated. This step will be performed during the cache
447 * post_check.
448 */
449 list_for_each_entry(cache, &caches_config, list) {
Tim Duesterhuse5ff1412021-01-02 22:31:53 +0100450 if (strcmp(cache->id, cconf->c.name) == 0)
Christopher Faulet95220e22018-12-07 17:34:39 +0100451 goto found;
Christopher Faulet95220e22018-12-07 17:34:39 +0100452 }
453
454 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
455 proxy_type_str(px), px->id, (char *)cconf->c.name);
456 return 1;
457
458 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100459 /* Here <cache> points on the cache the filter must use and <cconf>
460 * points on the cache filter configuration. */
461
462 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100463 * enabled and if it is after the cache. When the compression is before
464 * the cache, an error is returned. Also check if the cache filter must
465 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100466 list_for_each_entry(f, &px->filter_configs, list) {
467 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100468 /* The compression filter must be evaluated after the cache. */
469 if (comp) {
470 ha_alert("config: %s '%s': unable to enable the compression filter before "
471 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
472 return 1;
473 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100474 }
Christopher Faulet8f7fe1c2019-07-15 15:08:25 +0200475 else if (f->id == http_comp_flt_id)
Christopher Faulet27d93c32018-12-15 22:32:02 +0100476 comp = 1;
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200477 else if (f->id == fcgi_flt_id)
478 continue;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100479 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
480 /* Implicit declaration is only allowed with the
Christopher Faulet78fbb9f2019-08-11 23:11:03 +0200481 * compression and fcgi. For other filters, an implicit
Christopher Faulet27d93c32018-12-15 22:32:02 +0100482 * declaration is required. */
483 ha_alert("config: %s '%s': require an explicit filter declaration "
484 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
485 return 1;
486 }
487
Christopher Fauletafd819c2018-12-11 08:57:45 +0100488 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100489 return 0;
490}
491
492static int
Christopher Faulet65554e12020-03-06 14:52:06 +0100493cache_store_strm_init(struct stream *s, struct filter *filter)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100494{
Christopher Faulet65554e12020-03-06 14:52:06 +0100495 struct cache_st *st;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100496
Willy Tarreauacc5b012021-03-22 15:00:49 +0100497 st = pool_alloc(pool_head_cache_st);
Christopher Faulet65554e12020-03-06 14:52:06 +0100498 if (st == NULL)
499 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100500
Christopher Faulet65554e12020-03-06 14:52:06 +0100501 st->first_block = NULL;
502 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100503
Christopher Faulet65554e12020-03-06 14:52:06 +0100504 /* Register post-analyzer on AN_RES_WAIT_HTTP */
505 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100506 return 1;
507}
508
Christopher Faulet65554e12020-03-06 14:52:06 +0100509static void
510cache_store_strm_deinit(struct stream *s, struct filter *filter)
William Lallemand49dc0482017-11-24 14:33:54 +0100511{
512 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100513 struct cache_flt_conf *cconf = FLT_CONF(filter);
514 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100515 struct shared_context *shctx = shctx_ptr(cache);
516
William Lallemand49dc0482017-11-24 14:33:54 +0100517 /* Everything should be released in the http_end filter, but we need to do it
518 * there too, in case of errors */
William Lallemand49dc0482017-11-24 14:33:54 +0100519 if (st && st->first_block) {
William Lallemand49dc0482017-11-24 14:33:54 +0100520 shctx_lock(shctx);
521 shctx_row_dec_hot(shctx, st->first_block);
522 shctx_unlock(shctx);
William Lallemand49dc0482017-11-24 14:33:54 +0100523 }
524 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100525 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100526 filter->ctx = NULL;
527 }
William Lallemand49dc0482017-11-24 14:33:54 +0100528}
529
Christopher Faulet839791a2019-01-07 16:12:07 +0100530static int
531cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
532 unsigned an_bit)
533{
534 struct http_txn *txn = s->txn;
535 struct http_msg *msg = &txn->rsp;
536 struct cache_st *st = filter->ctx;
537
538 if (an_bit != AN_RES_WAIT_HTTP)
539 goto end;
540
541 /* Here we need to check if any compression filter precedes the cache
542 * filter. This is only possible when the compression is configured in
543 * the frontend while the cache filter is configured on the
544 * backend. This case cannot be detected during HAProxy startup. So in
545 * such cases, the cache is disabled.
546 */
547 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
548 pool_free(pool_head_cache_st, st);
549 filter->ctx = NULL;
550 }
551
552 end:
553 return 1;
554}
William Lallemand49dc0482017-11-24 14:33:54 +0100555
556static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100557cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
558{
559 struct cache_st *st = filter->ctx;
560
William Lallemand4da3f8a2017-10-31 14:33:34 +0100561 if (!(msg->chn->flags & CF_ISRESP) || !st)
562 return 1;
563
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200564 if (st->first_block)
Christopher Faulet67658c92018-12-06 21:59:39 +0100565 register_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100566 return 1;
567}
568
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200569static inline void disable_cache_entry(struct cache_st *st,
570 struct filter *filter, struct shared_context *shctx)
571{
572 struct cache_entry *object;
573
574 object = (struct cache_entry *)st->first_block->data;
575 filter->ctx = NULL; /* disable cache */
576 shctx_lock(shctx);
577 shctx_row_dec_hot(shctx, st->first_block);
Remi Tricot-Le Breton964caaf2020-12-15 14:30:12 +0100578 eb32_delete(&object->eb);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200579 object->eb.key = 0;
580 shctx_unlock(shctx);
581 pool_free(pool_head_cache_st, st);
582}
583
William Lallemand4da3f8a2017-10-31 14:33:34 +0100584static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100585cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
586 unsigned int offset, unsigned int len)
587{
Christopher Faulet95220e22018-12-07 17:34:39 +0100588 struct cache_flt_conf *cconf = FLT_CONF(filter);
589 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100590 struct cache_st *st = filter->ctx;
591 struct htx *htx = htxbuf(&msg->chn->buf);
592 struct htx_blk *blk;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200593 struct shared_block *fb;
Christopher Faulet497c7592020-03-02 16:19:50 +0100594 struct htx_ret htxret;
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200595 unsigned int orig_len, to_forward;
596 int ret;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100597
598 if (!len)
599 return len;
600
601 if (!st->first_block) {
602 unregister_data_filter(s, msg->chn, filter);
603 return len;
604 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100605
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200606 chunk_reset(&trash);
607 orig_len = len;
608 to_forward = 0;
Christopher Faulet497c7592020-03-02 16:19:50 +0100609
610 htxret = htx_find_offset(htx, offset);
611 blk = htxret.blk;
612 offset = htxret.ret;
613 for (; blk && len; blk = htx_get_next_blk(htx, blk)) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100614 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200615 uint32_t info, sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100616 struct ist v;
617
618 switch (type) {
619 case HTX_BLK_UNUSED:
620 break;
621
622 case HTX_BLK_DATA:
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100623 v = htx_get_blk_value(htx, blk);
Tim Duesterhus154374c2021-03-02 18:57:27 +0100624 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +0100625 v = isttrim(v, len);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100626
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200627 info = (type << 28) + v.len;
628 chunk_memcat(&trash, (char *)&info, sizeof(info));
Tim Duesterhus77508502022-03-15 13:11:06 +0100629 chunk_istcat(&trash, v);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100630 to_forward += v.len;
631 len -= v.len;
632 break;
633
634 default:
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200635 /* Here offset must always be 0 because only
636 * DATA blocks can be partially transferred. */
637 if (offset)
638 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100639 if (sz > len)
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200640 goto end;
641
642 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
643 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100644 to_forward += sz;
645 len -= sz;
646 break;
647 }
648
649 offset = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100650 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200651
652 end:
653 shctx_lock(shctx);
654 fb = shctx_row_reserve_hot(shctx, st->first_block, trash.data);
655 if (!fb) {
656 shctx_unlock(shctx);
657 goto no_cache;
658 }
659 shctx_unlock(shctx);
660
661 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
662 (unsigned char *)b_head(&trash), b_data(&trash));
663 if (ret < 0)
664 goto no_cache;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100665
666 return to_forward;
667
668 no_cache:
669 disable_cache_entry(st, filter, shctx);
670 unregister_data_filter(s, msg->chn, filter);
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200671 return orig_len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100672}
673
674static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100675cache_store_http_end(struct stream *s, struct filter *filter,
676 struct http_msg *msg)
677{
678 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100679 struct cache_flt_conf *cconf = FLT_CONF(filter);
680 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100681 struct shared_context *shctx = shctx_ptr(cache);
682 struct cache_entry *object;
683
684 if (!(msg->chn->flags & CF_ISRESP))
685 return 1;
686
687 if (st && st->first_block) {
688
689 object = (struct cache_entry *)st->first_block->data;
690
William Lallemand4da3f8a2017-10-31 14:33:34 +0100691 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +0100692 /* The whole payload was cached, the entry can now be used. */
693 object->complete = 1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100694 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100695 shctx_row_dec_hot(shctx, st->first_block);
696 shctx_unlock(shctx);
697
698 }
699 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100700 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100701 filter->ctx = NULL;
702 }
703
704 return 1;
705}
706
707 /*
708 * This intends to be used when checking HTTP headers for some
709 * word=value directive. Return a pointer to the first character of value, if
Willy Tarreau94a01e12021-01-06 17:35:12 +0100710 * the word was not found or if there wasn't any value assigned to it return NULL
William Lallemand4da3f8a2017-10-31 14:33:34 +0100711 */
712char *directive_value(const char *sample, int slen, const char *word, int wlen)
713{
714 int st = 0;
715
716 if (slen < wlen)
717 return 0;
718
719 while (wlen) {
720 char c = *sample ^ *word;
721 if (c && c != ('A' ^ 'a'))
722 return NULL;
723 sample++;
724 word++;
725 slen--;
726 wlen--;
727 }
728
729 while (slen) {
730 if (st == 0) {
731 if (*sample != '=')
732 return NULL;
733 sample++;
734 slen--;
735 st = 1;
736 continue;
737 } else {
738 return (char *)sample;
739 }
740 }
741
742 return NULL;
743}
744
745/*
746 * Return the maxage in seconds of an HTTP response.
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100747 * The returned value will always take the cache's configuration into account
748 * (cache->maxage) but the actual max age of the response will be set in the
749 * true_maxage parameter. It will be used to determine if a response is already
750 * stale or not.
William Lallemand4da3f8a2017-10-31 14:33:34 +0100751 * Compute the maxage using either:
752 * - the assigned max-age of the cache
753 * - the s-maxage directive
754 * - the max-age directive
755 * - (Expires - Data) headers
756 * - the default-max-age of the cache
757 *
758 */
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100759int http_calc_maxage(struct stream *s, struct cache *cache, int *true_maxage)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100760{
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200761 struct htx *htx = htxbuf(&s->res.buf);
762 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100763 long smaxage = -1;
764 long maxage = -1;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100765 int expires = -1;
766 struct tm tm = {};
767 time_t expires_val = 0;
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100768 char *endptr = NULL;
769 int offset = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100770
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100771 /* The Cache-Control max-age and s-maxage directives should be followed by
772 * a positive numerical value (see RFC 7234#5.2.1.1). According to the
773 * specs, a sender "should not" generate a quoted-string value but we will
774 * still accept this format since it isn't strictly forbidden. */
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200775 while (http_find_header(htx, ist("cache-control"), &ctx, 0)) {
776 char *value;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100777
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200778 value = directive_value(ctx.value.ptr, ctx.value.len, "s-maxage", 8);
779 if (value) {
780 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100781
Willy Tarreau49b04822021-11-08 11:44:47 +0100782 chunk_memcat(chk, value, ctx.value.len - 8 + 1);
783 chunk_memcat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100784 offset = (*chk->area == '"') ? 1 : 0;
785 smaxage = strtol(chk->area + offset, &endptr, 10);
Willy Tarreau1f38bdb2021-11-08 12:09:27 +0100786 if (unlikely(smaxage < 0 || endptr == chk->area + offset))
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100787 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100788 }
789
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200790 value = directive_value(ctx.value.ptr, ctx.value.len, "max-age", 7);
791 if (value) {
792 struct buffer *chk = get_trash_chunk();
Christopher Faulet5f2c49f2019-07-15 20:49:46 +0200793
Willy Tarreau49b04822021-11-08 11:44:47 +0100794 chunk_memcat(chk, value, ctx.value.len - 7 + 1);
795 chunk_memcat(chk, "", 1);
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100796 offset = (*chk->area == '"') ? 1 : 0;
797 maxage = strtol(chk->area + offset, &endptr, 10);
Willy Tarreau1f38bdb2021-11-08 12:09:27 +0100798 if (unlikely(maxage < 0 || endptr == chk->area + offset))
Remi Tricot-Le Bretonfcea3742020-12-03 18:19:30 +0100799 return -1;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100800 }
801 }
802
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100803 /* Look for Expires header if no s-maxage or max-age Cache-Control data
804 * was found. */
805 if (maxage == -1 && smaxage == -1) {
806 ctx.blk = NULL;
807 if (http_find_header(htx, ist("expires"), &ctx, 1)) {
808 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
809 expires_val = my_timegm(&tm);
810 /* A request having an expiring date earlier
811 * than the current date should be considered as
812 * stale. */
813 expires = (expires_val >= now.tv_sec) ?
814 (expires_val - now.tv_sec) : 0;
815 }
816 else {
817 /* Following RFC 7234#5.3, an invalid date
818 * format must be treated as a date in the past
819 * so the cache entry must be seen as already
820 * expired. */
821 expires = 0;
822 }
823 }
824 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100825
826
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100827 if (smaxage > 0) {
828 if (true_maxage)
829 *true_maxage = smaxage;
William Lallemand49b44532017-11-24 18:53:43 +0100830 return MIN(smaxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100831 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100832
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100833 if (maxage > 0) {
834 if (true_maxage)
835 *true_maxage = maxage;
William Lallemand49b44532017-11-24 18:53:43 +0100836 return MIN(maxage, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100837 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100838
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100839 if (expires >= 0) {
840 if (true_maxage)
841 *true_maxage = expires;
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100842 return MIN(expires, cache->maxage);
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100843 }
Remi Tricot-Le Bretona6476112020-10-28 17:52:53 +0100844
William Lallemand49b44532017-11-24 18:53:43 +0100845 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100846
847}
848
849
William Lallemanda400a3a2017-11-20 19:13:12 +0100850static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
851{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200852 struct cache_entry *object = (struct cache_entry *)block->data;
853
854 if (first == block && object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +0100855 delete_entry(object);
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200856 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100857}
858
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +0200859
860/* As per RFC 7234#4.3.2, in case of "If-Modified-Since" conditional request, the
861 * date value should be compared to a date determined by in a previous response (for
862 * the same entity). This date could either be the "Last-Modified" value, or the "Date"
863 * value of the response's reception time (by decreasing order of priority). */
864static time_t get_last_modified_time(struct htx *htx)
865{
866 time_t last_modified = 0;
867 struct http_hdr_ctx ctx = { .blk = NULL };
868 struct tm tm = {};
869
870 if (http_find_header(htx, ist("last-modified"), &ctx, 1)) {
871 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
872 last_modified = my_timegm(&tm);
873 }
874 }
875
876 if (!last_modified) {
877 ctx.blk = NULL;
878 if (http_find_header(htx, ist("date"), &ctx, 1)) {
879 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
880 last_modified = my_timegm(&tm);
881 }
882 }
883 }
884
885 /* Fallback on the current time if no "Last-Modified" or "Date" header
886 * was found. */
887 if (!last_modified)
888 last_modified = now.tv_sec;
889
890 return last_modified;
891}
892
William Lallemand41db4602017-10-30 11:15:51 +0100893/*
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100894 * Checks the vary header's value. The headers on which vary should be applied
Ilya Shipitsinf38a0182020-12-21 01:16:17 +0500895 * must be explicitly supported in the vary_information array (see cache.c). If
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100896 * any other header is mentioned, we won't store the response.
897 * Returns 1 if Vary-based storage can work, 0 otherwise.
898 */
899static int http_check_vary_header(struct htx *htx, unsigned int *vary_signature)
900{
901 unsigned int vary_idx;
902 unsigned int vary_info_count;
903 const struct vary_hashing_information *vary_info;
904 struct http_hdr_ctx ctx = { .blk = NULL };
905
906 int retval = 1;
907
908 *vary_signature = 0;
909
910 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
911 while (retval && http_find_header(htx, ist("Vary"), &ctx, 0)) {
912 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
913 vary_info = &vary_information[vary_idx];
914 if (isteqi(ctx.value, vary_info->hdr_name)) {
915 *vary_signature |= vary_info->value;
916 break;
917 }
918 }
919 retval = (vary_idx < vary_info_count);
920 }
921
922 return retval;
923}
924
925
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100926/*
927 * Look for the accept-encoding part of the secondary_key and replace the
928 * encoding bitmap part of the hash with the actual encoding of the response,
929 * extracted from the content-encoding header value.
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100930 * Responses that have an unknown encoding will not be cached if they also
931 * "vary" on the accept-encoding value.
932 * Returns 0 if we found a known encoding in the response, -1 otherwise.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100933 */
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100934static int set_secondary_key_encoding(struct htx *htx, char *secondary_key)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100935{
936 unsigned int resp_encoding_bitmap = 0;
937 const struct vary_hashing_information *info = vary_information;
938 unsigned int offset = 0;
939 unsigned int count = 0;
940 unsigned int hash_info_count = sizeof(vary_information)/sizeof(*vary_information);
941 unsigned int encoding_value;
942 struct http_hdr_ctx ctx = { .blk = NULL };
943
944 /* Look for the accept-encoding part of the secondary_key. */
945 while (count < hash_info_count && info->value != VARY_ACCEPT_ENCODING) {
946 offset += info->hash_length;
947 ++info;
948 ++count;
949 }
950
951 if (count == hash_info_count)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100952 return -1;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100953
954 while (http_find_header(htx, ist("content-encoding"), &ctx, 0)) {
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100955 if (parse_encoding_value(ctx.value, &encoding_value, NULL))
956 return -1; /* Do not store responses with an unknown encoding */
957 resp_encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100958 }
959
960 if (!resp_encoding_bitmap)
961 resp_encoding_bitmap |= VARY_ENCODING_IDENTITY;
962
963 /* Rewrite the bitmap part of the hash with the new bitmap that only
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +0500964 * corresponds the the response's encoding. */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100965 write_u32(secondary_key + offset, resp_encoding_bitmap);
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +0100966
967 return 0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +0100968}
969
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +0100970
971/*
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +0500972 * This function will store the headers of the response in a buffer and then
William Lallemand41db4602017-10-30 11:15:51 +0100973 * register a filter to store the data
974 */
975enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
Christopher Faulet8f3c2562019-06-03 22:19:18 +0200976 struct session *sess, struct stream *s, int flags)
William Lallemand41db4602017-10-30 11:15:51 +0100977{
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +0100978 int effective_maxage = 0;
979 int true_maxage = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100980 struct http_txn *txn = s->txn;
981 struct http_msg *msg = &txn->rsp;
982 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100983 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100984 struct cache_flt_conf *cconf = rule->arg.act.p[0];
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +0100985 struct cache *cache = cconf->c.cache;
986 struct shared_context *shctx = shctx_ptr(cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100987 struct cache_st *cache_ctx = NULL;
988 struct cache_entry *object, *old;
Willy Tarreau8b507582020-02-25 09:35:07 +0100989 unsigned int key = read_u32(txn->cache_hash);
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200990 struct htx *htx;
991 struct http_hdr_ctx ctx;
Christopher Fauletb0667472019-09-03 22:22:12 +0200992 size_t hdrs_len = 0;
Christopher Faulet95e7ea32019-07-15 21:01:29 +0200993 int32_t pos;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +0100994 unsigned int vary_signature = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100995
William Lallemand4da3f8a2017-10-31 14:33:34 +0100996 /* Don't cache if the response came from a cache */
997 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
998 s->target == &http_cache_applet.obj_type) {
999 goto out;
1000 }
1001
1002 /* cache only HTTP/1.1 */
1003 if (!(txn->req.flags & HTTP_MSGF_VER_11))
1004 goto out;
1005
Willy Tarreau6905d182019-10-01 17:59:17 +02001006 /* cache only GET method */
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001007 if (txn->meth != HTTP_METH_GET) {
1008 /* In case of successful unsafe method on a stored resource, the
1009 * cached entry must be invalidated (see RFC7234#4.4).
1010 * A "non-error response" is one with a 2xx (Successful) or 3xx
1011 * (Redirection) status code. */
1012 if (txn->status >= 200 && txn->status < 400) {
1013 switch (txn->meth) {
1014 case HTTP_METH_OPTIONS:
1015 case HTTP_METH_GET:
1016 case HTTP_METH_HEAD:
1017 case HTTP_METH_TRACE:
1018 break;
1019
1020 default: /* Any unsafe method */
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001021 /* Discard any corresponding entry in case of successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001022 * unsafe request (such as PUT, POST or DELETE). */
1023 shctx_lock(shctx);
1024
1025 old = entry_exist(cconf->c.cache, txn->cache_hash);
1026 if (old) {
1027 eb32_delete(&old->eb);
1028 old->eb.key = 0;
1029 }
1030 shctx_unlock(shctx);
1031 }
1032 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001033 goto out;
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001034 }
William Lallemand4da3f8a2017-10-31 14:33:34 +01001035
Willy Tarreauc9036c02019-01-11 19:38:25 +01001036 /* cache key was not computed */
1037 if (!key)
1038 goto out;
1039
William Lallemand4da3f8a2017-10-31 14:33:34 +01001040 /* cache only 200 status code */
1041 if (txn->status != 200)
1042 goto out;
1043
Christopher Faulet839791a2019-01-07 16:12:07 +01001044 /* Find the corresponding filter instance for the current stream */
1045 list_for_each_entry(filter, &s->strm_flt.filters, list) {
1046 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
1047 /* No filter ctx, don't cache anything */
1048 if (!filter->ctx)
1049 goto out;
1050 cache_ctx = filter->ctx;
1051 break;
1052 }
1053 }
1054
1055 /* from there, cache_ctx is always defined */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001056 htx = htxbuf(&s->res.buf);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001057
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001058 /* Do not cache too big objects. */
1059 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
1060 htx->data + htx->extra > shctx->max_obj_size)
1061 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001062
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001063 /* Only a subset of headers are supported in our Vary implementation. If
1064 * any other header is present in the Vary header value, we won't be
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001065 * able to use the cache. Likewise, if Vary header support is disabled,
1066 * avoid caching responses that contain such a header. */
1067 ctx.blk = NULL;
1068 if (cache->vary_processing_enabled) {
1069 if (!http_check_vary_header(htx, &vary_signature))
1070 goto out;
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001071 if (vary_signature) {
1072 /* If something went wrong during the secondary key
1073 * building, do not store the response. */
1074 if (!(txn->flags & TX_CACHE_HAS_SEC_KEY))
1075 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001076 http_request_reduce_secondary_key(vary_signature, txn->cache_secondary_hash);
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001077 }
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001078 }
1079 else if (http_find_header(htx, ist("Vary"), &ctx, 0)) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001080 goto out;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001081 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001082
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001083 http_check_response_for_cacheability(s, &s->res);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001084
Remi Tricot-Le Bretoncc9bf2e2020-11-12 11:14:41 +01001085 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK) || (txn->flags & TX_CACHE_IGNORE))
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001086 goto out;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001087
1088 shctx_lock(shctx);
1089 old = entry_exist(cache, txn->cache_hash);
1090 if (old) {
1091 if (vary_signature)
1092 old = secondary_entry_exist(cconf->c.cache, old,
1093 txn->cache_secondary_hash);
1094 if (old) {
1095 if (!old->complete) {
1096 /* An entry with the same primary key is already being
1097 * created, we should not try to store the current
1098 * response because it will waste space in the cache. */
1099 shctx_unlock(shctx);
1100 goto out;
1101 }
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001102 delete_entry(old);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001103 old->eb.key = 0;
1104 }
1105 }
1106 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry));
1107 if (!first) {
1108 shctx_unlock(shctx);
1109 goto out;
1110 }
1111 /* the received memory is not initialized, we need at least to mark
1112 * the object as not indexed yet.
1113 */
1114 object = (struct cache_entry *)first->data;
1115 memset(object, 0, sizeof(*object));
1116 object->eb.key = key;
1117 object->secondary_key_signature = vary_signature;
1118 /* We need to temporarily set a valid expiring time until the actual one
1119 * is set by the end of this function (in case of concurrent accesses to
1120 * the same resource). This way the second access will find an existing
1121 * but not yet usable entry in the tree and will avoid storing its data. */
1122 object->expire = now.tv_sec + 2;
1123
1124 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
1125 if (vary_signature)
1126 memcpy(object->secondary_key, txn->cache_secondary_hash, HTTP_CACHE_SEC_KEY_LEN);
1127
1128 /* Insert the entry in the tree even if the payload is not cached yet. */
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001129 if (insert_entry(cache, object) != &object->eb) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001130 object->eb.key = 0;
1131 shctx_unlock(shctx);
1132 goto out;
1133 }
1134 shctx_unlock(shctx);
1135
1136 /* reserve space for the cache_entry structure */
1137 first->len = sizeof(struct cache_entry);
1138 first->last_append = NULL;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001139
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001140 /* Determine the entry's maximum age (taking into account the cache's
1141 * configuration) as well as the response's explicit max age (extracted
1142 * from cache-control directives or the expires header). */
1143 effective_maxage = http_calc_maxage(s, cconf->c.cache, &true_maxage);
1144
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001145 ctx.blk = NULL;
1146 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
Tim Duesterhusc2942842021-01-02 22:47:17 +01001147 long long hdr_age;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001148 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
1149 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
1150 hdr_age = CACHE_ENTRY_MAX_AGE;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001151 /* A response with an Age value greater than its
1152 * announced max age is stale and should not be stored. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001153 object->age = hdr_age;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001154 if (unlikely(object->age > true_maxage))
1155 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001156 }
Remi Tricot-Le Breton51058d62020-12-03 18:19:32 +01001157 else
1158 goto out;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001159 http_remove_header(htx, &ctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001160 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001161
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001162 /* Build a last-modified time that will be stored in the cache_entry and
1163 * compared to a future If-Modified-Since client header. */
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001164 object->last_modified = get_last_modified_time(htx);
Remi Tricot Le Breton27091b42020-10-23 10:51:27 +02001165
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001166 chunk_reset(&trash);
1167 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
1168 struct htx_blk *blk = htx_get_blk(htx, pos);
1169 enum htx_blk_type type = htx_get_blk_type(blk);
1170 uint32_t sz = htx_get_blksz(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001171
Christopher Fauletb0667472019-09-03 22:22:12 +02001172 hdrs_len += sizeof(*blk) + sz;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001173 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
1174 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001175
1176 /* Look for optional ETag header.
1177 * We need to store the offset of the ETag value in order for
1178 * future conditional requests to be able to perform ETag
1179 * comparisons. */
1180 if (type == HTX_BLK_HDR) {
Tim Duesterhuse2fff102021-01-02 22:47:16 +01001181 struct ist header_name = htx_get_blk_name(htx, blk);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001182 if (isteq(header_name, ist("etag"))) {
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001183 object->etag_length = sz - istlen(header_name);
1184 object->etag_offset = sizeof(struct cache_entry) + b_data(&trash) - sz + istlen(header_name);
Remi Tricot-Le Bretondbb65b52020-10-22 10:40:04 +02001185 }
1186 }
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001187 if (type == HTX_BLK_EOH)
1188 break;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001189 }
1190
Christopher Fauletb0667472019-09-03 22:22:12 +02001191 /* Do not cache objects if the headers are too big. */
1192 if (hdrs_len > htx->size - global.tune.maxrewrite)
1193 goto out;
1194
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001195 /* If the response has a secondary_key, fill its key part related to
1196 * encodings with the actual encoding of the response. This way any
1197 * subsequent request having the same primary key will have its accepted
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001198 * encodings tested upon the cached response's one.
1199 * We will not cache a response that has an unknown encoding (not
Ilya Shipitsin7704b0e2021-01-23 02:11:59 +05001200 * explicitly supported in parse_encoding_value function). */
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001201 if (cache->vary_processing_enabled && vary_signature)
Remi Tricot-Le Breton6ca89162021-01-07 14:50:51 +01001202 if (set_secondary_key_encoding(htx, object->secondary_key))
1203 goto out;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01001204
William Lallemand4da3f8a2017-10-31 14:33:34 +01001205 shctx_lock(shctx);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001206 if (!shctx_row_reserve_hot(shctx, first, trash.data)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +01001207 shctx_unlock(shctx);
1208 goto out;
1209 }
1210 shctx_unlock(shctx);
1211
William Lallemand4da3f8a2017-10-31 14:33:34 +01001212 /* cache the headers in a http action because it allows to chose what
1213 * to cache, for example you might want to cache a response before
1214 * modifying some HTTP headers, or on the contrary after modifying
1215 * those headers.
1216 */
William Lallemand4da3f8a2017-10-31 14:33:34 +01001217 /* does not need to be locked because it's in the "hot" list,
1218 * copy the headers */
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001219 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
1220 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001221
1222 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +01001223 if (cache_ctx) {
1224 cache_ctx->first_block = first;
Christopher Faulet839791a2019-01-07 16:12:07 +01001225 /* store latest value and expiration time */
1226 object->latest_validation = now.tv_sec;
Remi Tricot-Le Breton795e1412020-12-03 18:19:29 +01001227 object->expire = now.tv_sec + effective_maxage;
Christopher Faulet839791a2019-01-07 16:12:07 +01001228 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001229 }
1230
1231out:
1232 /* if does not cache */
1233 if (first) {
1234 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +01001235 first->len = 0;
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001236 if (object->eb.key)
Remi Tricot-Le Breton65904e42020-12-10 17:58:41 +01001237 delete_entry(object);
William Lallemand08727662017-11-21 20:01:27 +01001238 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +01001239 shctx_row_dec_hot(shctx, first);
1240 shctx_unlock(shctx);
1241 }
1242
William Lallemand41db4602017-10-30 11:15:51 +01001243 return ACT_RET_CONT;
1244}
1245
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001246#define HTX_CACHE_INIT 0 /* Initial state. */
1247#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
1248#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001249#define HTX_CACHE_EOM 3 /* Cache entry completely forwarded. Finish the HTX message */
1250#define HTX_CACHE_END 4 /* Cache entry treatment terminated */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001251
William Lallemandecb73b12017-11-24 14:33:55 +01001252static void http_cache_applet_release(struct appctx *appctx)
1253{
Christopher Faulet95220e22018-12-07 17:34:39 +01001254 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +01001255 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +01001256 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +01001257 struct shared_block *first = block_ptr(cache_ptr);
1258
1259 shctx_lock(shctx_ptr(cache));
1260 shctx_row_dec_hot(shctx_ptr(cache), first);
1261 shctx_unlock(shctx_ptr(cache));
1262}
1263
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001264
1265static unsigned int htx_cache_dump_blk(struct appctx *appctx, struct htx *htx, enum htx_blk_type type,
1266 uint32_t info, struct shared_block *shblk, unsigned int offset)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001267{
Christopher Faulet95220e22018-12-07 17:34:39 +01001268 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1269 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001270 struct htx_blk *blk;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001271 char *ptr;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001272 unsigned int max, total;
1273 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001274
Christopher Faulet86e1c332021-12-20 17:09:39 +01001275 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(cs_si(appctx->owner)), htx));
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001276 if (!max)
1277 return 0;
Christopher Faulet2d7c5392019-06-03 10:41:26 +02001278 blksz = ((type == HTX_BLK_HDR || type == HTX_BLK_TLR)
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001279 ? (info & 0xff) + ((info >> 8) & 0xfffff)
1280 : info & 0xfffffff);
1281 if (blksz > max)
1282 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001283
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001284 blk = htx_add_blk(htx, type, blksz);
1285 if (!blk)
1286 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001287
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001288 blk->info = info;
1289 total = 4;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001290 ptr = htx_get_blk_ptr(htx, blk);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001291 while (blksz) {
1292 max = MIN(blksz, shctx->block_size - offset);
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001293 memcpy(ptr, (const char *)shblk->data + offset, max);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001294 offset += max;
1295 blksz -= max;
1296 total += max;
Christopher Faulet15a4ce82019-09-03 22:11:52 +02001297 ptr += max;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001298 if (blksz || offset == shctx->block_size) {
1299 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1300 offset = 0;
1301 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001302 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001303 appctx->ctx.cache.offset = offset;
1304 appctx->ctx.cache.next = shblk;
1305 appctx->ctx.cache.sent += total;
1306 return total;
1307}
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001308
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001309static unsigned int htx_cache_dump_data_blk(struct appctx *appctx, struct htx *htx,
1310 uint32_t info, struct shared_block *shblk, unsigned int offset)
1311{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001312
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001313 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1314 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
1315 unsigned int max, total, rem_data;
1316 uint32_t blksz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001317
Christopher Faulet86e1c332021-12-20 17:09:39 +01001318 max = htx_get_max_blksz(htx, channel_htx_recv_max(si_ic(cs_si(appctx->owner)), htx));
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001319 if (!max)
1320 return 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001321
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001322 rem_data = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001323 if (appctx->ctx.cache.rem_data) {
1324 blksz = appctx->ctx.cache.rem_data;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001325 total = 0;
Christopher Fauletbda83972019-06-11 09:58:09 +02001326 }
1327 else {
1328 blksz = (info & 0xfffffff);
1329 total = 4;
1330 }
1331 if (blksz > max) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001332 rem_data = blksz - max;
1333 blksz = max;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001334 }
1335
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001336 while (blksz) {
1337 size_t sz;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001338
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001339 max = MIN(blksz, shctx->block_size - offset);
1340 sz = htx_add_data(htx, ist2(shblk->data + offset, max));
1341 offset += sz;
1342 blksz -= sz;
1343 total += sz;
1344 if (sz < max)
1345 break;
1346 if (blksz || offset == shctx->block_size) {
1347 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1348 offset = 0;
1349 }
1350 }
1351
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001352 appctx->ctx.cache.offset = offset;
1353 appctx->ctx.cache.next = shblk;
1354 appctx->ctx.cache.sent += total;
1355 appctx->ctx.cache.rem_data = rem_data + blksz;
1356 return total;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001357}
1358
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001359static size_t htx_cache_dump_msg(struct appctx *appctx, struct htx *htx, unsigned int len,
1360 enum htx_blk_type mark)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001361{
Christopher Faulet95220e22018-12-07 17:34:39 +01001362 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1363 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001364 struct shared_block *shblk;
1365 unsigned int offset, sz;
1366 unsigned int ret, total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001367
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001368 while (len) {
1369 enum htx_blk_type type;
1370 uint32_t info;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001371
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001372 shblk = appctx->ctx.cache.next;
1373 offset = appctx->ctx.cache.offset;
1374 if (appctx->ctx.cache.rem_data) {
1375 type = HTX_BLK_DATA;
1376 info = 0;
1377 goto add_data_blk;
1378 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001379
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001380 /* Get info of the next HTX block. May be split on 2 shblk */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001381 sz = MIN(4, shctx->block_size - offset);
1382 memcpy((char *)&info, (const char *)shblk->data + offset, sz);
1383 offset += sz;
1384 if (sz < 4) {
1385 shblk = LIST_NEXT(&shblk->list, typeof(shblk), list);
1386 memcpy(((char *)&info)+sz, (const char *)shblk->data, 4 - sz);
1387 offset = (4 - sz);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001388 }
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001389
1390 /* Get payload of the next HTX block and insert it. */
1391 type = (info >> 28);
1392 if (type != HTX_BLK_DATA)
1393 ret = htx_cache_dump_blk(appctx, htx, type, info, shblk, offset);
1394 else {
1395 add_data_blk:
1396 ret = htx_cache_dump_data_blk(appctx, htx, info, shblk, offset);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001397 }
1398
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001399 if (!ret)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001400 break;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001401 total += ret;
1402 len -= ret;
1403
1404 if (appctx->ctx.cache.rem_data || type == mark)
1405 break;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001406 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001407
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001408 return total;
1409}
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001410
1411static int htx_cache_add_age_hdr(struct appctx *appctx, struct htx *htx)
1412{
1413 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1414 unsigned int age;
1415 char *end;
1416
1417 chunk_reset(&trash);
1418 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
1419 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1420 age = CACHE_ENTRY_MAX_AGE;
1421 end = ultoa_o(age, b_head(&trash), b_size(&trash));
1422 b_set_data(&trash, end - b_head(&trash));
1423 if (!http_add_header(htx, ist("Age"), ist2(b_head(&trash), b_data(&trash))))
1424 return 0;
1425 return 1;
1426}
1427
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001428static void http_cache_io_handler(struct appctx *appctx)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001429{
1430 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1431 struct shared_block *first = block_ptr(cache_ptr);
Christopher Faulet86e1c332021-12-20 17:09:39 +01001432 struct stream_interface *si = cs_si(appctx->owner);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001433 struct channel *req = si_oc(si);
1434 struct channel *res = si_ic(si);
1435 struct htx *req_htx, *res_htx;
1436 struct buffer *errmsg;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001437 unsigned int len;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001438 size_t ret, total = 0;
1439
Christopher Faulet8b1eed12022-03-07 16:44:30 +01001440 res_htx = htx_from_buf(&res->buf);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001441 total = res_htx->data;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001442
1443 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1444 goto out;
1445
Ilya Shipitsin6fb0f212020-04-02 15:25:26 +05001446 /* Check if the input buffer is available. */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001447 if (!b_size(&res->buf)) {
1448 si_rx_room_blk(si);
1449 goto out;
1450 }
1451
Willy Tarreauefef3232018-12-16 00:37:45 +01001452 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001453 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001454
1455 if (appctx->st0 == HTX_CACHE_INIT) {
1456 appctx->ctx.cache.next = block_ptr(cache_ptr);
1457 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1458 appctx->ctx.cache.sent = 0;
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001459 appctx->ctx.cache.rem_data = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001460 appctx->st0 = HTX_CACHE_HEADER;
1461 }
1462
1463 if (appctx->st0 == HTX_CACHE_HEADER) {
1464 /* Headers must be dump at once. Otherwise it is an error */
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001465 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1466 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_EOH);
1467 if (!ret || (htx_get_tail_type(res_htx) != HTX_BLK_EOH) ||
1468 !htx_cache_add_age_hdr(appctx, res_htx))
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001469 goto error;
1470
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001471 /* In case of a conditional request, we might want to send a
1472 * "304 Not Modified" response instead of the stored data. */
Tim Duesterhuse0142342020-10-22 21:15:06 +02001473 if (appctx->ctx.cache.send_notmodified) {
1474 if (!http_replace_res_status(res_htx, ist("304"), ist("Not Modified"))) {
1475 /* If replacing the status code fails we need to send the full response. */
1476 appctx->ctx.cache.send_notmodified = 0;
1477 }
1478 }
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001479
1480 /* Skip response body for HEAD requests or in case of "304 Not
1481 * Modified" response. */
1482 if (si_strm(si)->txn->meth == HTTP_METH_HEAD || appctx->ctx.cache.send_notmodified)
Christopher Fauletf0dd0372019-02-25 11:08:34 +01001483 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001484 else
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001485 appctx->st0 = HTX_CACHE_DATA;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001486 }
1487
1488 if (appctx->st0 == HTX_CACHE_DATA) {
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001489 len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1490 if (len) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001491 ret = htx_cache_dump_msg(appctx, res_htx, len, HTX_BLK_UNUSED);
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001492 if (ret < len) {
1493 si_rx_room_blk(si);
1494 goto out;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001495 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001496 }
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001497 appctx->st0 = HTX_CACHE_EOM;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001498 }
1499
1500 if (appctx->st0 == HTX_CACHE_EOM) {
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01001501 /* no more data are expected. */
1502 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletdbf1e882022-03-07 15:53:57 +01001503 si->cs->flags |= CS_FL_EOI;
1504 res->flags |= CF_EOI;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001505 appctx->st0 = HTX_CACHE_END;
1506 }
1507
1508 end:
Christopher Fauletadb36312019-02-25 11:40:49 +01001509 if (!(res->flags & CF_SHUTR) && appctx->st0 == HTX_CACHE_END) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001510 res->flags |= CF_READ_NULL;
1511 si_shutr(si);
1512 }
1513
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001514 out:
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001515 total = res_htx->data - total;
Christopher Faulet61123912019-01-02 14:10:01 +01001516 if (total)
1517 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001518 htx_to_buf(res_htx, &res->buf);
Christopher Fauletadb36312019-02-25 11:40:49 +01001519
1520 /* eat the whole request */
1521 if (co_data(req)) {
1522 req_htx = htx_from_buf(&req->buf);
1523 co_htx_skip(req, req_htx, co_data(req));
1524 htx_to_buf(req_htx, &req->buf);
1525 }
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001526 return;
1527
1528 error:
1529 /* Sent and HTTP error 500 */
1530 b_reset(&res->buf);
Christopher Fauletf7346382019-07-17 22:02:08 +02001531 errmsg = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001532 res->buf.data = b_data(errmsg);
1533 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1534 res_htx = htx_from_buf(&res->buf);
1535
Christopher Faulet8f3c2562019-06-03 22:19:18 +02001536 total = 0;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001537 appctx->st0 = HTX_CACHE_END;
1538 goto end;
1539}
1540
1541
Christopher Faulet95220e22018-12-07 17:34:39 +01001542static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001543{
1544 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001545 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001546
Christopher Faulet95220e22018-12-07 17:34:39 +01001547 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001548 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001549 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001550 }
1551
1552 /* check if a cache filter was already registered with this cache
1553 * name, if that's the case, must use it. */
1554 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001555 if (fconf->id == cache_store_flt_id) {
1556 cconf = fconf->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001557 if (cconf && strcmp((char *)cconf->c.name, name) == 0) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001558 rule->arg.act.p[0] = cconf;
1559 return 1;
1560 }
William Lallemand41db4602017-10-30 11:15:51 +01001561 }
1562 }
1563
Christopher Faulet95220e22018-12-07 17:34:39 +01001564 /* Create the filter cache config */
1565 cconf = calloc(1, sizeof(*cconf));
1566 if (!cconf) {
1567 memprintf(err, "out of memory\n");
1568 goto err;
1569 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001570 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001571 cconf->c.name = strdup(name);
1572 if (!cconf->c.name) {
1573 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001574 goto err;
1575 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001576
William Lallemand41db4602017-10-30 11:15:51 +01001577 /* register a filter to fill the cache buffer */
1578 fconf = calloc(1, sizeof(*fconf));
1579 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001580 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001581 goto err;
1582 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001583 fconf->id = cache_store_flt_id;
1584 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001585 fconf->ops = &cache_ops;
Willy Tarreau2b718102021-04-21 07:32:39 +02001586 LIST_APPEND(&proxy->filter_configs, &fconf->list);
William Lallemand41db4602017-10-30 11:15:51 +01001587
Christopher Faulet95220e22018-12-07 17:34:39 +01001588 rule->arg.act.p[0] = cconf;
1589 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001590
Christopher Faulet95220e22018-12-07 17:34:39 +01001591 err:
1592 free(cconf);
1593 return 0;
1594}
1595
1596enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1597 struct act_rule *rule, char **err)
1598{
1599 rule->action = ACT_CUSTOM;
1600 rule->action_ptr = http_action_store_cache;
1601
1602 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1603 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001604
Christopher Faulet95220e22018-12-07 17:34:39 +01001605 (*orig_arg)++;
1606 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001607}
1608
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001609/* This produces a sha1 hash of the concatenation of the HTTP method,
1610 * the first occurrence of the Host header followed by the path component
1611 * if it begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001612int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001613{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001614 struct http_txn *txn = s->txn;
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001615 struct htx *htx = htxbuf(&s->req.buf);
1616 struct htx_sl *sl;
1617 struct http_hdr_ctx ctx;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001618 struct ist uri;
William Lallemandf528fff2017-11-23 19:43:17 +01001619 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001620 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001621
William Lallemandf528fff2017-11-23 19:43:17 +01001622 trash = get_trash_chunk();
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001623 ctx.blk = NULL;
Baptiste Assmanndb92a832019-08-05 16:55:32 +02001624
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001625 sl = http_get_stline(htx);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001626 uri = htx_sl_req_uri(sl); // whole uri
1627 if (!uri.len)
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001628 return 0;
Willy Tarreauccc61d82019-10-17 09:28:28 +02001629
1630 /* In HTTP/1, most URIs are seen in origin form ('/path/to/resource'),
1631 * unless haproxy is deployed in front of an outbound cache. In HTTP/2,
1632 * URIs are almost always sent in absolute form with their scheme. In
1633 * this case, the scheme is almost always "https". In order to support
1634 * sharing of cache objects between H1 and H2, we'll hash the absolute
1635 * URI whenever known, or prepend "https://" + the Host header for
1636 * relative URIs. The difference will only appear on absolute HTTP/1
1637 * requests sent to an origin server, which practically is never met in
1638 * the real world so we don't care about the ability to share the same
1639 * key here.URIs are normalized from the absolute URI to an origin form as
1640 * well.
1641 */
1642 if (!(sl->flags & HTX_SL_F_HAS_AUTHORITY)) {
Willy Tarreau20020ae2019-10-29 13:02:15 +01001643 chunk_istcat(trash, ist("https://"));
Willy Tarreauccc61d82019-10-17 09:28:28 +02001644 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1645 return 0;
Willy Tarreau20020ae2019-10-29 13:02:15 +01001646 chunk_istcat(trash, ctx.value);
Willy Tarreauccc61d82019-10-17 09:28:28 +02001647 }
1648
Tim Duesterhus9f7ed8a2021-11-08 09:05:04 +01001649 chunk_istcat(trash, uri);
William Lallemandf528fff2017-11-23 19:43:17 +01001650
1651 /* hash everything */
1652 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001653 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001654 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1655
1656 return 1;
1657}
1658
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001659/* Looks for "If-None-Match" headers in the request and compares their value
1660 * with the one that might have been stored in the cache_entry. If any of them
1661 * matches, a "304 Not Modified" response should be sent instead of the cached
1662 * data.
1663 * Although unlikely in a GET/HEAD request, the "If-None-Match: *" syntax is
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001664 * valid and should receive a "304 Not Modified" response (RFC 7234#4.3.2).
1665 *
1666 * If no "If-None-Match" header was found, look for an "If-Modified-Since"
1667 * header and compare its value (date) to the one stored in the cache_entry.
1668 * If the request's date is later than the cached one, we also send a
1669 * "304 Not Modified" response (see RFCs 7232#3.3 and 7234#4.3.2).
1670 *
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001671 * Returns 1 if "304 Not Modified" should be sent, 0 otherwise.
1672 */
1673static int should_send_notmodified_response(struct cache *cache, struct htx *htx,
1674 struct cache_entry *entry)
1675{
1676 int retval = 0;
1677
1678 struct http_hdr_ctx ctx = { .blk = NULL };
1679 struct ist cache_entry_etag = IST_NULL;
1680 struct buffer *etag_buffer = NULL;
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001681 int if_none_match_found = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001682
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001683 struct tm tm = {};
1684 time_t if_modified_since = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001685
1686 /* If we find a "If-None-Match" header in the request, rebuild the
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001687 * cache_entry's ETag in order to perform comparisons.
1688 * There could be multiple "if-none-match" header lines. */
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001689 while (http_find_header(htx, ist("if-none-match"), &ctx, 0)) {
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001690 if_none_match_found = 1;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001691
1692 /* A '*' matches everything. */
1693 if (isteq(ctx.value, ist("*")) != 0) {
1694 retval = 1;
1695 break;
1696 }
1697
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001698 /* No need to rebuild an etag if none was stored in the cache. */
1699 if (entry->etag_length == 0)
1700 break;
1701
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001702 /* Rebuild the stored ETag. */
1703 if (etag_buffer == NULL) {
1704 etag_buffer = get_trash_chunk();
1705
1706 if (shctx_row_data_get(shctx_ptr(cache), block_ptr(entry),
1707 (unsigned char*)b_orig(etag_buffer),
1708 entry->etag_offset, entry->etag_length) == 0) {
1709 cache_entry_etag = ist2(b_orig(etag_buffer), entry->etag_length);
1710 } else {
1711 /* We could not rebuild the ETag in one go, we
1712 * won't send a "304 Not Modified" response. */
1713 break;
1714 }
1715 }
1716
1717 if (http_compare_etags(cache_entry_etag, ctx.value) == 1) {
1718 retval = 1;
1719 break;
1720 }
1721 }
1722
Remi Tricot-Le Breton53161d82020-10-23 10:51:28 +02001723 /* If the request did not contain an "If-None-Match" header, we look for
1724 * an "If-Modified-Since" header (see RFC 7232#3.3). */
1725 if (retval == 0 && if_none_match_found == 0) {
1726 ctx.blk = NULL;
1727 if (http_find_header(htx, ist("if-modified-since"), &ctx, 1)) {
1728 if (parse_http_date(istptr(ctx.value), istlen(ctx.value), &tm)) {
1729 if_modified_since = my_timegm(&tm);
1730
1731 /* We send a "304 Not Modified" response if the
1732 * entry's last modified date is earlier than
1733 * the one found in the "If-Modified-Since"
1734 * header. */
1735 retval = (entry->last_modified <= if_modified_since);
1736 }
1737 }
1738 }
1739
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001740 return retval;
1741}
1742
William Lallemand41db4602017-10-30 11:15:51 +01001743enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1744 struct session *sess, struct stream *s, int flags)
1745{
William Lallemand77c11972017-10-31 20:43:01 +01001746
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001747 struct http_txn *txn = s->txn;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001748 struct cache_entry *res, *sec_entry = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001749 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1750 struct cache *cache = cconf->c.cache;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001751 struct shared_block *entry_block;
1752
William Lallemand77c11972017-10-31 20:43:01 +01001753
Willy Tarreau6905d182019-10-01 17:59:17 +02001754 /* Ignore cache for HTTP/1.0 requests and for requests other than GET
1755 * and HEAD */
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001756 if (!(txn->req.flags & HTTP_MSGF_VER_11) ||
Willy Tarreau6905d182019-10-01 17:59:17 +02001757 (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD))
Christopher Fauletb3d4bca2019-02-25 10:59:33 +01001758 txn->flags |= TX_CACHE_IGNORE;
1759
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02001760 http_check_request_for_cacheability(s, &s->req);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001761
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001762 /* The request's hash has to be calculated for all requests, even POSTs
Ilya Shipitsinf38a0182020-12-21 01:16:17 +05001763 * or PUTs for instance because RFC7234 specifies that a successful
Remi Tricot-Le Breton72cffaf2020-12-03 18:19:31 +01001764 * "unsafe" method on a stored resource must invalidate it
1765 * (see RFC7234#4.4). */
1766 if (!sha1_hosturi(s))
Willy Tarreau504455c2017-12-22 17:47:35 +01001767 return ACT_RET_CONT;
1768
Willy Tarreau504455c2017-12-22 17:47:35 +01001769 if (s->txn->flags & TX_CACHE_IGNORE)
1770 return ACT_RET_CONT;
1771
Willy Tarreaua1214a52018-12-14 14:00:25 +01001772 if (px == strm_fe(s))
Willy Tarreau4781b152021-04-06 13:53:36 +02001773 _HA_ATOMIC_INC(&px->fe_counters.p.http.cache_lookups);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001774 else
Willy Tarreau4781b152021-04-06 13:53:36 +02001775 _HA_ATOMIC_INC(&px->be_counters.p.http.cache_lookups);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001776
William Lallemanda400a3a2017-11-20 19:13:12 +01001777 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001778 res = entry_exist(cache, s->txn->cache_hash);
Remi Tricot-Le Breton32434472020-11-25 10:09:43 +01001779 /* We must not use an entry that is not complete. */
1780 if (res && res->complete) {
William Lallemand77c11972017-10-31 20:43:01 +01001781 struct appctx *appctx;
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001782 entry_block = block_ptr(res);
1783 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
William Lallemanda400a3a2017-11-20 19:13:12 +01001784 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001785
1786 /* In case of Vary, we could have multiple entries with the same
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01001787 * primary hash. We need to calculate the secondary hash in order
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001788 * to find the actual entry we want (if it exists). */
1789 if (res->secondary_key_signature) {
1790 if (!http_request_build_secondary_key(s, res->secondary_key_signature)) {
1791 shctx_lock(shctx_ptr(cache));
1792 sec_entry = secondary_entry_exist(cache, res,
1793 s->txn->cache_secondary_hash);
1794 if (sec_entry && sec_entry != res) {
1795 /* The wrong row was added to the hot list. */
1796 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1797 entry_block = block_ptr(sec_entry);
1798 shctx_row_inc_hot(shctx_ptr(cache), entry_block);
1799 }
1800 res = sec_entry;
1801 shctx_unlock(shctx_ptr(cache));
1802 }
1803 else
1804 res = NULL;
1805 }
1806
1807 /* We looked for a valid secondary entry and could not find one,
1808 * the request must be forwarded to the server. */
1809 if (!res) {
1810 shctx_lock(shctx_ptr(cache));
1811 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
1812 shctx_unlock(shctx_ptr(cache));
1813 return ACT_RET_CONT;
1814 }
1815
William Lallemand77c11972017-10-31 20:43:01 +01001816 s->target = &http_cache_applet.obj_type;
Christopher Faulet7a58d792021-12-23 13:40:08 +01001817 if ((appctx = si_register_handler(cs_si(s->csb), objt_applet(s->target)))) {
Christopher Faulet95e7ea32019-07-15 21:01:29 +02001818 appctx->st0 = HTX_CACHE_INIT;
William Lallemand77c11972017-10-31 20:43:01 +01001819 appctx->rule = rule;
1820 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001821 appctx->ctx.cache.next = NULL;
1822 appctx->ctx.cache.sent = 0;
Remi Tricot-Le Breton6cb10382020-10-22 10:40:05 +02001823 appctx->ctx.cache.send_notmodified =
1824 should_send_notmodified_response(cache, htxbuf(&s->req.buf), res);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001825
1826 if (px == strm_fe(s))
Willy Tarreau4781b152021-04-06 13:53:36 +02001827 _HA_ATOMIC_INC(&px->fe_counters.p.http.cache_hits);
Willy Tarreaua1214a52018-12-14 14:00:25 +01001828 else
Willy Tarreau4781b152021-04-06 13:53:36 +02001829 _HA_ATOMIC_INC(&px->be_counters.p.http.cache_hits);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001830 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001831 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001832 shctx_lock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001833 shctx_row_dec_hot(shctx_ptr(cache), entry_block);
William Lallemand55e76742017-11-21 20:01:28 +01001834 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001835 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001836 }
1837 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001838 shctx_unlock(shctx_ptr(cache));
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001839
1840 /* Shared context does not need to be locked while we calculate the
1841 * secondary hash. */
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001842 if (!res && cache->vary_processing_enabled) {
Remi Tricot-Le Breton1785f3d2020-11-16 15:56:09 +01001843 /* Build a complete secondary hash until the server response
1844 * tells us which fields should be kept (if any). */
1845 http_request_prebuild_full_secondary_key(s);
1846 }
Olivier Houchardfccf8402017-11-01 14:04:02 +01001847 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001848}
1849
1850
1851enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1852 struct act_rule *rule, char **err)
1853{
William Lallemand41db4602017-10-30 11:15:51 +01001854 rule->action = ACT_CUSTOM;
1855 rule->action_ptr = http_action_req_cache_use;
1856
Christopher Faulet95220e22018-12-07 17:34:39 +01001857 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001858 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001859
1860 (*orig_arg)++;
1861 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001862}
1863
1864int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1865{
1866 int err_code = 0;
1867
1868 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1869
1870 if (!*args[1]) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001871 ha_alert("parsing [%s:%d] : '%s' expects a <name> argument\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001872 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001873 err_code |= ERR_ALERT | ERR_ABORT;
1874 goto out;
1875 }
1876
1877 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1878 err_code |= ERR_ABORT;
1879 goto out;
1880 }
1881
1882 if (tmp_cache_config == NULL) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001883 struct cache *cache_config;
1884
William Lallemand41db4602017-10-30 11:15:51 +01001885 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1886 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001887 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001888 err_code |= ERR_ALERT | ERR_ABORT;
1889 goto out;
1890 }
1891
1892 strlcpy2(tmp_cache_config->id, args[1], 33);
1893 if (strlen(args[1]) > 32) {
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001894 ha_warning("parsing [%s:%d]: cache name is limited to 32 characters, truncate to '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01001895 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001896 err_code |= ERR_WARN;
1897 }
Tim Duesterhusff4d86b2020-08-18 22:20:27 +02001898
1899 list_for_each_entry(cache_config, &caches_config, list) {
1900 if (strcmp(tmp_cache_config->id, cache_config->id) == 0) {
1901 ha_alert("parsing [%s:%d]: Duplicate cache name '%s'.\n",
1902 file, linenum, tmp_cache_config->id);
1903 err_code |= ERR_ALERT | ERR_ABORT;
1904 goto out;
1905 }
1906 }
1907
William Lallemand49b44532017-11-24 18:53:43 +01001908 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001909 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001910 tmp_cache_config->maxobjsz = 0;
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001911 tmp_cache_config->max_secondary_entries = DEFAULT_MAX_SECONDARY_ENTRY;
William Lallemand41db4602017-10-30 11:15:51 +01001912 }
1913 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001914 unsigned long int maxsize;
1915 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001916
1917 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1918 err_code |= ERR_ABORT;
1919 goto out;
1920 }
1921
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001922 maxsize = strtoul(args[1], &err, 10);
1923 if (err == args[1] || *err != '\0') {
1924 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1925 file, linenum, args[1]);
1926 err_code |= ERR_ABORT;
1927 goto out;
1928 }
1929
1930 if (maxsize > (UINT_MAX >> 20)) {
1931 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1932 file, linenum, args[1], UINT_MAX >> 20);
1933 err_code |= ERR_ABORT;
1934 goto out;
1935 }
1936
William Lallemand41db4602017-10-30 11:15:51 +01001937 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001938 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001939 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001940 } else if (strcmp(args[0], "max-age") == 0) {
1941 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1942 err_code |= ERR_ABORT;
1943 goto out;
1944 }
1945
1946 if (!*args[1]) {
1947 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1948 file, linenum, args[0]);
1949 err_code |= ERR_WARN;
1950 }
1951
1952 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001953 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001954 unsigned int maxobjsz;
1955 char *err;
1956
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001957 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1958 err_code |= ERR_ABORT;
1959 goto out;
1960 }
1961
1962 if (!*args[1]) {
1963 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1964 file, linenum, args[0]);
1965 err_code |= ERR_WARN;
1966 }
1967
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001968 maxobjsz = strtoul(args[1], &err, 10);
1969 if (err == args[1] || *err != '\0') {
1970 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1971 file, linenum, args[1]);
1972 err_code |= ERR_ABORT;
1973 goto out;
1974 }
1975 tmp_cache_config->maxobjsz = maxobjsz;
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001976 } else if (strcmp(args[0], "process-vary") == 0) {
1977 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1978 err_code |= ERR_ABORT;
1979 goto out;
1980 }
1981
1982 if (!*args[1]) {
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001983 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
Remi Tricot-Le Breton754b2422020-11-16 15:56:10 +01001984 file, linenum, args[0]);
1985 err_code |= ERR_WARN;
1986 }
Remi Tricot-Le Bretone6cc5b52020-12-23 18:13:53 +01001987 if (strcmp(args[1], "on") == 0)
1988 tmp_cache_config->vary_processing_enabled = 1;
1989 else if (strcmp(args[1], "off") == 0)
1990 tmp_cache_config->vary_processing_enabled = 0;
1991 else {
1992 ha_warning("parsing [%s:%d]: '%s' expects \"on\" or \"off\" (enable or disable vary processing).\n",
1993 file, linenum, args[0]);
1994 err_code |= ERR_WARN;
1995 }
Remi Tricot-Le Breton5853c0c2020-12-10 17:58:43 +01001996 } else if (strcmp(args[0], "max-secondary-entries") == 0) {
1997 unsigned int max_sec_entries;
1998 char *err;
1999
2000 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
2001 err_code |= ERR_ABORT;
2002 goto out;
2003 }
2004
2005 if (!*args[1]) {
2006 ha_warning("parsing [%s:%d]: '%s' expects a strictly positive number.\n",
2007 file, linenum, args[0]);
2008 err_code |= ERR_WARN;
2009 }
2010
2011 max_sec_entries = strtoul(args[1], &err, 10);
2012 if (err == args[1] || *err != '\0' || max_sec_entries == 0) {
2013 ha_warning("parsing [%s:%d]: max-secondary-entries wrong value '%s'\n",
2014 file, linenum, args[1]);
2015 err_code |= ERR_ABORT;
2016 goto out;
2017 }
2018 tmp_cache_config->max_secondary_entries = max_sec_entries;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002019 }
2020 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002021 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01002022 err_code |= ERR_ALERT | ERR_FATAL;
2023 goto out;
2024 }
2025out:
2026 return err_code;
2027}
2028
2029/* once the cache section is parsed */
2030
2031int cfg_post_parse_section_cache()
2032{
William Lallemand41db4602017-10-30 11:15:51 +01002033 int err_code = 0;
William Lallemand41db4602017-10-30 11:15:51 +01002034
2035 if (tmp_cache_config) {
William Lallemand41db4602017-10-30 11:15:51 +01002036
2037 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002038 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01002039 err_code |= ERR_FATAL | ERR_ALERT;
2040 goto out;
2041 }
2042
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002043 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002044 /* Default max. file size is a 256th of the cache size. */
2045 tmp_cache_config->maxobjsz =
2046 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02002047 }
2048 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
2049 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
2050 err_code |= ERR_FATAL | ERR_ALERT;
2051 goto out;
2052 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02002053
William Lallemandd1d1e222019-08-28 15:22:49 +02002054 /* add to the list of cache to init and reinit tmp_cache_config
2055 * for next cache section, if any.
2056 */
Willy Tarreau2b718102021-04-21 07:32:39 +02002057 LIST_APPEND(&caches_config, &tmp_cache_config->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002058 tmp_cache_config = NULL;
2059 return err_code;
2060 }
2061out:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002062 ha_free(&tmp_cache_config);
William Lallemandd1d1e222019-08-28 15:22:49 +02002063 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;
Willy Tarreau2b718102021-04-21 07:32:39 +02002096 LIST_APPEND(&caches, &cache->list);
2097 LIST_DELETE(&cache_config->list);
William Lallemandd1d1e222019-08-28 15:22:49 +02002098 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':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002184 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002185 *encoding_value = CHECK_ENCODING(encoding, "aes128gcm", VARY_ENCODING_AES128GCM);
2186 break;
2187 case 'b':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002188 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002189 *encoding_value = CHECK_ENCODING(encoding, "br", VARY_ENCODING_BR);
2190 break;
2191 case 'c':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002192 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002193 *encoding_value = CHECK_ENCODING(encoding, "compress", VARY_ENCODING_COMPRESS);
2194 break;
2195 case 'd':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002196 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002197 *encoding_value = CHECK_ENCODING(encoding, "deflate", VARY_ENCODING_DEFLATE);
2198 break;
2199 case 'e':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002200 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002201 *encoding_value = CHECK_ENCODING(encoding, "exi", VARY_ENCODING_EXI);
2202 break;
2203 case 'g':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002204 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002205 *encoding_value = CHECK_ENCODING(encoding, "gzip", VARY_ENCODING_GZIP);
2206 break;
2207 case 'i':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002208 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002209 *encoding_value = CHECK_ENCODING(encoding, "identity", VARY_ENCODING_IDENTITY);
2210 break;
2211 case 'p':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002212 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002213 *encoding_value = CHECK_ENCODING(encoding, "pack200-gzip", VARY_ENCODING_PACK200_GZIP);
2214 break;
2215 case 'x':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002216 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002217 *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':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002222 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002223 *encoding_value = CHECK_ENCODING(encoding, "zstd", VARY_ENCODING_ZSTD);
2224 break;
2225 case '*':
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002226 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002227 *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) {
Tim Duesterhus284fbe12021-11-04 22:35:44 +01002242 encoding = istnext(encoding);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002243
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) {
Tim Duesterhus3bc6af42021-06-18 15:09:28 +02002284 count++;
2285
2286 /* As per RFC7231#5.3.4, "An Accept-Encoding header field with a
2287 * combined field-value that is empty implies that the user agent
2288 * does not want any content-coding in response."
2289 *
2290 * We must (and did) count the existence of this empty header to not
2291 * hit the `count == 0` case below, but must ignore the value to not
2292 * include VARY_ENCODING_OTHER into the final bitmap.
2293 */
2294 if (istlen(ctx.value) == 0)
2295 continue;
2296
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002297 /* Turn accept-encoding value to lower case */
2298 ist2bin_lc(istptr(ctx.value), ctx.value);
Tim Duesterhus23b29452020-11-24 22:22:56 +01002299
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002300 /* Try to identify a known encoding and to manage null weights. */
2301 if (!parse_encoding_value(ctx.value, &encoding_value, &rejected_encoding)) {
2302 if (rejected_encoding)
2303 encoding_bmp_bl &= ~encoding_value;
2304 else
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002305 encoding_bitmap |= encoding_value;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002306 }
2307 else {
2308 /* Unknown encoding */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002309 encoding_bitmap |= VARY_ENCODING_OTHER;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002310 }
Remi Tricot-Le Breton8bb72aa2020-11-30 17:06:03 +01002311 }
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002312
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002313 /* If a "*" was found in the accepted encodings (without a null weight),
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002314 * all the encoding are accepted except the ones explicitly rejected. */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002315 if (encoding_bitmap & VARY_ENCODING_STAR) {
2316 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002317 }
2318
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002319 /* Clear explicitly rejected encodings from the bitmap */
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002320 encoding_bitmap &= encoding_bmp_bl;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002321
2322 /* As per RFC7231#5.3.4, "If no Accept-Encoding field is in the request,
2323 * any content-coding is considered acceptable by the user agent". */
2324 if (count == 0)
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002325 encoding_bitmap = ~0;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002326
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002327 /* A request with more than ACCEPT_ENCODING_MAX_ENTRIES accepted
2328 * encodings might be illegitimate so we will not use it. */
2329 if (count == ACCEPT_ENCODING_MAX_ENTRIES)
2330 return -1;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002331
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002332 write_u32(buf, encoding_bitmap);
2333 *buf_len = sizeof(encoding_bitmap);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002334
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002335 /* This function fills the hash buffer correctly even if no header was
2336 * found, hence the 0 return value (success). */
Tim Duesterhus23b29452020-11-24 22:22:56 +01002337 return 0;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002338}
Tim Duesterhus23b29452020-11-24 22:22:56 +01002339#undef ACCEPT_ENCODING_MAX_ENTRIES
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002340
2341/*
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002342 * Normalizer used by default for the Referer header. It only
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002343 * calculates a simple crc of the whole value.
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002344 * Only the first occurrence of the header will be taken into account in the
2345 * hash.
2346 * Returns 0 in case of success, 1 if the hash buffer should be filled with 0s
2347 * and -1 in case of error.
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002348 */
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002349static int default_normalizer(struct htx *htx, struct ist hdr_name,
2350 char *buf, unsigned int *buf_len)
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002351{
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002352 int retval = 1;
2353 struct http_hdr_ctx ctx = { .blk = NULL };
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002354
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002355 if (http_find_header(htx, hdr_name, &ctx, 1)) {
2356 retval = 0;
2357 write_u32(buf, hash_crc32(istptr(ctx.value), istlen(ctx.value)));
2358 *buf_len = sizeof(int);
2359 }
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002360
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002361 return retval;
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002362}
2363
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002364/*
Tim Duesterhused84d842021-01-18 13:41:17 +01002365 * Accept-Encoding bitmap comparison function.
2366 * Returns 0 if the bitmaps are compatible.
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002367 */
Tim Duesterhused84d842021-01-18 13:41:17 +01002368static int accept_encoding_bitmap_cmp(const void *ref, const void *new, unsigned int len)
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002369{
Tim Duesterhused84d842021-01-18 13:41:17 +01002370 uint32_t ref_bitmap = read_u32(ref);
2371 uint32_t new_bitmap = read_u32(new);
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002372
Tim Duesterhused84d842021-01-18 13:41:17 +01002373 if (!(ref_bitmap & VARY_ENCODING_OTHER)) {
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002374 /* All the bits set in the reference bitmap correspond to the
2375 * stored response' encoding and should all be set in the new
2376 * encoding bitmap in order for the client to be able to manage
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002377 * the response.
2378 *
2379 * If this is the case the cached response has encodings that
2380 * are accepted by the client. It can be served directly by
2381 * the cache (as far as the accept-encoding part is concerned).
2382 */
2383
Tim Duesterhused84d842021-01-18 13:41:17 +01002384 return (ref_bitmap & new_bitmap) != ref_bitmap;
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002385 }
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002386 else {
Tim Duesterhus1d66e392021-01-18 13:41:16 +01002387 return 1;
Tim Duesterhusdc38bc42020-12-29 12:43:53 +01002388 }
Remi Tricot-Le Bretonce9e7b22020-12-23 18:13:49 +01002389}
2390
2391
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002392/*
2393 * Pre-calculate the hashes of all the supported headers (in our Vary
2394 * implementation) of a given request. We have to calculate all the hashes
2395 * in advance because the actual Vary signature won't be known until the first
2396 * response.
2397 * Only the first occurrence of every header will be taken into account in the
2398 * hash.
2399 * If the header is not present, the hash portion of the given header will be
2400 * filled with zeros.
2401 * Returns 0 in case of success.
2402 */
2403static int http_request_prebuild_full_secondary_key(struct stream *s)
2404{
Remi Tricot-Le Bretonbba29122020-12-23 18:13:44 +01002405 /* The fake signature (second parameter) will ensure that every part of the
2406 * secondary key is calculated. */
2407 return http_request_build_secondary_key(s, ~0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002408}
2409
2410
2411/*
2412 * Calculate the secondary key for a request for which we already have a known
2413 * vary signature. The key is made by aggregating hashes calculated for every
2414 * header mentioned in the vary signature.
2415 * Only the first occurrence of every header will be taken into account in the
2416 * hash.
2417 * If the header is not present, the hash portion of the given header will be
2418 * filled with zeros.
2419 * Returns 0 in case of success.
2420 */
2421static int http_request_build_secondary_key(struct stream *s, int vary_signature)
2422{
2423 struct http_txn *txn = s->txn;
2424 struct htx *htx = htxbuf(&s->req.buf);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002425
2426 unsigned int idx;
2427 const struct vary_hashing_information *info = NULL;
2428 unsigned int hash_length = 0;
2429 int retval = 0;
2430 int offset = 0;
2431
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002432 for (idx = 0; idx < sizeof(vary_information)/sizeof(*vary_information) && retval >= 0; ++idx) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002433 info = &vary_information[idx];
2434
Remi Tricot-Le Bretone4421de2020-12-23 18:13:46 +01002435 /* The normalizing functions will be in charge of getting the
2436 * header values from the htx. This way they can manage multiple
2437 * occurrences of their processed header. */
2438 if ((vary_signature & info->value) && info->norm_fn != NULL &&
2439 !(retval = info->norm_fn(htx, info->hdr_name, &txn->cache_secondary_hash[offset], &hash_length))) {
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002440 offset += hash_length;
2441 }
2442 else {
2443 /* Fill hash with 0s. */
2444 hash_length = info->hash_length;
2445 memset(&txn->cache_secondary_hash[offset], 0, hash_length);
2446 offset += hash_length;
2447 }
2448 }
2449
Remi Tricot-Le Breton2b5c5cb2020-12-23 18:13:45 +01002450 if (retval >= 0)
2451 txn->flags |= TX_CACHE_HAS_SEC_KEY;
2452
2453 return (retval < 0);
Remi Tricot-Le Breton3d082362020-11-16 15:56:08 +01002454}
2455
2456/*
2457 * Build the actual secondary key of a given request out of the prebuilt key and
2458 * the actual vary signature (extracted from the response).
2459 * Returns 0 in case of success.
2460 */
2461static int http_request_reduce_secondary_key(unsigned int vary_signature,
2462 char prebuilt_key[HTTP_CACHE_SEC_KEY_LEN])
2463{
2464 int offset = 0;
2465 int global_offset = 0;
2466 int vary_info_count = 0;
2467 int keep = 0;
2468 unsigned int vary_idx;
2469 const struct vary_hashing_information *vary_info;
2470
2471 vary_info_count = sizeof(vary_information)/sizeof(*vary_information);
2472 for (vary_idx = 0; vary_idx < vary_info_count; ++vary_idx) {
2473 vary_info = &vary_information[vary_idx];
2474 keep = (vary_signature & vary_info->value) ? 0xff : 0;
2475
2476 for (offset = 0; offset < vary_info->hash_length; ++offset,++global_offset) {
2477 prebuilt_key[global_offset] &= keep;
2478 }
2479 }
2480
2481 return 0;
2482}
2483
2484
Christopher Faulet99a17a22018-12-11 09:18:27 +01002485
2486static int
2487parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
2488 struct flt_conf *fconf, char **err, void *private)
2489{
2490 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01002491 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002492 char *name = NULL;
2493 int pos = *cur_arg;
2494
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002495 /* Get the cache filter name. <pos> point on "cache" keyword */
2496 if (!*args[pos + 1]) {
Tim Duesterhusea969f62020-08-18 22:06:51 +02002497 memprintf(err, "%s : expects a <name> argument", args[pos]);
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002498 goto error;
2499 }
2500 name = strdup(args[pos + 1]);
2501 if (!name) {
2502 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
2503 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002504 }
Christopher Faulet2a37cdb2020-05-18 11:58:16 +02002505 pos += 2;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002506
2507 /* Check if an implicit filter with the same name already exists. If so,
2508 * we remove the implicit filter to use the explicit one. */
2509 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
2510 if (f->id != cache_store_flt_id)
2511 continue;
2512
2513 cconf = f->conf;
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01002514 if (strcmp(name, cconf->c.name) != 0) {
Christopher Faulet99a17a22018-12-11 09:18:27 +01002515 cconf = NULL;
2516 continue;
2517 }
2518
2519 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
2520 cconf = NULL;
2521 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
2522 px->id, name);
Tim Duesterhusd34b1ce2020-01-18 01:46:18 +01002523 goto error;
Christopher Faulet99a17a22018-12-11 09:18:27 +01002524 }
2525
2526 /* Remove the implicit filter. <cconf> is kept for the explicit one */
Willy Tarreau2b718102021-04-21 07:32:39 +02002527 LIST_DELETE(&f->list);
Christopher Faulet99a17a22018-12-11 09:18:27 +01002528 free(f);
2529 free(name);
2530 break;
2531 }
2532
2533 /* No implicit cache filter found, create configuration for the explicit one */
2534 if (!cconf) {
2535 cconf = calloc(1, sizeof(*cconf));
2536 if (!cconf) {
2537 memprintf(err, "%s: out of memory", args[*cur_arg]);
2538 goto error;
2539 }
2540 cconf->c.name = name;
2541 }
2542
2543 cconf->flags = 0;
2544 fconf->id = cache_store_flt_id;
2545 fconf->conf = cconf;
2546 fconf->ops = &cache_ops;
2547
2548 *cur_arg = pos;
2549 return 0;
2550
2551 error:
2552 free(name);
2553 free(cconf);
2554 return -1;
2555}
2556
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002557static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01002558{
2559 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
2560 return 1;
2561
2562 return 0;
2563}
2564
2565static int cli_io_handler_show_cache(struct appctx *appctx)
2566{
2567 struct cache* cache = appctx->ctx.cli.p0;
Christopher Faulet86e1c332021-12-20 17:09:39 +01002568 struct stream_interface *si = cs_si(appctx->owner);
William Lallemand1f49a362017-11-21 20:01:26 +01002569
William Lallemand1f49a362017-11-21 20:01:26 +01002570 if (cache == NULL) {
2571 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
2572 }
2573
2574 list_for_each_entry_from(cache, &caches, list) {
2575 struct eb32_node *node = NULL;
2576 unsigned int next_key;
2577 struct cache_entry *entry;
Remi Tricot-Le Bretone3e1e5f2020-11-27 15:48:40 +01002578 unsigned int i;
William Lallemand1f49a362017-11-21 20:01:26 +01002579
William Lallemand1f49a362017-11-21 20:01:26 +01002580 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02002581 if (!next_key) {
2582 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
2583 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002584 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02002585 return 0;
2586 }
2587 }
William Lallemand1f49a362017-11-21 20:01:26 +01002588
2589 appctx->ctx.cli.p0 = cache;
2590
2591 while (1) {
2592
2593 shctx_lock(shctx_ptr(cache));
Christopher Faulet27f88a92021-11-23 16:03:05 +01002594 node = eb32_lookup_ge(&cache->entries, next_key);
William Lallemand1f49a362017-11-21 20:01:26 +01002595 if (!node) {
2596 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02002597 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01002598 break;
2599 }
2600
2601 entry = container_of(node, struct cache_entry, eb);
William Lallemand1f49a362017-11-21 20:01:26 +01002602 next_key = node->key + 1;
Willy Tarreauf1de1b52022-04-13 11:21:39 +02002603
2604 if (entry->expire > now.tv_sec) {
2605 chunk_printf(&trash, "%p hash:%u vary:0x", entry, read_u32(entry->hash));
2606 for (i = 0; i < HTTP_CACHE_SEC_KEY_LEN; ++i)
2607 chunk_appendf(&trash, "%02x", (unsigned char)entry->secondary_key[i]);
2608 chunk_appendf(&trash, " size:%u (%u blocks), refcount:%u, expire:%d\n",
2609 block_ptr(entry)->len, block_ptr(entry)->block_count,
2610 block_ptr(entry)->refcount, entry->expire - (int)now.tv_sec);
2611 } else {
2612 /* time to remove that one */
2613 delete_entry(entry);
2614 entry->eb.key = 0;
2615 }
2616
William Lallemand1f49a362017-11-21 20:01:26 +01002617 appctx->ctx.cli.i0 = next_key;
2618
2619 shctx_unlock(shctx_ptr(cache));
2620
2621 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01002622 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01002623 return 0;
2624 }
2625 }
2626
2627 }
2628
2629 return 1;
2630
2631}
2632
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002633
2634/*
2635 * boolean, returns true if response was built out of a cache entry.
2636 */
2637static int
2638smp_fetch_res_cache_hit(const struct arg *args, struct sample *smp,
2639 const char *kw, void *private)
2640{
2641 smp->data.type = SMP_T_BOOL;
2642 smp->data.u.sint = (smp->strm ? (smp->strm->target == &http_cache_applet.obj_type) : 0);
2643
2644 return 1;
2645}
2646
2647/*
2648 * string, returns cache name (if response came from a cache).
2649 */
2650static int
2651smp_fetch_res_cache_name(const struct arg *args, struct sample *smp,
2652 const char *kw, void *private)
2653{
2654 struct appctx *appctx = NULL;
2655
2656 struct cache_flt_conf *cconf = NULL;
2657 struct cache *cache = NULL;
2658
2659 if (!smp->strm || smp->strm->target != &http_cache_applet.obj_type)
2660 return 0;
2661
2662 /* Get appctx from the stream_interface. */
Christopher Faulet95a61e82021-12-22 14:22:03 +01002663 appctx = cs_appctx(smp->strm->csb);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002664 if (appctx && appctx->rule) {
2665 cconf = appctx->rule->arg.act.p[0];
2666 if (cconf) {
2667 cache = cconf->c.cache;
2668
2669 smp->data.type = SMP_T_STR;
2670 smp->flags = SMP_F_CONST;
2671 smp->data.u.str.area = cache->id;
2672 smp->data.u.str.data = strlen(cache->id);
2673 return 1;
2674 }
2675 }
2676
2677 return 0;
2678}
2679
Christopher Faulet99a17a22018-12-11 09:18:27 +01002680/* Declare the filter parser for "cache" keyword */
2681static struct flt_kw_list filter_kws = { "CACHE", { }, {
2682 { "cache", parse_cache_flt, NULL },
2683 { NULL, NULL, NULL },
2684 }
2685};
2686
2687INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
2688
William Lallemand1f49a362017-11-21 20:01:26 +01002689static struct cli_kw_list cli_kws = {{},{
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002690 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
William Lallemande899af82017-11-22 16:41:26 +01002691 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01002692}};
2693
Willy Tarreau0108d902018-11-25 19:14:37 +01002694INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01002695
William Lallemand41db4602017-10-30 11:15:51 +01002696static struct action_kw_list http_res_actions = {
2697 .kw = {
2698 { "cache-store", parse_cache_store },
2699 { NULL, NULL }
2700 }
2701};
2702
Willy Tarreau0108d902018-11-25 19:14:37 +01002703INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
2704
William Lallemand41db4602017-10-30 11:15:51 +01002705static struct action_kw_list http_req_actions = {
2706 .kw = {
2707 { "cache-use", parse_cache_use },
2708 { NULL, NULL }
2709 }
2710};
2711
Willy Tarreau0108d902018-11-25 19:14:37 +01002712INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
2713
Willy Tarreau2231b632019-03-29 18:26:52 +01002714struct applet http_cache_applet = {
William Lallemand41db4602017-10-30 11:15:51 +01002715 .obj_type = OBJ_TYPE_APPLET,
2716 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01002717 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01002718 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01002719};
2720
Willy Tarreaue6552512018-11-26 11:33:13 +01002721/* config parsers for this section */
2722REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
William Lallemandd1d1e222019-08-28 15:22:49 +02002723REGISTER_POST_CHECK(post_check_cache);
Remi Tricot-Le Bretonbf971212020-10-27 11:55:57 +01002724
2725
2726/* Note: must not be declared <const> as its list will be overwritten */
2727static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
2728 { "res.cache_hit", smp_fetch_res_cache_hit, 0, NULL, SMP_T_BOOL, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2729 { "res.cache_name", smp_fetch_res_cache_name, 0, NULL, SMP_T_STR, SMP_USE_HRSHP, SMP_VAL_RESPONSE },
2730 { /* END */ },
2731 }
2732};
2733
2734INITCALL1(STG_REGISTER, sample_register_fetches, &sample_fetch_keywords);