-
Notifications
You must be signed in to change notification settings - Fork 103
/
cache.c
3740 lines (3234 loc) · 96.1 KB
/
cache.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Tempesta FW
*
* HTTP cache (RFC 7234).
*
* Copyright (C) 2014 NatSys Lab. ([email protected]).
* Copyright (C) 2015-2024 Tempesta Technologies, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/freezer.h>
#include <linux/irq_work.h>
#include <linux/ipv6.h>
#include <linux/kthread.h>
#include <linux/tcp.h>
#include <linux/topology.h>
#include <linux/nodemask.h>
#undef DEBUG
#if DBG_CACHE > 0
#define DEBUG DBG_CACHE
#endif
#include "tdb.h"
#include "apm.h"
#include "lib/str.h"
#include "tempesta_fw.h"
#include "vhost.h"
#include "cache.h"
#include "http_msg.h"
#include "http_sess.h"
#include "procfs.h"
#include "sync_socket.h"
#include "work_queue.h"
#include "lib/common.h"
#if MAX_NUMNODES > ((1 << 16) - 1)
#warning "Please set CONFIG_NODES_SHIFT to less than 16"
#endif
static const int tfw_cache_spec_headers_304[] = {
[0 ... TFW_HTTP_HDR_RAW] = 0,
[TFW_HTTP_HDR_ETAG] = 1,
[TFW_HTTP_HDR_CONTENT_LOCATION] = 1,
};
static const TfwStr tfw_cache_raw_headers_304[] = {
TFW_STR_STRING("cache-control:"),
TFW_STR_STRING("date:"),
TFW_STR_STRING("expires:"),
TFW_STR_STRING("last-modified:"),
TFW_STR_STRING("vary:"),
/* Etag are Spec headers */
};
#define TFW_CACHE_304_SPEC_HDRS_NUM 1 /* ETag. */
#define TFW_CACHE_304_HDRS_NUM \
ARRAY_SIZE(tfw_cache_raw_headers_304) + TFW_CACHE_304_SPEC_HDRS_NUM
/* Flags stored in a Cache Entry. */
#define TFW_CE_MUST_REVAL 0x0001 /* MUST revalidate if stale. */
#define TFW_CE_STALE_IF_ERROR 0x0002
/*
* @trec - Database record descriptor;
* @key_len - length of key (URI + Host header);
* @status_len - length of response status code;
* @rph_len - length of response reason phrase;
* @hdr_num - number of headers;
* @hdr_len - length of whole headers data;
* @hdr_h2_off - start of http/2-only headers in the headers list;
* @body_len - length of the response body;
* @method - request method, part of the key;
* @flags - various cache entry flags;
* @age - the value of response Age: header field;
* @date - the value of response Date: header field;
* @req_time - the time the request was issued;
* @resp_time - the time the response was received;
* @lifetime - the cache entry's current lifetime;
* @last_modified - the value of response Last-Modified: header field;
* @key - the cache entry key (URI + Host header);
* @status - pointer to status line;
* @hdrs - pointer to list of HTTP headers;
* @body - pointer to response body;
* @hdrs_304 - pointers to headers used to build 304 response;
* @stale_if_error - the value of response "Cache-control: stale_if_error"
* header field;
* @version - HTTP version of the response;
* @resp_status - Http status of the cached response.
* @hmflags - flags of the response after parsing and post-processing.
* @etag - entity-tag, stored as a pointer to ETag header in @hdrs.
*/
typedef struct {
TdbVRec trec;
#define ce_body key_len
unsigned int key_len;
unsigned int status_len;
unsigned int rph_len;
unsigned int hdr_num;
unsigned int hdr_h2_off;
unsigned int hdr_len;
unsigned int body_len;
unsigned int method: 4;
unsigned int flags: 28;
long age;
long date;
long req_time;
long resp_time;
long lifetime;
long last_modified;
long key;
long status;
long hdrs;
long body;
long hdrs_304[TFW_CACHE_304_HDRS_NUM];
long stale_if_error;
DECLARE_BITMAP (hmflags, _TFW_HTTP_FLAGS_NUM);
unsigned char version;
unsigned short resp_status;
TfwStr etag;
} TfwCacheEntry;
#define CE_BODY_SIZE \
(sizeof(TfwCacheEntry) - offsetof(TfwCacheEntry, ce_body))
static size_t
ce_total_size(const TfwCacheEntry *ce)
{
return ce->key_len + ce->status_len + ce->rph_len + ce->hdr_len +
ce->body_len + CE_BODY_SIZE;
}
#if defined(DEBUG)
#define CE_DBGBUF_LEN 1024
static DEFINE_PER_CPU(char *, ce_dbg_buf) = NULL;
static void
__tfw_dbg_dump_ce(const TfwCacheEntry *ce)
{
char *buf;
int len = 0;
buf = *this_cpu_ptr(&ce_dbg_buf);
bzero_fast(buf, CE_DBGBUF_LEN);
#define CE_DUMP_MEMBER(fmt, ...) \
snprintf(buf + len, CE_DBGBUF_LEN - len, " %14s: " fmt "\n", \
__VA_ARGS__)
len += CE_DUMP_MEMBER("key %lx, chunk_next %d, len %d total_len: %lu",
"TdbVRec", ce->trec.key, ce->trec.chunk_next,
ce->trec.len, ce_total_size(ce));
len += CE_DUMP_MEMBER("%d", "key_len", ce->key_len);
len += CE_DUMP_MEMBER("%d", "status_len", ce->status_len);
len += CE_DUMP_MEMBER("%d", "rph_len", ce->rph_len);
len += CE_DUMP_MEMBER("%d", "hdr_num", ce->hdr_num);
len += CE_DUMP_MEMBER("%d", "hdr_h2_off", ce->hdr_h2_off);
len += CE_DUMP_MEMBER("%d", "hdr_len", ce->hdr_len);
len += CE_DUMP_MEMBER("%d", "body_len", ce->body_len);
len += CE_DUMP_MEMBER("%d", "method", ce->method);
len += CE_DUMP_MEMBER("%d", "flags", ce->flags);
len += CE_DUMP_MEMBER("%lu", "age", ce->age);
len += CE_DUMP_MEMBER("%lu", "date", ce->date);
len += CE_DUMP_MEMBER("%lu", "req_time", ce->req_time);
len += CE_DUMP_MEMBER("%lu", "resp_time", ce->resp_time);
len += CE_DUMP_MEMBER("%lu", "last_modified", ce->last_modified);
len += CE_DUMP_MEMBER("%lx", "key off", ce->key);
len += CE_DUMP_MEMBER("%lx", "status off", ce->status);
len += CE_DUMP_MEMBER("%lx", "hdrs off", ce->hdrs);
len += CE_DUMP_MEMBER("%lx", "body off", ce->body);
/* @hmflags occupies a single ulong */
len += CE_DUMP_MEMBER("%lx [%*pbl]", "hmflags", *ce->hmflags,
_TFW_HTTP_FLAGS_NUM, ce->hmflags);
len += CE_DUMP_MEMBER("%x", "version", ce->version);
len += CE_DUMP_MEMBER("%d", "resp_status", ce->resp_status);
T_DBG("Tdb CE [%p]: \n%s", ce, buf);
}
#else
#define __tfw_dbg_dump_ce(...)
#endif
/* TfwCStr contains duplicated header. */
#define TFW_CSTR_DUPLICATE TFW_STR_DUPLICATE
/* TfwCStr contains special header and its id. */
#define TFW_CSTR_SPEC_IDX 0x2
/**
* String header for cache entries used for TfwStr serialization.
*
* @flags - TFW_CSTR_DUPLICATE and TFW_CSTR_HPACK_IDX or zero;
* @name_len - Header name length. Used for raw headers;
* @name_len_sz - HPACK int size of @name_len;
* @len - Total string length or number of duplicates;
* @idx - HPACK static index or index of special header;
*/
typedef struct {
unsigned long flags : 8,
name_len: 11,
name_len_sz : 2,
len : 35,
idx : 8;
} TfwCStr;
#define TFW_CSTR_MAXLEN (1UL << 56)
#define TFW_CSTR_HDRLEN (sizeof(TfwCStr))
/* Work to copy response body to database. */
typedef struct {
TfwHttpMsg *msg;
tfw_http_cache_cb_t action;
unsigned long __unused[2];
} TfwCWork;
typedef struct {
struct tasklet_struct tasklet;
struct irq_work ipi_work;
TfwRBQueue wq;
} TfwWorkTasklet;
/* Cache modes. */
typedef enum {
TFW_CACHE_UNDEFINED = -1,
TFW_CACHE_NONE = 0,
TFW_CACHE_SHARD,
TFW_CACHE_REPLICA,
} TfwCacheMode;
static struct {
int cache;
unsigned int methods;
unsigned long db_size;
const char *db_path;
} cache_cfg __read_mostly = {
.cache = TFW_CACHE_UNDEFINED,
.methods = 0,
.db_size = 0,
.db_path = NULL
};
unsigned int cache_default_ttl;
typedef struct {
int *cpu;
atomic_t cpu_idx;
unsigned int nr_cpus;
TDB *db;
} CaNode;
static CaNode *c_nodes;
typedef int tfw_cache_write_actor_t(TDB *, TdbVRec **, TfwHttpResp *, char **,
size_t, TfwDecodeCacheIter *);
/*
* TODO the thread doesn't do anything for now, however, kthread_stop() crashes
* on restarts, so comment to logic out.
*/
#if 0
static struct task_struct *cache_mgr_thr;
#endif
static DEFINE_PER_CPU(TfwWorkTasklet, cache_wq);
#define RESP_BUF_LEN 128
static DEFINE_PER_CPU(char[RESP_BUF_LEN], g_c_buf);
static TfwStr g_crlf = { .data = S_CRLF, .len = SLEN(S_CRLF) };
/*
* Iterate over request URI and Host header to process request key.
* uri_path and host are not expected to be empty, because we check
* it previosly but we should not crash.
*/
#define TFW_CACHE_REQ_KEYITER(c, uri_path, host, u_end, h_start, \
h_end, u_fin, h_fin) \
c = NULL; \
if (!(u_fin = WARN_ON_ONCE(TFW_STR_EMPTY(uri_path)))) { \
if (TFW_STR_PLAIN(uri_path)) { \
c = uri_path; \
u_end = (uri_path) + 1; \
} else { \
c = (uri_path)->chunks; \
u_end = (uri_path)->chunks + (uri_path)->nchunks; \
} \
} \
if (!(h_fin = WARN_ON_ONCE(TFW_STR_EMPTY(host)))) { \
if (likely(!TFW_STR_PLAIN(host))) { \
h_start = (host)->chunks; \
h_end = (host)->chunks + (host)->nchunks; \
} else { \
h_start = host; \
h_end = (host) + 1; \
} \
c = c ? : h_start; \
} \
for ( ; !u_fin || !h_fin; \
++c, u_fin = u_fin ? true : (c == u_end), \
h_fin = h_fin ? true : (c == h_end), \
c = (c == u_end) ? h_start : c)
/*
* The mask of non-cacheable methods per RFC 7231 4.2.3.
* Safe methods that do not depend on a current or authoritative response
* are defined as cacheable: GET, HEAD, and POST.
* Note: caching of POST method responses need further support.
* Issue #506 describes, which steps must be made to support caching of POST
* requests.
*/
static unsigned int tfw_cache_nc_methods =
~((1 << TFW_HTTP_METH_GET) | (1 << TFW_HTTP_METH_HEAD) |
(1 << TFW_HTTP_METH_POST));
static inline bool
__cache_method_nc_test(tfw_http_meth_t method)
{
BUILD_BUG_ON(sizeof(tfw_cache_nc_methods) * BITS_PER_BYTE
< _TFW_HTTP_METH_COUNT);
return tfw_cache_nc_methods & (1 << method);
}
static inline void
__cache_method_add(tfw_http_meth_t method)
{
cache_cfg.methods |= (1 << method);
}
static inline bool
__cache_method_test(tfw_http_meth_t method)
{
return cache_cfg.methods & (1 << method);
}
static inline bool
tfw_cache_msg_cacheable(TfwHttpReq *req)
{
/* POST request is not idempotent, but can be cacheble. */
return cache_cfg.cache && __cache_method_test(req->method) &&
(!tfw_http_req_is_nip(req)
|| req->method == TFW_HTTP_METH_POST);
}
/**
* Get NUMA node by the cache key.
* The function gives different results if number of nodes changes,
* e.g. due to hot-plug CPU. Cache eviction restores memory acquired by
* inaccessible entries. The event of new/dead CPU is rare, so there is
* no sense to use expensive rendezvous hashing.
*/
static unsigned short
tfw_cache_key_node(unsigned long key)
{
return key % num_online_nodes();
}
/**
* Release node-cpu map.
*/
static void
tfw_release_node_cpus(void)
{
int node;
if(!c_nodes)
return;
for(node = 0; node < nr_online_nodes; node++) {
if(c_nodes[node].cpu)
kfree(c_nodes[node].cpu);
}
kfree(c_nodes);
}
/**
* Create node-cpu map to use queue_work_on() for nodes scheduling.
* 0th CPU is reserved for other tasks.
* At the moment we doesn't support CPU hotplug, so enumerate only online CPUs.
*/
static int
tfw_init_node_cpus(void)
{
int nr_cpus, cpu, node;
T_DBG2("nr_online_nodes: %d", nr_online_nodes);
c_nodes = kzalloc(nr_online_nodes * sizeof(CaNode), GFP_KERNEL);
if(!c_nodes) {
T_ERR("Failed to allocate nodes map for cache work scheduler");
return -ENOMEM;
}
for_each_node_with_cpus(node) {
nr_cpus = nr_cpus_node(node);
T_DBG2("node: %d nr_cpus: %d",node, nr_cpus);
c_nodes[node].cpu = kmalloc(nr_cpus * sizeof(int), GFP_KERNEL);
if(!c_nodes[node].cpu) {
T_ERR("Failed to allocate CPU array for node %d for cache work scheduler",
node);
return -ENOMEM;
}
}
for_each_online_cpu(cpu) {
node = cpu_to_node(cpu);
T_DBG2("node: %d cpu: %d",node, cpu);
c_nodes[node].cpu[c_nodes[node].nr_cpus++] = cpu;
}
return 0;
}
static TDB *
node_db(void)
{
return c_nodes[numa_node_id()].db;
}
/**
* Get a CPU identifier from @node to schedule a work.
* The request should be processed on remote node, use round robin strategy
* to distribute such requests.
*
* Note that atomic_t is a signed 32-bit value, and it's intentionally
* cast to unsigned type value before taking a modulo operation.
* If this place becomes a hot spot, then @cpu_idx may be made per_cpu.
*/
static int
tfw_cache_sched_cpu(TfwHttpReq *req)
{
CaNode *node = &c_nodes[req->node];
unsigned int idx = atomic_inc_return(&node->cpu_idx);
return node->cpu[idx % node->nr_cpus];
}
/*
* Find caching policy in specific vhost and location.
*/
static int
tfw_cache_policy(TfwVhost *vhost, TfwLocation *loc, TfwStr *arg)
{
TfwCaPolicy *capo;
/* Search locations in current loc. */
if (loc && loc->capo_sz) {
if ((capo = tfw_capolicy_match(loc, arg)))
return capo->cmd;
}
/*
* Search default policies in current vhost.
* If there's none, then search global default policies.
*/
loc = vhost->loc_dflt;
if (loc && loc->capo_sz) {
if ((capo = tfw_capolicy_match(loc, arg)))
return capo->cmd;
} else {
TfwVhost *vhost_dflt = vhost->vhost_dflt;
if (!vhost_dflt)
return TFW_D_CACHE_BYPASS;
loc = vhost_dflt->loc_dflt;
if (loc && loc->capo_sz) {
if ((capo = tfw_capolicy_match(loc, arg)))
return capo->cmd;
}
}
return TFW_D_CACHE_BYPASS;
}
/*
* Decide if the cache can be employed. For a request that means
* that it can be served from cache if there's a cached response.
* For a response it means that the response can be stored in cache.
*
* Various cache action/control directives are consulted when making
* the resulting decision.
*/
static bool
tfw_cache_employ_req(TfwHttpReq *req)
{
int cmd = tfw_cache_policy(req->vhost, req->location, &req->uri_path);
if (cmd == TFW_D_CACHE_BYPASS) {
req->cache_ctl.flags |= TFW_HTTP_CC_CFG_CACHE_BYPASS;
return false;
}
/* cache_fulfill - work as usual in cache mode. */
BUG_ON(cmd != TFW_D_CACHE_FULFILL);
/* CC_NO_CACHE also may be set by http chain rules */
if (req->cache_ctl.flags & TFW_HTTP_CC_NO_CACHE)
/*
* TODO: RFC 7234 4. "... a cache MUST NOT reuse a stored
* response, unless... the request does not contain the no-cache
* pragma, nor the no-cache cache directive unless the stored
* response is successfully validated."
*
* We can validate the stored response and serve request from
* cache. This reduces traffic to origin server.
*/
return false;
return true;
}
/**
* Check whether the response status code is defined as cacheable by default
* by RFC 7231 6.1.
*/
static inline bool
tfw_cache_status_bydef(TfwHttpResp *resp)
{
/*
* TODO: Add 206 (Partial Content) status. Requires support
* of incomplete responses, Range: and Content-Range: header
* fields, and RANGE request method.
*/
switch (resp->status) {
case 200: case 203: case 204:
case 300: case 301: case 308:
return true;
case 404: case 405: case 410: case 414:
case 501:
/*
* According RFC 9111 all this status codes are cacheble
* but we don't cache response to POST request if fails.
*/
if (resp->req->method == TFW_HTTP_METH_GET
|| resp->req->method == TFW_HTTP_METH_HEAD)
return true;
}
return false;
}
static unsigned int
tfw_cache_get_effective_resp_flags(TfwHttpResp *resp, TfwHttpReq *req)
{
unsigned int cc_ignore_flags =
tfw_vhost_get_cc_ignore(req->location, req->vhost);
return resp->cache_ctl.flags & ~cc_ignore_flags;
}
static bool
tfw_cache_employ_resp(TfwHttpResp *resp)
{
TfwHttpReq *req = resp->req;
unsigned int effective_resp_flags =
tfw_cache_get_effective_resp_flags(resp, req);
#define CC_REQ_DONTCACHE \
(TFW_HTTP_CC_CFG_CACHE_BYPASS | TFW_HTTP_CC_NO_STORE)
#define CC_RESP_DONTCACHE \
(TFW_HTTP_CC_NO_STORE | TFW_HTTP_CC_PRIVATE \
| TFW_HTTP_CC_NO_CACHE)
#define CC_RESP_EXPLICIT_FRESH_INFO \
(TFW_HTTP_CC_HDR_EXPIRES | TFW_HTTP_CC_MAX_AGE \
| TFW_HTTP_CC_S_MAXAGE)
#define CC_RESP_CACHEIT \
(CC_RESP_EXPLICIT_FRESH_INFO | TFW_HTTP_CC_PUBLIC)
/*
* RFC 9111 3.5:
* A shared cache MUST NOT use a cached response to a request with an
* Authorization header field (Section 11.6.2 of [HTTP]) to satisfy any
* subsequent request unless the response contains a Cache-Control field
* with a response directive (Section 5.2.2) that allows it to be stored
* by a shared cache, and the cache conforms to the requirements of that
* directive for that response.
* In this specification, the following response directives have such an
* effect: must-revalidate (Section 5.2.2.2), public (Section 5.2.2.9),
* and s-maxage (Section 5.2.2.10).
*/
#define CC_RESP_AUTHCAN \
(TFW_HTTP_CC_S_MAXAGE | TFW_HTTP_CC_PUBLIC \
| TFW_HTTP_CC_MUST_REVAL)
/*
* TODO: Response no-cache -- should be cached.
* Should turn on unconditional revalidation.
*/
if (req->cache_ctl.flags & CC_REQ_DONTCACHE)
return false;
if (effective_resp_flags & CC_RESP_DONTCACHE)
return false;
if (!(req->cache_ctl.flags & TFW_HTTP_CC_IS_PRESENT)
&& (req->cache_ctl.flags & TFW_HTTP_CC_PRAGMA_NO_CACHE))
return false;
if (!(effective_resp_flags & TFW_HTTP_CC_IS_PRESENT)
&& (effective_resp_flags & TFW_HTTP_CC_PRAGMA_NO_CACHE))
return false;
if ((req->cache_ctl.flags & TFW_HTTP_CC_HDR_AUTHORIZATION)
&& !(effective_resp_flags & CC_RESP_AUTHCAN))
return false;
if (!(effective_resp_flags & CC_RESP_CACHEIT)
&& !tfw_cache_status_bydef(resp))
return false;
/*
* According to RFC 9110 9.3.3:
* Responses to POST requests are only cacheable when they include
* explicit freshness information and a Content-Location header field
* that has the same value as the POST's target URI.
*/
if (req->method == TFW_HTTP_METH_POST) {
TfwStr *h = &resp->h_tbl->tbl[TFW_HTTP_HDR_CONTENT_LOCATION];
TfwStr h_val;
if (!(effective_resp_flags & CC_RESP_EXPLICIT_FRESH_INFO))
return false;
tfw_http_msg_srvhdr_val(h, TFW_HTTP_HDR_CONTENT_LOCATION,
&h_val);
/*
* According to RFC 9110 8.7:
* If Content-Location is included in a 2xx (Successful)
* response message and its value refers (after conversion
* to absolute form) to a URI that is the same as the target
* URI, then the recipient MAY consider the content to be a
* current representation of that resource at the time indicated
* by the message origination date. But our research showed that
* none of the legitimate clients use absolute forms of URI, so
* we do not convert URI and Content-Location to absolute form.
*/
if (tfw_strcmp(&h_val, &req->uri_path))
return false;
}
#undef CC_RESP_AUTHCAN
#undef CC_RESP_CACHEIT
#undef CC_RESP_DONTCACHE
#undef CC_REQ_DONTCACHE
return true;
}
/*
* Calculate freshness lifetime according to RFC 7234 4.2.1.
*/
static long
tfw_cache_calc_lifetime(TfwHttpResp *resp)
{
long lifetime;
TfwHttpReq *req = resp->req;
unsigned int effective_resp_flags =
tfw_cache_get_effective_resp_flags(resp, req);
if (effective_resp_flags & TFW_HTTP_CC_S_MAXAGE)
lifetime = resp->cache_ctl.s_maxage;
else if (effective_resp_flags & TFW_HTTP_CC_MAX_AGE)
lifetime = resp->cache_ctl.max_age;
else if (resp->cache_ctl.flags & TFW_HTTP_CC_HDR_EXPIRES)
lifetime = resp->cache_ctl.expires - resp->date;
else
lifetime = req->cache_ctl.default_ttl;
return lifetime;
}
/*
* Calculate the current entry age according to RFC 7234 4.2.3.
*/
static long
tfw_cache_entry_age(TfwCacheEntry *ce)
{
long apparent_age = max_t(long, 0, ce->resp_time - ce->date);
long corrected_age = ce->age + ce->resp_time - ce->req_time;
long initial_age = max(apparent_age, corrected_age);
return (initial_age + tfw_current_timestamp() - ce->resp_time);
}
/*
* Given Cache Control arguments in the request and the response,
* as well as the stored cache entry parameters, determine if the
* cache entry is live and may be served to a client. For that,
* the cache entry freshness is calculated according to RFC 7234
* 4.2, 5.2.1.1, 5.2.1.2, and 5.2.1.3.
*
* Returns the value of calculated cache entry lifetime if the entry
* is live and may be served to a client. Returns zero if the entry
* may not be served.
*
* Note that if the returned value of lifetime is greater than
* ce->lifetime, then the entry is stale but still may be served
* to a client, provided that the cache policy allows that.
*/
static long
tfw_cache_entry_is_live(TfwHttpReq *req, TfwCacheEntry *ce, long ce_age)
{
long ce_lifetime, lt_fresh = UINT_MAX;
if (ce->lifetime <= 0)
return 0;
#define CC_LIFETIME_FRESH (TFW_HTTP_CC_MAX_AGE | TFW_HTTP_CC_MIN_FRESH)
if (req->cache_ctl.flags & CC_LIFETIME_FRESH) {
long lt_max_age = UINT_MAX, lt_min_fresh = UINT_MAX;
if (req->cache_ctl.flags & TFW_HTTP_CC_MAX_AGE)
lt_max_age = req->cache_ctl.max_age;
if (req->cache_ctl.flags & TFW_HTTP_CC_MIN_FRESH)
lt_min_fresh = ce->lifetime - req->cache_ctl.min_fresh;
lt_fresh = min(lt_max_age, lt_min_fresh);
}
/*
* RFC 7234 Section 4.2.4:
* A cache MUST NOT generate a stale response if it is prohibited by an
* explicit in-protocol directive (e.g., by a "no-store" or "no-cache"
* cache directive, a "must-revalidate" cache-response-directive, or an
* applicable "s-maxage" or "proxy-revalidate" cache-response-directive;
* see Section 5.2.2).
*/
/* tfw_cache_copy_resp() calculates the TFW_CE_MUST_REVAL flag */
if (!(req->cache_ctl.flags & TFW_HTTP_CC_MAX_STALE)
|| (ce->flags & TFW_CE_MUST_REVAL))
{
ce_lifetime = min(lt_fresh, ce->lifetime);
} else {
long lt_max_stale = ce->lifetime + req->cache_ctl.max_stale;
ce_lifetime = min(lt_fresh, lt_max_stale);
}
#undef CC_LIFETIME_FRESH
return ce_age > ce_lifetime ? 0 : ce_lifetime;
}
static bool
tfw_cache_cond_none_match(TfwHttpReq *req, TfwCacheEntry *ce)
{
TfwStr match_list, iter;
if (TFW_STR_EMPTY(&ce->etag))
return true;
if (req->cond.flags & TFW_HTTP_COND_ETAG_ANY)
return false;
match_list = req->h_tbl->tbl[TFW_HTTP_HDR_IF_NONE_MATCH];
iter = tfw_str_next_str_val(&match_list);
while (!TFW_STR_EMPTY(&iter)) {
/* RFC 7232 3.2: Weak validation. Don't check WEAK tagging. */
if (!tfw_strcmpspn(&iter, &ce->etag, '"'))
return false;
iter = tfw_str_next_str_val(&iter);
}
return true;
}
/**
* Add a new header with size of @len starting from @data to HTTP response @resp,
* expanding the @resp with new skb/frags if needed.
*/
static int
tfw_cache_h2_write(TDB *db, TdbVRec **trec, TfwHttpResp *resp, char **data,
size_t len, TfwDecodeCacheIter *dc_iter)
{
TfwStr c = { 0 };
TdbVRec *tr = *trec;
TfwHttpTransIter *mit = &resp->mit;
TfwMsgIter *it = &mit->iter;
int r = 0, copied = 0;
while (1) {
c.data = *data;
c.len = min(tr->data + tr->len - *data, (long)(len - copied));
if (!dc_iter->skip) {
r = tfw_http_msg_expand_data(it, &resp->msg.skb_head,
&c, &mit->start_off);
if (unlikely(r))
break;
dc_iter->acc_len += c.len;
}
copied += c.len;
*data += c.len;
T_DBG3("%s: len='%zu', copied='%d', dc_iter->acc_len='%lu',"
" dc_iter->skip='%d'\n", __func__, len, copied,
dc_iter->acc_len, dc_iter->skip);
if (copied == len)
break;
tr = *trec = tdb_next_rec_chunk(db, tr);
BUG_ON(!tr);
*data = tr->data;
}
return r;
}
/**
* Same as @tfw_cache_h2_write(), but also decode the header from HTTP/2 format
* before writing it into the response (used e.g. for HTTP/1.1-response creation
* from cache).
*/
static int
tfw_cache_h2_decode_write(TDB *db, TdbVRec **trec, TfwHttpResp *resp,
char **data, size_t len, TfwDecodeCacheIter *dc_iter)
{
unsigned long m_len;
TdbVRec *tr = *trec;
int r = 0, acc = 0;
TfwHPack hp = {};
while (1) {
m_len = min(tr->data + tr->len - *data, (long)(len - acc));
if (!dc_iter->skip) {
r = tfw_hpack_cache_decode_expand(&hp, resp, *data,
m_len, dc_iter);
if (unlikely(r))
break;
}
acc += m_len;
*data += m_len;
if (acc == len) {
TFW_STR_INIT(&dc_iter->hdr_data);
break;
}
tr = *trec = tdb_next_rec_chunk(db, tr);
BUG_ON(!tr);
*data = tr->data;
}
return r;
}
static int
tfw_cache_set_status(TDB *db, TfwCacheEntry *ce, TfwHttpResp *resp,
TdbVRec **trec, char **p, unsigned long *acc_len)
{
int r;
TfwMsgIter *it = &resp->mit.iter;
struct sk_buff **skb_head = &resp->msg.skb_head;
bool h2_mode = TFW_MSG_H2(resp->req);
TfwDecodeCacheIter dc_iter = {};
if (h2_mode)
resp->mit.start_off = FRAME_HEADER_SIZE;
else
dc_iter.skip = true;
r = tfw_cache_h2_write(db, trec, resp, p, ce->status_len, &dc_iter);
if (unlikely(r))
return r;
resp->status = ce->resp_status;
if (!h2_mode) {
char buf[H2_STAT_VAL_LEN];
TfwStr s_line = {
.chunks = (TfwStr []){
{ .data = S_0, .len = SLEN(S_0) },
{ .data = buf, .len = H2_STAT_VAL_LEN}
},
.len = SLEN(S_0) + H2_STAT_VAL_LEN,
.nchunks = 2
};
if (!tfw_ultoa(ce->resp_status, __TFW_STR_CH(&s_line, 1)->data,
H2_STAT_VAL_LEN))
return -E2BIG;
r = tfw_http_msg_expand_data(it, skb_head, &s_line, NULL);
if (unlikely(r))
return r;
*acc_len += s_line.len;
}
dc_iter.skip = h2_mode ? true : false;
r = tfw_cache_h2_write(db, trec, resp, p, ce->rph_len, &dc_iter);
if (unlikely(r))
return r;
*acc_len += dc_iter.acc_len;
if (!h2_mode) {
r = tfw_http_msg_expand_data(it, skb_head, &g_crlf, NULL);
if (unlikely(r))
return r;
*acc_len += g_crlf.len;
}
return 0;
}
static bool
tfw_cache_skip_hdr(const TfwCStr *str, char *p, const TfwHdrMods *h_mods)
{
unsigned int i;
const TfwHdrModsDesc *desc;
/*
* Move to beggining of the header name. Skip first byte of HPACK
* string and name length size.
*/
TfwStr hdr = { .data = p + str->name_len_sz + 1,
.len = str->name_len };
/* Fast path for special headers */
if (str->flags & TFW_CSTR_SPEC_IDX) {
desc = h_mods->spec_hdrs[str->idx];
/* Skip only resp_hdr_set headers */
return desc ? !desc->append : false;
}
if (str->idx) {
unsigned short hpack_idx = str->idx;
if (hpack_idx <= HPACK_STATIC_TABLE_REGULAR)
return false;
return test_bit(hpack_idx, h_mods->s_tbl);
}
for (i = h_mods->spec_num; i < h_mods->sz; ++i) {
char* mod_hdr_name;
size_t mod_hdr_len;
desc = &h_mods->hdrs[i];
mod_hdr_len = TFW_STR_CHUNK(desc->hdr, 0)->len;
if (desc->append || mod_hdr_len != hdr.len)
continue;
mod_hdr_name = TFW_STR_CHUNK(desc->hdr, 0)->data;
if (!tfw_cstricmp(hdr.data, mod_hdr_name, hdr.len))
return true;
}
return false;
}
/**
* Write HTTP header to skb data.
*/
static int
tfw_cache_build_resp_hdr(TDB *db, TfwHttpResp *resp, TfwHdrMods *hmods,
TdbVRec **trec, char **p, unsigned long *acc_len,
bool skip)
{
tfw_cache_write_actor_t *write_actor;
TfwCStr *s;
TfwHttpReq *req = resp->req;
TfwDecodeCacheIter dc_iter = { .h_mods = hmods, .skip = skip };
int d, dn, r = 0;
/* Go to the next chunk if we at the end of current. */
#define NEXT_CHUNK() \
do { \
if (*p - (*trec)->data == (*trec)->len) { \
*trec = tdb_next_rec_chunk(db, (*trec)); \
*p = (*trec)->data; \
} \
} while (0)
BUG_ON(!req);
write_actor = !TFW_MSG_H2(req) ? tfw_cache_h2_decode_write
: tfw_cache_h2_write;
NEXT_CHUNK();
s = (TfwCStr *)*p;
*p += TFW_CSTR_HDRLEN;
BUG_ON(*p > (*trec)->data + (*trec)->len);
if (likely(!(s->flags & TFW_CSTR_DUPLICATE))) {
if (!skip && dc_iter.h_mods)
dc_iter.skip = tfw_cache_skip_hdr(s, *p, hmods);
r = write_actor(db, trec, resp, p, s->len, &dc_iter);
if (likely(!r))
*acc_len += dc_iter.acc_len;
return r;
}
if (!skip && dc_iter.h_mods)
dc_iter.skip = tfw_cache_skip_hdr((TfwCStr *)*p,
*p + TFW_CSTR_HDRLEN, hmods);
/* Process duplicated headers. */
dn = s->len;