blob: a2d93758f5a4fd04a9379a12219a088d2a519d52 [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
William Lallemand41db4602017-10-30 11:15:51 +010013#include <eb32tree.h>
William Lallemandf528fff2017-11-23 19:43:17 +010014#include <import/sha1.h>
William Lallemand41db4602017-10-30 11:15:51 +010015
William Lallemand75d93292017-11-21 20:01:24 +010016#include <types/action.h>
William Lallemand1f49a362017-11-21 20:01:26 +010017#include <types/cli.h>
William Lallemand75d93292017-11-21 20:01:24 +010018#include <types/filters.h>
19#include <types/proxy.h>
20#include <types/shctx.h>
21
William Lallemand41db4602017-10-30 11:15:51 +010022#include <proto/channel.h>
William Lallemand1f49a362017-11-21 20:01:26 +010023#include <proto/cli.h>
William Lallemand41db4602017-10-30 11:15:51 +010024#include <proto/proxy.h>
25#include <proto/hdr_idx.h>
Christopher Faulet54a8d5a2018-12-07 12:21:11 +010026#include <proto/http_htx.h>
William Lallemand41db4602017-10-30 11:15:51 +010027#include <proto/filters.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020028#include <proto/http_rules.h>
William Lallemand41db4602017-10-30 11:15:51 +010029#include <proto/proto_http.h>
30#include <proto/log.h>
31#include <proto/stream.h>
32#include <proto/stream_interface.h>
33#include <proto/shctx.h>
34
William Lallemand41db4602017-10-30 11:15:51 +010035
36#include <common/cfgparse.h>
37#include <common/hash.h>
Willy Tarreaub96b77e2018-12-11 10:22:41 +010038#include <common/htx.h>
Willy Tarreau0108d902018-11-25 19:14:37 +010039#include <common/initcall.h>
William Lallemand41db4602017-10-30 11:15:51 +010040
41/* flt_cache_store */
Christopher Faulet1f672c52018-12-03 14:30:41 +010042#define CACHE_F_LEGACY_HTTP 0x00000001 /* The cache is used to store raw HTTP
43 * messages (legacy implementation) */
44#define CACHE_F_HTX 0x00000002 /* The cache is used to store HTX messages */
William Lallemand41db4602017-10-30 11:15:51 +010045
Christopher Faulet27d93c32018-12-15 22:32:02 +010046#define CACHE_FLT_F_IMPLICIT_DECL 0x00000001 /* The cache filtre was implicitly declared (ie without
Christopher Faulet99a17a22018-12-11 09:18:27 +010047 * the filter keyword) */
Christopher Fauletafd819c2018-12-11 08:57:45 +010048
Christopher Fauletf4a4ef72018-12-07 17:39:53 +010049const char *cache_store_flt_id = "cache store filter";
William Lallemand41db4602017-10-30 11:15:51 +010050
51struct applet http_cache_applet;
52
53struct flt_ops cache_ops;
54
55struct cache {
Willy Tarreaufd5efb52017-11-26 08:54:31 +010056 struct list list; /* cache linked list */
William Lallemand41db4602017-10-30 11:15:51 +010057 struct eb_root entries; /* head of cache entries based on keys */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010058 unsigned int maxage; /* max-age */
59 unsigned int maxblocks;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +020060 unsigned int maxobjsz; /* max-object-size (in bytes) */
Willy Tarreaufd5efb52017-11-26 08:54:31 +010061 char id[33]; /* cache name */
Christopher Faulet1f672c52018-12-03 14:30:41 +010062 unsigned int flags; /* CACHE_F_* */
William Lallemand41db4602017-10-30 11:15:51 +010063};
64
Christopher Faulet95220e22018-12-07 17:34:39 +010065/* cache config for filters */
66struct cache_flt_conf {
67 union {
68 struct cache *cache; /* cache used by the filter */
69 char *name; /* cache name used during conf parsing */
70 } c;
71 unsigned int flags; /* CACHE_FLT_F_* */
72};
73
William Lallemand41db4602017-10-30 11:15:51 +010074/*
75 * cache ctx for filters
76 */
77struct cache_st {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +010078 int hdrs_len; // field used in legacy mode only
William Lallemand41db4602017-10-30 11:15:51 +010079 struct shared_block *first_block;
80};
81
82struct cache_entry {
83 unsigned int latest_validation; /* latest validation date */
84 unsigned int expire; /* expiration date */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +020085 unsigned int age; /* Origin server "Age" header value */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +010086 unsigned int eoh; /* Origin server end of headers offset. */ // field used in legacy mode only
87
88 unsigned int hdrs_len; // field used in HTX mode only
89 unsigned int data_len; // field used in HTX mode only
90
William Lallemand41db4602017-10-30 11:15:51 +010091 struct eb32_node eb; /* ebtree node used to hold the cache object */
William Lallemandf528fff2017-11-23 19:43:17 +010092 char hash[20];
William Lallemand41db4602017-10-30 11:15:51 +010093 unsigned char data[0];
94};
95
96#define CACHE_BLOCKSIZE 1024
Willy Tarreau96062a12018-11-11 14:00:28 +010097#define CACHE_ENTRY_MAX_AGE 2147483648U
William Lallemand41db4602017-10-30 11:15:51 +010098
99static struct list caches = LIST_HEAD_INIT(caches);
100static struct cache *tmp_cache_config = NULL;
101
Willy Tarreau8ceae722018-11-26 11:58:30 +0100102DECLARE_STATIC_POOL(pool_head_cache_st, "cache_st", sizeof(struct cache_st));
103
William Lallemandf528fff2017-11-23 19:43:17 +0100104struct cache_entry *entry_exist(struct cache *cache, char *hash)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100105{
106 struct eb32_node *node;
107 struct cache_entry *entry;
108
William Lallemandf528fff2017-11-23 19:43:17 +0100109 node = eb32_lookup(&cache->entries, (*(unsigned int *)hash));
William Lallemand4da3f8a2017-10-31 14:33:34 +0100110 if (!node)
111 return NULL;
112
113 entry = eb32_entry(node, struct cache_entry, eb);
William Lallemandf528fff2017-11-23 19:43:17 +0100114
115 /* if that's not the right node */
116 if (memcmp(entry->hash, hash, sizeof(entry->hash)))
117 return NULL;
118
William Lallemand08727662017-11-21 20:01:27 +0100119 if (entry->expire > now.tv_sec) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100120 return entry;
William Lallemand08727662017-11-21 20:01:27 +0100121 } else {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100122 eb32_delete(node);
William Lallemand08727662017-11-21 20:01:27 +0100123 entry->eb.key = 0;
124 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100125 return NULL;
126
127}
128
129static inline struct shared_context *shctx_ptr(struct cache *cache)
130{
131 return (struct shared_context *)((unsigned char *)cache - ((struct shared_context *)NULL)->data);
132}
133
William Lallemand77c11972017-10-31 20:43:01 +0100134static inline struct shared_block *block_ptr(struct cache_entry *entry)
135{
136 return (struct shared_block *)((unsigned char *)entry - ((struct shared_block *)NULL)->data);
137}
138
139
140
William Lallemand41db4602017-10-30 11:15:51 +0100141static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100142cache_store_init(struct proxy *px, struct flt_conf *fconf)
William Lallemand41db4602017-10-30 11:15:51 +0100143{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100144 fconf->flags |= FLT_CFG_FL_HTX;
William Lallemand41db4602017-10-30 11:15:51 +0100145 return 0;
146}
147
Christopher Faulet95220e22018-12-07 17:34:39 +0100148static void
149cache_store_deinit(struct proxy *px, struct flt_conf *fconf)
150{
151 struct cache_flt_conf *cconf = fconf->conf;
152
153 free(cconf);
154}
155
William Lallemand4da3f8a2017-10-31 14:33:34 +0100156static int
Christopher Faulet95220e22018-12-07 17:34:39 +0100157cache_store_check(struct proxy *px, struct flt_conf *fconf)
158{
159 struct cache_flt_conf *cconf = fconf->conf;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100160 struct flt_conf *f;
Christopher Faulet95220e22018-12-07 17:34:39 +0100161 struct cache *cache;
Christopher Faulet27d93c32018-12-15 22:32:02 +0100162 int comp = 0;
Christopher Faulet95220e22018-12-07 17:34:39 +0100163
164 /* resolve the cache name to a ptr in the filter config */
165 list_for_each_entry(cache, &caches, list) {
166 if (!strcmp(cache->id, cconf->c.name)) {
167 /* there can be only one filter per cache, so we free it there */
168 cache->flags |= ((px->options2 & PR_O2_USE_HTX)
169 ? CACHE_F_HTX
170 : CACHE_F_LEGACY_HTTP);
171
172 free(cconf->c.name);
173 cconf->c.cache = cache;
174 goto found;
175 }
176 }
177
178 ha_alert("config: %s '%s': unable to find the cache '%s' referenced by the filter 'cache'.\n",
179 proxy_type_str(px), px->id, (char *)cconf->c.name);
180 return 1;
181
182 found:
Christopher Fauletafd819c2018-12-11 08:57:45 +0100183 /* Here <cache> points on the cache the filter must use and <cconf>
184 * points on the cache filter configuration. */
185
186 /* Check all filters for proxy <px> to know if the compression is
Christopher Faulet27d93c32018-12-15 22:32:02 +0100187 * enabled and if it is after the cache. When the compression is before
188 * the cache, an error is returned. Also check if the cache filter must
189 * be explicitly declaired or not. */
Christopher Fauletafd819c2018-12-11 08:57:45 +0100190 list_for_each_entry(f, &px->filter_configs, list) {
191 if (f == fconf) {
Christopher Faulet27d93c32018-12-15 22:32:02 +0100192 /* The compression filter must be evaluated after the cache. */
193 if (comp) {
194 ha_alert("config: %s '%s': unable to enable the compression filter before "
195 "the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
196 return 1;
197 }
Christopher Faulet99a17a22018-12-11 09:18:27 +0100198 }
Christopher Faulet27d93c32018-12-15 22:32:02 +0100199 else if (f->id == http_comp_flt_id) {
Christopher Fauletafd819c2018-12-11 08:57:45 +0100200 if (!(px->options2 & PR_O2_USE_HTX)) {
201 ha_alert("config: %s '%s' : compression and cache filters cannot be "
202 "both enabled on non HTX proxy.\n",
203 proxy_type_str(px), px->id);
204 return 1;
205 }
Christopher Faulet27d93c32018-12-15 22:32:02 +0100206 comp = 1;
Christopher Fauletafd819c2018-12-11 08:57:45 +0100207 }
Christopher Faulet27d93c32018-12-15 22:32:02 +0100208 else if ((f->id != fconf->id) && (cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
209 /* Implicit declaration is only allowed with the
210 * compression. For other filters, an implicit
211 * declaration is required. */
212 ha_alert("config: %s '%s': require an explicit filter declaration "
213 "to use the cache '%s'.\n", proxy_type_str(px), px->id, cache->id);
214 return 1;
215 }
216
Christopher Fauletafd819c2018-12-11 08:57:45 +0100217 }
Christopher Faulet95220e22018-12-07 17:34:39 +0100218 return 0;
219}
220
221static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100222cache_store_chn_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
223{
224 if (!(chn->flags & CF_ISRESP))
225 return 1;
226
227 if (filter->ctx == NULL) {
228 struct cache_st *st;
229
Willy Tarreaubafbe012017-11-24 17:34:44 +0100230 st = pool_alloc_dirty(pool_head_cache_st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100231 if (st == NULL)
232 return -1;
233
234 st->hdrs_len = 0;
235 st->first_block = NULL;
236 filter->ctx = st;
Christopher Faulet839791a2019-01-07 16:12:07 +0100237
238 /* Register post-analyzer on AN_RES_WAIT_HTTP */
239 filter->post_analyzers |= AN_RES_WAIT_HTTP;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100240 }
241
William Lallemand4da3f8a2017-10-31 14:33:34 +0100242 return 1;
243}
244
245static int
William Lallemand49dc0482017-11-24 14:33:54 +0100246cache_store_chn_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
247{
248 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100249 struct cache_flt_conf *cconf = FLT_CONF(filter);
250 struct cache *cache = cconf->c.cache;
William Lallemand49dc0482017-11-24 14:33:54 +0100251 struct shared_context *shctx = shctx_ptr(cache);
252
253 if (!(chn->flags & CF_ISRESP))
254 return 1;
255
256 /* Everything should be released in the http_end filter, but we need to do it
257 * there too, in case of errors */
258
259 if (st && st->first_block) {
260
261 shctx_lock(shctx);
262 shctx_row_dec_hot(shctx, st->first_block);
263 shctx_unlock(shctx);
264
265 }
266 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100267 pool_free(pool_head_cache_st, st);
William Lallemand49dc0482017-11-24 14:33:54 +0100268 filter->ctx = NULL;
269 }
270
271 return 1;
272}
273
Christopher Faulet839791a2019-01-07 16:12:07 +0100274static int
275cache_store_post_analyze(struct stream *s, struct filter *filter, struct channel *chn,
276 unsigned an_bit)
277{
278 struct http_txn *txn = s->txn;
279 struct http_msg *msg = &txn->rsp;
280 struct cache_st *st = filter->ctx;
281
282 if (an_bit != AN_RES_WAIT_HTTP)
283 goto end;
284
285 /* Here we need to check if any compression filter precedes the cache
286 * filter. This is only possible when the compression is configured in
287 * the frontend while the cache filter is configured on the
288 * backend. This case cannot be detected during HAProxy startup. So in
289 * such cases, the cache is disabled.
290 */
291 if (st && (msg->flags & HTTP_MSGF_COMPRESSING)) {
292 pool_free(pool_head_cache_st, st);
293 filter->ctx = NULL;
294 }
295
296 end:
297 return 1;
298}
William Lallemand49dc0482017-11-24 14:33:54 +0100299
300static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100301cache_store_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
302{
303 struct cache_st *st = filter->ctx;
304
William Lallemand4da3f8a2017-10-31 14:33:34 +0100305 if (!(msg->chn->flags & CF_ISRESP) || !st)
306 return 1;
307
Christopher Faulet67658c92018-12-06 21:59:39 +0100308 if (st->first_block) {
309 register_data_filter(s, msg->chn, filter);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100310 if (!IS_HTX_STRM(s))
311 st->hdrs_len = msg->sov;
Christopher Faulet67658c92018-12-06 21:59:39 +0100312 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100313 return 1;
314}
315
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200316static inline void disable_cache_entry(struct cache_st *st,
317 struct filter *filter, struct shared_context *shctx)
318{
319 struct cache_entry *object;
320
321 object = (struct cache_entry *)st->first_block->data;
322 filter->ctx = NULL; /* disable cache */
323 shctx_lock(shctx);
324 shctx_row_dec_hot(shctx, st->first_block);
325 object->eb.key = 0;
326 shctx_unlock(shctx);
327 pool_free(pool_head_cache_st, st);
328}
329
William Lallemand4da3f8a2017-10-31 14:33:34 +0100330static int
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100331cache_store_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
332 unsigned int offset, unsigned int len)
333{
Christopher Faulet95220e22018-12-07 17:34:39 +0100334 struct cache_flt_conf *cconf = FLT_CONF(filter);
335 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100336 struct cache_st *st = filter->ctx;
337 struct htx *htx = htxbuf(&msg->chn->buf);
338 struct htx_blk *blk;
339 struct htx_ret htx_ret;
340 struct cache_entry *object;
341 int ret, to_forward = 0;
342
343 if (!len)
344 return len;
345
346 if (!st->first_block) {
347 unregister_data_filter(s, msg->chn, filter);
348 return len;
349 }
350 object = (struct cache_entry *)st->first_block->data;
351
352 htx_ret = htx_find_blk(htx, offset);
353 blk = htx_ret.blk;
354 offset = htx_ret.ret;
355
356 while (blk && len) {
357 struct shared_block *fb;
358 enum htx_blk_type type = htx_get_blk_type(blk);
359 uint32_t sz = htx_get_blksz(blk);
360 struct ist v;
361
362 switch (type) {
363 case HTX_BLK_UNUSED:
364 break;
365
366 case HTX_BLK_DATA:
367 case HTX_BLK_TLR:
368 v = htx_get_blk_value(htx, blk);
369 v.ptr += offset;
370 v.len -= offset;
371 if (v.len > len)
372 v.len = len;
373
374 shctx_lock(shctx);
375 fb = shctx_row_reserve_hot(shctx, st->first_block, v.len);
376 if (!fb) {
377 shctx_unlock(shctx);
378 goto no_cache;
379 }
380 shctx_unlock(shctx);
381
382 ret = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
383 (unsigned char *)v.ptr, v.len);
384 if (ret < 0)
385 goto no_cache;
386
387 if (type == HTX_BLK_DATA)
388 object->data_len += v.len;
389 to_forward += v.len;
390 len -= v.len;
391 break;
392
393 default:
394 sz -= offset;
395 if (sz > len)
396 sz = len;
397 to_forward += sz;
398 len -= sz;
399 break;
400 }
401
402 offset = 0;
403 blk = htx_get_next_blk(htx, blk);
404 }
405
406 return to_forward;
407
408 no_cache:
409 disable_cache_entry(st, filter, shctx);
410 unregister_data_filter(s, msg->chn, filter);
411 return len;
412}
413
414static int
William Lallemand4da3f8a2017-10-31 14:33:34 +0100415cache_store_http_forward_data(struct stream *s, struct filter *filter,
416 struct http_msg *msg, unsigned int len)
417{
418 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100419 struct cache_flt_conf *cconf = FLT_CONF(filter);
420 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100421 int ret;
422
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200423 ret = 0;
424
William Lallemand4da3f8a2017-10-31 14:33:34 +0100425 /*
426 * We need to skip the HTTP headers first, because we saved them in the
427 * http-response action.
428 */
Christopher Faulet67658c92018-12-06 21:59:39 +0100429 if (!(msg->chn->flags & CF_ISRESP) || !st) {
430 /* should never happen */
431 unregister_data_filter(s, msg->chn, filter);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100432 return len;
Christopher Faulet67658c92018-12-06 21:59:39 +0100433 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100434
435 if (!len) {
Joseph Herlant8dae5b32018-11-15 14:07:53 -0800436 /* Nothing to forward */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100437 ret = len;
438 }
William Lallemand10935bc2017-11-14 14:39:23 +0100439 else if (st->hdrs_len >= len) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100440 /* Forward part of headers */
441 ret = len;
442 st->hdrs_len -= len;
443 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100444 else {
William Lallemand10935bc2017-11-14 14:39:23 +0100445 /* Forward data */
Christopher Faulet67658c92018-12-06 21:59:39 +0100446 if (st->first_block) {
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200447 int to_append, append;
448 struct shared_block *fb;
449
450 to_append = MIN(ci_contig_data(msg->chn), len - st->hdrs_len);
451
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200452 shctx_lock(shctx);
453 fb = shctx_row_reserve_hot(shctx, st->first_block, to_append);
454 if (!fb) {
Olivier Houchardcd2867a2017-11-01 13:58:21 +0100455 shctx_unlock(shctx);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200456 disable_cache_entry(st, filter, shctx);
Christopher Faulet67658c92018-12-06 21:59:39 +0100457 unregister_data_filter(s, msg->chn, filter);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200458 return len;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100459 }
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200460 shctx_unlock(shctx);
461
Frédéric Lécaillea2219f52018-10-22 16:59:13 +0200462 /* Skip remaining headers to fill the cache */
463 c_adv(msg->chn, st->hdrs_len);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200464 append = shctx_row_data_append(shctx, st->first_block, st->first_block->last_append,
465 (unsigned char *)ci_head(msg->chn), to_append);
466 ret = st->hdrs_len + to_append - append;
467 /* Rewind the buffer to forward all data */
468 c_rew(msg->chn, st->hdrs_len);
469 st->hdrs_len = 0;
Christopher Faulet67658c92018-12-06 21:59:39 +0100470 if (ret < 0) {
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200471 disable_cache_entry(st, filter, shctx);
Christopher Faulet67658c92018-12-06 21:59:39 +0100472 unregister_data_filter(s, msg->chn, filter);
473 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100474 }
Christopher Faulet67658c92018-12-06 21:59:39 +0100475 else {
476 /* should never happen */
477 unregister_data_filter(s, msg->chn, filter);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200478 ret = len;
Christopher Faulet67658c92018-12-06 21:59:39 +0100479 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100480 }
481
482 if ((ret != len) ||
483 (FLT_NXT(filter, msg->chn) != FLT_FWD(filter, msg->chn) + ret))
484 task_wakeup(s->task, TASK_WOKEN_MSG);
485
486 return ret;
487}
488
489static int
490cache_store_http_end(struct stream *s, struct filter *filter,
491 struct http_msg *msg)
492{
493 struct cache_st *st = filter->ctx;
Christopher Faulet95220e22018-12-07 17:34:39 +0100494 struct cache_flt_conf *cconf = FLT_CONF(filter);
495 struct cache *cache = cconf->c.cache;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100496 struct shared_context *shctx = shctx_ptr(cache);
497 struct cache_entry *object;
498
499 if (!(msg->chn->flags & CF_ISRESP))
500 return 1;
501
502 if (st && st->first_block) {
503
504 object = (struct cache_entry *)st->first_block->data;
505
506 /* does not need to test if the insertion worked, if it
507 * doesn't, the blocks will be reused anyway */
508
509 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +0100510 if (eb32_insert(&cache->entries, &object->eb) != &object->eb) {
511 object->eb.key = 0;
512 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100513 /* remove from the hotlist */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100514 shctx_row_dec_hot(shctx, st->first_block);
515 shctx_unlock(shctx);
516
517 }
518 if (st) {
Willy Tarreaubafbe012017-11-24 17:34:44 +0100519 pool_free(pool_head_cache_st, st);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100520 filter->ctx = NULL;
521 }
522
523 return 1;
524}
525
526 /*
527 * This intends to be used when checking HTTP headers for some
528 * word=value directive. Return a pointer to the first character of value, if
529 * the word was not found or if there wasn't any value assigned ot it return NULL
530 */
531char *directive_value(const char *sample, int slen, const char *word, int wlen)
532{
533 int st = 0;
534
535 if (slen < wlen)
536 return 0;
537
538 while (wlen) {
539 char c = *sample ^ *word;
540 if (c && c != ('A' ^ 'a'))
541 return NULL;
542 sample++;
543 word++;
544 slen--;
545 wlen--;
546 }
547
548 while (slen) {
549 if (st == 0) {
550 if (*sample != '=')
551 return NULL;
552 sample++;
553 slen--;
554 st = 1;
555 continue;
556 } else {
557 return (char *)sample;
558 }
559 }
560
561 return NULL;
562}
563
564/*
565 * Return the maxage in seconds of an HTTP response.
566 * Compute the maxage using either:
567 * - the assigned max-age of the cache
568 * - the s-maxage directive
569 * - the max-age directive
570 * - (Expires - Data) headers
571 * - the default-max-age of the cache
572 *
573 */
William Lallemand49b44532017-11-24 18:53:43 +0100574int http_calc_maxage(struct stream *s, struct cache *cache)
William Lallemand4da3f8a2017-10-31 14:33:34 +0100575{
576 struct http_txn *txn = s->txn;
577 struct hdr_ctx ctx;
578
579 int smaxage = -1;
580 int maxage = -1;
581
582
William Lallemand4da3f8a2017-10-31 14:33:34 +0100583 ctx.idx = 0;
584
585 /* loop on the Cache-Control values */
Willy Tarreau178b9872018-06-19 07:13:36 +0200586 while (http_find_header2("Cache-Control", 13, ci_head(&s->res), &txn->hdr_idx, &ctx)) {
William Lallemand4da3f8a2017-10-31 14:33:34 +0100587 char *directive = ctx.line + ctx.val;
588 char *value;
589
590 value = directive_value(directive, ctx.vlen, "s-maxage", 8);
591 if (value) {
Willy Tarreau83061a82018-07-13 11:56:34 +0200592 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100593
594 chunk_strncat(chk, value, ctx.vlen - 8 + 1);
595 chunk_strncat(chk, "", 1);
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200596 maxage = atoi(chk->area);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100597 }
598
599 value = directive_value(ctx.line + ctx.val, ctx.vlen, "max-age", 7);
600 if (value) {
Willy Tarreau83061a82018-07-13 11:56:34 +0200601 struct buffer *chk = get_trash_chunk();
William Lallemand4da3f8a2017-10-31 14:33:34 +0100602
603 chunk_strncat(chk, value, ctx.vlen - 7 + 1);
604 chunk_strncat(chk, "", 1);
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200605 smaxage = atoi(chk->area);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100606 }
607 }
608
609 /* TODO: Expires - Data */
610
611
612 if (smaxage > 0)
William Lallemand49b44532017-11-24 18:53:43 +0100613 return MIN(smaxage, cache->maxage);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100614
615 if (maxage > 0)
William Lallemand49b44532017-11-24 18:53:43 +0100616 return MIN(maxage, cache->maxage);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100617
William Lallemand49b44532017-11-24 18:53:43 +0100618 return cache->maxage;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100619
620}
621
622
William Lallemanda400a3a2017-11-20 19:13:12 +0100623static void cache_free_blocks(struct shared_block *first, struct shared_block *block)
624{
Willy Tarreau5bd37fa2018-04-04 20:17:03 +0200625 struct cache_entry *object = (struct cache_entry *)block->data;
626
627 if (first == block && object->eb.key)
628 eb32_delete(&object->eb);
629 object->eb.key = 0;
William Lallemanda400a3a2017-11-20 19:13:12 +0100630}
631
William Lallemand41db4602017-10-30 11:15:51 +0100632/*
633 * This fonction will store the headers of the response in a buffer and then
634 * register a filter to store the data
635 */
636enum act_return http_action_store_cache(struct act_rule *rule, struct proxy *px,
637 struct session *sess, struct stream *s, int flags)
638{
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200639 unsigned int age;
640 long long hdr_age;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100641 struct http_txn *txn = s->txn;
642 struct http_msg *msg = &txn->rsp;
643 struct filter *filter;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100644 struct shared_block *first = NULL;
Christopher Faulet95220e22018-12-07 17:34:39 +0100645 struct cache_flt_conf *cconf = rule->arg.act.p[0];
646 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet839791a2019-01-07 16:12:07 +0100647 struct cache_st *cache_ctx = NULL;
648 struct cache_entry *object, *old;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100649
William Lallemand4da3f8a2017-10-31 14:33:34 +0100650 /* Don't cache if the response came from a cache */
651 if ((obj_type(s->target) == OBJ_TYPE_APPLET) &&
652 s->target == &http_cache_applet.obj_type) {
653 goto out;
654 }
655
656 /* cache only HTTP/1.1 */
657 if (!(txn->req.flags & HTTP_MSGF_VER_11))
658 goto out;
659
660 /* cache only GET method */
661 if (txn->meth != HTTP_METH_GET)
662 goto out;
663
664 /* cache only 200 status code */
665 if (txn->status != 200)
666 goto out;
667
Christopher Faulet839791a2019-01-07 16:12:07 +0100668 /* Find the corresponding filter instance for the current stream */
669 list_for_each_entry(filter, &s->strm_flt.filters, list) {
670 if (FLT_ID(filter) == cache_store_flt_id && FLT_CONF(filter) == cconf) {
671 /* No filter ctx, don't cache anything */
672 if (!filter->ctx)
673 goto out;
674 cache_ctx = filter->ctx;
675 break;
676 }
677 }
678
679 /* from there, cache_ctx is always defined */
680
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100681 if (IS_HTX_STRM(s)) {
682 struct htx *htx = htxbuf(&s->res.buf);
683 struct http_hdr_ctx ctx;
684 int32_t pos;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100685
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100686 /* Do not cache too big objects. */
687 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
688 htx->data + htx->extra > shctx->max_obj_size)
689 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100690
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100691 /* Does not manage Vary at the moment. We will need a secondary key later for that */
692 ctx.blk = NULL;
693 if (http_find_header(htx, ist("Vary"), &ctx, 0))
694 goto out;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100695
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100696 htx_check_response_for_cacheability(s, &s->res);
697
698 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK))
699 goto out;
700
701 age = 0;
702 ctx.blk = NULL;
703 if (http_find_header(htx, ist("Age"), &ctx, 0)) {
704 if (!strl2llrc(ctx.value.ptr, ctx.value.len, &hdr_age) && hdr_age > 0) {
705 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
706 hdr_age = CACHE_ENTRY_MAX_AGE;
707 age = hdr_age;
708 }
709 http_remove_header(htx, &ctx);
710 }
711
712 chunk_reset(&trash);
713 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
714 struct htx_blk *blk = htx_get_blk(htx, pos);
Christopher Fauletafd819c2018-12-11 08:57:45 +0100715 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100716 uint32_t sz = htx_get_blksz(blk);
717
718 chunk_memcat(&trash, (char *)&blk->info, sizeof(blk->info));
Christopher Fauletafd819c2018-12-11 08:57:45 +0100719 if (type == HTX_BLK_EOH)
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100720 break;
721 chunk_memcat(&trash, htx_get_blk_ptr(htx, blk), sz);
722 }
723 }
724 else {
725 struct hdr_ctx ctx;
726
727 /* Do not cache too big objects. */
728 if ((msg->flags & HTTP_MSGF_CNT_LEN) && shctx->max_obj_size > 0 &&
729 msg->sov + msg->body_len > shctx->max_obj_size)
730 goto out;
731
732 /* Does not manage Vary at the moment. We will need a secondary key later for that */
733 ctx.idx = 0;
734 if (http_find_header2("Vary", 4, ci_head(txn->rsp.chn), &txn->hdr_idx, &ctx))
735 goto out;
736
737 check_response_for_cacheability(s, &s->res);
738
739 if (!(txn->flags & TX_CACHEABLE) || !(txn->flags & TX_CACHE_COOK))
740 goto out;
741
742 age = 0;
743 ctx.idx = 0;
744 if (http_find_header2("Age", 3, ci_head(txn->rsp.chn), &txn->hdr_idx, &ctx)) {
745 if (!strl2llrc(ctx.line + ctx.val, ctx.vlen, &hdr_age) && hdr_age > 0) {
746 if (unlikely(hdr_age > CACHE_ENTRY_MAX_AGE))
747 hdr_age = CACHE_ENTRY_MAX_AGE;
748 age = hdr_age;
749 }
750 http_remove_header2(msg, &txn->hdr_idx, &ctx);
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200751 }
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200752 }
753
William Lallemand4da3f8a2017-10-31 14:33:34 +0100754 shctx_lock(shctx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100755 if (IS_HTX_STRM(s))
756 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry) + trash.data);
757 else
758 first = shctx_row_reserve_hot(shctx, NULL, sizeof(struct cache_entry) + msg->sov);
William Lallemand4da3f8a2017-10-31 14:33:34 +0100759 if (!first) {
760 shctx_unlock(shctx);
761 goto out;
762 }
763 shctx_unlock(shctx);
764
Willy Tarreau1093a452018-04-06 19:02:25 +0200765 /* the received memory is not initialized, we need at least to mark
766 * the object as not indexed yet.
767 */
768 object = (struct cache_entry *)first->data;
769 object->eb.node.leaf_p = NULL;
770 object->eb.key = 0;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200771 object->age = age;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100772 if (IS_HTX_STRM(s)) {
773 object->hdrs_len = trash.data;
774 object->data_len = 0;
775 }
776 else
777 object->eoh = msg->eoh;
Willy Tarreau1093a452018-04-06 19:02:25 +0200778
William Lallemand4da3f8a2017-10-31 14:33:34 +0100779 /* reserve space for the cache_entry structure */
780 first->len = sizeof(struct cache_entry);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +0200781 first->last_append = NULL;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100782 /* cache the headers in a http action because it allows to chose what
783 * to cache, for example you might want to cache a response before
784 * modifying some HTTP headers, or on the contrary after modifying
785 * those headers.
786 */
787
788 /* does not need to be locked because it's in the "hot" list,
789 * copy the headers */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100790 if (IS_HTX_STRM(s)) {
791 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)trash.area, trash.data) < 0)
792 goto out;
793 }
794 else {
795 if (shctx_row_data_append(shctx, first, NULL, (unsigned char *)ci_head(&s->res), msg->sov) < 0)
796 goto out;
797 }
William Lallemand4da3f8a2017-10-31 14:33:34 +0100798
799 /* register the buffer in the filter ctx for filling it with data*/
Christopher Faulet839791a2019-01-07 16:12:07 +0100800 if (cache_ctx) {
801 cache_ctx->first_block = first;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100802
Christopher Faulet839791a2019-01-07 16:12:07 +0100803 object->eb.key = (*(unsigned int *)&txn->cache_hash);
804 memcpy(object->hash, txn->cache_hash, sizeof(object->hash));
805 /* Insert the node later on caching success */
William Lallemand4da3f8a2017-10-31 14:33:34 +0100806
Christopher Faulet839791a2019-01-07 16:12:07 +0100807 shctx_lock(shctx);
Christopher Faulet95220e22018-12-07 17:34:39 +0100808
Christopher Faulet839791a2019-01-07 16:12:07 +0100809 old = entry_exist(cconf->c.cache, txn->cache_hash);
810 if (old) {
811 eb32_delete(&old->eb);
812 old->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100813 }
Christopher Faulet839791a2019-01-07 16:12:07 +0100814 shctx_unlock(shctx);
815
816 /* store latest value and expiration time */
817 object->latest_validation = now.tv_sec;
818 object->expire = now.tv_sec + http_calc_maxage(s, cconf->c.cache);
819 return ACT_RET_CONT;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100820 }
821
822out:
823 /* if does not cache */
824 if (first) {
825 shctx_lock(shctx);
William Lallemand08727662017-11-21 20:01:27 +0100826 first->len = 0;
827 object->eb.key = 0;
William Lallemand4da3f8a2017-10-31 14:33:34 +0100828 shctx_row_dec_hot(shctx, first);
829 shctx_unlock(shctx);
830 }
831
William Lallemand41db4602017-10-30 11:15:51 +0100832 return ACT_RET_CONT;
833}
834
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +0200835#define HTTP_CACHE_INIT 0 /* Initial state. */
836#define HTTP_CACHE_HEADER 1 /* Cache entry headers forwarded. */
837#define HTTP_CACHE_FWD 2 /* Cache entry completely forwarded. */
838#define HTTP_CACHE_END 3 /* Cache entry treatment terminated. */
William Lallemand77c11972017-10-31 20:43:01 +0100839
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100840#define HTX_CACHE_INIT 0 /* Initial state. */
841#define HTX_CACHE_HEADER 1 /* Cache entry headers forwarding */
842#define HTX_CACHE_DATA 2 /* Cache entry data forwarding */
843#define HTX_CACHE_EOD 3 /* Cache entry data forwarded. DATA->TLR transition */
844#define HTX_CACHE_TLR 4 /* Cache entry trailers forwarding */
845#define HTX_CACHE_EOM 5 /* Cache entry completely forwarded. Finish the HTX message */
846#define HTX_CACHE_END 6 /* Cache entry treatment terminated */
847
William Lallemandecb73b12017-11-24 14:33:55 +0100848static void http_cache_applet_release(struct appctx *appctx)
849{
Christopher Faulet95220e22018-12-07 17:34:39 +0100850 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
William Lallemandecb73b12017-11-24 14:33:55 +0100851 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
Christopher Faulet95220e22018-12-07 17:34:39 +0100852 struct cache *cache = cconf->c.cache;
William Lallemandecb73b12017-11-24 14:33:55 +0100853 struct shared_block *first = block_ptr(cache_ptr);
854
855 shctx_lock(shctx_ptr(cache));
856 shctx_row_dec_hot(shctx_ptr(cache), first);
857 shctx_unlock(shctx_ptr(cache));
858}
859
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100860static size_t htx_cache_dump_headers(struct appctx *appctx, struct htx *htx)
861{
Christopher Faulet95220e22018-12-07 17:34:39 +0100862 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
863 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100864 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
865 struct shared_block *shblk = appctx->ctx.cache.next;
866 struct buffer *tmp = get_trash_chunk();
867 char *end;
868 unsigned int offset, len, age;
869
870 offset = appctx->ctx.cache.offset;
871 len = cache_ptr->hdrs_len;
872
873 /* 1. Retrieve all headers from the cache */
874 list_for_each_entry_from(shblk, &shctx->hot, list) {
875 int sz;
876
877 sz = MIN(len, shctx->block_size - offset);
878 if (!chunk_memcat(tmp, (const char *)shblk->data + offset, sz))
879 return 0;
880
881 offset += sz;
882 len -= sz;
883 if (!len)
884 break;
885 offset = 0;
886 }
887 appctx->ctx.cache.offset = offset;
888 appctx->ctx.cache.next = shblk;
889 appctx->ctx.cache.sent += b_data(tmp);
890
891 /* 2. push these headers in the HTX message */
892 offset = 0;
893 while (offset < b_data(tmp)) {
894 struct htx_blk *blk;
895 enum htx_blk_type type;
896 uint32_t info, sz;
897
898 /* Read the header's info */
899 memcpy((char *)&info, b_peek(tmp, offset), 4);
900 type = (info >> 28);
901 sz = ((type == HTX_BLK_HDR)
902 ? (info & 0xff) + ((info >> 8) & 0xfffff)
903 : info & 0xfffffff);
904
905 /* Create the block with the right type and the right size */
906 blk = htx_add_blk(htx, type, sz);
907 if (!blk)
908 return 0;
909
910 /* Copy info and data */
911 blk->info = info;
912 memcpy(htx_get_blk_ptr(htx, blk), b_peek(tmp, offset+4), sz);
913
914 /* next header */
915 offset += 4 + sz;
916 }
917
918 /* 3. Append "age" header */
919 chunk_reset(tmp);
920 age = MAX(0, (int)(now.tv_sec - cache_ptr->latest_validation)) + cache_ptr->age;
921 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
922 age = CACHE_ENTRY_MAX_AGE;
923 end = ultoa_o(age, b_head(tmp), b_size(tmp));
924 b_set_data(tmp, end - b_head(tmp));
925
926 if (!http_add_header(htx, ist("Age"), ist2(b_head(tmp), b_data(tmp))))
927 return 0;
928
929 return htx->data;
930}
931
932static size_t htx_cache_dump_data(struct appctx *appctx, struct htx *htx,
933 enum htx_blk_type type, unsigned int len)
934{
Christopher Faulet95220e22018-12-07 17:34:39 +0100935 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
936 struct shared_context *shctx = shctx_ptr(cconf->c.cache);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100937 struct shared_block *shblk = appctx->ctx.cache.next;
Christopher Fauletcc156622019-01-07 14:07:29 +0100938 uint32_t max = channel_htx_recv_max(si_ic(appctx->owner), htx);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +0100939 unsigned int offset;
940 size_t total = 0;
941
942 offset = appctx->ctx.cache.offset;
943 if (len > max)
944 len = max;
945 if (!len)
946 goto end;
947
948 list_for_each_entry_from(shblk, &shctx->hot, list) {
949 struct ist data;
950 int sz;
951
952 sz = MIN(len, shctx->block_size - offset);
953 data = ist2((const char *)shblk->data + offset, sz);
954 if (type == HTX_BLK_DATA) {
955 if (!htx_add_data(htx, data))
956 break;
957 }
958 else { /* HTX_BLK_TLR */
959 if (!htx_add_trailer(htx, data))
960 break;
961 }
962
963 offset += sz;
964 len -= sz;
965 total += sz;
966 if (!len)
967 break;
968 offset = 0;
969 }
970 appctx->ctx.cache.offset = offset;
971 appctx->ctx.cache.next = shblk;
972 appctx->ctx.cache.sent += total;
973
974 end:
975 return total;
976}
977static void htx_cache_io_handler(struct appctx *appctx)
978{
979 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
980 struct shared_block *first = block_ptr(cache_ptr);
981 struct stream_interface *si = appctx->owner;
982 struct channel *req = si_oc(si);
983 struct channel *res = si_ic(si);
984 struct htx *req_htx, *res_htx;
985 struct buffer *errmsg;
986 size_t ret, total = 0;
987
988 res_htx = htxbuf(&res->buf);
989
990 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
991 goto out;
992
993 /* Check if the input buffer is avalaible. */
994 if (!b_size(&res->buf)) {
995 si_rx_room_blk(si);
996 goto out;
997 }
998
Willy Tarreauefef3232018-12-16 00:37:45 +0100999 if (res->flags & (CF_SHUTW|CF_SHUTR|CF_SHUTW_NOW))
Willy Tarreau273e9642018-12-16 00:35:15 +01001000 appctx->st0 = HTX_CACHE_END;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001001
1002 if (appctx->st0 == HTX_CACHE_INIT) {
1003 appctx->ctx.cache.next = block_ptr(cache_ptr);
1004 appctx->ctx.cache.offset = sizeof(*cache_ptr);
1005 appctx->ctx.cache.sent = 0;
1006 appctx->st0 = HTX_CACHE_HEADER;
1007 }
1008
1009 if (appctx->st0 == HTX_CACHE_HEADER) {
1010 /* Headers must be dump at once. Otherwise it is an error */
1011 ret = htx_cache_dump_headers(appctx, res_htx);
1012 if (!ret)
1013 goto error;
1014
1015 total += ret;
1016 if (cache_ptr->data_len)
1017 appctx->st0 = HTX_CACHE_DATA;
1018 else if (first->len > sizeof(*cache_ptr) + appctx->ctx.cache.sent) {
1019 /* Headers have benn sent (hrds_len) and there is no data
1020 * (data_len == 0). So, all the remaining is the
1021 * trailers */
1022 appctx->st0 = HTX_CACHE_EOD;
1023 }
1024 else
1025 appctx->st0 = HTX_CACHE_EOM;
1026 }
1027
1028 if (appctx->st0 == HTX_CACHE_DATA) {
1029 unsigned int len = cache_ptr->hdrs_len + cache_ptr->data_len - appctx->ctx.cache.sent;
1030
1031 ret = htx_cache_dump_data(appctx, res_htx, HTX_BLK_DATA, len);
Christopher Faulet61123912019-01-02 14:10:01 +01001032 total += ret;
1033 res_htx->extra = (len - ret);
1034 if (ret < len) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001035 si_rx_room_blk(si);
1036 goto out;
1037 }
1038
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001039 if (cache_ptr->hdrs_len + cache_ptr->data_len == appctx->ctx.cache.sent) {
1040 if (first->len > sizeof(*cache_ptr) + appctx->ctx.cache.sent) {
1041 /* Headers and all data have been sent
1042 * (hrds_len + data_len == sent). So, all the remaining
1043 * is the trailers */
1044 appctx->st0 = HTX_CACHE_EOD;
1045 }
1046 else
1047 appctx->st0 = HTX_CACHE_EOM;
1048 }
1049 }
1050
1051 if (appctx->st0 == HTX_CACHE_EOD) {
1052 if (!htx_add_endof(res_htx, HTX_BLK_EOD)) {
1053 si_rx_room_blk(si);
1054 goto out;
1055 }
1056
1057 total++;
1058 appctx->st0 = HTX_CACHE_TLR;
1059 }
1060
1061 if (appctx->st0 == HTX_CACHE_TLR) {
1062 unsigned int len = first->len - sizeof(*cache_ptr) - appctx->ctx.cache.sent;
1063
1064 ret = htx_cache_dump_data(appctx, res_htx, HTX_BLK_TLR, len);
Christopher Faulet74b41ba2019-01-04 16:15:34 +01001065 total += ret;
Christopher Faulet61123912019-01-02 14:10:01 +01001066 if (ret < len) {
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001067 si_rx_room_blk(si);
1068 goto out;
1069 }
1070
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001071 if (first->len == sizeof(*cache_ptr) + appctx->ctx.cache.sent)
1072 appctx->st0 = HTX_CACHE_EOM;
1073 }
1074
1075 if (appctx->st0 == HTX_CACHE_EOM) {
1076 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
1077 si_rx_room_blk(si);
1078 goto out;
1079 }
1080
1081 total++;
1082 appctx->st0 = HTX_CACHE_END;
1083 }
1084
1085 end:
1086 if (appctx->st0 == HTX_CACHE_END) {
1087 /* eat the whole request */
1088 req_htx = htxbuf(&req->buf);
1089 htx_reset(req_htx);
1090 htx_to_buf(req_htx, &req->buf);
1091 co_set_data(req, 0);
1092 res->flags |= CF_READ_NULL;
1093 si_shutr(si);
1094 }
1095
1096 if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST))
1097 si_shutw(si);
1098
1099 if (appctx->st0 == HTX_CACHE_END) {
1100 if ((req->flags & CF_SHUTW) && (si->state == SI_ST_EST)) {
1101 si_shutr(si);
1102 res->flags |= CF_READ_NULL;
1103 }
1104 }
1105 out:
Christopher Faulet61123912019-01-02 14:10:01 +01001106 if (total)
1107 channel_add_input(res, total);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001108
1109 /* we have left the request in the buffer for the case where we
1110 * process a POST, and this automatically re-enables activity on
1111 * read. It's better to indicate that we want to stop reading when
1112 * we're sending, so that we know there's at most one direction
1113 * deciding to wake the applet up. It saves it from looping when
1114 * emitting large blocks into small TCP windows.
1115 */
1116 htx_to_buf(res_htx, &res->buf);
1117 if (!channel_is_empty(res))
1118 si_stop_get(si);
1119 return;
1120
1121 error:
1122 /* Sent and HTTP error 500 */
1123 b_reset(&res->buf);
1124 errmsg = &htx_err_chunks[HTTP_ERR_500];
1125 res->buf.data = b_data(errmsg);
1126 memcpy(res->buf.area, b_head(errmsg), b_data(errmsg));
1127 res_htx = htx_from_buf(&res->buf);
1128
1129 total = res_htx->data;
1130 appctx->st0 = HTX_CACHE_END;
1131 goto end;
1132}
1133
1134
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001135/*
1136 * Append an "Age" header into <chn> channel for this <ce> cache entry.
Joseph Herlant8dae5b32018-11-15 14:07:53 -08001137 * This is the responsibility of the caller to insure there is enough
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001138 * data in the channel.
1139 *
1140 * Returns the number of bytes inserted if succeeded, 0 if failed.
1141 */
1142static int cache_channel_append_age_header(struct cache_entry *ce, struct channel *chn)
1143{
1144 unsigned int age;
1145
1146 age = MAX(0, (int)(now.tv_sec - ce->latest_validation)) + ce->age;
1147 if (unlikely(age > CACHE_ENTRY_MAX_AGE))
1148 age = CACHE_ENTRY_MAX_AGE;
1149
1150 chunk_reset(&trash);
1151 chunk_printf(&trash, "Age: %u", age);
1152
1153 return ci_insert_line2(chn, ce->eoh, trash.area, trash.data);
1154}
1155
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001156static int cache_channel_row_data_get(struct appctx *appctx, int len)
William Lallemand77c11972017-10-31 20:43:01 +01001157{
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001158 int ret, total;
William Lallemand77c11972017-10-31 20:43:01 +01001159 struct stream_interface *si = appctx->owner;
1160 struct channel *res = si_ic(si);
Christopher Faulet95220e22018-12-07 17:34:39 +01001161 struct cache_flt_conf *cconf = appctx->rule->arg.act.p[0];
1162 struct cache *cache = cconf->c.cache;
William Lallemand77c11972017-10-31 20:43:01 +01001163 struct shared_context *shctx = shctx_ptr(cache);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001164 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
1165 struct shared_block *blk, *next = appctx->ctx.cache.next;
1166 int offset;
1167
1168 total = 0;
1169 offset = 0;
1170
1171 if (!next) {
1172 offset = sizeof(struct cache_entry);
1173 next = block_ptr(cache_ptr);
1174 }
1175
1176 blk = next;
1177 list_for_each_entry_from(blk, &shctx->hot, list) {
1178 int sz;
1179
1180 if (len <= 0)
1181 break;
1182
1183 sz = MIN(len, shctx->block_size - offset);
1184
1185 ret = ci_putblk(res, (const char *)blk->data + offset, sz);
1186 if (unlikely(offset))
1187 offset = 0;
1188 if (ret <= 0) {
1189 if (ret == -3 || ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01001190 si_rx_room_blk(si);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001191 break;
1192 }
1193 return -1;
1194 }
1195
1196 total += sz;
1197 len -= sz;
1198 }
1199 appctx->ctx.cache.next = blk;
1200
1201 return total;
1202}
1203
1204static void http_cache_io_handler(struct appctx *appctx)
1205{
1206 struct stream_interface *si = appctx->owner;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001207 struct stream *s = si_strm(si);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001208 struct channel *res = si_ic(si);
1209 struct cache_entry *cache_ptr = appctx->ctx.cache.entry;
William Lallemand77c11972017-10-31 20:43:01 +01001210 struct shared_block *first = block_ptr(cache_ptr);
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001211 unsigned int *sent = &appctx->ctx.cache.sent;
1212
1213 if (IS_HTX_STRM(s))
1214 return htx_cache_io_handler(appctx);
William Lallemand77c11972017-10-31 20:43:01 +01001215
1216 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
1217 goto out;
1218
Joseph Herlant8dae5b32018-11-15 14:07:53 -08001219 /* Check if the input buffer is available. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02001220 if (res->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01001221 /* buf.size==0 means we failed to get a buffer and were
1222 * already subscribed to a wait list to get a buffer.
1223 */
William Lallemand77c11972017-10-31 20:43:01 +01001224 goto out;
1225 }
1226
Willy Tarreauefef3232018-12-16 00:37:45 +01001227 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
William Lallemand77c11972017-10-31 20:43:01 +01001228 appctx->st0 = HTTP_CACHE_END;
1229
1230 /* buffer are aligned there, should be fine */
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001231 if (appctx->st0 == HTTP_CACHE_HEADER || appctx->st0 == HTTP_CACHE_INIT) {
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001232 int len = first->len - *sent - sizeof(struct cache_entry);
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001233 if (len > 0) {
1234 int ret;
1235
1236 ret = cache_channel_row_data_get(appctx, len);
1237 if (ret == -1)
1238 appctx->st0 = HTTP_CACHE_END;
1239 else
1240 *sent += ret;
Frédéric Lécaillee7a770c2018-10-26 14:29:22 +02001241 if (appctx->st0 == HTTP_CACHE_INIT && *sent > cache_ptr->eoh &&
1242 cache_channel_append_age_header(cache_ptr, res))
1243 appctx->st0 = HTTP_CACHE_HEADER;
Christopher Faulet61123912019-01-02 14:10:01 +01001244 else if (ret == len) {
1245 *sent = 0;
1246 appctx->st0 = HTTP_CACHE_FWD;
1247 }
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001248 }
1249 else {
1250 *sent = 0;
1251 appctx->st0 = HTTP_CACHE_FWD;
William Lallemand77c11972017-10-31 20:43:01 +01001252 }
William Lallemand77c11972017-10-31 20:43:01 +01001253 }
1254
1255 if (appctx->st0 == HTTP_CACHE_FWD) {
1256 /* eat the whole request */
Willy Tarreau178b9872018-06-19 07:13:36 +02001257 co_skip(si_oc(si), co_data(si_oc(si))); // NOTE: when disabled does not repport the correct status code
William Lallemand77c11972017-10-31 20:43:01 +01001258 res->flags |= CF_READ_NULL;
1259 si_shutr(si);
1260 }
1261
1262 if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST))
1263 si_shutw(si);
1264out:
1265 ;
1266}
1267
Christopher Faulet95220e22018-12-07 17:34:39 +01001268static int parse_cache_rule(struct proxy *proxy, const char *name, struct act_rule *rule, char **err)
William Lallemand41db4602017-10-30 11:15:51 +01001269{
1270 struct flt_conf *fconf;
Christopher Faulet95220e22018-12-07 17:34:39 +01001271 struct cache_flt_conf *cconf = NULL;
William Lallemand41db4602017-10-30 11:15:51 +01001272
Christopher Faulet95220e22018-12-07 17:34:39 +01001273 if (!*name || strcmp(name, "if") == 0 || strcmp(name, "unless") == 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001274 memprintf(err, "expects a cache name");
Christopher Faulet95220e22018-12-07 17:34:39 +01001275 goto err;
William Lallemand41db4602017-10-30 11:15:51 +01001276 }
1277
1278 /* check if a cache filter was already registered with this cache
1279 * name, if that's the case, must use it. */
1280 list_for_each_entry(fconf, &proxy->filter_configs, list) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001281 if (fconf->id == cache_store_flt_id) {
1282 cconf = fconf->conf;
1283 if (cconf && !strcmp((char *)cconf->c.name, name)) {
1284 rule->arg.act.p[0] = cconf;
1285 return 1;
1286 }
William Lallemand41db4602017-10-30 11:15:51 +01001287 }
1288 }
1289
Christopher Faulet95220e22018-12-07 17:34:39 +01001290 /* Create the filter cache config */
1291 cconf = calloc(1, sizeof(*cconf));
1292 if (!cconf) {
1293 memprintf(err, "out of memory\n");
1294 goto err;
1295 }
Christopher Faulet99a17a22018-12-11 09:18:27 +01001296 cconf->flags = CACHE_FLT_F_IMPLICIT_DECL;
Christopher Faulet95220e22018-12-07 17:34:39 +01001297 cconf->c.name = strdup(name);
1298 if (!cconf->c.name) {
1299 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001300 goto err;
1301 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001302
William Lallemand41db4602017-10-30 11:15:51 +01001303 /* register a filter to fill the cache buffer */
1304 fconf = calloc(1, sizeof(*fconf));
1305 if (!fconf) {
Christopher Faulet95220e22018-12-07 17:34:39 +01001306 memprintf(err, "out of memory\n");
William Lallemand41db4602017-10-30 11:15:51 +01001307 goto err;
1308 }
Christopher Faulet95220e22018-12-07 17:34:39 +01001309 fconf->id = cache_store_flt_id;
1310 fconf->conf = cconf;
William Lallemand41db4602017-10-30 11:15:51 +01001311 fconf->ops = &cache_ops;
1312 LIST_ADDQ(&proxy->filter_configs, &fconf->list);
1313
Christopher Faulet95220e22018-12-07 17:34:39 +01001314 rule->arg.act.p[0] = cconf;
1315 return 1;
William Lallemand41db4602017-10-30 11:15:51 +01001316
Christopher Faulet95220e22018-12-07 17:34:39 +01001317 err:
1318 free(cconf);
1319 return 0;
1320}
1321
1322enum act_parse_ret parse_cache_store(const char **args, int *orig_arg, struct proxy *proxy,
1323 struct act_rule *rule, char **err)
1324{
1325 rule->action = ACT_CUSTOM;
1326 rule->action_ptr = http_action_store_cache;
1327
1328 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
1329 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001330
Christopher Faulet95220e22018-12-07 17:34:39 +01001331 (*orig_arg)++;
1332 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001333}
1334
William Lallemandf528fff2017-11-23 19:43:17 +01001335/* This produces a sha1 hash of the concatenation of the first
1336 * occurrence of the Host header followed by the path component if it
1337 * begins with a slash ('/'). */
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001338int sha1_hosturi(struct stream *s)
William Lallemandf528fff2017-11-23 19:43:17 +01001339{
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001340 struct http_txn *txn = s->txn;
William Lallemandf528fff2017-11-23 19:43:17 +01001341 blk_SHA_CTX sha1_ctx;
Willy Tarreau83061a82018-07-13 11:56:34 +02001342 struct buffer *trash;
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001343
William Lallemandf528fff2017-11-23 19:43:17 +01001344 trash = get_trash_chunk();
1345
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001346 if (IS_HTX_STRM(s)) {
1347 struct htx *htx = htxbuf(&s->req.buf);
1348 struct htx_sl *sl;
1349 struct http_hdr_ctx ctx;
1350 struct ist path;
William Lallemandf528fff2017-11-23 19:43:17 +01001351
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001352 ctx.blk = NULL;
1353 if (!http_find_header(htx, ist("Host"), &ctx, 0))
1354 return 0;
1355 chunk_memcat(trash, ctx.value.ptr, ctx.value.len);
1356
1357 sl = http_find_stline(htx);
1358 path = http_get_path(htx_sl_req_uri(sl));
1359 if (!path.ptr)
1360 return 0;
1361 chunk_memcat(trash, path.ptr, path.len);
1362 }
1363 else {
1364 struct hdr_ctx ctx;
1365 char *path;
1366 char *end;
1367
1368 /* retrive the host */
1369 ctx.idx = 0;
1370 if (!http_find_header2("Host", 4, ci_head(txn->req.chn), &txn->hdr_idx, &ctx))
1371 return 0;
1372 chunk_strncat(trash, ctx.line + ctx.val, ctx.vlen);
1373
1374 /* now retrieve the path */
1375 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
1376 path = http_txn_get_path(txn);
1377 if (!path)
1378 return 0;
1379 chunk_strncat(trash, path, end - path);
1380 }
William Lallemandf528fff2017-11-23 19:43:17 +01001381
1382 /* hash everything */
1383 blk_SHA1_Init(&sha1_ctx);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001384 blk_SHA1_Update(&sha1_ctx, trash->area, trash->data);
William Lallemandf528fff2017-11-23 19:43:17 +01001385 blk_SHA1_Final((unsigned char *)txn->cache_hash, &sha1_ctx);
1386
1387 return 1;
1388}
1389
William Lallemand41db4602017-10-30 11:15:51 +01001390enum act_return http_action_req_cache_use(struct act_rule *rule, struct proxy *px,
1391 struct session *sess, struct stream *s, int flags)
1392{
William Lallemand77c11972017-10-31 20:43:01 +01001393
William Lallemand77c11972017-10-31 20:43:01 +01001394 struct cache_entry *res;
Christopher Faulet95220e22018-12-07 17:34:39 +01001395 struct cache_flt_conf *cconf = rule->arg.act.p[0];
1396 struct cache *cache = cconf->c.cache;
William Lallemand77c11972017-10-31 20:43:01 +01001397
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001398 if (IS_HTX_STRM(s))
1399 htx_check_request_for_cacheability(s, &s->req);
1400 else
1401 check_request_for_cacheability(s, &s->req);
1402
Willy Tarreau504455c2017-12-22 17:47:35 +01001403 if ((s->txn->flags & (TX_CACHE_IGNORE|TX_CACHEABLE)) == TX_CACHE_IGNORE)
1404 return ACT_RET_CONT;
1405
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001406 if (!sha1_hosturi(s))
Willy Tarreau7704b1e2017-12-22 16:32:43 +01001407 return ACT_RET_CONT;
William Lallemandf528fff2017-11-23 19:43:17 +01001408
Willy Tarreau504455c2017-12-22 17:47:35 +01001409 if (s->txn->flags & TX_CACHE_IGNORE)
1410 return ACT_RET_CONT;
1411
Willy Tarreaua1214a52018-12-14 14:00:25 +01001412 if (px == strm_fe(s))
1413 HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_lookups, 1);
1414 else
1415 HA_ATOMIC_ADD(&px->be_counters.p.http.cache_lookups, 1);
1416
William Lallemanda400a3a2017-11-20 19:13:12 +01001417 shctx_lock(shctx_ptr(cache));
William Lallemandf528fff2017-11-23 19:43:17 +01001418 res = entry_exist(cache, s->txn->cache_hash);
William Lallemand77c11972017-10-31 20:43:01 +01001419 if (res) {
1420 struct appctx *appctx;
William Lallemanda400a3a2017-11-20 19:13:12 +01001421 shctx_row_inc_hot(shctx_ptr(cache), block_ptr(res));
1422 shctx_unlock(shctx_ptr(cache));
William Lallemand77c11972017-10-31 20:43:01 +01001423 s->target = &http_cache_applet.obj_type;
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001424 if ((appctx = si_register_handler(&s->si[1], objt_applet(s->target)))) {
William Lallemand77c11972017-10-31 20:43:01 +01001425 appctx->st0 = HTTP_CACHE_INIT;
1426 appctx->rule = rule;
1427 appctx->ctx.cache.entry = res;
Frédéric Lécaille8df65ae2018-10-22 18:01:48 +02001428 appctx->ctx.cache.next = NULL;
1429 appctx->ctx.cache.sent = 0;
Willy Tarreaua1214a52018-12-14 14:00:25 +01001430
1431 if (px == strm_fe(s))
1432 HA_ATOMIC_ADD(&px->fe_counters.p.http.cache_hits, 1);
1433 else
1434 HA_ATOMIC_ADD(&px->be_counters.p.http.cache_hits, 1);
Olivier Houchardfccf8402017-11-01 14:04:02 +01001435 return ACT_RET_CONT;
William Lallemand77c11972017-10-31 20:43:01 +01001436 } else {
William Lallemand55e76742017-11-21 20:01:28 +01001437 shctx_lock(shctx_ptr(cache));
1438 shctx_row_dec_hot(shctx_ptr(cache), block_ptr(res));
1439 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001440 return ACT_RET_YIELD;
William Lallemand77c11972017-10-31 20:43:01 +01001441 }
1442 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001443 shctx_unlock(shctx_ptr(cache));
Olivier Houchardfccf8402017-11-01 14:04:02 +01001444 return ACT_RET_CONT;
William Lallemand41db4602017-10-30 11:15:51 +01001445}
1446
1447
1448enum act_parse_ret parse_cache_use(const char **args, int *orig_arg, struct proxy *proxy,
1449 struct act_rule *rule, char **err)
1450{
William Lallemand41db4602017-10-30 11:15:51 +01001451 rule->action = ACT_CUSTOM;
1452 rule->action_ptr = http_action_req_cache_use;
1453
Christopher Faulet95220e22018-12-07 17:34:39 +01001454 if (!parse_cache_rule(proxy, args[*orig_arg], rule, err))
William Lallemand41db4602017-10-30 11:15:51 +01001455 return ACT_RET_PRS_ERR;
William Lallemand41db4602017-10-30 11:15:51 +01001456
1457 (*orig_arg)++;
1458 return ACT_RET_PRS_OK;
William Lallemand41db4602017-10-30 11:15:51 +01001459}
1460
1461int cfg_parse_cache(const char *file, int linenum, char **args, int kwm)
1462{
1463 int err_code = 0;
1464
1465 if (strcmp(args[0], "cache") == 0) { /* new cache section */
1466
1467 if (!*args[1]) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001468 ha_alert("parsing [%s:%d] : '%s' expects an <id> argument\n",
1469 file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001470 err_code |= ERR_ALERT | ERR_ABORT;
1471 goto out;
1472 }
1473
1474 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1475 err_code |= ERR_ABORT;
1476 goto out;
1477 }
1478
1479 if (tmp_cache_config == NULL) {
1480 tmp_cache_config = calloc(1, sizeof(*tmp_cache_config));
1481 if (!tmp_cache_config) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001482 ha_alert("parsing [%s:%d]: out of memory.\n", file, linenum);
William Lallemand41db4602017-10-30 11:15:51 +01001483 err_code |= ERR_ALERT | ERR_ABORT;
1484 goto out;
1485 }
1486
1487 strlcpy2(tmp_cache_config->id, args[1], 33);
1488 if (strlen(args[1]) > 32) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001489 ha_warning("parsing [%s:%d]: cache id is limited to 32 characters, truncate to '%s'.\n",
1490 file, linenum, tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001491 err_code |= ERR_WARN;
1492 }
William Lallemand49b44532017-11-24 18:53:43 +01001493 tmp_cache_config->maxage = 60;
William Lallemand41db4602017-10-30 11:15:51 +01001494 tmp_cache_config->maxblocks = 0;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001495 tmp_cache_config->maxobjsz = 0;
Christopher Faulet1f672c52018-12-03 14:30:41 +01001496 tmp_cache_config->flags = 0;
William Lallemand41db4602017-10-30 11:15:51 +01001497 }
1498 } else if (strcmp(args[0], "total-max-size") == 0) {
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001499 unsigned long int maxsize;
1500 char *err;
William Lallemand41db4602017-10-30 11:15:51 +01001501
1502 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1503 err_code |= ERR_ABORT;
1504 goto out;
1505 }
1506
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001507 maxsize = strtoul(args[1], &err, 10);
1508 if (err == args[1] || *err != '\0') {
1509 ha_warning("parsing [%s:%d]: total-max-size wrong value '%s'\n",
1510 file, linenum, args[1]);
1511 err_code |= ERR_ABORT;
1512 goto out;
1513 }
1514
1515 if (maxsize > (UINT_MAX >> 20)) {
1516 ha_warning("parsing [%s:%d]: \"total-max-size\" (%s) must not be greater than %u\n",
1517 file, linenum, args[1], UINT_MAX >> 20);
1518 err_code |= ERR_ABORT;
1519 goto out;
1520 }
1521
William Lallemand41db4602017-10-30 11:15:51 +01001522 /* size in megabytes */
Frédéric Lécailleb9b8b6b2018-10-25 20:17:45 +02001523 maxsize *= 1024 * 1024 / CACHE_BLOCKSIZE;
William Lallemand41db4602017-10-30 11:15:51 +01001524 tmp_cache_config->maxblocks = maxsize;
William Lallemand49b44532017-11-24 18:53:43 +01001525 } else if (strcmp(args[0], "max-age") == 0) {
1526 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1527 err_code |= ERR_ABORT;
1528 goto out;
1529 }
1530
1531 if (!*args[1]) {
1532 ha_warning("parsing [%s:%d]: '%s' expects an age parameter in seconds.\n",
1533 file, linenum, args[0]);
1534 err_code |= ERR_WARN;
1535 }
1536
1537 tmp_cache_config->maxage = atoi(args[1]);
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001538 } else if (strcmp(args[0], "max-object-size") == 0) {
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001539 unsigned int maxobjsz;
1540 char *err;
1541
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001542 if (alertif_too_many_args(1, file, linenum, args, &err_code)) {
1543 err_code |= ERR_ABORT;
1544 goto out;
1545 }
1546
1547 if (!*args[1]) {
1548 ha_warning("parsing [%s:%d]: '%s' expects a maximum file size parameter in bytes.\n",
1549 file, linenum, args[0]);
1550 err_code |= ERR_WARN;
1551 }
1552
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001553 maxobjsz = strtoul(args[1], &err, 10);
1554 if (err == args[1] || *err != '\0') {
1555 ha_warning("parsing [%s:%d]: max-object-size wrong value '%s'\n",
1556 file, linenum, args[1]);
1557 err_code |= ERR_ABORT;
1558 goto out;
1559 }
1560 tmp_cache_config->maxobjsz = maxobjsz;
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001561 }
1562 else if (*args[0] != 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001563 ha_alert("parsing [%s:%d] : unknown keyword '%s' in 'cache' section\n", file, linenum, args[0]);
William Lallemand41db4602017-10-30 11:15:51 +01001564 err_code |= ERR_ALERT | ERR_FATAL;
1565 goto out;
1566 }
1567out:
1568 return err_code;
1569}
1570
1571/* once the cache section is parsed */
1572
1573int cfg_post_parse_section_cache()
1574{
1575 struct shared_context *shctx;
1576 int err_code = 0;
1577 int ret_shctx;
1578
1579 if (tmp_cache_config) {
1580 struct cache *cache;
1581
1582 if (tmp_cache_config->maxblocks <= 0) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01001583 ha_alert("Size not specified for cache '%s'\n", tmp_cache_config->id);
William Lallemand41db4602017-10-30 11:15:51 +01001584 err_code |= ERR_FATAL | ERR_ALERT;
1585 goto out;
1586 }
1587
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001588 if (!tmp_cache_config->maxobjsz) {
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001589 /* Default max. file size is a 256th of the cache size. */
1590 tmp_cache_config->maxobjsz =
1591 (tmp_cache_config->maxblocks * CACHE_BLOCKSIZE) >> 8;
Frédéric Lécaille4eba5442018-10-25 20:29:31 +02001592 }
1593 else if (tmp_cache_config->maxobjsz > tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2) {
1594 ha_alert("\"max-object-size\" is limited to an half of \"total-max-size\" => %u\n", tmp_cache_config->maxblocks * CACHE_BLOCKSIZE / 2);
1595 err_code |= ERR_FATAL | ERR_ALERT;
1596 goto out;
1597 }
Frédéric Lécaillea2219f52018-10-22 16:59:13 +02001598
1599 ret_shctx = shctx_init(&shctx, tmp_cache_config->maxblocks, CACHE_BLOCKSIZE,
1600 tmp_cache_config->maxobjsz, sizeof(struct cache), 1);
William Lallemand4da3f8a2017-10-31 14:33:34 +01001601
Frédéric Lécaillebc584492018-10-25 20:18:59 +02001602 if (ret_shctx <= 0) {
William Lallemand41db4602017-10-30 11:15:51 +01001603 if (ret_shctx == SHCTX_E_INIT_LOCK)
Christopher Faulet767a84b2017-11-24 16:50:31 +01001604 ha_alert("Unable to initialize the lock for the cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001605 else
Christopher Faulet767a84b2017-11-24 16:50:31 +01001606 ha_alert("Unable to allocate cache.\n");
William Lallemand41db4602017-10-30 11:15:51 +01001607
1608 err_code |= ERR_FATAL | ERR_ALERT;
1609 goto out;
1610 }
William Lallemanda400a3a2017-11-20 19:13:12 +01001611 shctx->free_block = cache_free_blocks;
William Lallemand41db4602017-10-30 11:15:51 +01001612 memcpy(shctx->data, tmp_cache_config, sizeof(struct cache));
1613 cache = (struct cache *)shctx->data;
1614 cache->entries = EB_ROOT_UNIQUE;
William Lallemand41db4602017-10-30 11:15:51 +01001615 LIST_ADDQ(&caches, &cache->list);
1616 }
1617out:
1618 free(tmp_cache_config);
1619 tmp_cache_config = NULL;
1620 return err_code;
1621
1622}
1623
1624/*
1625 * Resolve the cache name to a pointer once the file is completely read.
1626 */
1627int cfg_cache_postparser()
1628{
William Lallemand41db4602017-10-30 11:15:51 +01001629 struct cache *cache;
William Lallemand41db4602017-10-30 11:15:51 +01001630 int err = 0;
Christopher Faulet1f672c52018-12-03 14:30:41 +01001631
1632 /* Check if the cache is used by HTX and legacy HTTP proxies in same
1633 * time
1634 */
1635 list_for_each_entry(cache, &caches, list) {
1636 if ((cache->flags & (CACHE_F_HTX|CACHE_F_LEGACY_HTTP)) == (CACHE_F_HTX|CACHE_F_LEGACY_HTTP)) {
1637 ha_alert("Cache '%s': cannot be used by HTX and legacy HTTP proxies in same time.\n",
1638 cache->id);
1639 err++;
1640 }
1641 }
1642
William Lallemand41db4602017-10-30 11:15:51 +01001643 return err;
1644}
1645
1646
1647struct flt_ops cache_ops = {
1648 .init = cache_store_init,
Christopher Faulet95220e22018-12-07 17:34:39 +01001649 .check = cache_store_check,
1650 .deinit = cache_store_deinit,
William Lallemand41db4602017-10-30 11:15:51 +01001651
William Lallemand4da3f8a2017-10-31 14:33:34 +01001652 /* Handle channels activity */
1653 .channel_start_analyze = cache_store_chn_start_analyze,
William Lallemand49dc0482017-11-24 14:33:54 +01001654 .channel_end_analyze = cache_store_chn_end_analyze,
Christopher Faulet839791a2019-01-07 16:12:07 +01001655 .channel_post_analyze = cache_store_post_analyze,
William Lallemand4da3f8a2017-10-31 14:33:34 +01001656
1657 /* Filter HTTP requests and responses */
1658 .http_headers = cache_store_http_headers,
Christopher Faulet54a8d5a2018-12-07 12:21:11 +01001659 .http_payload = cache_store_http_payload,
William Lallemand4da3f8a2017-10-31 14:33:34 +01001660 .http_end = cache_store_http_end,
1661
1662 .http_forward_data = cache_store_http_forward_data,
1663
William Lallemand41db4602017-10-30 11:15:51 +01001664};
1665
Christopher Faulet99a17a22018-12-11 09:18:27 +01001666
1667
1668static int
1669parse_cache_flt(char **args, int *cur_arg, struct proxy *px,
1670 struct flt_conf *fconf, char **err, void *private)
1671{
1672 struct flt_conf *f, *back;
Willy Tarreaua73da1e2018-12-14 10:19:28 +01001673 struct cache_flt_conf *cconf = NULL;
Christopher Faulet99a17a22018-12-11 09:18:27 +01001674 char *name = NULL;
1675 int pos = *cur_arg;
1676
1677 /* Get the cache filter name*/
1678 if (!strcmp(args[pos], "cache")) {
1679 if (!*args[pos + 1]) {
1680 memprintf(err, "%s : expects an <id> argument", args[pos]);
1681 goto error;
1682 }
1683 name = strdup(args[pos + 1]);
1684 if (!name) {
1685 memprintf(err, "%s '%s' : out of memory", args[pos], args[pos + 1]);
1686 goto error;
1687 }
1688 pos += 2;
1689 }
1690
1691 /* Check if an implicit filter with the same name already exists. If so,
1692 * we remove the implicit filter to use the explicit one. */
1693 list_for_each_entry_safe(f, back, &px->filter_configs, list) {
1694 if (f->id != cache_store_flt_id)
1695 continue;
1696
1697 cconf = f->conf;
1698 if (strcmp(name, cconf->c.name)) {
1699 cconf = NULL;
1700 continue;
1701 }
1702
1703 if (!(cconf->flags & CACHE_FLT_F_IMPLICIT_DECL)) {
1704 cconf = NULL;
1705 memprintf(err, "%s: multiple explicit declarations of the cache filter '%s'",
1706 px->id, name);
1707 return -1;
1708 }
1709
1710 /* Remove the implicit filter. <cconf> is kept for the explicit one */
1711 LIST_DEL(&f->list);
1712 free(f);
1713 free(name);
1714 break;
1715 }
1716
1717 /* No implicit cache filter found, create configuration for the explicit one */
1718 if (!cconf) {
1719 cconf = calloc(1, sizeof(*cconf));
1720 if (!cconf) {
1721 memprintf(err, "%s: out of memory", args[*cur_arg]);
1722 goto error;
1723 }
1724 cconf->c.name = name;
1725 }
1726
1727 cconf->flags = 0;
1728 fconf->id = cache_store_flt_id;
1729 fconf->conf = cconf;
1730 fconf->ops = &cache_ops;
1731
1732 *cur_arg = pos;
1733 return 0;
1734
1735 error:
1736 free(name);
1737 free(cconf);
1738 return -1;
1739}
1740
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02001741static int cli_parse_show_cache(char **args, char *payload, struct appctx *appctx, void *private)
William Lallemand1f49a362017-11-21 20:01:26 +01001742{
1743 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
1744 return 1;
1745
1746 return 0;
1747}
1748
1749static int cli_io_handler_show_cache(struct appctx *appctx)
1750{
1751 struct cache* cache = appctx->ctx.cli.p0;
1752 struct stream_interface *si = appctx->owner;
1753
William Lallemand1f49a362017-11-21 20:01:26 +01001754 if (cache == NULL) {
1755 cache = LIST_ELEM((caches).n, typeof(struct cache *), list);
1756 }
1757
1758 list_for_each_entry_from(cache, &caches, list) {
1759 struct eb32_node *node = NULL;
1760 unsigned int next_key;
1761 struct cache_entry *entry;
1762
William Lallemand1f49a362017-11-21 20:01:26 +01001763 next_key = appctx->ctx.cli.i0;
Willy Tarreauafe1de52018-04-04 11:56:43 +02001764 if (!next_key) {
1765 chunk_printf(&trash, "%p: %s (shctx:%p, available blocks:%d)\n", cache, cache->id, shctx_ptr(cache), shctx_ptr(cache)->nbav);
1766 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01001767 si_rx_room_blk(si);
Willy Tarreauafe1de52018-04-04 11:56:43 +02001768 return 0;
1769 }
1770 }
William Lallemand1f49a362017-11-21 20:01:26 +01001771
1772 appctx->ctx.cli.p0 = cache;
1773
1774 while (1) {
1775
1776 shctx_lock(shctx_ptr(cache));
1777 node = eb32_lookup_ge(&cache->entries, next_key);
1778 if (!node) {
1779 shctx_unlock(shctx_ptr(cache));
Willy Tarreauafe1de52018-04-04 11:56:43 +02001780 appctx->ctx.cli.i0 = 0;
William Lallemand1f49a362017-11-21 20:01:26 +01001781 break;
1782 }
1783
1784 entry = container_of(node, struct cache_entry, eb);
Willy Tarreauafe1de52018-04-04 11:56:43 +02001785 chunk_printf(&trash, "%p hash:%u size:%u (%u blocks), refcount:%u, expire:%d\n", entry, (*(unsigned int *)entry->hash), block_ptr(entry)->len, block_ptr(entry)->block_count, block_ptr(entry)->refcount, entry->expire - (int)now.tv_sec);
William Lallemand1f49a362017-11-21 20:01:26 +01001786
1787 next_key = node->key + 1;
1788 appctx->ctx.cli.i0 = next_key;
1789
1790 shctx_unlock(shctx_ptr(cache));
1791
1792 if (ci_putchk(si_ic(si), &trash) == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01001793 si_rx_room_blk(si);
William Lallemand1f49a362017-11-21 20:01:26 +01001794 return 0;
1795 }
1796 }
1797
1798 }
1799
1800 return 1;
1801
1802}
1803
Christopher Faulet99a17a22018-12-11 09:18:27 +01001804/* Declare the filter parser for "cache" keyword */
1805static struct flt_kw_list filter_kws = { "CACHE", { }, {
1806 { "cache", parse_cache_flt, NULL },
1807 { NULL, NULL, NULL },
1808 }
1809};
1810
1811INITCALL1(STG_REGISTER, flt_register_keywords, &filter_kws);
1812
William Lallemand1f49a362017-11-21 20:01:26 +01001813static struct cli_kw_list cli_kws = {{},{
William Lallemande899af82017-11-22 16:41:26 +01001814 { { "show", "cache", NULL }, "show cache : show cache status", cli_parse_show_cache, cli_io_handler_show_cache, NULL, NULL },
1815 {{},}
William Lallemand1f49a362017-11-21 20:01:26 +01001816}};
1817
Willy Tarreau0108d902018-11-25 19:14:37 +01001818INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand1f49a362017-11-21 20:01:26 +01001819
William Lallemand41db4602017-10-30 11:15:51 +01001820static struct action_kw_list http_res_actions = {
1821 .kw = {
1822 { "cache-store", parse_cache_store },
1823 { NULL, NULL }
1824 }
1825};
1826
Willy Tarreau0108d902018-11-25 19:14:37 +01001827INITCALL1(STG_REGISTER, http_res_keywords_register, &http_res_actions);
1828
William Lallemand41db4602017-10-30 11:15:51 +01001829static struct action_kw_list http_req_actions = {
1830 .kw = {
1831 { "cache-use", parse_cache_use },
1832 { NULL, NULL }
1833 }
1834};
1835
Willy Tarreau0108d902018-11-25 19:14:37 +01001836INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_actions);
1837
William Lallemand41db4602017-10-30 11:15:51 +01001838struct applet http_cache_applet = {
1839 .obj_type = OBJ_TYPE_APPLET,
1840 .name = "<CACHE>", /* used for logging */
William Lallemand77c11972017-10-31 20:43:01 +01001841 .fct = http_cache_io_handler,
William Lallemandecb73b12017-11-24 14:33:55 +01001842 .release = http_cache_applet_release,
William Lallemand41db4602017-10-30 11:15:51 +01001843};
1844
Willy Tarreaue6552512018-11-26 11:33:13 +01001845/* config parsers for this section */
1846REGISTER_CONFIG_SECTION("cache", cfg_parse_cache, cfg_post_parse_section_cache);
1847REGISTER_CONFIG_POSTPARSER("cache", cfg_cache_postparser);