-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathcache.c
2712 lines (2368 loc) · 70.5 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-2022 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 "tdb.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,
};
static const TfwStr tfw_cache_raw_headers_304[] = {
TFW_STR_STRING("cache-control:"),
TFW_STR_STRING("content-location:"),
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. */
/*
* @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;
* @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];
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))
/**
* String header for cache entries used for TfwStr serialization.
*
* @flags - only TFW_STR_DUPLICATE or zero;
* @len - string length or number of duplicates;
*/
typedef struct {
unsigned long flags : 8,
len : 56;
} 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;
static struct {
int cache;
unsigned int methods;
unsigned long db_size;
const char *db_path;
} cache_cfg __read_mostly;
/* Cache modes. */
enum {
TFW_CACHE_NONE = 0,
TFW_CACHE_SHARD,
TFW_CACHE_REPLICA,
};
typedef struct {
int cpu[NR_CPUS];
atomic_t cpu_idx;
unsigned int nr_cpus;
TDB *db;
} CaNode;
static CaNode c_nodes[MAX_NUMNODES];
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. */
#define TFW_CACHE_REQ_KEYITER(c, uri_path, host, u_end, h_start, h_end) \
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 (!TFW_STR_EMPTY(host)) { \
BUG_ON(TFW_STR_PLAIN(host)); \
h_start = (host)->chunks; \
h_end = (host)->chunks + (host)->nchunks; \
} else { \
h_start = h_end = u_end; \
} \
for ( ; c != h_end; ++c, 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 is not supported at this time.
* 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));
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);
}
bool
tfw_cache_msg_cacheable(TfwHttpReq *req)
{
return cache_cfg.cache && __cache_method_test(req->method);
}
/**
* 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();
}
/**
* Just choose any CPU for each node to use queue_work_on() for
* nodes scheduling. Reserve 0th CPU for other tasks.
*/
static void
tfw_init_node_cpus(void)
{
int cpu, node;
for_each_online_cpu(cpu) {
node = cpu_to_node(cpu);
c_nodes[node].cpu[c_nodes[node].nr_cpus++] = cpu;
}
}
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 404: case 405: case 410: case 414:
case 501:
return true;
}
return false;
}
static bool
tfw_cache_employ_resp(TfwHttpResp *resp)
{
TfwHttpReq *req = resp->req;
unsigned int cc_ignore_flags =
tfw_vhost_get_cc_ignore(req->location, req->vhost);
unsigned int effective_resp_flags =
resp->cache_ctl.flags & ~cc_ignore_flags;
#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_CACHEIT \
(TFW_HTTP_CC_HDR_EXPIRES | TFW_HTTP_CC_MAX_AGE \
| TFW_HTTP_CC_S_MAXAGE | TFW_HTTP_CC_PUBLIC)
#define CC_RESP_AUTHCAN \
(TFW_HTTP_CC_S_MAXAGE | TFW_HTTP_CC_PUBLIC \
| TFW_HTTP_CC_MUST_REVAL | TFW_HTTP_CC_PROXY_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;
#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 cc_ignore_flags =
tfw_vhost_get_cc_ignore(req->location, req->vhost);
unsigned int effective_resp_flags =
resp->cache_ctl.flags & ~cc_ignore_flags;
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
/* For now, set "unlimited" lifetime in this case. */
lifetime = UINT_MAX; /* TODO: Heuristic lifetime. */
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 = tfw_cache_entry_age(ce);
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_lifetime > ce_age ? ce_lifetime : 0;
}
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) {
bzero_fast(dc_iter->__off,
sizeof(*dc_iter)
- offsetof(TfwDecodeCacheIter, __off));
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;
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;
}
/**
* 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 = (TfwCStr *)*p;
TfwHttpReq *req = resp->req;
TfwDecodeCacheIter dc_iter = { .h_mods = hmods, .skip = skip};
int d, dn, r = 0;
BUG_ON(!req);
write_actor = !TFW_MSG_H2(req) || dc_iter.h_mods
? tfw_cache_h2_decode_write
: tfw_cache_h2_write;
*p += TFW_CSTR_HDRLEN;
BUG_ON(*p > (*trec)->data + (*trec)->len);
if (likely(!(s->flags & TFW_STR_DUPLICATE))) {
r = write_actor(db, trec, resp, p, s->len, &dc_iter);
if (likely(!r))
*acc_len += dc_iter.acc_len;
return r;
}
/* Process duplicated headers. */
dn = s->len;
for (d = 0; d < dn; ++d) {
s = (TfwCStr *)*p;
BUG_ON(s->flags);
*p += TFW_CSTR_HDRLEN;
r = write_actor(db, trec, resp, p, s->len, &dc_iter);
if (unlikely(r))
break;
}
*acc_len += dc_iter.acc_len;
return r;
}
/**
* RFC 7232 Section-4.1: The server generating a 304 response MUST generate:
* Cache-Control, Content-Location, Date, ETag, Expires, and Vary.
* Last-Modified might be used if the response does not have an ETag field.
*
* The 304 response should be as short as possible, we don't need to add
* extra headers.
*/
static void
tfw_cache_send_304(TfwHttpReq *req, TfwCacheEntry *ce)
{
char *p;
int r, i;
TfwMsgIter *it;
TfwHttpResp *resp;
struct sk_buff **skb_head;
unsigned int stream_id = 0;
unsigned long h_len = 0;
TdbVRec *trec = &ce->trec;
TDB *db = node_db();
WARN_ON_ONCE(!list_empty(&req->fwd_list));
WARN_ON_ONCE(!list_empty(&req->nip_list));
if (!(resp = tfw_http_msg_alloc_resp_light(req)))
goto err_create;
it = &resp->mit.iter;
skb_head = &resp->msg.skb_head;
if (!TFW_MSG_H2(req)) {
r = tfw_http_prep_304(req, skb_head, it);
if (unlikely(r))
goto err_setup;
} else {
stream_id = tfw_h2_stream_id_close(req, HTTP2_HEADERS,
HTTP2_F_END_STREAM);
if (unlikely(!stream_id))
goto err_setup;
resp->mit.start_off = FRAME_HEADER_SIZE;
r = tfw_h2_resp_status_write(resp, 304, TFW_H2_TRANS_EXPAND,
true);
if (unlikely(r))
goto err_setup;
}
/* Put 304 headers */
for (i = 0; i < ARRAY_SIZE(ce->hdrs_304); ++i) {
if (!ce->hdrs_304[i])
continue;
p = TDB_PTR(db->hdr, ce->hdrs_304[i]);
while (trec && (p > trec->data + trec->len))
trec = tdb_next_rec_chunk(db, trec);
BUG_ON(!trec);
if (tfw_cache_build_resp_hdr(db, resp, NULL, &trec, &p, &h_len,
false))
{
goto err_setup;
}
}
if (!TFW_MSG_H2(req)) {
if (tfw_http_msg_expand_data(it, skb_head, &g_crlf, NULL))
goto err_setup;
tfw_http_resp_fwd(resp);
return;
}
if (tfw_h2_frame_local_resp(resp, stream_id, h_len, NULL))
goto err_setup;
tfw_h2_resp_fwd(resp);
return;
err_setup:
T_WARN("Can't build 304 response, key=%lx\n", ce->key);
tfw_http_msg_free((TfwHttpMsg *)resp);
err_create:
tfw_http_resp_build_error(req);
}
/**
* Received request can contain validation information. Process it according to
* RFC 7234 Section 4.3.2.
*
* Return value:
* @true: @req can be served from cache;
* @false: Response was sent to client (412 or 304).
*/
static bool
tfw_handle_validation_req(TfwHttpReq *req, TfwCacheEntry *ce)
{
if ((ce->resp_status != 200) && (ce->resp_status != 206))
return true;
/* RFC 7232 Section 5. */
/* TODO: Add CONNECT */
if ((req->method == TFW_HTTP_METH_OPTIONS)
|| (req->method == TFW_HTTP_METH_TRACE))
return true;
/* If-None-Match: */
if (!TFW_STR_EMPTY(&req->h_tbl->tbl[TFW_HTTP_HDR_IF_NONE_MATCH])) {
if (!tfw_cache_cond_none_match(req, ce)) {
if ((req->method == TFW_HTTP_METH_GET)
|| (req->method == TFW_HTTP_METH_HEAD))
tfw_cache_send_304(req, ce);
else
tfw_http_send_resp(req, 412,
"request validation: "
"precondition failed");
return false;
}
}
/* If-Modified-Since: */
else if (req->cond.m_date
&& ((req->method == TFW_HTTP_METH_GET)
|| (req->method == TFW_HTTP_METH_HEAD)))
{
bool send_304 = false;
if (ce->last_modified) {
if (ce->last_modified <= req->cond.m_date)
send_304 = true;
}
else if (ce->date) {
if (ce->date <= req->cond.m_date)
send_304 = true;
}
else {
if (ce->resp_time <= req->cond.m_date)
send_304 = true;
}
if (send_304) {
tfw_cache_send_304(req, ce);
return false;
}
}
/* TODO #499: Range GET requests. RFC 7232 Section 6, step 5. */
return true;
}
static bool
tfw_cache_entry_key_eq(TDB *db, TfwHttpReq *req, TfwCacheEntry *ce)
{
/* Record key starts at first data chunk. */
int n, c_off = 0, t_off;
TdbVRec *trec = &ce->trec;
TfwStr *c, *h_start, *u_end, *h_end;
TfwStr host_val, *host = &req->h_tbl->tbl[TFW_HTTP_HDR_HOST];
if ((req->method != TFW_HTTP_METH_PURGE) && (ce->method != req->method))
return false;
/*
* Get 'host' header value (from HTTP/2 or HTTP/1.1 request) for
* strict comparison.
*/
tfw_http_msg_clnthdr_val(req, host, TFW_HTTP_HDR_HOST, &host_val);
if (req->uri_path.len + host_val.len != ce->key_len)
return false;
t_off = CE_BODY_SIZE;
TFW_CACHE_REQ_KEYITER(c, &req->uri_path, &host_val, u_end, h_start,
h_end)
{
if (!trec)
return false;
this_chunk:
n = min(c->len - c_off, (unsigned long)trec->len - t_off);
/* Cache key is stored in lower case. */
if (tfw_cstricmp_2lc(c->data + c_off, trec->data + t_off, n))
return false;
c_off = (n == c->len - c_off) ? 0 : c_off + n;
if (n == trec->len - t_off) {
t_off = 0;
trec = tdb_next_rec_chunk(db, trec);
if (trec && c_off)
goto this_chunk;
} else {
t_off += n;
}
}
return true;
}
/*
* Select the most appropriate cache entry for this request.
*/
static TfwCacheEntry *
tfw_cache_dbce_get(TDB *db, TdbIter *iter, TfwHttpReq *req)
{
TfwCacheEntry *ce, *ce_best;
unsigned long key = tfw_http_req_key_calc(req);
*iter = tdb_rec_get(db, key);
if (TDB_ITER_BAD(*iter)) {
TFW_INC_STAT_BH(cache.misses);
return NULL;
}
/*
* Cache may store one or more responses to the effective Request URI.
* Basically, it is sufficient to store only the most recent response and
* remove other representations from cache. (RFC 7234 4: When more than
* one suitable response is stored, a cache MUST use the most recent
* response) But there are still some cases when it is needed to store
* more than one representation:
* - If selected representation of the effective Request URI depends
* on client capabilities. See RFC 7234 4.1 (Vary Header).
* - If origin server has several states of the resource, so during
* revalidation we can get the current state without downloading the
* full representation. This can reduce traffic to origin server.
* See RFC 7323 2.1 for the example.
*
* TODO: tfw_cache_entry_key_eq() should be extended to support
* secondary keys (#508) and to skip not current representations.
* Currently this function is used only to serve clients.
*/
ce = (TfwCacheEntry *)iter->rec;
ce_best = NULL;
do {
/*
* Pick the best cache record. The "best" record is either the
* first live record that we find, or the most recent stale
* record. We have to iterate through the entire bucket, unless
* we find a live record early, so we take an extra read lock
* here.
*/
/* TODO #522: replace a cache entry on a new entry insertion
* (e.g. the bucket can not contain both the stale and fresh
* entries) and rework the loop. */
if (tfw_cache_entry_key_eq(db, req, ce)) {
if (tfw_cache_entry_is_live(req, ce)) {
if (ce_best)
tdb_rec_put(ce_best);
ce_best = ce;
break;
}