include/punk/punk_cget.h

filter: Statementstmt 98.5% 208 / 211 Branchbran 69.3% 222 / 320 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 80.9% 430 / 531 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xs/context.xs ↑ Summary include/punk/punk_computed.h »
1 #ifndef PUNK_CGET_H
2 #define PUNK_CGET_H
3  
4 /* Punk::Plugin::ConditionalGet - the strong validator.
5 *
6 * get '/api/orders' => sub { ... }, {
7 * etag => sub { $_[0]->model('Order')->max_updated_at },
8 * };
9 *
10 * The application supplies something it knows cheaply that identifies the
11 * entity. An unchanged one answers 304 WITHOUT RUNNING THE HANDLER: no
12 * render, no queries, no serialisation. That is the whole point - the body
13 * ETag saves bandwidth, this saves the server.
14 *
15 * ---- why this is here and not in a hook --------------------------------
16 *
17 * A web route runs the before_dispatch chain, THEN the route's guards, then
18 * the handler. So a validator on the public before_dispatch hook would run
19 * BEFORE authentication - and a user who has logged out, still holding a tag
20 * from when they were logged in, would send it, get a 304, and their browser
21 * would render the private page it still has instead of the login redirect
22 * the guard would have produced. The plugin would have turned an
23 * authorisation check into a cache hit.
24 *
25 * So the check sits between the guards and the handler, where no public hook
26 * phase runs. That gap is recorded rather than worked around: as it stands,
27 * `before_dispatch` cannot be used for anything that must respect a guard.
28 */
29  
30 /* Is this a method a 304 may answer? RFC 9110 13.1.3 - a conditional POST
31 * means If-Match and optimistic concurrency, which is a different feature
32 * wearing the same header family, and is deliberately out of scope. */
33 152 static int pcg_cond_method(const char *method, STRLEN mlen) {
34 142 ▶ return (mlen == 3 && memEQ(method, "GET", 3))
Branch: 1 branch
BranchTrueFalseTotal
return (mlen == 3 && memEQ(method, "GET", 3)) 0 142 142
35 294 ▶ || (mlen == 4 && memEQ(method, "HEAD", 4));
Branch: 3 branches
BranchTrueFalseTotal
|| (mlen == 4 && memEQ(method, "HEAD", 4)); 142 10 152
|| (mlen == 4 && memEQ(method, "HEAD", 4)); 10 0 10
|| (mlen == 4 && memEQ(method, "HEAD", 4)); 8 2 10
36 }
37  
38 /* A strong entity-tag from whatever the application returned.
39 *
40 * Quoting is done here so an application returning 42 and one returning "42"
41 * cannot produce two different tags for one entity - the same rule
42 * psf_respond already applies to its `etag` option.
43 *
44 * Strong, never W/: the application is asserting that this value identifies
45 * the entity, which is exactly what a strong validator means. */
46 42 static SV *pcg_quote(pTHX_ SV *v) {
47 STRLEN l;
48 42 const char *p = SvPV_const(v, l);
49 /* already quoted: the quotes are kept and what is between them is
50 * filtered exactly as an unquoted value is */
51 42 ▶ if (l >= 2 && p[0] == '"' && p[l - 1] == '"') { p++; l -= 2; }
Branch: 3 branches
BranchTrueFalseTotal
if (l >= 2 && p[0] == '"' && p[l - 1] == '"') { p++; l -= 2; } 42 0 42
if (l >= 2 && p[0] == '"' && p[l - 1] == '"') { p++; l -= 2; } 6 36 42
if (l >= 2 && p[0] == '"' && p[l - 1] == '"') { p++; l -= 2; } 6 0 6
52 {
53 42 SV *out = newSVpvs("\"");
54 STRLEN i;
55 241 ▶ for (i = 0; i < l; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < l; i++) { 199 42 241
56 /* A validator is application data - a column value, a build
57 * revision - and it is about to become a response header. A quote
58 * or a control byte in it would end the tag early or split the
59 * response, so they are dropped rather than escaped: an
60 * entity-tag has no escaping mechanism to use. */
61 199 unsigned char ch = (unsigned char)p[i];
62 199 ▶ if (ch < 0x21 || ch == '"' || ch == 0x7f) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (ch < 0x21 || ch == '"' || ch == 0x7f) continue; 196 3 199
if (ch < 0x21 || ch == '"' || ch == 0x7f) continue; 195 1 196
if (ch < 0x21 || ch == '"' || ch == 0x7f) continue; 0 195 195
63 195 sv_catpvn(out, (const char *)&ch, 1);
64 }
65 42 sv_catpvs(out, "\"");
66 42 return out;
67 }
68 }
69  
70 /* Set a validator header on the response object the handler will add to, so
71 * the 200 carries it as well. A client never given a validator can never send
72 * one back, which would make the whole feature inert on its second request.
73 *
74 * The response object is FORCED here even when the handler would never have
75 * touched it - that is the cost of putting a tag on a plain `$c->text`
76 * response, and it is one allocation on a route that opted in. */
77 54 static void pcg_set_hdr(pTHX_ SV *c, const char *name, SV *val) {
78 54 AV *cav = pcx_av(aTHX_ c);
79 SV *resobj;
80 AV *res, *hdrs;
81 54 ▶ if (!cav) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!cav) return; 0 54 54
82 54 resobj = pcx_force(aTHX_ cav, PCX_RES, "Punk::Response", NULL);
83 54 ▶ if (!resobj || !SvROK(resobj) || SvTYPE(SvRV(resobj)) != SVt_PVAV) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!resobj || !SvROK(resobj) || SvTYPE(SvRV(resobj)) != SVt_PVAV) return; 54 0 54
if (!resobj || !SvROK(resobj) || SvTYPE(SvRV(resobj)) != SVt_PVAV) return; 54 0 54
if (!resobj || !SvROK(resobj) || SvTYPE(SvRV(resobj)) != SVt_PVAV) return; 0 54 54
84 54 res = (AV *)SvRV(resobj);
85 /* punk_res_headers, not pcx_res_headers: the second only reads, and a
86 * response nothing has set a header on yet has no pair-AV to read - the
87 * tag would be dropped on exactly the plain `$c->text` route this is
88 * most worth having on. This is the accessor $c->header reaches. */
89 54 hdrs = punk_res_headers(aTHX_ res);
90 54 ▶ if (!hdrs) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!hdrs) return; 0 54 54
91 54 av_push(hdrs, newSVpv(name, 0));
92 54 av_push(hdrs, newSVsv(val));
93 }
94  
95 /* Run one validator coderef over $c. Returns the result (+1, or undef);
96 * *errp gets the croak (+1) and the caller answers with the app's 500 -
97 * application code running before the handler must not fail silently. */
98 58 static SV *pcg_run_validator(pTHX_ SV *cb, SV *c, SV **errp) {
99 58 dSP; int count; SV *val;
100 58 ENTER; SAVETMPS;
101 58 ▶ PUSHMARK(SP); EXTEND(SP, 1);
Branch: 2 branches
BranchTrueFalseTotal
PUSHMARK(SP); EXTEND(SP, 1); 0 58 58
PUSHMARK(SP); EXTEND(SP, 1); 0 58 58
102 58 PUSHs(c);
103 58 PUTBACK;
104 58 count = call_sv(cb, G_SCALAR | G_EVAL);
105 58 SPAGAIN;
106 58 ▶ val = count > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
val = count > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef; 58 0 58
107 58 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 58 0 58
108 58 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 58 0 58
if (SvTRUE(ERRSV)) { 2 56 58
109 2 SvREFCNT_dec(val);
110 2 ▶ *errp = newSVsv(ERRSV);
Branch: 1 branch
BranchTrueFalseTotal
*errp = newSVsv(ERRSV); 2 0 2
111 2 return NULL;
112 }
113 56 return val;
114 }
115  
116 /* ---- the 304, in one place ---------------------------------------------------
117 *
118 * A 304 is a response whose correctness is mostly about what is ABSENT, and
119 * getting that wrong produces the worst failure in this feature: a client
120 * that waits for a body which will never arrive, or a cache that stores an
121 * entry it can never validate again. Neither is caught by a test asserting
122 * the status is 304.
123 *
124 * Both halves of this plugin build theirs here, and it has to agree with the
125 * third producer in the dist - psf_respond's, for files - because two
126 * answers to "what does a 304 look like" inside one framework is a bug
127 * waiting for somebody to compare them.
128 *
129 * RFC 9110 15.4.5: send the headers that would have gone on the 200 and that
130 * the cache needs to update its entry. So everything the response had
131 * gathered is kept - Cache-Control, Vary, the security headers, the
132 * Set-Cookie the session write-back just added - EXCEPT the ones describing
133 * a representation that is not being sent.
134 */
135  
136 /* Does this header describe the representation rather than the resource?
137 * Content-Length above all: a bodyless response that claims a length is how
138 * a client is taught to wait. psf_respond's 304 sends none of these either. */
139 49 static int pcg_entity_header(pTHX_ const char *k, STRLEN l) {
140 8 ▶ return (l == 12 && foldEQ(k, "Content-Type", 12))
Branch: 1 branch
BranchTrueFalseTotal
return (l == 12 && foldEQ(k, "Content-Type", 12)) 0 8 8
141 41 ▶ || (l == 14 && foldEQ(k, "Content-Length", 14))
Branch: 2 branches
BranchTrueFalseTotal
|| (l == 14 && foldEQ(k, "Content-Length", 14)) 10 31 41
|| (l == 14 && foldEQ(k, "Content-Length", 14)) 2 8 10
142 98 ▶ || (l == 16 && foldEQ(k, "Content-Encoding", 16));
Branch: 3 branches
BranchTrueFalseTotal
|| (l == 16 && foldEQ(k, "Content-Encoding", 16)); 8 41 49
|| (l == 16 && foldEQ(k, "Content-Encoding", 16)); 0 33 33
|| (l == 16 && foldEQ(k, "Content-Encoding", 16)); 0 0 0
143 }
144  
145 /* The 304 triplet (+1), with `tag` (ownership moves; NULL on a route whose
146 * only validator is a date - the Last-Modified travels in `src`, set on the
147 * response object before the check) and everything in `src` that a 304 may
148 * carry. src may be NULL - a route where nothing set a header before the
149 * check ran. */
150 28 static SV *pcg_304(pTHX_ SV *tag, AV *src) {
151 28 AV *resp = newAV(), *hdr = newAV(), *body = newAV();
152 28 ▶ SSize_t i, n = src ? av_len(src) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
SSize_t i, n = src ? av_len(src) + 1 : 0; 28 0 28
153  
154 28 ▶ if (tag) {
Branch: 1 branch
BranchTrueFalseTotal
if (tag) { 26 2 28
155 26 av_push(hdr, newSVpvs("ETag"));
156 26 av_push(hdr, tag); /* ownership moves */
157 }
158 77 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 49 28 77
159 49 SV **k = av_fetch(src, i, 0);
160 49 SV **v = av_fetch(src, i + 1, 0);
161 STRLEN kl;
162 const char *kp;
163 83 ▶ if (!(k && *k && SvOK(*k))) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(k && *k && SvOK(*k))) continue; 49 0 49
if (!(k && *k && SvOK(*k))) continue; 49 0 49
if (!(k && *k && SvOK(*k))) continue; 0 49 49
164 49 kp = SvPV_const(*k, kl);
165 49 ▶ if (pcg_entity_header(aTHX_ kp, kl)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (pcg_entity_header(aTHX_ kp, kl)) continue; 16 33 49
166 /* the tag just added wins over one already in the source - which is
167 * the strong half's own, put there so the 200 would carry it */
168 33 ▶ if (tag && kl == 4 && foldEQ(kp, "ETag", 4)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (tag && kl == 4 && foldEQ(kp, "ETag", 4)) continue; 31 2 33
if (tag && kl == 4 && foldEQ(kp, "ETag", 4)) continue; 22 9 31
if (tag && kl == 4 && foldEQ(kp, "ETag", 4)) continue; 18 4 22
169 15 av_push(hdr, newSVsv(*k));
170 15 ▶ av_push(hdr, (v && *v) ? newSVsv(*v) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(hdr, (v && *v) ? newSVsv(*v) : newSV(0)); 15 0 15
av_push(hdr, (v && *v) ? newSVsv(*v) : newSV(0)); 15 0 15
171 }
172 28 av_push(resp, newSViv(304));
173 28 av_push(resp, newRV_noinc((SV *)hdr));
174 28 av_push(resp, newRV_noinc((SV *)body)); /* empty: a 304 has no body */
175 28 return newRV_noinc((SV *)resp);
176 }
177  
178 /* The check, run between a route's guards and its handler.
179 *
180 * Returns 1 when the request has been ANSWERED and the handler must be
181 * skipped, with exactly one of *out (the 304 triplet) and *errp (what the
182 * validator croaked with) set. Returns 0 to carry on.
183 *
184 * A croaking validator is the app's 500, not a silent full response: it is
185 * application code running before the handler, and swallowing its error
186 * would hide a broken query behind a page that merely got slower.
187 */
188 104 static int pcg_check(pTHX_ SV *c, HV *rech, HV *env, const char *method,
189 STRLEN mlen, SV **out, SV **errp) {
190 104 SV **ep = hv_fetchs(rech, K_ETAG, 0);
191 104 SV **lp = hv_fetchs(rech, K_LAST_MODIFIED, 0);
192 104 ▶ int has_et = ep && *ep && SvROK(*ep) && SvTYPE(SvRV(*ep)) == SVt_PVCV;
Branch: 4 branches
BranchTrueFalseTotal
int has_et = ep && *ep && SvROK(*ep) && SvTYPE(SvRV(*ep)) == SVt_PVCV; 83 21 104
int has_et = ep && *ep && SvROK(*ep) && SvTYPE(SvRV(*ep)) == SVt_PVCV; 83 0 83
int has_et = ep && *ep && SvROK(*ep) && SvTYPE(SvRV(*ep)) == SVt_PVCV; 45 38 83
int has_et = ep && *ep && SvROK(*ep) && SvTYPE(SvRV(*ep)) == SVt_PVCV; 45 0 45
193 104 ▶ int has_lm = lp && *lp && SvROK(*lp) && SvTYPE(SvRV(*lp)) == SVt_PVCV;
Branch: 4 branches
BranchTrueFalseTotal
int has_lm = lp && *lp && SvROK(*lp) && SvTYPE(SvRV(*lp)) == SVt_PVCV; 14 90 104
int has_lm = lp && *lp && SvROK(*lp) && SvTYPE(SvRV(*lp)) == SVt_PVCV; 14 0 14
int has_lm = lp && *lp && SvROK(*lp) && SvTYPE(SvRV(*lp)) == SVt_PVCV; 14 0 14
int has_lm = lp && *lp && SvROK(*lp) && SvTYPE(SvRV(*lp)) == SVt_PVCV; 14 0 14
194 104 SV *val, *tag = NULL;
195 char ldate[64];
196 104 int have_date = 0, matched;
197  
198 104 *out = NULL;
199 104 *errp = NULL;
200 104 ▶ if (!has_et && !has_lm) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!has_et && !has_lm) return 0; 59 45 104
if (!has_et && !has_lm) return 0; 48 11 59
201 56 ▶ if (!pcg_cond_method(method, mlen)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!pcg_cond_method(method, mlen)) return 0; 1 55 56
202  
203 /* The validators run on EVERY request to the route, not only the
204 * conditional ones: the 200 needs its validators too, and a client never
205 * given one can never send one back.
206 *
207 * undef means "I do not know", and that validator contributes nothing. A
208 * validator that cannot answer must not be able to produce a wrong 304,
209 * and saying so has to be cheaper to write than guessing. */
210 55 ▶ if (has_et) {
Branch: 1 branch
BranchTrueFalseTotal
if (has_et) { 44 11 55
211 44 val = pcg_run_validator(aTHX_ *ep, c, errp);
212 44 ▶ if (!val) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!val) return 1; 1 43 44
213 43 ▶ if (SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(val)) { 42 1 43
214 42 tag = pcg_quote(aTHX_ val);
215 /* Two characters is an empty tag - nothing the validator
216 * returned survived. Treat it as undef rather than emitting
217 * `""`, which every client would then match against for ever. */
218 42 ▶ if (SvCUR(tag) <= 2) { SvREFCNT_dec(tag); tag = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (SvCUR(tag) <= 2) { SvREFCNT_dec(tag); tag = NULL; } 0 42 42
219 42 ▶ if (tag) pcg_set_hdr(aTHX_ c, "ETag", tag);
Branch: 1 branch
BranchTrueFalseTotal
if (tag) pcg_set_hdr(aTHX_ c, "ETag", tag); 42 0 42
220 }
221 43 SvREFCNT_dec(val);
222 }
223 54 ▶ if (has_lm) {
Branch: 1 branch
BranchTrueFalseTotal
if (has_lm) { 14 40 54
224 14 val = pcg_run_validator(aTHX_ *lp, c, errp);
225 14 ▶ if (!val) { if (tag) SvREFCNT_dec(tag); return 1; }
Branch: 2 branches
BranchTrueFalseTotal
if (!val) { if (tag) SvREFCNT_dec(tag); return 1; } 1 13 14
if (!val) { if (tag) SvREFCNT_dec(tag); return 1; } 0 1 1
226 13 ▶ if (SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(val)) { 12 1 13
227 /* An epoch, clamped to now: a Last-Modified in the future is a
228 * clock-skew statement no cache can use well, and RFC 9110
229 * 8.8.2 says a recipient replaces one with the response's Date
230 * anyway - clamping at generation is the same answer, earlier. */
231 12 time_t when = (time_t)SvIV(val);
232 12 time_t now = time(NULL);
233 12 ▶ if (when > now) when = now;
Branch: 1 branch
BranchTrueFalseTotal
if (when > now) when = now; 1 11 12
234 12 ps_http_date(ldate, sizeof ldate, when);
235 12 have_date = 1;
236 {
237 12 SV *dsv = sv_2mortal(newSVpv(ldate, 0));
238 12 pcg_set_hdr(aTHX_ c, "Last-Modified", dsv);
239 }
240 }
241 13 SvREFCNT_dec(val);
242 }
243 53 ▶ if (!tag && !have_date) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!tag && !have_date) return 0; 11 42 53
if (!tag && !have_date) return 0; 2 9 11
244  
245 /* One function holds the whole decision, and it is the file path's:
246 * If-None-Match wins over If-Modified-Since (RFC 9110 13.1.3), and the
247 * date comparison is exact - the date they were given is the date we
248 * would send. Exact is deliberate: there is no date parser in this
249 * dist, an unrecognised or stale date simply fails to match, and the
250 * failure direction is a re-send, never a wrong 304. The cost is the
251 * one-second grain any HTTP date already has. */
252 51 ▶ { STRLEN tl = tag ? SvCUR(tag) : 0;
Branch: 1 branch
BranchTrueFalseTotal
{ STRLEN tl = tag ? SvCUR(tag) : 0; 42 9 51
253 93 ▶ const char *tp = tag ? SvPV_const(tag, tl) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
const char *tp = tag ? SvPV_const(tag, tl) : NULL; 42 9 51
254 51 ▶ matched = psf_not_modified(aTHX_ env, tp, tl,
Branch: 1 branch
BranchTrueFalseTotal
matched = psf_not_modified(aTHX_ env, tp, tl, 12 39 51
255 have_date ? ldate : NULL);
256 }
257 51 ▶ if (!matched) { if (tag) SvREFCNT_dec(tag); return 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (!matched) { if (tag) SvREFCNT_dec(tag); return 0; } 31 20 51
if (!matched) { if (tag) SvREFCNT_dec(tag); return 0; } 24 7 31
258  
259 { /* A 304 is a RESPONSE, not an absence of one. It goes back as an
260 * ordinary triplet and through punk_finish_c like any other, so
261 * everything that decorates a response still decorates it - the
262 * session write-back, the security headers - and only the handler is
263 * skipped.
264 *
265 * The headers a guard or a before_dispatch hook already set come with
266 * it. They were set by code that DID run, on a request that is being
267 * answered, and a `Vary` or a `Cache-Control` among them is exactly
268 * what a 304 must not lose. */
269 20 AV *cav = pcx_av(aTHX_ c);
270 20 ▶ AV *res = cav ? pcx_res_av(aTHX_ cav) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
AV *res = cav ? pcx_res_av(aTHX_ cav) : NULL; 20 0 20
271 20 ▶ *out = pcg_304(aTHX_ tag, res ? pcx_res_headers(aTHX_ res) : NULL);
Branch: 1 branch
BranchTrueFalseTotal
*out = pcg_304(aTHX_ tag, res ? pcx_res_headers(aTHX_ res) : NULL); 20 0 20
272 20 return 1;
273 }
274 }
275  
276 /* ---- the body ETag ----------------------------------------------------------
277 *
278 * get '/dashboard' => sub { ... }, { etag => 1 };
279 *
280 * The rendered bytes are hashed and an unchanged response becomes a 304.
281 *
282 * BE HONEST ABOUT WHAT THIS BUYS. It saves the wire and the client's parse
283 * and re-render, which on a polled JSON route is most of what the client was
284 * spending. It saves the server NOTHING: the queries ran, the template
285 * rendered, the encoder ran, and the hash is added cost on top - paid on
286 * every request to the route, including the ones that end in a full 200.
287 * Measured at ~3.5 us on a 1.7 KB body against a route that took 1.3 us to
288 * produce it. Against a route that spends 5 ms in the database it is 0.07%
289 * and worth having; against a route like that one it is not.
290 *
291 * It runs on the after-dispatch chain, which is public, and it is appended
292 * LAST at compile: an application hook that rewrites the body must have
293 * already run, or the tag would describe bytes nobody was sent. Being last
294 * also puts it after the session write-back, which is why the 304 below
295 * keeps the 200's headers rather than building a fresh set - dropping a
296 * Set-Cookie the write-back had just added would log the user out. */
297  
298 /* Weak, not strong: two responses with identical bytes are the same entity
299 * for the purpose of not re-sending them, but nothing here can promise
300 * byte-equality across a Vary axis this does not control, and a strong tag
301 * would license If-Range on a body that has no ranges. */
302 35 static SV *pcg_body_tag(pTHX_ AV *body) {
303 U32 h[8];
304 unsigned char sum[32];
305 char hex[PA_DIGEST_LEN + 1];
306 unsigned char buf[64];
307 35 size_t total = 0, rem = 0;
308 35 SSize_t i, n = av_len(body) + 1;
309 SV *out;
310  
311 35 memcpy(h, ps_sha256_iv, sizeof h);
312 72 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 37 35 72
313 37 SV **e = av_fetch(body, i, 0);
314 const char *p;
315 STRLEN l;
316 37 ▶ if (!(e && *e && SvOK(*e))) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(e && *e && SvOK(*e))) continue; 37 0 37
if (!(e && *e && SvOK(*e))) continue; 37 0 37
if (!(e && *e && SvOK(*e))) continue; 0 37 37
317 37 p = SvPV_const(*e, l);
318 37 total += l;
319 /* The pieces are hashed as one stream, so how the handler happened
320 * to split its body does not change the tag: a template that
321 * returns one string and one that returns three must agree. */
322 277 ▶ while (l) {
Branch: 1 branch
BranchTrueFalseTotal
while (l) { 240 37 277
323 240 ▶ size_t take = (rem + l >= 64) ? 64 - rem : l;
Branch: 1 branch
BranchTrueFalseTotal
size_t take = (rem + l >= 64) ? 64 - rem : l; 203 37 240
324 240 memcpy(buf + rem, p, take);
325 240 rem += take; p += take; l -= take;
326 240 ▶ if (rem == 64) { ps_sha256_blocks(h, buf, 1); rem = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (rem == 64) { ps_sha256_blocks(h, buf, 1); rem = 0; } 203 37 240
327 }
328 }
329 35 ps_sha256_final(h, buf, rem, total, sum);
330 35 pa_hex(sum, PA_DIGEST_LEN / 2, hex);
331 35 out = newSVpvs("W/\"");
332 35 sv_catpvn(out, hex, PA_DIGEST_LEN);
333 35 sv_catpvs(out, "\"");
334 35 return out;
335 }
336  
337 /* ---- what a validator does to a shared cache --------------------------------
338 *
339 * An ETag is a storage instruction. A response that is per-user, or
340 * per-encoding, and that carries a validator with nothing saying what it
341 * depends on, can be stored by any intermediary and handed to the next
342 * request for the same URL - and then confidently revalidated, because now
343 * there is a tag to revalidate with. For a per-user dashboard that is a
344 * disclosure, and this plugin is exactly what will be reached for on those
345 * routes.
346 *
347 * Two rules, and both resolve ambiguity by saying MORE rather than less. A
348 * missing header costs a re-send; a wrong one costs correctness, and in the
349 * authenticated case, confidentiality.
350 */
351  
352 /* Is a header present, and what is its value? */
353 167 static SV *pcg_hdr_get(pTHX_ AV *h, const char *name, STRLEN nl) {
354 167 ▶ SSize_t i, n = h ? av_len(h) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
SSize_t i, n = h ? av_len(h) + 1 : 0; 167 0 167
355 718 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 563 155 718
356 563 SV **k = av_fetch(h, i, 0);
357 STRLEN kl;
358 const char *kp;
359 563 ▶ if (!(k && *k && SvOK(*k))) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(k && *k && SvOK(*k))) continue; 563 0 563
if (!(k && *k && SvOK(*k))) continue; 563 0 563
if (!(k && *k && SvOK(*k))) continue; 0 563 563
360 563 kp = SvPV_const(*k, kl);
361 563 ▶ if (kl == nl && foldEQ(kp, name, nl)) {
Branch: 2 branches
BranchTrueFalseTotal
if (kl == nl && foldEQ(kp, name, nl)) { 24 539 563
if (kl == nl && foldEQ(kp, name, nl)) { 12 12 24
362 12 SV **v = av_fetch(h, i + 1, 0);
363 12 ▶ return (v && *v) ? *v : &PL_sv_undef;
Branch: 2 branches
BranchTrueFalseTotal
return (v && *v) ? *v : &PL_sv_undef; 12 0 12
return (v && *v) ? *v : &PL_sv_undef; 12 0 12
364 }
365 }
366 155 return NULL;
367 }
368  
369 /* The cache-safety pass, run over anything this plugin tagged - the 200 and
370 * the 304, from either half. */
371 88 static void pcg_cache_safety(pTHX_ AV *h, HV *env) {
372 88 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 88 88
373  
374 /* Vary: Accept-Encoding, always. Punk does not compress - Hyperman does,
375 * on the write path, after Punk has stopped looking - so two clients,
376 * one accepting gzip and one not, get the same entity and the same tag
377 * from here and different BYTES from the server. A shared cache needs to
378 * be told that, or it stores one and serves it to both. It is the same
379 * reasoning that puts this header on every response from a static mount,
380 * compressed or not, and it is the honest place for it: we are the ones
381 * handing out the validator the cache will key on.
382 *
383 * Merged through pa_vary_add, so an application that already declared
384 * what it varies on keeps every token it named. */
385 88 pa_vary_add(aTHX_ h, "Accept-Encoding", 15);
386  
387 /* Cache-Control: private, when the response could be about one person
388 * and the application has not said what it wants.
389 *
390 * Two signals, and the second is the one that matters. A Set-Cookie on
391 * the RESPONSE is the obvious one - a session, an auth identity, a CSRF
392 * mirror - but it is not enough on its own: a signed-in user reading a
393 * page that changes nothing gets no write-back and no Set-Cookie, which
394 * is precisely the per-user response somebody put an ETag on. So a
395 * Cookie or Authorization on the REQUEST counts too.
396 *
397 * That is deliberately broad. A public page carrying an analytics
398 * cookie loses shared-cache storage on the routes that opted into
399 * ETags, which costs a re-send; the other direction costs one user
400 * being handed another user's dashboard. An application that knows the
401 * page is public says so, and is never overruled - it may have meant
402 * `public` and known why.
403 *
404 * (Authorization is already covered for shared caches by RFC 9111 3.5;
405 * saying `private` as well costs a header and covers the caches that
406 * read this one and not that rule.) */
407 88 ▶ if (!pcg_hdr_get(aTHX_ h, "Cache-Control", 13)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pcg_hdr_get(aTHX_ h, "Cache-Control", 13)) { 79 9 88
408 79 int personal = pcg_hdr_get(aTHX_ h, "Set-Cookie", 10) ? 1 : 0;
409 79 ▶ if (!personal && env) {
Branch: 2 branches
BranchTrueFalseTotal
if (!personal && env) { 76 3 79
if (!personal && env) { 76 0 76
410 76 SV **e = hv_fetchs(env, "HTTP_COOKIE", 0);
411 76 ▶ if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1;
Branch: 4 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 9 67 76
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 9 0 9
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 9 0 9
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 9 0 9
412 else {
413 67 e = hv_fetchs(env, "HTTP_AUTHORIZATION", 0);
414 67 ▶ if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1;
Branch: 4 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 1 66 67
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 1 0 1
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 1 0 1
if (e && *e && SvOK(*e) && SvCUR(*e)) personal = 1; 1 0 1
415 }
416 }
417 79 ▶ if (personal) {
Branch: 1 branch
BranchTrueFalseTotal
if (personal) { 13 66 79
418 13 av_push(h, newSVpvs("Cache-Control"));
419 13 av_push(h, newSVpvs("private"));
420 }
421 }
422 }
423  
424 /* The after-dispatch hook: ($c, $triplet) -> a triplet, or nothing.
425 *
426 * It does two jobs, and runs for BOTH halves. For `etag => 1` it hashes the
427 * body and may turn the response into a 304; for either half it then runs
428 * the cache-safety pass, which has to happen here rather than at the check
429 * because the Set-Cookie it reads is added by the session write-back - and
430 * this hook is appended after that one. */
431 XS_INTERNAL(pcg_after_cb);
432 106 XS_INTERNAL(pcg_after_cb) {
433 106 dXSARGS;
434 SV *c, *resp;
435 106 AV *ra, *hdrs = NULL, *body;
436 SV **sp2, **hp, **bp;
437 106 HV *env, *rech = NULL;
438 const char *method;
439 106 STRLEN mlen = 3;
440 SV *tag;
441 SSize_t i, hn;
442 106 int strong = 0;
443  
444 106 ▶ if (items < 2) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (items < 2) XSRETURN_EMPTY; 0 106 106
445 106 c = ST(0);
446 106 resp = ST(1);
447 106 ▶ if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) XSRETURN_EMPTY;
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) XSRETURN_EMPTY; 106 0 106
if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) XSRETURN_EMPTY; 0 106 106
448 106 ra = (AV *)SvRV(resp);
449  
450 { /* the matched route, and its option. A route that did not ask for a
451 * body ETag costs two hv_fetches on the way out, which is what an
452 * app-wide hook has to cost when most routes are not using it. */
453 106 AV *cav = pcx_av(aTHX_ c);
454 106 ▶ SV *m = cav ? pcx_get(aTHX_ cav, PCX_MATCH) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *m = cav ? pcx_get(aTHX_ cav, PCX_MATCH) : NULL; 106 0 106
455 SV **rp;
456 106 ▶ if (!(m && SvROK(m) && SvTYPE(SvRV(m)) == SVt_PVHV)) XSRETURN_EMPTY;
Branch: 3 branches
BranchTrueFalseTotal
if (!(m && SvROK(m) && SvTYPE(SvRV(m)) == SVt_PVHV)) XSRETURN_EMPTY; 106 0 106
if (!(m && SvROK(m) && SvTYPE(SvRV(m)) == SVt_PVHV)) XSRETURN_EMPTY; 106 0 106
if (!(m && SvROK(m) && SvTYPE(SvRV(m)) == SVt_PVHV)) XSRETURN_EMPTY; 0 106 106
457 106 rp = hv_fetchs((HV *)SvRV(m), "route", 0);
458 106 ▶ if (!(rp && *rp && SvROK(*rp) && SvTYPE(SvRV(*rp)) == SVt_PVHV))
Branch: 4 branches
BranchTrueFalseTotal
if (!(rp && *rp && SvROK(*rp) && SvTYPE(SvRV(*rp)) == SVt_PVHV)) 106 0 106
if (!(rp && *rp && SvROK(*rp) && SvTYPE(SvRV(*rp)) == SVt_PVHV)) 106 0 106
if (!(rp && *rp && SvROK(*rp) && SvTYPE(SvRV(*rp)) == SVt_PVHV)) 106 0 106
if (!(rp && *rp && SvROK(*rp) && SvTYPE(SvRV(*rp)) == SVt_PVHV)) 0 106 106
459 0 XSRETURN_EMPTY;
460 106 rech = (HV *)SvRV(*rp);
461 }
462 { /* the body ETag is `etag => 1`; a coderef is the strong validator,
463 * and `last_modified` is always one - both answered for themselves
464 * before the handler ran and only want the cache-safety pass below.
465 * A route with last_modified alone still hands out a validator a
466 * cache will key on, so it is not exempt from saying what that
467 * depends on. */
468 106 SV **et = hv_fetchs(rech, K_ETAG, 0);
469 106 SV **lm = hv_fetchs(rech, K_LAST_MODIFIED, 0);
470 106 ▶ int has_et = et && *et && SvOK(*et);
Branch: 3 branches
BranchTrueFalseTotal
int has_et = et && *et && SvOK(*et); 85 21 106
int has_et = et && *et && SvOK(*et); 85 0 85
int has_et = et && *et && SvOK(*et); 85 0 85
471 106 ▶ int has_lm = lm && *lm && SvOK(*lm);
Branch: 3 branches
BranchTrueFalseTotal
int has_lm = lm && *lm && SvOK(*lm); 14 92 106
int has_lm = lm && *lm && SvOK(*lm); 14 0 14
int has_lm = lm && *lm && SvOK(*lm); 14 0 14
472 106 ▶ if (!has_et && !has_lm) XSRETURN_EMPTY;
Branch: 2 branches
BranchTrueFalseTotal
if (!has_et && !has_lm) XSRETURN_EMPTY; 21 85 106
if (!has_et && !has_lm) XSRETURN_EMPTY; 10 11 21
473 96 ▶ strong = (has_et && SvROK(*et)) || !has_et ? 1 : 0;
Branch: 3 branches
BranchTrueFalseTotal
strong = (has_et && SvROK(*et)) || !has_et ? 1 : 0; 85 11 96
strong = (has_et && SvROK(*et)) || !has_et ? 1 : 0; 38 47 85
strong = (has_et && SvROK(*et)) || !has_et ? 1 : 0; 11 38 49
474 }
475  
476 { /* GET and HEAD. Only a 200 is hashed - an error response is not the
477 * resource, and a 500 that renders identically twice must not be
478 * cached as though it were - but a 304 still gets the cache-safety
479 * pass, since it is the response a cache will store against. */
480 96 AV *cav = pcx_av(aTHX_ c);
481 96 ▶ SV *envsv = cav ? pcx_get(aTHX_ cav, PCX_ENV) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *envsv = cav ? pcx_get(aTHX_ cav, PCX_ENV) : NULL; 96 0 96
482 96 SV **stp = av_fetch(ra, 0, 0);
483 IV status;
484 96 ▶ if (!(envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV))
Branch: 3 branches
BranchTrueFalseTotal
if (!(envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV)) 96 0 96
if (!(envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV)) 96 0 96
if (!(envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV)) 0 96 96
485 0 XSRETURN_EMPTY;
486 96 env = (HV *)SvRV(envsv);
487 96 ▶ status = (stp && *stp) ? SvIV(*stp) : 0;
Branch: 2 branches
BranchTrueFalseTotal
status = (stp && *stp) ? SvIV(*stp) : 0; 96 0 96
status = (stp && *stp) ? SvIV(*stp) : 0; 96 0 96
488 96 sp2 = hv_fetchs(env, "REQUEST_METHOD", 0);
489 192 ▶ method = (sp2 && *sp2 && SvOK(*sp2)) ? SvPV_const(*sp2, mlen) : "GET";
Branch: 3 branches
BranchTrueFalseTotal
method = (sp2 && *sp2 && SvOK(*sp2)) ? SvPV_const(*sp2, mlen) : "GET"; 96 0 96
method = (sp2 && *sp2 && SvOK(*sp2)) ? SvPV_const(*sp2, mlen) : "GET"; 96 0 96
method = (sp2 && *sp2 && SvOK(*sp2)) ? SvPV_const(*sp2, mlen) : "GET"; 96 0 96
490 96 ▶ if (!pcg_cond_method(method, mlen)) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (!pcg_cond_method(method, mlen)) XSRETURN_EMPTY; 1 95 96
491 95 ▶ if (status != 200 && status != 304) XSRETURN_EMPTY;
Branch: 2 branches
BranchTrueFalseTotal
if (status != 200 && status != 304) XSRETURN_EMPTY; 26 69 95
if (status != 200 && status != 304) XSRETURN_EMPTY; 6 20 26
492  
493 /* the strong half, and any 304: nothing to hash, but the response
494 * carries a validator and needs saying what it depends on */
495 89 ▶ if (strong || status == 304) {
Branch: 2 branches
BranchTrueFalseTotal
if (strong || status == 304) { 36 53 89
if (strong || status == 304) { 0 36 36
496 53 SV **hh = av_fetch(ra, 1, 0);
497 53 ▶ if (hh && *hh && SvROK(*hh) && SvTYPE(SvRV(*hh)) == SVt_PVAV)
Branch: 4 branches
BranchTrueFalseTotal
if (hh && *hh && SvROK(*hh) && SvTYPE(SvRV(*hh)) == SVt_PVAV) 53 0 53
if (hh && *hh && SvROK(*hh) && SvTYPE(SvRV(*hh)) == SVt_PVAV) 53 0 53
if (hh && *hh && SvROK(*hh) && SvTYPE(SvRV(*hh)) == SVt_PVAV) 53 0 53
if (hh && *hh && SvROK(*hh) && SvTYPE(SvRV(*hh)) == SVt_PVAV) 53 0 53
498 53 pcg_cache_safety(aTHX_ (AV *)SvRV(*hh), env);
499 53 XSRETURN_EMPTY;
500 }
501 }
502  
503 36 hp = av_fetch(ra, 1, 0);
504 36 bp = av_fetch(ra, 2, 0);
505 36 ▶ if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV)
Branch: 4 branches
BranchTrueFalseTotal
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) 36 0 36
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) 36 0 36
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) 36 0 36
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) 36 0 36
506 36 hdrs = (AV *)SvRV(*hp);
507 /* Only an arrayref body can be hashed. A filehandle or a
508 * Punk::SendFile::Reader would have to be consumed to be read, and a
509 * send_file response already carries a strong validator of its own -
510 * there is nothing to add there and something to break. */
511 36 ▶ if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV))
Branch: 4 branches
BranchTrueFalseTotal
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 36 0 36
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 36 0 36
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 36 0 36
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 1 35 36
512 1 XSRETURN_EMPTY;
513 35 body = (AV *)SvRV(*bp);
514  
515 /* A response that already carries a tag has been validated by something
516 * that knew more than this does - send_file, or the strong validator on
517 * the same route. Do not replace it. */
518 35 ▶ hn = hdrs ? av_len(hdrs) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
hn = hdrs ? av_len(hdrs) + 1 : 0; 35 0 35
519 124 ▶ for (i = 0; i + 1 < hn; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < hn; i += 2) { 89 35 124
520 89 SV **k = av_fetch(hdrs, i, 0);
521 STRLEN kl;
522 const char *kp;
523 89 ▶ if (!(k && *k && SvOK(*k))) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(k && *k && SvOK(*k))) continue; 89 0 89
if (!(k && *k && SvOK(*k))) continue; 89 0 89
if (!(k && *k && SvOK(*k))) continue; 0 89 89
524 89 kp = SvPV_const(*k, kl);
525 89 ▶ if (kl == 4 && foldEQ(kp, "ETag", 4)) XSRETURN_EMPTY;
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 4 && foldEQ(kp, "ETag", 4)) XSRETURN_EMPTY; 8 81 89
if (kl == 4 && foldEQ(kp, "ETag", 4)) XSRETURN_EMPTY; 0 8 8
526 }
527  
528 35 tag = pcg_body_tag(aTHX_ body);
529  
530 /* Compare the QUOTED part, not the `W/` prefix. psf_etag_in strips a
531 * weak prefix off each list entry before comparing, so handing it our
532 * own prefix would mean a tag we issued could never match itself coming
533 * back - which looks exactly like a working feature that never 304s. */
534 35 ▶ if (!psf_not_modified(aTHX_ env, SvPVX(tag) + 2, SvCUR(tag) - 2, NULL)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!psf_not_modified(aTHX_ env, SvPVX(tag) + 2, SvCUR(tag) - 2, NULL)) { 27 8 35
535 27 ▶ if (hdrs) { /* the 200 carries it */
Branch: 1 branch
BranchTrueFalseTotal
if (hdrs) { /* the 200 carries it */ 27 0 27
536 27 av_push(hdrs, newSVpvs("ETag"));
537 27 av_push(hdrs, tag);
538 27 pcg_cache_safety(aTHX_ hdrs, env);
539 }
540 0 else SvREFCNT_dec(tag);
541 27 XSRETURN_EMPTY; /* the response stands */
542 }
543  
544 /* the 304, through the one builder - the 200's headers minus the ones
545 * describing a body that is no longer being sent. Everything else the
546 * response gathered is kept, and being LAST on the after chain means
547 * that includes the session write-back's Set-Cookie. */
548 {
549 8 SV *out = pcg_304(aTHX_ tag, hdrs);
550 8 SV **h2 = av_fetch((AV *)SvRV(out), 1, 0);
551 8 ▶ if (h2 && *h2 && SvROK(*h2))
Branch: 3 branches
BranchTrueFalseTotal
if (h2 && *h2 && SvROK(*h2)) 8 0 8
if (h2 && *h2 && SvROK(*h2)) 8 0 8
if (h2 && *h2 && SvROK(*h2)) 8 0 8
552 8 pcg_cache_safety(aTHX_ (AV *)SvRV(*h2), env);
553 8 ST(0) = sv_2mortal(out);
554 }
555 8 XSRETURN(1);
556 }
557  
558 #endif /* PUNK_CGET_H */
« xs/context.xs ↑ Summary include/punk/punk_computed.h »