xs/context.xs

filter: Statementstmt 94.5% 500 / 529 Branchbran 69.0% 424 / 614 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 80.8% 924 / 1143 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/punk/punk_health.h ↑ Summary include/punk/punk_cget.h »
1 MODULE = Punk PACKAGE = Punk::Context
2  
3 PROTOTYPES: DISABLE
4  
5 # The per-request context, in C (punk_context.h): the whole class lives here -
6 # the constructor, the plain slot accessors and the methods. lib/Punk/Context.pm
7 # is documentation only.
8  
9 # Fast per-request constructor: bless an AV with just the slots the dispatcher
10 # fills (env, app, match); req/res/stash/openapi stay unset (lazy).
11 SV *
12 _build(class, env, app, match)
13 SV *class
14 SV *env
15 SV *app
16 SV *match
17 CODE:
18 {
19 4 AV *av = newAV();
20 4 av_extend(av, PCX_MATCH);
21 4 (void)av_store(av, PCX_ENV, newSVsv(env));
22 4 (void)av_store(av, PCX_APP, newSVsv(app));
23 4 (void)av_store(av, PCX_MATCH, newSVsv(match));
24 4 RETVAL = sv_bless(newRV_noinc((SV *)av), gv_stashsv(class, GV_ADD));
25 }
26 OUTPUT:
27 RETVAL
28  
29 # ---- slot accessors ----------------------------------------------------------
30  
31 # The plain read/write accessors. The ALIAS index is the position in pcx_slots
32 # below, not the slot number itself - keeping the mapping explicit means the
33 # enum in punk_context.h can be reordered without silently rewiring these.
34 SV *
35 env(self, ...)
36 SV *self
37 ALIAS:
38 app = 1
39 _req = 2
40 _res = 3
41 stash_hv = 4
42 openapi_params = 5
43 match = 6
44 CODE:
45 {
46 static const I32 pcx_slots[] = {
47 PCX_ENV, PCX_APP, PCX_REQ, PCX_RES,
48 PCX_STASH, PCX_OPENAPI, PCX_MATCH
49 };
50 161 AV *av = pcx_av(aTHX_ self);
51 160 I32 slot = pcx_slots[ix];
52 SV **e;
53 160 ▶ if (items > 1) (void)av_store(av, slot, newSVsv(ST(1)));
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) (void)av_store(av, slot, newSVsv(ST(1))); 7 153 160
54 160 e = av_fetch(av, slot, 0);
55 160 ▶ RETVAL = (e && *e) ? newSVsv(*e) : newSV(0);
Branch: 2 branches
BranchTrueFalseTotal
RETVAL = (e && *e) ? newSVsv(*e) : newSV(0); 158 2 160
RETVAL = (e && *e) ? newSVsv(*e) : newSV(0); 158 0 158
56 }
57 OUTPUT:
58 RETVAL
59  
60 # ---- lazy sub-objects --------------------------------------------------------
61  
62 SV *
63 req(self)
64 SV *self
65 CODE:
66 {
67 3001 AV *av = pcx_av(aTHX_ self);
68 3001 RETVAL = newSVsv(pcx_force(aTHX_ av, PCX_REQ, "Punk::Request",
69 pcx_get(aTHX_ av, PCX_ENV)));
70 }
71 OUTPUT:
72 RETVAL
73  
74 SV *
75 res(self)
76 SV *self
77 CODE:
78 {
79 10 AV *av = pcx_av(aTHX_ self);
80 10 RETVAL = newSVsv(pcx_force(aTHX_ av, PCX_RES, "Punk::Response", NULL));
81 }
82 OUTPUT:
83 RETVAL
84  
85 # The outbound user agent: one Fetch per worker, shared by every request it
86 # serves, so the keep-alive pool and DNS state survive between them. The slot
87 # here only memoises the lookup for this request; punk_ua.h owns the agent and
88 # its pid check. Bound to the worker's loop, so a call made from a handler does
89 # not stop the worker answering others.
90 SV *
91 ua(self, name = NULL)
92 SV *self
93 SV *name
94 CODE:
95 {
96 34 AV *av = pcx_av(aTHX_ self);
97 STRLEN nl;
98 14 ▶ const char *n = (name && SvOK(name)) ? SvPV_const(name, nl)
Branch: 1 branch
BranchTrueFalseTotal
const char *n = (name && SvOK(name)) ? SvPV_const(name, nl) 7 0 7
99 34 ▶ : (nl = sizeof(K_DEFAULT) - 1,
Branch: 1 branch
BranchTrueFalseTotal
: (nl = sizeof(K_DEFAULT) - 1, 7 27 34
100 K_DEFAULT);
101 /* Memoised per name, so a handler naming the same agent twice gets
102 * one agent - and one jar, when the jar is per request. */
103 34 SV *memo = pcx_get(aTHX_ av, PCX_UA);
104 HV *seen;
105 SV **e;
106 34 ▶ if (memo && SvROK(memo) && SvTYPE(SvRV(memo)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (memo && SvROK(memo) && SvTYPE(SvRV(memo)) == SVt_PVHV) 4 30 34
if (memo && SvROK(memo) && SvTYPE(SvRV(memo)) == SVt_PVHV) 4 0 4
if (memo && SvROK(memo) && SvTYPE(SvRV(memo)) == SVt_PVHV) 4 0 4
107 4 seen = (HV *)SvRV(memo);
108 else {
109 30 seen = newHV();
110 30 (void)av_store(av, PCX_UA, newRV_noinc((SV *)seen));
111 }
112 34 e = hv_fetch(seen, n, (I32)nl, 0);
113 34 ▶ if (e && *e && SvROK(*e)) RETVAL = newSVsv(*e);
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvROK(*e)) RETVAL = newSVsv(*e); 4 30 34
if (e && *e && SvROK(*e)) RETVAL = newSVsv(*e); 4 0 4
if (e && *e && SvROK(*e)) RETVAL = newSVsv(*e); 4 0 4
114 else {
115 /* +1 from pua_agent; the cache takes that reference */
116 30 SV *u = pua_agent(aTHX_ pcx_get(aTHX_ av, PCX_APP), n, nl);
117 29 (void)hv_store(seen, n, (I32)nl, u, 0);
118 29 RETVAL = newSVsv(u);
119 }
120 }
121 OUTPUT:
122 RETVAL
123  
124 SV *
125 stash(self)
126 SV *self
127 CODE:
128 {
129 44 AV *av = pcx_av(aTHX_ self);
130 44 SV *s = pcx_get(aTHX_ av, PCX_STASH);
131 44 ▶ if (!s) {
Branch: 1 branch
BranchTrueFalseTotal
if (!s) { 22 22 44
132 22 s = newRV_noinc((SV *)newHV());
133 22 (void)av_store(av, PCX_STASH, s);
134 }
135 44 RETVAL = newSVsv(s);
136 }
137 OUTPUT:
138 RETVAL
139  
140 SV *
141 openapi(self)
142 SV *self
143 CODE:
144 {
145 13 SV *o = pcx_get(aTHX_ pcx_av(aTHX_ self), PCX_OPENAPI);
146 13 ▶ RETVAL = o ? newSVsv(o) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = o ? newSVsv(o) : &PL_sv_undef; 12 1 13
147 }
148 OUTPUT:
149 RETVAL
150  
151 # Validated OpenAPI params win (path, then query), then web route captures,
152 # then the request (query, then form body).
153 SV *
154 param(self, name)
155 SV *self
156 SV *name
157 CODE:
158 {
159 107378 SV *v = pcx_param(aTHX_ pcx_av(aTHX_ self), name);
160 107378 ▶ RETVAL = v ? v : newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = v ? v : newSV(0); 65 107313 107378
161 }
162 OUTPUT:
163 RETVAL
164  
165 # params -> all of them merged, in that same precedence
166 # params(@k) -> just those, as a list of values in list context (undef
167 # for a name no layer has) or a hashref of the ones that
168 # are there in scalar context, which is the filter-hash
169 # shape: my %f = %{ $c->params(qw(state queue)) };
170 #
171 # Results are written back over the argument slots, one behind the name
172 # being read, so no key is overwritten before it has been looked up.
173 void
174 params(self, ...)
175 SV *self
176 PPCODE:
177 {
178 19 AV *av = pcx_av(aTHX_ self);
179 int i;
180 19 ▶ if (items < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (items < 2) { 14 5 19
181 14 ST(0) = sv_2mortal(newRV_noinc((SV *)pcx_params_merged(aTHX_ av)));
182 14 XSRETURN(1);
183 }
184 5 ▶ if (GIMME_V == G_ARRAY) {
Branch: 1 branch
BranchTrueFalseTotal
if (GIMME_V == G_ARRAY) { 4 1 5
185 10 ▶ for (i = 1; i < items; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i < items; i++) { 6 4 10
186 6 SV *v = pcx_param(aTHX_ av, ST(i));
187 6 ▶ ST(i - 1) = sv_2mortal(v ? v : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
ST(i - 1) = sv_2mortal(v ? v : newSV(0)); 3 3 6
188 }
189 4 XSRETURN(items - 1);
190 }
191 else {
192 1 HV *out = newHV();
193 5 ▶ for (i = 1; i < items; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i < items; i++) { 4 1 5
194 4 SV *v = pcx_param(aTHX_ av, ST(i));
195 4 ▶ if (v) (void)hv_store_ent(out, ST(i), v, 0);
Branch: 1 branch
BranchTrueFalseTotal
if (v) (void)hv_store_ent(out, ST(i), v, 0); 3 1 4
196 }
197 1 ST(0) = sv_2mortal(newRV_noinc((SV *)out));
198 1 XSRETURN(1);
199 }
200 }
201  
202 SV *
203 model(self, name)
204 SV *self
205 SV *name
206 CODE:
207 {
208 89 SV *app = pcx_get(aTHX_ pcx_av(aTHX_ self), PCX_APP);
209 89 dSP; int count;
210 89 ENTER; SAVETMPS;
211 89 ▶ PUSHMARK(SP); EXTEND(SP, 2);
Branch: 2 branches
BranchTrueFalseTotal
PUSHMARK(SP); EXTEND(SP, 2); 0 89 89
PUSHMARK(SP); EXTEND(SP, 2); 0 89 89
212 89 ▶ PUSHs(app ? app : &PL_sv_undef); PUSHs(name); PUTBACK;
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(app ? app : &PL_sv_undef); PUSHs(name); PUTBACK; 89 0 89
213 89 count = call_method("model_instance", G_SCALAR);
214 89 SPAGAIN;
215 89 ▶ RETVAL = count > 0 ? newSVsv(POPs) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = count > 0 ? newSVsv(POPs) : &PL_sv_undef; 89 0 89
216 89 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 89 0 89
217 }
218 OUTPUT:
219 RETVAL
220  
221 # $app->render_view($self, @_)
222 SV *
223 render(self, ...)
224 SV *self
225 CODE:
226 {
227 2161 AV *av = pcx_av(aTHX_ self);
228 2161 SV *app = pcx_get(aTHX_ av, PCX_APP);
229 2161 int nargs = items - 1, i;
230 SV **argv, *r;
231 2161 Newx(argv, nargs + 1, SV *); /* capture args before any stack work */
232 2161 argv[0] = self;
233 4417 ▶ for (i = 0; i < nargs; i++) argv[i + 1] = ST(i + 1);
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nargs; i++) argv[i + 1] = ST(i + 1); 2256 2161 4417
234 2161 ▶ r = pcx_call_meth(aTHX_ app ? app : &PL_sv_undef, "render_view",
Branch: 1 branch
BranchTrueFalseTotal
r = pcx_call_meth(aTHX_ app ? app : &PL_sv_undef, "render_view", 2161 0 2161
235 argv, nargs + 1, 1);
236 2151 Safefree(argv);
237 2151 ▶ RETVAL = r ? r : newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = r ? r : newSV(0); 0 2151 2151
238 }
239 OUTPUT:
240 RETVAL
241  
242 # fragment($template, \%data?, %over): render with no layout, and
243 # `Cache-Control: private, no-store` on the finished response.
244 #
245 # A fragment is one user's data swapped into one user's page - the panel
246 # PDFMake-Site rendered through a private engine - and a shared cache handing
247 # it to the next visitor is a leak, so the header is the default and not a
248 # reminder. The public, cacheable partial is `render` with layout => undef and
249 # a Cache-Control of its own. A `layout` override here croaks: a fragment with
250 # a layout is a page, and the caller wanted `render`.
251 SV *
252 fragment(self, ...)
253 SV *self
254 CODE:
255 {
256 6 AV *av = pcx_av(aTHX_ self);
257 6 SV *app = pcx_get(aTHX_ av, PCX_APP);
258 6 int nargs = items - 1, i, n = 0;
259 SV **argv, *r, *lay;
260 6 ▶ if (nargs < 1)
Branch: 1 branch
BranchTrueFalseTotal
if (nargs < 1) 0 6 6
261 0 croak("Punk::Context::fragment: a template name is required");
262 /* ST(1) template, ST(2) data, ST(3..) overrides - every override
263 * pair is checked for `layout` before anything is called */
264 7 ▶ for (i = 3; i + 1 < items; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 3; i + 1 < items; i += 2) { 2 5 7
265 2 STRLEN kl; const char *k = SvPV_const(ST(i), kl);
266 2 ▶ if (kl == 6 && memEQ(k, "layout", 6))
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 6 && memEQ(k, "layout", 6)) 2 0 2
if (kl == 6 && memEQ(k, "layout", 6)) 1 1 2
267 1 croak("Punk::Context::fragment: a fragment has no layout - "
268 "to render inside one, use render(..., layout => ...)");
269 }
270 /* self, template, data (undef if not given), overrides, layout, undef */
271 5 Newx(argv, nargs + 4, SV *);
272 5 argv[n++] = self;
273 5 argv[n++] = ST(1);
274 5 ▶ argv[n++] = items > 2 ? ST(2) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
argv[n++] = items > 2 ? ST(2) : &PL_sv_undef; 4 1 5
275 7 ▶ for (i = 3; i < items; i++) argv[n++] = ST(i);
Branch: 1 branch
BranchTrueFalseTotal
for (i = 3; i < items; i++) argv[n++] = ST(i); 2 5 7
276 5 lay = sv_2mortal(newSVpvs("layout"));
277 5 argv[n++] = lay;
278 5 argv[n++] = &PL_sv_undef;
279 5 ▶ r = pcx_call_meth(aTHX_ app ? app : &PL_sv_undef, "render_view",
Branch: 1 branch
BranchTrueFalseTotal
r = pcx_call_meth(aTHX_ app ? app : &PL_sv_undef, "render_view", 5 0 5
280 argv, n, 1);
281 5 Safefree(argv);
282 5 ▶ if (!r) r = newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
if (!r) r = newSV(0); 0 5 5
283 /* the header: replace an existing Cache-Control, else append one */
284 5 ▶ if (SvROK(r) && SvTYPE(SvRV(r)) == SVt_PVAV) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(r) && SvTYPE(SvRV(r)) == SVt_PVAV) { 5 0 5
if (SvROK(r) && SvTYPE(SvRV(r)) == SVt_PVAV) { 5 0 5
285 5 SV **hp = av_fetch((AV *)SvRV(r), 1, 0);
286 5 ▶ if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 5 0 5
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 5 0 5
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 5 0 5
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 5 0 5
287 5 AV *hd = (AV *)SvRV(*hp);
288 5 SSize_t j, hn = av_len(hd) + 1;
289 5 int found = 0;
290 17 ▶ for (j = 0; j + 1 < hn; j += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j + 1 < hn; j += 2) { 12 5 17
291 12 SV **nm = av_fetch(hd, j, 0);
292 STRLEN nl; const char *np;
293 12 ▶ if (!(nm && *nm && SvOK(*nm))) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(nm && *nm && SvOK(*nm))) continue; 12 0 12
if (!(nm && *nm && SvOK(*nm))) continue; 12 0 12
if (!(nm && *nm && SvOK(*nm))) continue; 0 12 12
294 12 np = SvPV_const(*nm, nl);
295 12 ▶ if (nl == 13 && foldEQ(np, "Cache-Control", (I32)13)) {
Branch: 2 branches
BranchTrueFalseTotal
if (nl == 13 && foldEQ(np, "Cache-Control", (I32)13)) { 1 11 12
if (nl == 13 && foldEQ(np, "Cache-Control", (I32)13)) { 1 0 1
296 1 SV **vp = av_fetch(hd, j + 1, 1);
297 1 ▶ if (vp && *vp) sv_setpvs(*vp, "private, no-store");
Branch: 2 branches
BranchTrueFalseTotal
if (vp && *vp) sv_setpvs(*vp, "private, no-store"); 1 0 1
if (vp && *vp) sv_setpvs(*vp, "private, no-store"); 1 0 1
298 1 found = 1;
299 }
300 }
301 5 ▶ if (!found) {
Branch: 1 branch
BranchTrueFalseTotal
if (!found) { 4 1 5
302 4 av_push(hd, newSVpvs("Cache-Control"));
303 4 av_push(hd, newSVpvs("private, no-store"));
304 }
305 }
306 }
307 5 RETVAL = r;
308 }
309 OUTPUT:
310 RETVAL
311  
312 # ---- finished responses ------------------------------------------------------
313  
314 SV *
315 json(self, data, status = &PL_sv_undef)
316 SV *self
317 SV *data
318 SV *status
319 CODE:
320 {
321 922 AV *av = pcx_av(aTHX_ self);
322 922 AV *res = pcx_res_av(aTHX_ av);
323 922 IV st = ps_status_arg(aTHX_ status);
324 913 SV *bytes = pcx_json(aTHX_ av, data);
325 913 ▶ if (!st) st = pcx_res_status(aTHX_ res);
Branch: 1 branch
BranchTrueFalseTotal
if (!st) st = pcx_res_status(aTHX_ res); 873 40 913
326 913 ▶ if (!st) st = 200;
Branch: 1 branch
BranchTrueFalseTotal
if (!st) st = 200; 868 45 913
327 940 ▶ RETVAL = punk_triplet_ct(aTHX_ st, "application/json", 16,
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = punk_triplet_ct(aTHX_ st, "application/json", 16, 27 886 913
328 27 bytes, res ? pcx_res_headers(aTHX_ res) : NULL);
329 }
330 OUTPUT:
331 RETVAL
332  
333 # A File::Raw::XML::Document or ::Node is serialised; a string is markup the
334 # caller already built and goes out as it stands. Anything else is refused
335 # rather than stringified, which is the difference between an empty element
336 # and a body reading HASH(0x7f...).
337 SV *
338 xml(self, data, status = &PL_sv_undef)
339 SV *self
340 SV *data
341 SV *status
342 CODE:
343 {
344 7 AV *av = pcx_av(aTHX_ self);
345 7 AV *res = pcx_res_av(aTHX_ av);
346 7 IV st = ps_status_arg(aTHX_ status);
347 SV *bytes;
348 7 ▶ if (SvROK(data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(data)) { 6 1 7
349 6 SV *err = NULL;
350 6 ▶ if (!punk_xml_is(aTHX_ data))
Branch: 1 branch
BranchTrueFalseTotal
if (!punk_xml_is(aTHX_ data)) 1 5 6
351 1 croak("Punk: xml() takes a File::Raw::XML::Document, a "
352 "::Node, or a string of markup");
353 5 bytes = punk_xml_bytes(aTHX_ data, &err);
354 5 ▶ if (!bytes) croak("%s", err ? SvPV_nolen(err) : "Punk: xml");
Branch: 2 branches
BranchTrueFalseTotal
if (!bytes) croak("%s", err ? SvPV_nolen(err) : "Punk: xml"); 0 5 5
if (!bytes) croak("%s", err ? SvPV_nolen(err) : "Punk: xml"); 0 0 0
355 }
356 1 else bytes = newSVsv(data);
357 6 ▶ if (!st) st = pcx_res_status(aTHX_ res);
Branch: 1 branch
BranchTrueFalseTotal
if (!st) st = pcx_res_status(aTHX_ res); 5 1 6
358 6 ▶ if (!st) st = 200;
Branch: 1 branch
BranchTrueFalseTotal
if (!st) st = 200; 5 1 6
359 6 ▶ RETVAL = punk_triplet(aTHX_ st,
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = punk_triplet(aTHX_ st, 0 6 6
360 sv_2mortal(newSVpvs(PK_XML_CT)),
361 0 bytes, res ? pcx_res_headers(aTHX_ res) : NULL);
362 }
363 OUTPUT:
364 RETVAL
365  
366 SV *
367 text(self, body, status = &PL_sv_undef)
368 SV *self
369 SV *body
370 SV *status
371 ALIAS:
372 html = 1
373 CODE:
374 {
375 109686 AV *av = pcx_av(aTHX_ self);
376 109686 AV *res = pcx_res_av(aTHX_ av);
377 109686 IV st = ps_status_arg(aTHX_ status);
378 109670 ▶ if (!st) st = pcx_res_status(aTHX_ res);
Branch: 1 branch
BranchTrueFalseTotal
if (!st) st = pcx_res_status(aTHX_ res); 109632 38 109670
379 109670 ▶ if (!st) st = 200;
Branch: 1 branch
BranchTrueFalseTotal
if (!st) st = 200; 109627 43 109670
380 109670 RETVAL = ix == 1
381 30 ▶ ? punk_triplet_ct(aTHX_ st, "text/html; charset=utf-8", 24,
Branch: 1 branch
BranchTrueFalseTotal
? punk_triplet_ct(aTHX_ st, "text/html; charset=utf-8", 24, 3 24 27
382 3 newSVsv(body), res ? pcx_res_headers(aTHX_ res) : NULL)
383 109742 ▶ : punk_triplet_ct(aTHX_ st, "text/plain; charset=utf-8", 25,
Branch: 2 branches
BranchTrueFalseTotal
: punk_triplet_ct(aTHX_ st, "text/plain; charset=utf-8", 25, 27 109643 109670
: punk_triplet_ct(aTHX_ st, "text/plain; charset=utf-8", 25, 72 109571 109643
384 72 newSVsv(body), res ? pcx_res_headers(aTHX_ res) : NULL);
385 }
386 OUTPUT:
387 RETVAL
388  
389 # safe_path($path, $fallback?): $path when it is a same-origin relative path,
390 # otherwise the fallback (undef by default). The guard for anything that
391 # redirects to a destination the request supplied - ?to=, ?return=, ?next=.
392 # (Do not start a line in here with the word after "#" being if/else/endif:
393 # xsubpp reads it as a preprocessor directive.)
394 SV *
395 safe_path(self, path, fallback = &PL_sv_undef)
396 SV *self
397 SV *path
398 SV *fallback
399 CODE:
400 {
401 PERL_UNUSED_VAR(self);
402 38 RETVAL = pk_same_origin_path(aTHX_ path)
403 19 ▶ ? newSVsv(path) : newSVsv(fallback);
Branch: 1 branch
BranchTrueFalseTotal
? newSVsv(path) : newSVsv(fallback); 6 13 19
404 }
405 OUTPUT:
406 RETVAL
407  
408 # $c->origin - the request's scheme and host, when that host is the
409 # application's canonical one or on its allowlist; the canonical origin when
410 # it is anything else; undef when no `host` was declared. The raw header is
411 # never returned (punk_host.h).
412 SV *
413 origin(self)
414 SV *self
415 CODE:
416 {
417 220026 int st = 0;
418 220026 SV *o = pk_origin_of(aTHX_ self, &st);
419 220026 ▶ RETVAL = o ? o : newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = o ? o : newSV(0); 1 220025 220026
420 }
421 OUTPUT:
422 RETVAL
423  
424 # $c->url_for($name, %args) - the URL of a named route.
425 #
426 # $c->url_for('book', id => 42) # /books/42
427 # $c->url_for('book', id => 42, page => 2) # /books/42?page=2
428 # $c->url_for('book', id => 42, absolute => 1) # https://example.com/books/42
429 #
430 # An argument naming a capture fills that segment; anything left over is the
431 # query string, keys sorted. `absolute` and `query` are reserved words rather
432 # than captures - they are refused as route names for that reason.
433 #
434 # Every result carries the application's prefix: the path on `host` and then
435 # SCRIPT_NAME, which are layers rather than alternatives (a proxy strips one,
436 # a PSGI mount adds the other, and the browser sees both). A relative URL is
437 # an href resolved against a page that is already under the prefix, so it
438 # needs the prefix exactly as much as an absolute one does.
439 #
440 # `absolute` joins $c->origin, which is the canonical origin unless the
441 # request's Host is on the allowlist and is never the raw header - so a link
442 # built here and mailed cannot be poisoned by a crafted Host.
443 SV *
444 url_for(self, name, ...)
445 SV *self
446 SV *name
447 CODE:
448 {
449 83 AV *av = pcx_av(aTHX_ self);
450 83 SV *appsv = pcx_get(aTHX_ av, PCX_APP);
451 83 HV *h, *args, *query = NULL;
452 83 SV *namesv, *routersv, *prefix = NULL, *origin = NULL;
453 HE *he;
454 SV *val;
455 83 IV absolute = 0;
456 int i;
457  
458 83 ▶ if ((items - 2) % 2)
Branch: 1 branch
BranchTrueFalseTotal
if ((items - 2) % 2) 0 83 83
459 0 croak("Punk: url_for takes a route name then key => value pairs");
460 83 ▶ if (!SvOK(name) || !SvCUR(name))
Branch: 2 branches
BranchTrueFalseTotal
if (!SvOK(name) || !SvCUR(name)) 83 0 83
if (!SvOK(name) || !SvCUR(name)) 0 83 83
461 0 croak("Punk: url_for needs a route name");
462 83 ▶ if (!(appsv && SvROK(appsv) && SvTYPE(SvRV(appsv)) == SVt_PVHV))
Branch: 3 branches
BranchTrueFalseTotal
if (!(appsv && SvROK(appsv) && SvTYPE(SvRV(appsv)) == SVt_PVHV)) 83 0 83
if (!(appsv && SvROK(appsv) && SvTYPE(SvRV(appsv)) == SVt_PVHV)) 83 0 83
if (!(appsv && SvROK(appsv) && SvTYPE(SvRV(appsv)) == SVt_PVHV)) 0 83 83
463 0 croak("Punk: url_for: no application on this context");
464 83 h = (HV *)SvRV(appsv);
465  
466 83 args = (HV *)sv_2mortal((SV *)newHV());
467 164 ▶ for (i = 2; i + 1 < items; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 2; i + 1 < items; i += 2) { 81 83 164
468 STRLEN kl;
469 81 const char *k = SvPV_const(ST(i), kl);
470 81 ▶ if (kl == 8 && memEQ(k, "absolute", 8)) {
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 8 && memEQ(k, "absolute", 8)) { 8 73 81
if (kl == 8 && memEQ(k, "absolute", 8)) { 8 0 8
471 8 absolute = SvTRUE(ST(i + 1)) ? 1 : 0;
472 10 continue;
473 }
474 73 ▶ if (kl == 5 && memEQ(k, "query", 5)) {
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 5 && memEQ(k, "query", 5)) { 2 71 73
if (kl == 5 && memEQ(k, "query", 5)) { 2 0 2
475 2 SV *q = ST(i + 1);
476 2 ▶ if (!(SvROK(q) && SvTYPE(SvRV(q)) == SVt_PVHV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(q) && SvTYPE(SvRV(q)) == SVt_PVHV)) 2 0 2
if (!(SvROK(q) && SvTYPE(SvRV(q)) == SVt_PVHV)) 0 2 2
477 0 croak("Punk: url_for('%s'): `query` takes a hashref",
478 SvPV_nolen(name));
479 2 query = (HV *)SvRV(q);
480 2 continue;
481 }
482 71 (void)hv_store(args, k, (I32)kl, newSVsv(ST(i + 1)), 0);
483 }
484  
485 83 namesv = app_get(aTHX_ h, K_NAMES_C);
486 83 ▶ he = (namesv && SvROK(namesv) && SvTYPE(SvRV(namesv)) == SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
he = (namesv && SvROK(namesv) && SvTYPE(SvRV(namesv)) == SVt_PVHV) 83 0 83
he = (namesv && SvROK(namesv) && SvTYPE(SvRV(namesv)) == SVt_PVHV) 83 0 83
487 166 ▶ ? hv_fetch_ent((HV *)SvRV(namesv), name, 0, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? hv_fetch_ent((HV *)SvRV(namesv), name, 0, 0) : NULL; 83 0 83
488 83 ▶ if (!he)
Branch: 1 branch
BranchTrueFalseTotal
if (!he) 2 81 83
489 2 croak("Punk: url_for: no route is named '%s' - a name is "
490 "declared with { name => '...' } on the route, and it is "
491 "one namespace for the whole application",
492 SvPV_nolen(name));
493 81 val = HeVAL(he);
494  
495 81 routersv = app_get(aTHX_ h, K_ROUTER);
496 81 ▶ if (!(routersv && SvROK(routersv)))
Branch: 2 branches
BranchTrueFalseTotal
if (!(routersv && SvROK(routersv))) 81 0 81
if (!(routersv && SvROK(routersv))) 0 81 81
497 0 croak("Punk: url_for: this application is not compiled");
498  
499 { /* prefix = the path on `host`, then SCRIPT_NAME */
500 81 SV *hp = app_get(aTHX_ h, K_HOST_PATH_C);
501 81 SV *envsv = pcx_get(aTHX_ av, PCX_ENV);
502 81 ▶ SV **sn = (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
SV **sn = (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 81 0 81
SV **sn = (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 81 0 81
503 162 ▶ ? hv_fetchs((HV *)SvRV(envsv), "SCRIPT_NAME", 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? hv_fetchs((HV *)SvRV(envsv), "SCRIPT_NAME", 0) : NULL; 81 0 81
504 81 ▶ int have_hp = (hp && SvOK(hp) && SvCUR(hp));
Branch: 3 branches
BranchTrueFalseTotal
int have_hp = (hp && SvOK(hp) && SvCUR(hp)); 3 78 81
int have_hp = (hp && SvOK(hp) && SvCUR(hp)); 3 0 3
int have_hp = (hp && SvOK(hp) && SvCUR(hp)); 3 0 3
505 81 ▶ int have_sn = (sn && *sn && SvOK(*sn) && SvCUR(*sn));
Branch: 4 branches
BranchTrueFalseTotal
int have_sn = (sn && *sn && SvOK(*sn) && SvCUR(*sn)); 4 77 81
int have_sn = (sn && *sn && SvOK(*sn) && SvCUR(*sn)); 4 0 4
int have_sn = (sn && *sn && SvOK(*sn) && SvCUR(*sn)); 4 0 4
int have_sn = (sn && *sn && SvOK(*sn) && SvCUR(*sn)); 4 0 4
506 81 ▶ if (have_hp || have_sn) {
Branch: 2 branches
BranchTrueFalseTotal
if (have_hp || have_sn) { 78 3 81
if (have_hp || have_sn) { 3 75 78
507 6 prefix = sv_2mortal(newSVpvs(""));
508 6 ▶ if (have_hp) sv_catsv(prefix, hp);
Branch: 1 branch
BranchTrueFalseTotal
if (have_hp) sv_catsv(prefix, hp); 3 3 6
509 6 ▶ if (have_sn) sv_catsv(prefix, *sn);
Branch: 1 branch
BranchTrueFalseTotal
if (have_sn) sv_catsv(prefix, *sn); 4 2 6
510 }
511 }
512  
513 81 ▶ if (absolute) {
Branch: 1 branch
BranchTrueFalseTotal
if (absolute) { 8 73 81
514 8 int st = 0;
515 8 origin = pk_origin_of(aTHX_ self, &st);
516 8 ▶ if (!origin)
Branch: 1 branch
BranchTrueFalseTotal
if (!origin) 1 7 8
517 1 croak("Punk: url_for('%s', absolute => 1): the application "
518 "declared no `host`, and the request's Host is not "
519 "something a link may be built on - declare "
520 "host 'https://example.com'", SvPV_nolen(name));
521 7 sv_2mortal(origin);
522 }
523  
524 /* A route's entry is a record index; an API operation's is a
525 * reference to [ mount prefix, parsed template ]. One table, two
526 * kinds of route, and the shape says which. */
527 91 ▶ if (SvROK(val) && SvTYPE(SvRV(val)) == SVt_PVAV) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(val) && SvTYPE(SvRV(val)) == SVt_PVAV) { 13 67 80
if (SvROK(val) && SvTYPE(SvRV(val)) == SVt_PVAV) { 13 0 13
528 13 AV *pair = (AV *)SvRV(val);
529 13 SV **mp = av_fetch(pair, 0, 0);
530 13 SV **tm = av_fetch(pair, 1, 0);
531 13 RETVAL = pk_url_build_op(aTHX_
532 26 ▶ (AV *)SvRV(*tm), (mp && *mp) ? *mp : NULL,
Branch: 1 branch
BranchTrueFalseTotal
(AV *)SvRV(*tm), (mp && *mp) ? *mp : NULL, 13 0 13
533 13 ▶ args, query, prefix, origin, SvPV_nolen(name));
Branch: 1 branch
BranchTrueFalseTotal
args, query, prefix, origin, SvPV_nolen(name)); 13 0 13
534 }
535 else
536 67 RETVAL = pk_url_build(aTHX_ punk_router_of(aTHX_ routersv),
537 SvIV(val), args, query, prefix, origin,
538 67 SvPV_nolen(name));
539 }
540 OUTPUT:
541 RETVAL
542  
543 # $c->host_allowed - true when the request's Host is one the application
544 # declared: the canonical host, or a match on the allowlist. The signal an
545 # application needs to refuse an unknown host rather than answer for it.
546 IV
547 host_allowed(self)
548 SV *self
549 CODE:
550 {
551 20 int st = 0;
552 20 SV *o = pk_origin_of(aTHX_ self, &st);
553 20 ▶ if (o) SvREFCNT_dec(o);
Branch: 1 branch
BranchTrueFalseTotal
if (o) SvREFCNT_dec(o); 19 1 20
554 20 ▶ RETVAL = st > 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = st > 0 ? 1 : 0; 17 3 20
555 }
556 OUTPUT:
557 RETVAL
558  
559 # $c->asset('/static/app.css') - the content-addressed URL for a file under
560 # a static mount: '/static/app.9f3a1c2b0d4e5f60.css', which serves with a
561 # year and `immutable` because that URL cannot come to mean anything else.
562 # A URL under no static mount, under one with fingerprinting off, or naming
563 # a file that cannot be read comes back exactly as it went in - the page
564 # still works, it just revalidates.
565 SV *
566 asset(self, url)
567 SV *self
568 SV *url
569 CODE:
570 {
571 9 AV *av = pcx_av(aTHX_ self);
572 9 SV *app = pcx_get(aTHX_ av, PCX_APP);
573 9 SV *out = NULL;
574 9 ▶ if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) {
Branch: 3 branches
BranchTrueFalseTotal
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) { 9 0 9
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) { 9 0 9
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) { 9 0 9
575 9 SV *mp = app_get(aTHX_ (HV *)SvRV(app), K_MOUNTS_C);
576 9 ▶ if (mp && SvROK(mp) && SvTYPE(SvRV(mp)) == SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (mp && SvROK(mp) && SvTYPE(SvRV(mp)) == SVt_PVAV) 9 0 9
if (mp && SvROK(mp) && SvTYPE(SvRV(mp)) == SVt_PVAV) 9 0 9
if (mp && SvROK(mp) && SvTYPE(SvRV(mp)) == SVt_PVAV) 9 0 9
577 9 out = pa_asset_for(aTHX_ (AV *)SvRV(mp), url);
578 }
579 9 ▶ RETVAL = out ? out : newSVsv(url);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = out ? out : newSVsv(url); 5 4 9
580 }
581 OUTPUT:
582 RETVAL
583  
584 # $c->escape_html($text) - the five HTML characters escaped (punk_escape.h),
585 # the escape Punk writes its own markup with; the empty string for an
586 # undefined value, the UTF-8 flag kept.
587 SV *
588 escape_html(self, text)
589 SV *self
590 SV *text
591 CODE:
592 {
593 STRLEN len;
594 const char *p;
595 PERL_UNUSED_VAR(self);
596 13 RETVAL = newSVpvs("");
597 13 ▶ if (SvOK(text)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(text)) { 12 1 13
598 12 p = SvPV_const(text, len);
599 12 ▶ SvGROW(RETVAL, len + 1);
Branch: 2 branches
BranchTrueFalseTotal
SvGROW(RETVAL, len + 1); 12 0 12
SvGROW(RETVAL, len + 1); 3 9 12
600 12 punk_html_escape(aTHX_ RETVAL, p, len);
601 12 ▶ if (SvUTF8(text)) SvUTF8_on(RETVAL);
Branch: 1 branch
BranchTrueFalseTotal
if (SvUTF8(text)) SvUTF8_on(RETVAL); 1 11 12
602 }
603 }
604 OUTPUT:
605 RETVAL
606  
607 SV *
608 redirect(self, url, status = &PL_sv_undef)
609 SV *self
610 SV *url
611 SV *status
612 CODE:
613 {
614 24 AV *av = pcx_av(aTHX_ self);
615 24 AV *res = pcx_res_av(aTHX_ av);
616 24 ▶ AV *rh = res ? pcx_res_headers(aTHX_ res) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
AV *rh = res ? pcx_res_headers(aTHX_ res) : NULL; 0 24 24
617 24 AV *hdr = newAV();
618 24 AV *body = newAV();
619 24 AV *resp = newAV();
620 24 IV st = ps_status_arg(aTHX_ status);
621 { /* a Location is one header line: a CR, LF or NUL in a URL built
622 * from the request would end it and start another */
623 STRLEN ul, ui;
624 46 ▶ const char *up = SvOK(url) ? SvPV_const(url, ul) : "";
Branch: 1 branch
BranchTrueFalseTotal
const char *up = SvOK(url) ? SvPV_const(url, ul) : ""; 23 0 23
625 23 ▶ if (!SvOK(url)) ul = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(url)) ul = 0; 0 23 23
626 123 ▶ for (ui = 0; ui < ul; ui++)
Branch: 1 branch
BranchTrueFalseTotal
for (ui = 0; ui < ul; ui++) 104 19 123
627 104 ▶ if (up[ui] == '\r' || up[ui] == '\n' || up[ui] == '\0')
Branch: 3 branches
BranchTrueFalseTotal
if (up[ui] == '\r' || up[ui] == '\n' || up[ui] == '\0') 102 2 104
if (up[ui] == '\r' || up[ui] == '\n' || up[ui] == '\0') 101 1 102
if (up[ui] == '\r' || up[ui] == '\n' || up[ui] == '\0') 1 100 101
628 4 croak("Punk: a redirect location may not contain CR, LF "
629 "or NUL");
630 }
631 19 ▶ if (!st) st = 302;
Branch: 1 branch
BranchTrueFalseTotal
if (!st) st = 302; 18 1 19
632 19 av_push(hdr, newSVpvs("Location"));
633 19 av_push(hdr, newSVsv(url));
634 19 av_push(hdr, newSVpvs("Content-Length"));
635 19 av_push(hdr, newSViv(0));
636 19 ▶ if (rh) {
Branch: 1 branch
BranchTrueFalseTotal
if (rh) { 0 19 19
637 0 SSize_t i, n = av_len(rh) + 1;
638 0 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 0 0 0
639 0 SV **e = av_fetch(rh, i, 0);
640 0 ▶ av_push(hdr, e && *e ? newSVsv(*e) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(hdr, e && *e ? newSVsv(*e) : newSV(0)); 0 0 0
av_push(hdr, e && *e ? newSVsv(*e) : newSV(0)); 0 0 0
641 }
642 }
643 19 av_push(body, newSVpvs(""));
644 19 av_extend(resp, 2);
645 19 av_push(resp, newSViv(st));
646 19 av_push(resp, newRV_noinc((SV *)hdr));
647 19 av_push(resp, newRV_noinc((SV *)body));
648 19 RETVAL = newRV_noinc((SV *)resp);
649 }
650 OUTPUT:
651 RETVAL
652  
653 SV *
654 not_found(self)
655 SV *self
656 CODE:
657 PERL_UNUSED_VAR(self);
658 7 RETVAL = punk_triplet(aTHX_ 404,
659 sv_2mortal(newSVpvs("application/json")),
660 newSVpvs("{\"errors\":[{\"message\":\"Not Found\"}]}"),
661 NULL);
662 OUTPUT:
663 RETVAL
664  
665 # respond_to(json => sub {...}, html => sub {...}, any => sub {...}):
666 # Accept negotiation (punk_accept.h). The most acceptable offered format's
667 # coderef is called with $c and its return is the response; `any` catches a
668 # request nothing else fits, and without it that request is a 406. A client
669 # that is indifferent (no Accept, or only a wildcard match) gets the format
670 # its own Content-Type names if that is offered, else the first registered.
671 # Every outcome carries Vary: Accept.
672 SV *
673 respond_to(self, ...)
674 SV *self
675 CODE:
676 {
677 #define PRT_MAX 16
678 28 AV *av = pcx_av(aTHX_ self);
679 SV *cbs[PRT_MAX];
680 const char *bt[PRT_MAX], *bs[PRT_MAX];
681 STRLEN btl[PRT_MAX], bsl[PRT_MAX];
682 int bq[PRT_MAX], bspec[PRT_MAX];
683 28 SV *any_cb = NULL, *accept_sv = NULL, *ctype_sv = NULL;
684 pa_range ranges[PA_RANGE_MAX];
685 28 int nb = 0, nr = 0, have_accept = 0, i;
686 28 int best = -1, best_q = 0, best_spec = -1, best_order = 0;
687  
688 28 ▶ if (items < 3 || !(items % 2))
Branch: 2 branches
BranchTrueFalseTotal
if (items < 3 || !(items % 2)) 27 1 28
if (items < 3 || !(items % 2)) 1 26 27
689 2 croak("Punk: respond_to takes format => coderef pairs");
690 87 ▶ for (i = 1; i + 1 < items; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i + 1 < items; i += 2) { 64 23 87
691 64 STRLEN nl; const char *nm = SvPV_const(ST(i), nl);
692 64 SV *cb = ST(i + 1);
693 64 ▶ if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 63 1 64
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 0 63 63
694 1 croak("Punk: respond_to format '%.*s' needs a coderef",
695 (int)nl, nm);
696 63 ▶ if (nl == 3 && memEQ(nm, "any", 3)) { any_cb = cb; continue; }
Branch: 2 branches
BranchTrueFalseTotal
if (nl == 3 && memEQ(nm, "any", 3)) { any_cb = cb; continue; } 8 55 63
if (nl == 3 && memEQ(nm, "any", 3)) { any_cb = cb; continue; } 1 7 8
697 62 ▶ if (nb >= PRT_MAX)
Branch: 1 branch
BranchTrueFalseTotal
if (nb >= PRT_MAX) 1 61 62
698 1 croak("Punk: respond_to takes at most %d formats", PRT_MAX);
699 61 ▶ if (!pa_fmt_mime(nm, nl, &bt[nb], &btl[nb], &bs[nb], &bsl[nb]))
Branch: 1 branch
BranchTrueFalseTotal
if (!pa_fmt_mime(nm, nl, &bt[nb], &btl[nb], &bs[nb], &bsl[nb])) 1 60 61
700 1 croak("Punk: respond_to does not know format '%.*s' - "
701 "name a full media type", (int)nl, nm);
702 60 cbs[nb] = cb;
703 60 nb++;
704 }
705  
706 { /* the request's Accept and Content-Type, straight off the env */
707 23 SV *env = pcx_get(aTHX_ av, PCX_ENV);
708 23 ▶ if (env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV) {
Branch: 3 branches
BranchTrueFalseTotal
if (env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV) { 23 0 23
if (env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV) { 23 0 23
if (env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV) { 23 0 23
709 23 HV *eh = (HV *)SvRV(env);
710 23 SV **e = hv_fetchs(eh, "HTTP_ACCEPT", 0);
711 23 ▶ if (e && *e && SvOK(*e) && SvCUR(*e)) accept_sv = *e;
Branch: 4 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e) && SvCUR(*e)) accept_sv = *e; 22 1 23
if (e && *e && SvOK(*e) && SvCUR(*e)) accept_sv = *e; 22 0 22
if (e && *e && SvOK(*e) && SvCUR(*e)) accept_sv = *e; 22 0 22
if (e && *e && SvOK(*e) && SvCUR(*e)) accept_sv = *e; 22 0 22
712 23 e = hv_fetchs(eh, "CONTENT_TYPE", 0);
713 23 ▶ if (e && *e && SvOK(*e) && SvCUR(*e)) ctype_sv = *e;
Branch: 4 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e) && SvCUR(*e)) ctype_sv = *e; 4 19 23
if (e && *e && SvOK(*e) && SvCUR(*e)) ctype_sv = *e; 4 0 4
if (e && *e && SvOK(*e) && SvCUR(*e)) ctype_sv = *e; 4 0 4
if (e && *e && SvOK(*e) && SvCUR(*e)) ctype_sv = *e; 1 3 4
714 }
715 }
716 23 ▶ if (accept_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (accept_sv) { 22 1 23
717 22 STRLEN al; const char *a = SvPV_const(accept_sv, al);
718 22 nr = pa_parse(a, al, ranges, PA_RANGE_MAX);
719 /* unparseable garbage is indifference, not an error */
720 22 have_accept = nr > 0;
721 }
722  
723 67 ▶ for (i = 0; i < nb; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nb; i++) { 44 23 67
724 44 int q = 1000, order = 0, spec = 0;
725 44 ▶ if (have_accept) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_accept) { 42 2 44
726 42 spec = pa_match(aTHX_ ranges, nr, bt[i], btl[i],
727 bs[i], bsl[i], &q, &order);
728 42 ▶ if (spec < 0 || q <= 0) { bq[i] = -1; bspec[i] = -1; continue; }
Branch: 2 branches
BranchTrueFalseTotal
if (spec < 0 || q <= 0) { bq[i] = -1; bspec[i] = -1; continue; } 26 16 42
if (spec < 0 || q <= 0) { bq[i] = -1; bspec[i] = -1; continue; } 1 25 26
729 }
730 27 bq[i] = q; bspec[i] = spec;
731 27 ▶ if (best < 0
Branch: 1 branch
BranchTrueFalseTotal
if (best < 0 6 21 27
732 6 ▶ || q > best_q
Branch: 1 branch
BranchTrueFalseTotal
|| q > best_q 4 2 6
733 4 ▶ || (q == best_q && spec > best_spec)
Branch: 2 branches
BranchTrueFalseTotal
|| (q == best_q && spec > best_spec) 3 1 4
|| (q == best_q && spec > best_spec) 3 0 3
734 4 ▶ || (q == best_q && spec == best_spec && order < best_order)) {
Branch: 3 branches
BranchTrueFalseTotal
|| (q == best_q && spec == best_spec && order < best_order)) { 3 1 4
|| (q == best_q && spec == best_spec && order < best_order)) { 3 0 3
|| (q == best_q && spec == best_spec && order < best_order)) { 0 3 3
735 23 best = i; best_q = q; best_spec = spec; best_order = order;
736 }
737 }
738  
739 /* An indifferent client (wildcard or no Accept) that itself sent one
740 * of the offered types wants that type back - a JSON POST from curl
741 * with no Accept should not be answered in HTML. Only a branch as
742 * acceptable as the provisional winner may take over. */
743 23 ▶ if (best >= 0 && best_spec == 0 && ctype_sv) {
Branch: 3 branches
BranchTrueFalseTotal
if (best >= 0 && best_spec == 0 && ctype_sv) { 21 2 23
if (best >= 0 && best_spec == 0 && ctype_sv) { 4 17 21
if (best >= 0 && best_spec == 0 && ctype_sv) { 1 3 4
744 1 STRLEN cl; const char *cs = SvPV_const(ctype_sv, cl);
745 1 const char *ce = (const char *)memchr(cs, ';', cl);
746 1 ▶ STRLEN ml = ce ? (STRLEN)(ce - cs) : cl;
Branch: 1 branch
BranchTrueFalseTotal
STRLEN ml = ce ? (STRLEN)(ce - cs) : cl; 0 1 1
747 1 const char *slash = (const char *)memchr(cs, '/', ml);
748 1 ▶ while (ml && pa_ws(cs[ml - 1])) ml--;
Branch: 2 branches
BranchTrueFalseTotal
while (ml && pa_ws(cs[ml - 1])) ml--; 1 0 1
while (ml && pa_ws(cs[ml - 1])) ml--; 0 1 1
749 1 ▶ if (slash && slash > cs) {
Branch: 2 branches
BranchTrueFalseTotal
if (slash && slash > cs) { 1 0 1
if (slash && slash > cs) { 1 0 1
750 1 STRLEN tl1 = (STRLEN)(slash - cs);
751 1 const char *s1 = slash + 1;
752 1 ▶ STRLEN sl1 = ml > tl1 ? ml - tl1 - 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
STRLEN sl1 = ml > tl1 ? ml - tl1 - 1 : 0; 1 0 1
753 2 ▶ for (i = 0; i < nb; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nb; i++) { 2 0 2
754 2 ▶ if (bq[i] == best_q
Branch: 1 branch
BranchTrueFalseTotal
if (bq[i] == best_q 2 0 2
755 2 ▶ && btl[i] == tl1 && foldEQ(bt[i], cs, (I32)tl1)
Branch: 2 branches
BranchTrueFalseTotal
&& btl[i] == tl1 && foldEQ(bt[i], cs, (I32)tl1) 1 1 2
&& btl[i] == tl1 && foldEQ(bt[i], cs, (I32)tl1) 1 0 1
756 1 ▶ && bsl[i] == sl1 && foldEQ(bs[i], s1, (I32)sl1)) {
Branch: 2 branches
BranchTrueFalseTotal
&& bsl[i] == sl1 && foldEQ(bs[i], s1, (I32)sl1)) { 1 0 1
&& bsl[i] == sl1 && foldEQ(bs[i], s1, (I32)sl1)) { 1 0 1
757 1 best = i;
758 1 break;
759 }
760 }
761 }
762 }
763  
764 { /* every outcome of a negotiation varies on Accept */
765 23 SV *res = pcx_force(aTHX_ av, PCX_RES, "Punk::Response", NULL);
766 23 AV *rav = pcx_res_av(aTHX_ av);
767 PERL_UNUSED_VAR(res);
768 23 ▶ if (rav) pa_vary_accept(aTHX_ punk_res_headers(aTHX_ rav));
Branch: 1 branch
BranchTrueFalseTotal
if (rav) pa_vary_accept(aTHX_ punk_res_headers(aTHX_ rav)); 23 0 23
769 }
770  
771 24 ▶ if (best < 0 && !any_cb) {
Branch: 2 branches
BranchTrueFalseTotal
if (best < 0 && !any_cb) { 2 21 23
if (best < 0 && !any_cb) { 1 1 2
772 1 AV *rav = pcx_res_av(aTHX_ av);
773 2 ▶ RETVAL = punk_triplet(aTHX_ 406,
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = punk_triplet(aTHX_ 406, 1 0 1
774 sv_2mortal(newSVpvs("application/json")),
775 newSVpvs("{\"errors\":[{\"message\":"
776 "\"Not Acceptable\"}]}"),
777 1 rav ? punk_res_headers(aTHX_ rav) : NULL);
778 }
779 else {
780 22 ▶ SV *cb = best >= 0 ? cbs[best] : any_cb;
Branch: 1 branch
BranchTrueFalseTotal
SV *cb = best >= 0 ? cbs[best] : any_cb; 21 1 22
781 22 dSP; int count;
782 22 ENTER; SAVETMPS;
783 22 ▶ PUSHMARK(SP); EXTEND(SP, 1); PUSHs(self); PUTBACK;
Branch: 2 branches
BranchTrueFalseTotal
PUSHMARK(SP); EXTEND(SP, 1); PUSHs(self); PUTBACK; 0 22 22
PUSHMARK(SP); EXTEND(SP, 1); PUSHs(self); PUTBACK; 0 22 22
784 22 count = call_sv(cb, G_SCALAR);
785 22 SPAGAIN;
786 22 ▶ RETVAL = count > 0 ? newSVsv(POPs) : newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = count > 0 ? newSVsv(POPs) : newSV(0); 22 0 22
787 22 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 22 0 22
788 }
789 #undef PRT_MAX
790 }
791 OUTPUT:
792 RETVAL
793  
794 # ---- pending response state --------------------------------------------------
795  
796 # no args -> the pending status (or undef); with args -> set it, chainable.
797 SV *
798 status(self, ...)
799 SV *self
800 CODE:
801 {
802 26 AV *av = pcx_av(aTHX_ self);
803 26 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 26 0 26
804 26 SV *sval = ST(1); /* capture before forcing/pushing */
805 26 (void)ps_status_arg(aTHX_ sval);
806 18 SV *res = pcx_force(aTHX_ av, PCX_RES, "Punk::Response", NULL);
807 18 (void)pcx_call_meth(aTHX_ res, "status", &sval, 1, 0);
808 18 RETVAL = newSVsv(self);
809 }
810 else {
811 0 AV *res = pcx_res_av(aTHX_ av);
812 0 IV st = pcx_res_status(aTHX_ res);
813 0 ▶ RETVAL = st ? newSViv(st) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = st ? newSViv(st) : &PL_sv_undef; 0 0 0
814 }
815 }
816 OUTPUT:
817 RETVAL
818  
819 # header($name) -> read; header(Name => $v, ...) / no args -> set, chainable.
820 SV *
821 header(self, ...)
822 SV *self
823 CODE:
824 {
825 57 AV *av = pcx_av(aTHX_ self);
826 57 ▶ int set = (items > 2 || items == 1);
Branch: 2 branches
BranchTrueFalseTotal
int set = (items > 2 || items == 1); 0 57 57
int set = (items > 2 || items == 1); 0 0 0
827 57 int nargs = items - 1, i;
828 SV **argv, *res, *r;
829 /* captured before the stack is reused, and in a mortal: the response
830 * croaks on a header it will not send, and this must go with it */
831 57 ▶ argv = (SV **)SvPVX(sv_2mortal(
Branch: 1 branch
BranchTrueFalseTotal
argv = (SV **)SvPVX(sv_2mortal( 57 0 57
832 newSV((nargs > 0 ? nargs : 1) * sizeof(SV *))));
833 171 ▶ for (i = 0; i < nargs; i++) argv[i] = ST(i + 1);
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nargs; i++) argv[i] = ST(i + 1); 114 57 171
834 57 res = pcx_force(aTHX_ av, PCX_RES, "Punk::Response", NULL);
835 57 r = pcx_call_meth(aTHX_ res, "header", argv, nargs, set ? 0 : 1);
836 52 ▶ if (set) RETVAL = newSVsv(self);
Branch: 1 branch
BranchTrueFalseTotal
if (set) RETVAL = newSVsv(self); 52 0 52
837 0 ▶ else RETVAL = r ? r : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
else RETVAL = r ? r : &PL_sv_undef; 0 0 0
838 }
839 OUTPUT:
840 RETVAL
841  
842 # cookie($name) reads (via the request); cookie($name => $value, %opts) sets a
843 # Set-Cookie on the response (undef value deletes). Set form chains. Options
844 # may also arrive as one trailing hashref, in either direction - which is how
845 # the read form takes any at all: cookie('theme', { signed => 1 }).
846 #
847 # `signed => 1` signs with the SESSION's machinery and the session's secret,
848 # deliberately: pk_session_sign/verify already exist, the verify is already
849 # constant-time, and if `secret` ever grows rotation (a list: newest signs,
850 # all verify) signed cookies inherit it by riding the same key path. Do not
851 # build a second HMAC or a second key schedule here.
852 SV *
853 cookie(self, ...)
854 SV *self
855 CODE:
856 {
857 42 AV *av = pcx_av(aTHX_ self);
858 25 ▶ int read_opts = items == 3 && SvROK(ST(2))
Branch: 1 branch
BranchTrueFalseTotal
int read_opts = items == 3 && SvROK(ST(2)) 12 13 25
859 67 ▶ && SvTYPE(SvRV(ST(2))) == SVt_PVHV;
Branch: 2 branches
BranchTrueFalseTotal
&& SvTYPE(SvRV(ST(2))) == SVt_PVHV; 25 17 42
&& SvTYPE(SvRV(ST(2))) == SVt_PVHV; 12 0 12
860 42 ▶ if (items <= 2 || read_opts) { /* read via the request */
Branch: 2 branches
BranchTrueFalseTotal
if (items <= 2 || read_opts) { /* read via the request */ 40 2 42
if (items <= 2 || read_opts) { /* read via the request */ 12 28 40
861 14 SV *req = pcx_force(aTHX_ av, PCX_REQ, "Punk::Request",
862 pcx_get(aTHX_ av, PCX_ENV));
863 SV *argv[1], *r;
864 14 ▶ argv[0] = items >= 2 ? ST(1) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
argv[0] = items >= 2 ? ST(1) : &PL_sv_undef; 14 0 14
865 14 r = pcx_call_meth(aTHX_ req, "cookie", argv, 1, 1);
866 14 ▶ if (read_opts && r && SvOK(r)) {
Branch: 3 branches
BranchTrueFalseTotal
if (read_opts && r && SvOK(r)) { 12 2 14
if (read_opts && r && SvOK(r)) { 12 0 12
if (read_opts && r && SvOK(r)) { 12 0 12
867 12 SV **sg = hv_fetchs((HV *)SvRV(ST(2)), "signed", 0);
868 12 ▶ if (sg && *sg && SvTRUE(*sg)) {
Branch: 3 branches
BranchTrueFalseTotal
if (sg && *sg && SvTRUE(*sg)) { 12 0 12
if (sg && *sg && SvTRUE(*sg)) { 12 0 12
if (sg && *sg && SvTRUE(*sg)) { 12 0 12
869 12 HV *scfg = ps_cfg(aTHX_ self);
870 12 STRLEN kl = 0;
871 12 const char *key = scfg
872 12 ▶ ? ps_cfg_str(aTHX_ scfg, "secret", "", &kl) : "";
Branch: 1 branch
BranchTrueFalseTotal
? ps_cfg_str(aTHX_ scfg, "secret", "", &kl) : ""; 11 1 12
873 STRLEN cl;
874 const char *cv2;
875 SV *payload;
876 12 ▶ if (!kl)
Branch: 1 branch
BranchTrueFalseTotal
if (!kl) 1 11 12
877 1 croak("Punk: signed cookies sign with the session's "
878 "secret - add `session secret => ...`");
879 11 cv2 = SvPV_const(r, cl);
880 11 payload = pk_session_verify(aTHX_ cv2, cl, key, kl);
881 11 SvREFCNT_dec(r);
882 11 r = NULL;
883 11 ▶ if (payload) {
Branch: 1 branch
BranchTrueFalseTotal
if (payload) { 7 4 11
884 /* The NAME is under the MAC. A signed value the
885 * client moved onto another cookie decodes to the
886 * wrong `name=` prefix and fails closed, like any
887 * other tamper - without this, any two signed
888 * cookies could be swapped for each other and both
889 * would verify. */
890 STRLEN pl, nl2;
891 7 const char *p = SvPV_const(payload, pl);
892 7 ▶ const char *n2 = SvPV_const(ST(1), nl2);
Branch: 1 branch
BranchTrueFalseTotal
const char *n2 = SvPV_const(ST(1), nl2); 7 0 7
893 7 ▶ if (pl > nl2 && memEQ(p, n2, nl2) && p[nl2] == '=')
Branch: 3 branches
BranchTrueFalseTotal
if (pl > nl2 && memEQ(p, n2, nl2) && p[nl2] == '=') 7 0 7
if (pl > nl2 && memEQ(p, n2, nl2) && p[nl2] == '=') 6 1 7
if (pl > nl2 && memEQ(p, n2, nl2) && p[nl2] == '=') 6 0 6
894 6 r = newSVpvn(p + nl2 + 1, pl - nl2 - 1);
895 7 SvREFCNT_dec(payload);
896 }
897 }
898 }
899 13 ▶ RETVAL = r ? r : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = r ? r : &PL_sv_undef; 8 5 13
900 }
901 else { /* set */
902 28 SV *name = ST(1), *value = ST(2), *ck, *res, *hargv[2], *r;
903 28 HV *opts = (HV *)sv_2mortal((SV *)newHV());
904 int i;
905 35 ▶ if (items == 4 && SvROK(ST(3)) && SvTYPE(SvRV(ST(3))) == SVt_PVHV) {
Branch: 3 branches
BranchTrueFalseTotal
if (items == 4 && SvROK(ST(3)) && SvTYPE(SvRV(ST(3))) == SVt_PVHV) { 7 21 28
if (items == 4 && SvROK(ST(3)) && SvTYPE(SvRV(ST(3))) == SVt_PVHV) { 7 0 7
if (items == 4 && SvROK(ST(3)) && SvTYPE(SvRV(ST(3))) == SVt_PVHV) { 7 0 7
906 7 HV *oh = (HV *)SvRV(ST(3));
907 HE *he;
908 7 hv_iterinit(oh);
909 17 ▶ while ((he = hv_iternext(oh)))
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(oh))) 10 7 17
910 10 ▶ (void)hv_store_ent(opts, HeSVKEY_force(he),
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_store_ent(opts, HeSVKEY_force(he), 10 0 10
(void)hv_store_ent(opts, HeSVKEY_force(he), 0 10 10
911 newSVsv(HeVAL(he)), 0);
912 }
913 else {
914 32 ▶ for (i = 3; i + 1 < items; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 3; i + 1 < items; i += 2) { 11 21 32
915 11 STRLEN kl; const char *k = SvPV_const(ST(i), kl);
916 11 (void)hv_store(opts, k, (I32)kl, newSVsv(ST(i + 1)), 0);
917 }
918 }
919 {
920 28 SV **sg = hv_fetchs(opts, "signed", 0);
921 28 ▶ if (sg && *sg && SvTRUE(*sg) && value && SvOK(value)) {
Branch: 5 branches
BranchTrueFalseTotal
if (sg && *sg && SvTRUE(*sg) && value && SvOK(value)) { 8 20 28
if (sg && *sg && SvTRUE(*sg) && value && SvOK(value)) { 8 0 8
if (sg && *sg && SvTRUE(*sg) && value && SvOK(value)) { 8 0 8
if (sg && *sg && SvTRUE(*sg) && value && SvOK(value)) { 8 0 8
if (sg && *sg && SvTRUE(*sg) && value && SvOK(value)) { 8 0 8
922 8 HV *scfg = ps_cfg(aTHX_ self);
923 8 STRLEN kl = 0;
924 8 const char *key = scfg
925 8 ▶ ? ps_cfg_str(aTHX_ scfg, "secret", "", &kl) : "";
Branch: 1 branch
BranchTrueFalseTotal
? ps_cfg_str(aTHX_ scfg, "secret", "", &kl) : ""; 7 1 8
926 SV *payload;
927 8 ▶ if (!kl)
Branch: 1 branch
BranchTrueFalseTotal
if (!kl) 1 7 8
928 1 croak("Punk: signed cookies sign with the session's "
929 "secret - add `session secret => ...`");
930 7 payload = sv_2mortal(newSVsv(name));
931 7 sv_catpvs(payload, "=");
932 7 sv_catsv(payload, value);
933 7 value = sv_2mortal(pk_session_sign(aTHX_ payload,
934 key, kl));
935 }
936 }
937 27 ck = sv_2mortal(pk_build_cookie(aTHX_ name, value, opts));
938 18 res = pcx_force(aTHX_ av, PCX_RES, "Punk::Response", NULL);
939 18 hargv[0] = sv_2mortal(newSVpvs("Set-Cookie"));
940 18 hargv[1] = ck;
941 18 r = pcx_call_meth(aTHX_ res, "header", hargv, 2, 0);
942 18 ▶ if (r) SvREFCNT_dec(r);
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); 0 18 18
943 18 RETVAL = newSVsv(self);
944 }
945 }
946 OUTPUT:
947 RETVAL
948  
949 # upload($name): the Punk::Upload for that multipart field, via the request.
950 SV *
951 upload(self, name)
952 SV *self
953 SV *name
954 CODE:
955 {
956 0 AV *av = pcx_av(aTHX_ self);
957 0 SV *req = pcx_force(aTHX_ av, PCX_REQ, "Punk::Request",
958 pcx_get(aTHX_ av, PCX_ENV));
959 SV *argv[1], *r;
960 0 argv[0] = name;
961 0 r = pcx_call_meth(aTHX_ req, "upload", argv, 1, 1);
962 0 ▶ RETVAL = r ? r : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = r ? r : &PL_sv_undef; 0 0 0
963 }
964 OUTPUT:
965 RETVAL
966  
967 # csrf_token: the live single-use token, minted into the session on first ask
968 # (which dirties the session, so the cookie follows). csrf_field is the hidden
969 # input a form needs, escaped and ready to drop into a template with `raw`.
970 SV *
971 csrf_token(self)
972 SV *self
973 ALIAS:
974 csrf_field = 1
975 CODE:
976 {
977 SV *tok;
978 20 ▶ if (!pcf_cfg(aTHX_ self))
Branch: 1 branch
BranchTrueFalseTotal
if (!pcf_cfg(aTHX_ self)) 0 20 20
979 0 croak("Punk: no csrf configured (add a `csrf` keyword)");
980 20 tok = pcf_token(aTHX_ self, 1);
981 20 ▶ if (!tok) { RETVAL = newSV(0); }
Branch: 1 branch
BranchTrueFalseTotal
if (!tok) { RETVAL = newSV(0); } 0 20 20
982 20 ▶ else if (!ix) { RETVAL = newSVsv(tok); }
Branch: 1 branch
BranchTrueFalseTotal
else if (!ix) { RETVAL = newSVsv(tok); } 16 4 20
983 else {
984 4 HV *cfg = pcf_cfg(aTHX_ self);
985 STRLEN fl;
986 4 const char *field = ps_cfg_str(aTHX_ cfg, "field", "_csrf", &fl);
987 4 SV *out = newSVpvs("<input type=\"hidden\" name=\"");
988 4 pcf_attr_escape(aTHX_ out, field, fl);
989 4 sv_catpvs(out, "\" value=\"");
990 {
991 STRLEN tl;
992 4 const char *tv = SvPV_const(tok, tl);
993 4 pcf_attr_escape(aTHX_ out, tv, tl);
994 }
995 4 sv_catpvs(out, "\">");
996 4 RETVAL = out;
997 }
998 }
999 OUTPUT:
1000 RETVAL
1001  
1002 # session: the signed cookie-backed hashref (loaded once, written back if
1003 # changed). session_expire logs out - empties it and deletes the cookie.
1004 SV *
1005 session(self)
1006 SV *self
1007 CODE:
1008 115 RETVAL = ps_load(aTHX_ self);
1009 OUTPUT:
1010 RETVAL
1011  
1012 SV *
1013 session_expire(self)
1014 SV *self
1015 CODE:
1016 {
1017 12 HV *stash = ps_stash(aTHX_ pcx_av(aTHX_ self));
1018 12 (void)hv_stores(stash, "punk.session", newRV_noinc((SV *)newHV()));
1019 12 (void)hv_stores(stash, "punk.session.expire", newSViv(1));
1020 12 RETVAL = newSVsv(self);
1021 }
1022 OUTPUT:
1023 RETVAL
1024  
1025 # session_rotate: keep the session, give it a new name.
1026 #
1027 # Call it at the privilege boundary - a login, an elevation - and nowhere else.
1028 # Session fixation is the attack: somebody plants a known id in a victim's
1029 # browser and waits for them to log in. If logging in writes the user into the
1030 # session the attacker planted, the attacker's id is now an authenticated
1031 # session. The cookie session is immune by accident, because its value changes
1032 # wholesale when its contents do. A stored session is not: the id survives the
1033 # login unless something changes it.
1034 #
1035 # $c->login calls it, because a login is that boundary by definition, and
1036 # that is the only automatic call. "Privilege changed" is application
1037 # knowledge, and every candidate for guessing it is wrong - rotating whenever
1038 # the session gains a key rotates on a shopping basket, rotating on every POST
1039 # is a store write per form submission, and watching for a key named `user_id`
1040 # is a convention nobody agreed to.
1041 SV *
1042 session_rotate(self)
1043 SV *self
1044 CODE:
1045 {
1046 8 AV *av = pcx_av(aTHX_ self);
1047 8 HV *stash = ps_stash(aTHX_ av);
1048 /* Load first: the contents have to survive the rotation, and a
1049 * handler that rotates before touching $c->session would otherwise
1050 * leave the write-back with no session to write. */
1051 8 SV *sess = ps_load(aTHX_ self);
1052 /* a new name, and a new CSRF token to go with it */
1053 8 ▶ if (sess && SvROK(sess) && SvTYPE(SvRV(sess)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (sess && SvROK(sess) && SvTYPE(SvRV(sess)) == SVt_PVHV) 8 0 8
if (sess && SvROK(sess) && SvTYPE(SvRV(sess)) == SVt_PVHV) 8 0 8
if (sess && SvROK(sess) && SvTYPE(SvRV(sess)) == SVt_PVHV) 8 0 8
1054 8 (void)hv_delete((HV *)SvRV(sess), "punk.csrf", 9, G_DISCARD);
1055 8 SvREFCNT_dec(sess);
1056 /* The old id to retire, or undef when this session is new, which
1057 * still marks the write-back as rotating so an unchanged session is
1058 * written under the new name. */
1059 8 ps_mark_rotate(aTHX_ self, ps_cfg(aTHX_ self), stash);
1060 8 RETVAL = newSVsv(self);
1061 }
1062 OUTPUT:
1063 RETVAL
1064  
1065 # flash: one-request messages over the session (punk_flash.h). Any flash call
1066 # rotates the inbound hash out of the session, so the consuming response's
1067 # cookie no longer carries it; writes fill a fresh outbound hash the NEXT
1068 # request will read. No args: the whole inbound hashref (the template
1069 # hand-off). One arg: one inbound value. Pairs: set outbound, chainable.
1070 SV *
1071 flash(self, ...)
1072 SV *self
1073 CODE:
1074 {
1075 38 ▶ if (items == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items == 1) { 3 35 38
1076 3 RETVAL = newRV_inc((SV *)pf_inbound(aTHX_ self));
1077 }
1078 35 ▶ else if (items == 2) {
Branch: 1 branch
BranchTrueFalseTotal
else if (items == 2) { 20 15 35
1079 20 HV *in = pf_inbound(aTHX_ self);
1080 20 HE *he = hv_fetch_ent(in, ST(1), 0, 0);
1081 20 ▶ RETVAL = he ? newSVsv(HeVAL(he)) : newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = he ? newSVsv(HeVAL(he)) : newSV(0); 13 7 20
1082 }
1083 15 ▶ else if ((items - 1) % 2) {
Branch: 1 branch
BranchTrueFalseTotal
else if ((items - 1) % 2) { 1 14 15
1084 1 croak("Punk: flash(key => value, ...) takes pairs");
1085 }
1086 else {
1087 I32 i;
1088 HV *out;
1089 14 (void)pf_inbound(aTHX_ self); /* rotate before writing */
1090 13 out = pf_outbound(aTHX_ self);
1091 31 ▶ for (i = 1; i + 1 < items; i += 2)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i + 1 < items; i += 2) 18 13 31
1092 18 (void)hv_store_ent(out, ST(i), newSVsv(ST(i + 1)), 0);
1093 13 RETVAL = newSVsv(self);
1094 }
1095 }
1096 OUTPUT:
1097 RETVAL
1098  
1099 # validate: collecting request validation, all in C (punk_validate.h, on
1100 # the JSON::Schema::Fast C ABI). With a schema, runs a validation and
1101 # returns the Punk::Validate::Result (also stashed at punk.validation).
1102 # With no arguments, the reader: the last Result this request produced -
1103 # a route-level validate ran before the handler, so this is how the
1104 # handler collects its outcome - or undef.
1105 SV *
1106 validate(self, schema = &PL_sv_undef, source = &PL_sv_undef)
1107 SV *self
1108 SV *schema
1109 SV *source
1110 CODE:
1111 {
1112 717 ▶ if (items == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items == 1) { 4 713 717
1113 4 HV *stash = ps_stash(aTHX_ pcx_av(aTHX_ self));
1114 4 SV **v = hv_fetchs(stash, "punk.validation", 0);
1115 4 ▶ RETVAL = (v && *v && SvOK(*v)) ? newSVsv(*v) : newSV(0);
Branch: 3 branches
BranchTrueFalseTotal
RETVAL = (v && *v && SvOK(*v)) ? newSVsv(*v) : newSV(0); 3 1 4
RETVAL = (v && *v && SvOK(*v)) ? newSVsv(*v) : newSV(0); 3 0 3
RETVAL = (v && *v && SvOK(*v)) ? newSVsv(*v) : newSV(0); 3 0 3
1116 }
1117 else {
1118 713 RETVAL = pv_validate(aTHX_ self, schema, source);
1119 }
1120 }
1121 OUTPUT:
1122 RETVAL
1123  
1124 # flash_keep: re-arm this request's inbound flash for one more request - the
1125 # redirect-through-a-redirect case. Chainable.
1126 SV *
1127 flash_keep(self)
1128 SV *self
1129 CODE:
1130 {
1131 1 HV *in = pf_inbound(aTHX_ self);
1132 1 HV *out = pf_outbound(aTHX_ self);
1133 HE *he;
1134 1 hv_iterinit(in);
1135 3 ▶ while ((he = hv_iternext(in))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(in))) { 2 1 3
1136 2 (void)hv_store_ent(out, hv_iterkeysv(he),
1137 newSVsv(HeVAL(he)), 0);
1138 }
1139 1 RETVAL = newSVsv(self);
1140 }
1141 OUTPUT:
1142 RETVAL
1143  
1144 # response state the finish path folds in without forcing a response object
1145 SV *
1146 _status(self)
1147 SV *self
1148 CODE:
1149 {
1150 2154 AV *res = pcx_res_av(aTHX_ pcx_av(aTHX_ self));
1151 2154 ▶ SV **e = res ? av_fetch(res, PS_STATUS, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV **e = res ? av_fetch(res, PS_STATUS, 0) : NULL; 2 2152 2154
1152 2154 ▶ RETVAL = (e && *e) ? newSVsv(*e) : &PL_sv_undef;
Branch: 2 branches
BranchTrueFalseTotal
RETVAL = (e && *e) ? newSVsv(*e) : &PL_sv_undef; 1 2153 2154
RETVAL = (e && *e) ? newSVsv(*e) : &PL_sv_undef; 1 0 1
1153 }
1154 OUTPUT:
1155 RETVAL
1156  
1157 SV *
1158 _headers(self)
1159 SV *self
1160 CODE:
1161 {
1162 2156 AV *res = pcx_res_av(aTHX_ pcx_av(aTHX_ self));
1163 2156 RETVAL = res ? newRV_inc((SV *)punk_res_headers(aTHX_ res))
1164 2156 ▶ : newRV_noinc((SV *)newAV());
Branch: 1 branch
BranchTrueFalseTotal
: newRV_noinc((SV *)newAV()); 2 2154 2156
1165 }
1166 OUTPUT:
1167 RETVAL
1168  
1169 # ---- abuse controls: Hyperman's v3 arena via the ABI (punk_hm) --------------
1170 #
1171 # These reach the shared denylist / rate counters Hyperman maps before it forks
1172 # its workers. They FAIL OPEN: with no Hyperman >= ABI v3 under us (plackup, an
1173 # older server) punk_hm() is NULL, block_ip is a no-op returning 0 and rate_hit
1174 # reports "allowed", so rate limiting is never the reason a request is refused.
1175  
1176 # $c->block_ip([$ip [, $ttl]]) / $c->unblock_ip([$ip])
1177 # Denylist (or lift) an IP at the edge; $ip defaults to this request's
1178 # REMOTE_ADDR, $ttl seconds (0 = permanent). Returns 1 if the edge arena is
1179 # present (the change took), else 0.
1180 IV
1181 block_ip(self, ...)
1182 SV *self
1183 ALIAS:
1184 unblock_ip = 1
1185 CODE:
1186 {
1187 7 const hm_abi *A = punk_hm(aTHX);
1188 7 const char *ip = NULL;
1189 7 HV *cenv = NULL;
1190 {
1191 7 AV *av = pcx_av(aTHX_ self);
1192 7 SV **e = av_fetch(av, PCX_ENV, 0);
1193 7 ▶ if (e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV)
Branch: 4 branches
BranchTrueFalseTotal
if (e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV) 7 0 7
if (e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV) 7 0 7
if (e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV) 7 0 7
if (e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV) 7 0 7
1194 7 cenv = (HV *)SvRV(*e);
1195 }
1196 7 ▶ if (items > 1 && SvOK(ST(1))) {
Branch: 2 branches
BranchTrueFalseTotal
if (items > 1 && SvOK(ST(1))) { 5 2 7
if (items > 1 && SvOK(ST(1))) { 5 0 5
1197 10 ip = SvPV_nolen(ST(1));
1198 2 ▶ } else if (cenv) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (cenv) { 2 0 2
1199 2 SV **r = hv_fetchs(cenv, "REMOTE_ADDR", 0);
1200 4 ▶ if (r && *r && SvOK(*r)) ip = SvPV_nolen(*r);
Branch: 3 branches
BranchTrueFalseTotal
if (r && *r && SvOK(*r)) ip = SvPV_nolen(*r); 2 0 2
if (r && *r && SvOK(*r)) ip = SvPV_nolen(*r); 2 0 2
if (r && *r && SvOK(*r)) ip = SvPV_nolen(*r); 2 0 2
1201 }
1202 /* Behind a proxy, banning the address the socket came from bans the
1203 * load balancer and takes the site down - and punk.peer_addr only
1204 * exists when a `proxy` policy resolved this request, so this cannot
1205 * fire on a directly-exposed app. Boot-time config cannot catch it;
1206 * a silent no-op would leave an operator believing they had banned
1207 * someone, which is worse than an error. */
1208 7 ▶ if (ix == 0 && cenv && ip && *ip) {
Branch: 4 branches
BranchTrueFalseTotal
if (ix == 0 && cenv && ip && *ip) { 5 2 7
if (ix == 0 && cenv && ip && *ip) { 5 0 5
if (ix == 0 && cenv && ip && *ip) { 5 0 5
if (ix == 0 && cenv && ip && *ip) { 5 0 5
1209 5 SV **pa = hv_fetchs(cenv, "punk.peer_addr", 0);
1210 5 ▶ if (pa && *pa && SvOK(*pa)) {
Branch: 3 branches
BranchTrueFalseTotal
if (pa && *pa && SvOK(*pa)) { 2 3 5
if (pa && *pa && SvOK(*pa)) { 2 0 2
if (pa && *pa && SvOK(*pa)) { 2 0 2
1211 STRLEN pl;
1212 2 const char *peer = SvPV_const(*pa, pl);
1213 2 ▶ if (pl && strlen(ip) == pl && memEQ(ip, peer, pl))
Branch: 3 branches
BranchTrueFalseTotal
if (pl && strlen(ip) == pl && memEQ(ip, peer, pl)) 2 0 2
if (pl && strlen(ip) == pl && memEQ(ip, peer, pl)) 1 1 2
if (pl && strlen(ip) == pl && memEQ(ip, peer, pl)) 1 0 1
1214 1 croak("Punk: block_ip would denylist %s, which is the "
1215 "reverse proxy this request came through, not a "
1216 "client - that would take the site down. Ban the "
1217 "client address ($c->req->address) instead", ip);
1218 }
1219 }
1220 6 ▶ if (!A || !A->deny_add || !ip || !*ip) {
Branch: 4 branches
BranchTrueFalseTotal
if (!A || !A->deny_add || !ip || !*ip) { 5 1 6
if (!A || !A->deny_add || !ip || !*ip) { 5 0 5
if (!A || !A->deny_add || !ip || !*ip) { 5 0 5
if (!A || !A->deny_add || !ip || !*ip) { 0 5 5
1221 1 RETVAL = 0;
1222 5 ▶ } else if (ix == 1) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (ix == 1) { 2 3 5
1223 2 A->deny_remove(ip);
1224 2 RETVAL = 1;
1225 } else {
1226 3 ▶ long ttl = (items > 2 && SvOK(ST(2))) ? (long)SvIV(ST(2)) : 0;
Branch: 2 branches
BranchTrueFalseTotal
long ttl = (items > 2 && SvOK(ST(2))) ? (long)SvIV(ST(2)) : 0; 1 2 3
long ttl = (items > 2 && SvOK(ST(2))) ? (long)SvIV(ST(2)) : 0; 1 0 1
1227 3 A->deny_add(ip, ttl);
1228 3 RETVAL = 1;
1229 }
1230 }
1231 OUTPUT:
1232 RETVAL
1233  
1234 # $c->rate_hit($key, $limit, $window) -> ($ok, $remaining, $reset)
1235 # Count one hit against the opaque $key under $limit per $window seconds.
1236 # $limit <= 0 is unlimited. Fail-open with no arena: (1, $limit-1, next-window).
1237 void
1238 rate_hit(self, key, limit, window)
1239 SV *self
1240 SV *key
1241 IV limit
1242 IV window
1243 PPCODE:
1244 {
1245 4 const hm_abi *A = punk_hm(aTHX);
1246 STRLEN klen;
1247 4 const char *k = SvPV(key, klen);
1248 4 IV rem = 0, reset = 0;
1249 int ok;
1250 PERL_UNUSED_VAR(self);
1251 4 ▶ if (A && A->ratelimit_hit) {
Branch: 2 branches
BranchTrueFalseTotal
if (A && A->ratelimit_hit) { 3 1 4
if (A && A->ratelimit_hit) { 3 0 3
1252 3 ok = A->ratelimit_hit(k, klen, limit, window, &rem, &reset);
1253 } else {
1254 1 long now = (long)time(NULL);
1255 1 ▶ long w = window > 0 ? window : 60;
Branch: 1 branch
BranchTrueFalseTotal
long w = window > 0 ? window : 60; 1 0 1
1256 1 ok = 1;
1257 1 rem = limit > 0 ? limit - 1 : -1;
1258 1 reset = now - (now % w) + w;
1259 }
1260 4 ▶ XPUSHs(sv_2mortal(newSViv(ok)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSViv(ok))); 0 4 4
1261 4 ▶ XPUSHs(sv_2mortal(newSViv(rem)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSViv(rem))); 0 4 4
1262 4 ▶ XPUSHs(sv_2mortal(newSViv(reset)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSViv(reset))); 0 4 4
1263 }
1264  
1265 # ---- the cross-worker bus ---------------------------------------------------
1266  
1267 # publish($topic, $payload)
1268 #
1269 # 1 on the ring: every worker in the pool will see it
1270 # 0 local only - there is no pool (not under Hyperman, or a Hyperman
1271 # without the bus), so nobody else will
1272 # -1 refused: too big for a bus slot
1273 #
1274 # Three outcomes rather than true or false, because "the pool got it" and
1275 # "only I got it" are different facts, and an application that cannot tell
1276 # them apart cannot diagnose why the other workers stayed quiet.
1277 IV
1278 publish(self, topic, payload)
1279 SV *self
1280 SV *topic
1281 SV *payload
1282 CODE:
1283 PERL_UNUSED_VAR(self);
1284 0 ▶ RETVAL = punk_bus_app_publish(aTHX_ topic, payload);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = punk_bus_app_publish(aTHX_ topic, payload); 0 0 0
1285 OUTPUT:
1286 RETVAL
1287  
1288 # subscribe($topic, $cb, %opt)
1289 #
1290 # $cb is called as $cb->($topic, $payload) in this worker.
1291 #
1292 # `group => $name` is the only difference between the two delivery modes:
1293 # without it every worker's subscriber sees every message (what a fanout
1294 # wants), with it exactly one member of the named group sees each (work spread
1295 # across the pool, with no scheduler - a busy worker simply is not there to
1296 # claim).
1297 #
1298 # Register at BOOT, not per request. A subscription made inside a request
1299 # lands in one worker and lasts as long as that process, which is the same
1300 # class of mistake the bus exists to fix.
1301 IV
1302 subscribe(self, topic, cb, ...)
1303 SV *self
1304 SV *topic
1305 SV *cb
1306 CODE:
1307 {
1308 0 SV *group = &PL_sv_undef;
1309 int i;
1310 PERL_UNUSED_VAR(self);
1311 0 ▶ for (i = 3; i + 1 < items; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 3; i + 1 < items; i += 2) { 0 0 0
1312 0 const char *k = SvPV_nolen(ST(i));
1313 0 ▶ if (strEQ(k, "group")) group = ST(i + 1);
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(k, "group")) group = ST(i + 1); 0 0 0
1314 }
1315 0 ▶ RETVAL = punk_bus_app_subscribe(aTHX_ topic, cb, group);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = punk_bus_app_subscribe(aTHX_ topic, cb, group); 0 0 0
1316 }
1317 OUTPUT:
1318 RETVAL
1319  
1320 # $c->cache / $c->cache($name) - a cache store.
1321 #
1322 # Built once, at to_app, and shared by every request on this worker: a store
1323 # constructed per request would be a cache that never hits.
1324 #
1325 # Named stores exist because a session cache and a rendered-page cache want
1326 # different budgets and different lifetimes, and sharing one means the big
1327 # cold thing evicts the small hot thing.
1328 SV *
1329 cache(self, name = NULL)
1330 SV *self
1331 SV *name
1332 CODE:
1333 {
1334 10 AV *av = pcx_av(aTHX_ self);
1335 10 SV *app = pcx_get(aTHX_ av, PCX_APP);
1336 STRLEN nl;
1337 8 ▶ const char *n = (name && SvOK(name)) ? SvPV_const(name, nl)
Branch: 1 branch
BranchTrueFalseTotal
const char *n = (name && SvOK(name)) ? SvPV_const(name, nl) 4 0 4
1338 10 ▶ : (nl = sizeof(K_DEFAULT) - 1,
Branch: 1 branch
BranchTrueFalseTotal
: (nl = sizeof(K_DEFAULT) - 1, 4 6 10
1339 K_DEFAULT);
1340 10 SV **slot = NULL, **built = NULL;
1341 10 ▶ if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 10 0 10
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 10 0 10
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 10 0 10
1342 10 built = hv_fetchs((HV *)SvRV(app), "cache", 0);
1343 10 ▶ if (built && *built && SvROK(*built)
Branch: 3 branches
BranchTrueFalseTotal
if (built && *built && SvROK(*built) 9 1 10
if (built && *built && SvROK(*built) 9 0 9
if (built && *built && SvROK(*built) 9 0 9
1344 9 ▶ && SvTYPE(SvRV(*built)) == SVt_PVHV)
Branch: 1 branch
BranchTrueFalseTotal
&& SvTYPE(SvRV(*built)) == SVt_PVHV) 9 0 9
1345 9 slot = hv_fetch((HV *)SvRV(*built), n, (I32)nl, 0);
1346 10 ▶ if (!(slot && *slot && SvOK(*slot)))
Branch: 3 branches
BranchTrueFalseTotal
if (!(slot && *slot && SvOK(*slot))) 8 2 10
if (!(slot && *slot && SvOK(*slot))) 8 0 8
if (!(slot && *slot && SvOK(*slot))) 0 8 8
1347 2 croak("Punk: no cache named '%s' (add a `cache` keyword)", n);
1348 8 RETVAL = newSVsv(*slot);
1349 }
1350 OUTPUT:
1351 RETVAL
1352  
1353 # after_response($code): run $code once this response has been handed to the
1354 # server, off the request's own path. The queue is per request (PCX_AFTER_RES);
1355 # `hook after_response` is the application-wide half, and both are drained
1356 # together by punk_afterres.h. Chains.
1357 SV *
1358 after_response(self, code)
1359 SV *self
1360 SV *code
1361 CODE:
1362 {
1363 9 AV *av = pcx_av(aTHX_ self);
1364 SV *q;
1365 9 ▶ if (!(SvROK(code) && SvTYPE(SvRV(code)) == SVt_PVCV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(code) && SvTYPE(SvRV(code)) == SVt_PVCV)) 8 1 9
if (!(SvROK(code) && SvTYPE(SvRV(code)) == SVt_PVCV)) 0 8 8
1366 1 croak("Punk: after_response takes a code reference");
1367 8 q = pcx_get(aTHX_ av, PCX_AFTER_RES);
1368 8 ▶ if (!(q && SvROK(q) && SvTYPE(SvRV(q)) == SVt_PVAV)) {
Branch: 3 branches
BranchTrueFalseTotal
if (!(q && SvROK(q) && SvTYPE(SvRV(q)) == SVt_PVAV)) { 2 6 8
if (!(q && SvROK(q) && SvTYPE(SvRV(q)) == SVt_PVAV)) { 2 0 2
if (!(q && SvROK(q) && SvTYPE(SvRV(q)) == SVt_PVAV)) { 0 2 2
1369 6 q = newRV_noinc((SV *)newAV());
1370 6 ▶ if (!av_store(av, PCX_AFTER_RES, q)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!av_store(av, PCX_AFTER_RES, q)) { 0 6 6
1371 0 SvREFCNT_dec(q);
1372 0 croak("Punk: after_response could not queue");
1373 }
1374 }
1375 8 av_push((AV *)SvRV(q), newSVsv(code));
1376 8 RETVAL = newSVsv(self);
1377 }
1378 OUTPUT:
1379 RETVAL
« include/punk/punk_health.h ↑ Summary include/punk/punk_cget.h »