include/punk/punk_sendfile.h

filter: Statementstmt 97.7% 382 / 391 Branchbran 78.0% 398 / 510 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 86.5% 780 / 901 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/punk/punk_response.h ↑ Summary xs/log.xs »
1 /* punk_sendfile.h - $c->send_file: downloads with validators and ranges.
2 *
3 * One decision core (psf_respond) turns a source - a file path or an
4 * in-memory SV - plus the request's validator and Range headers into a
5 * finished PSGI triplet: 200, 206 with Content-Range, 304, or 416. A 206
6 * from a file rides Punk::SendFile::Reader, a bounded getline/close body,
7 * so the range is byte-correct on any PSGI server without trusting it to
8 * stop at Content-Length on a filehandle; a full-file 200 stays a real
9 * glob, the Punk::Static convention. The path is used as given - the
10 * traversal guard belongs to whoever built it out of untrusted input.
11 */
12  
13 #ifndef PUNK_SENDFILE_H
14 #define PUNK_SENDFILE_H
15  
16 /* ---- Range: bytes=first-last / bytes=-suffix ------------------------------
17 * Single range only. RFC 9110 lets a server ignore any Range header, so a
18 * multi-range set, another unit or a malformed value is IGNORE (the full
19 * 200); a syntactically valid range past the end is UNSAT (416). An
20 * invalid spec (last < first) makes the header invalid: IGNORE, per the
21 * RFC's "MUST ignore", not 416. */
22  
23 enum {
24 PSF_RANGE_NONE = 0, /* no Range header */
25 PSF_RANGE_OK = 1, /* one satisfiable range in *off / *n */
26 PSF_RANGE_UNSAT = 2, /* valid but unsatisfiable: 416 */
27 PSF_RANGE_IGNORE = 3 /* malformed or multi-range: full 200 */
28 };
29  
30 /* 1*DIGIT into a UV; 1 ok, 0 no digits, -1 overflow. */
31 76 static int psf_digits(const char **pp, const char *end, UV *out) {
32 76 const char *p = *pp;
33 76 UV acc = 0;
34 76 int any = 0;
35 224 ▶ while (p < end && *p >= '0' && *p <= '9') {
Branch: 3 branches
BranchTrueFalseTotal
while (p < end && *p >= '0' && *p <= '9') { 192 32 224
while (p < end && *p >= '0' && *p <= '9') { 151 41 192
while (p < end && *p >= '0' && *p <= '9') { 149 2 151
36 149 UV d = (UV)(*p - '0');
37 149 ▶ if (acc > (UV_MAX - d) / 10) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (acc > (UV_MAX - d) / 10) return -1; 1 148 149
38 148 acc = acc * 10 + d;
39 148 any = 1;
40 148 p++;
41 }
42 75 ▶ if (!any) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!any) return 0; 3 72 75
43 72 *pp = p;
44 72 *out = acc;
45 72 return 1;
46 }
47  
48 51 static int psf_parse_range(const char *v, STRLEN len, UV size,
49 UV *off, UV *n) {
50 51 const char *p = v, *end = v + len;
51 static const char unit[5] = { 'b','y','t','e','s' };
52 51 UV first = 0, last = 0;
53 51 int have_last = 0, i, r;
54  
55 52 ▶ while (p < end && (*p == ' ' || *p == '\t')) p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < end && (*p == ' ' || *p == '\t')) p++; 51 1 52
while (p < end && (*p == ' ' || *p == '\t')) p++; 1 50 51
while (p < end && (*p == ' ' || *p == '\t')) p++; 0 50 50
56 51 ▶ if (end - p < 6) return PSF_RANGE_IGNORE;
Branch: 1 branch
BranchTrueFalseTotal
if (end - p < 6) return PSF_RANGE_IGNORE; 1 50 51
57 290 ▶ for (i = 0; i < 5; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 5; i++) 242 48 290
58 242 ▶ if (toLOWER((U8)p[i]) != unit[i]) return PSF_RANGE_IGNORE;
Branch: 2 branches
BranchTrueFalseTotal
if (toLOWER((U8)p[i]) != unit[i]) return PSF_RANGE_IGNORE; 5 237 242
if (toLOWER((U8)p[i]) != unit[i]) return PSF_RANGE_IGNORE; 2 240 242
59 48 ▶ if (p[5] != '=') return PSF_RANGE_IGNORE;
Branch: 1 branch
BranchTrueFalseTotal
if (p[5] != '=') return PSF_RANGE_IGNORE; 1 47 48
60 47 p += 6;
61  
62 47 ▶ if (p < end && *p == '-') { /* suffix: -N */
Branch: 2 branches
BranchTrueFalseTotal
if (p < end && *p == '-') { /* suffix: -N */ 46 1 47
if (p < end && *p == '-') { /* suffix: -N */ 8 38 46
63 8 p++;
64 8 ▶ if (psf_digits(&p, end, &first) != 1) return PSF_RANGE_IGNORE;
Branch: 1 branch
BranchTrueFalseTotal
if (psf_digits(&p, end, &first) != 1) return PSF_RANGE_IGNORE; 1 7 8
65 7 ▶ while (p < end && (*p == ' ' || *p == '\t')) p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < end && (*p == ' ' || *p == '\t')) p++; 1 6 7
while (p < end && (*p == ' ' || *p == '\t')) p++; 0 1 1
while (p < end && (*p == ' ' || *p == '\t')) p++; 0 1 1
66 7 ▶ if (p != end) return PSF_RANGE_IGNORE; /* comma: multi-range */
Branch: 1 branch
BranchTrueFalseTotal
if (p != end) return PSF_RANGE_IGNORE; /* comma: multi-range */ 1 6 7
67 6 ▶ if (first == 0 || size == 0) return PSF_RANGE_UNSAT;
Branch: 2 branches
BranchTrueFalseTotal
if (first == 0 || size == 0) return PSF_RANGE_UNSAT; 5 1 6
if (first == 0 || size == 0) return PSF_RANGE_UNSAT; 1 4 5
68 4 ▶ if (first > size) first = size;
Branch: 1 branch
BranchTrueFalseTotal
if (first > size) first = size; 1 3 4
69 4 *off = size - first;
70 4 *n = first;
71 4 return PSF_RANGE_OK;
72 }
73  
74 39 r = psf_digits(&p, end, &first);
75 39 ▶ if (r != 1 || p >= end || *p != '-') return PSF_RANGE_IGNORE;
Branch: 3 branches
BranchTrueFalseTotal
if (r != 1 || p >= end || *p != '-') return PSF_RANGE_IGNORE; 36 3 39
if (r != 1 || p >= end || *p != '-') return PSF_RANGE_IGNORE; 36 0 36
if (r != 1 || p >= end || *p != '-') return PSF_RANGE_IGNORE; 0 36 36
76 36 p++;
77 36 ▶ if (p < end && *p >= '0' && *p <= '9') {
Branch: 3 branches
BranchTrueFalseTotal
if (p < end && *p >= '0' && *p <= '9') { 29 7 36
if (p < end && *p >= '0' && *p <= '9') { 29 0 29
if (p < end && *p >= '0' && *p <= '9') { 29 0 29
78 29 ▶ if (psf_digits(&p, end, &last) != 1) return PSF_RANGE_IGNORE;
Branch: 1 branch
BranchTrueFalseTotal
if (psf_digits(&p, end, &last) != 1) return PSF_RANGE_IGNORE; 0 29 29
79 29 have_last = 1;
80 }
81 37 ▶ while (p < end && (*p == ' ' || *p == '\t')) p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < end && (*p == ' ' || *p == '\t')) p++; 5 32 37
while (p < end && (*p == ' ' || *p == '\t')) p++; 1 4 5
while (p < end && (*p == ' ' || *p == '\t')) p++; 0 4 4
82 36 ▶ if (p != end) return PSF_RANGE_IGNORE; /* comma or junk */
Branch: 1 branch
BranchTrueFalseTotal
if (p != end) return PSF_RANGE_IGNORE; /* comma or junk */ 4 32 36
83 32 ▶ if (have_last && last < first) return PSF_RANGE_IGNORE;
Branch: 2 branches
BranchTrueFalseTotal
if (have_last && last < first) return PSF_RANGE_IGNORE; 25 7 32
if (have_last && last < first) return PSF_RANGE_IGNORE; 1 24 25
84 31 ▶ if (first >= size) return PSF_RANGE_UNSAT; /* covers size == 0 */
Branch: 1 branch
BranchTrueFalseTotal
if (first >= size) return PSF_RANGE_UNSAT; /* covers size == 0 */ 5 26 31
85 26 ▶ if (!have_last || last > size - 1) last = size - 1;
Branch: 2 branches
BranchTrueFalseTotal
if (!have_last || last > size - 1) last = size - 1; 23 3 26
if (!have_last || last > size - 1) last = size - 1; 1 22 23
86 26 *off = first;
87 26 *n = last - first + 1;
88 26 return PSF_RANGE_OK;
89 }
90  
91 /* ---- validators ------------------------------------------------------------
92 * The ETag is strong and nginx-shaped: "<hex mtime>-<hex size>", with the
93 * mtime's nanoseconds as a third field when the filesystem keeps them. Without
94 * that field a file rewritten in place to the same size inside one second
95 * keeps its tag, and If-None-Match answers 304 for bytes the client has never
96 * seen. */
97  
98 #define PSF_ETAG_MAX 64
99  
100 106 static void psf_etag(char *out, size_t outlen, UV mtime, UV ns, UV size) {
101 106 ▶ if (ns)
Branch: 1 branch
BranchTrueFalseTotal
if (ns) 82 24 106
102 82 my_snprintf(out, outlen, "\"%" UVxf "-%" UVxf "-%" UVxf "\"",
103 mtime, size, ns);
104 else
105 24 my_snprintf(out, outlen, "\"%" UVxf "-%" UVxf "\"", mtime, size);
106 106 }
107  
108 /* Is `etag` in a comma-separated entity-tag list (If-None-Match)? Weak
109 * comparison: a W/ prefix on a list entry is skipped. An entity-tag may
110 * legally contain a comma, but a split fragment of one can never carry
111 * both quotes, so it can never falsely equal our fully quoted tag. */
112 57 static int psf_etag_in(const char *h, STRLEN hlen,
113 const char *etag, STRLEN elen) {
114 57 const char *p = h, *end = h + hlen;
115 75 ▶ while (p < end) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < end) { 62 13 75
116 const char *e;
117 72 ▶ while (p < end && (*p == ' ' || *p == '\t' || *p == ',')) p++;
Branch: 4 branches
BranchTrueFalseTotal
while (p < end && (*p == ' ' || *p == '\t' || *p == ',')) p++; 72 0 72
while (p < end && (*p == ' ' || *p == '\t' || *p == ',')) p++; 5 67 72
while (p < end && (*p == ' ' || *p == '\t' || *p == ',')) p++; 0 67 67
while (p < end && (*p == ' ' || *p == '\t' || *p == ',')) p++; 5 62 67
118 62 ▶ if (p >= end) break;
Branch: 1 branch
BranchTrueFalseTotal
if (p >= end) break; 0 62 62
119 62 e = p;
120 894 ▶ while (e < end && *e != ',') e++;
Branch: 2 branches
BranchTrueFalseTotal
while (e < end && *e != ',') e++; 837 57 894
while (e < end && *e != ',') e++; 832 5 837
121 {
122 62 const char *q = e;
123 62 ▶ while (q > p && (q[-1] == ' ' || q[-1] == '\t')) q--;
Branch: 3 branches
BranchTrueFalseTotal
while (q > p && (q[-1] == ' ' || q[-1] == '\t')) q--; 62 0 62
while (q > p && (q[-1] == ' ' || q[-1] == '\t')) q--; 0 62 62
while (q > p && (q[-1] == ' ' || q[-1] == '\t')) q--; 0 62 62
124 62 ▶ if (q - p == 1 && *p == '*') return 1;
Branch: 2 branches
BranchTrueFalseTotal
if (q - p == 1 && *p == '*') return 1; 2 60 62
if (q - p == 1 && *p == '*') return 1; 2 0 2
125 60 ▶ if (q - p > 2 && p[0] == 'W' && p[1] == '/') p += 2;
Branch: 3 branches
BranchTrueFalseTotal
if (q - p > 2 && p[0] == 'W' && p[1] == '/') p += 2; 60 0 60
if (q - p > 2 && p[0] == 'W' && p[1] == '/') p += 2; 13 47 60
if (q - p > 2 && p[0] == 'W' && p[1] == '/') p += 2; 13 0 13
126 /* weak comparison both ways: our own tag may be a weak one */
127 60 ▶ if (elen > 2 && etag[0] == 'W' && etag[1] == '/') {
Branch: 3 branches
BranchTrueFalseTotal
if (elen > 2 && etag[0] == 'W' && etag[1] == '/') { 60 0 60
if (elen > 2 && etag[0] == 'W' && etag[1] == '/') { 5 55 60
if (elen > 2 && etag[0] == 'W' && etag[1] == '/') { 5 0 5
128 5 ▶ if ((STRLEN)(q - p) == elen - 2
Branch: 1 branch
BranchTrueFalseTotal
if ((STRLEN)(q - p) == elen - 2 4 1 5
129 4 ▶ && memEQ(p, etag + 2, elen - 2)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
&& memEQ(p, etag + 2, elen - 2)) return 1; 3 1 4
130 }
131 55 ▶ else if ((STRLEN)(q - p) == elen && memEQ(p, etag, elen)) return 1;
Branch: 2 branches
BranchTrueFalseTotal
else if ((STRLEN)(q - p) == elen && memEQ(p, etag, elen)) return 1; 43 12 55
else if ((STRLEN)(q - p) == elen && memEQ(p, etag, elen)) return 1; 39 4 43
132 }
133 18 p = e;
134 }
135 13 return 0;
136 }
137  
138 /* If-None-Match wins over If-Modified-Since (RFC 9110 13.1.3); the date
139 * comparison is the ps_serve_file convention - an exact match is all we
140 * need, the date they were given is the date we would send. */
141 267 static int psf_not_modified(pTHX_ HV *env, const char *etag, STRLEN elen,
142 const char *date) {
143 267 SV **e = hv_fetchs(env, "HTTP_IF_NONE_MATCH", 0);
144 267 ▶ if (e && *e && SvOK(*e)) {
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) { 62 205 267
if (e && *e && SvOK(*e)) { 62 0 62
if (e && *e && SvOK(*e)) { 62 0 62
145 STRLEN l, i;
146 62 const char *h = SvPV(*e, l);
147 /* an empty one is no condition at all, and must not switch off the
148 * date check the way a real one does */
149 66 ▶ for (i = 0; i < l && (h[i] == ' ' || h[i] == '\t'); i++) ;
Branch: 3 branches
BranchTrueFalseTotal
for (i = 0; i < l && (h[i] == ' ' || h[i] == '\t'); i++) ; 62 4 66
for (i = 0; i < l && (h[i] == ' ' || h[i] == '\t'); i++) ; 3 59 62
for (i = 0; i < l && (h[i] == ' ' || h[i] == '\t'); i++) ; 1 58 59
150 62 ▶ if (i < l) return etag ? psf_etag_in(h, l, etag, elen) : 0;
Branch: 2 branches
BranchTrueFalseTotal
if (i < l) return etag ? psf_etag_in(h, l, etag, elen) : 0; 58 4 62
if (i < l) return etag ? psf_etag_in(h, l, etag, elen) : 0; 57 1 58
151 }
152 209 e = hv_fetchs(env, "HTTP_IF_MODIFIED_SINCE", 0);
153 209 ▶ if (e && *e && SvOK(*e) && date)
Branch: 4 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e) && date) 13 196 209
if (e && *e && SvOK(*e) && date) 13 0 13
if (e && *e && SvOK(*e) && date) 13 0 13
if (e && *e && SvOK(*e) && date) 12 1 13
154 24 return strEQ(SvPV_nolen(*e), date);
155 197 return 0;
156 }
157  
158 /* If-Range: ranges stay honoured only on an exact validator match. A weak
159 * tag never matches (RFC 9110 13.1.5), a mismatch means the full 200. */
160 6 static int psf_if_range_ok(const char *h, STRLEN hlen,
161 const char *etag, STRLEN elen,
162 const char *date) {
163 6 const char *p = h, *end = h + hlen;
164 6 ▶ while (p < end && (*p == ' ' || *p == '\t')) p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < end && (*p == ' ' || *p == '\t')) p++; 6 0 6
while (p < end && (*p == ' ' || *p == '\t')) p++; 0 6 6
while (p < end && (*p == ' ' || *p == '\t')) p++; 0 6 6
165 6 ▶ while (end > p && (end[-1] == ' ' || end[-1] == '\t')) end--;
Branch: 3 branches
BranchTrueFalseTotal
while (end > p && (end[-1] == ' ' || end[-1] == '\t')) end--; 6 0 6
while (end > p && (end[-1] == ' ' || end[-1] == '\t')) end--; 0 6 6
while (end > p && (end[-1] == ' ' || end[-1] == '\t')) end--; 0 6 6
166 6 ▶ if (p >= end) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (p >= end) return 0; 0 6 6
167 6 ▶ if (end - p > 2 && p[0] == 'W' && p[1] == '/') return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (end - p > 2 && p[0] == 'W' && p[1] == '/') return 0; 6 0 6
if (end - p > 2 && p[0] == 'W' && p[1] == '/') return 0; 2 4 6
if (end - p > 2 && p[0] == 'W' && p[1] == '/') return 0; 2 0 2
168 4 ▶ if (*p == '"')
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '"') 3 1 4
169 3 ▶ return etag && (STRLEN)(end - p) == elen && memEQ(p, etag, elen);
Branch: 3 branches
BranchTrueFalseTotal
return etag && (STRLEN)(end - p) == elen && memEQ(p, etag, elen); 3 0 3
return etag && (STRLEN)(end - p) == elen && memEQ(p, etag, elen); 1 2 3
return etag && (STRLEN)(end - p) == elen && memEQ(p, etag, elen); 1 0 1
170 1 ▶ return date && (STRLEN)(end - p) == strlen(date)
Branch: 1 branch
BranchTrueFalseTotal
return date && (STRLEN)(end - p) == strlen(date) 1 0 1
171 2 ▶ && memEQ(p, date, (STRLEN)(end - p));
Branch: 2 branches
BranchTrueFalseTotal
&& memEQ(p, date, (STRLEN)(end - p)); 1 0 1
&& memEQ(p, date, (STRLEN)(end - p)); 1 0 1
172 }
173  
174 /* ---- Content-Disposition (RFC 6266 / RFC 5987) ---------------------------- */
175  
176 16 static SV *psf_disposition(pTHX_ SV *filename, int inline_) {
177 16 ▶ SV *out = newSVpv(inline_ ? "inline" : "attachment", 0);
Branch: 1 branch
BranchTrueFalseTotal
SV *out = newSVpv(inline_ ? "inline" : "attachment", 0); 3 13 16
178 16 ▶ if (filename && SvOK(filename)) {
Branch: 2 branches
BranchTrueFalseTotal
if (filename && SvOK(filename)) { 15 1 16
if (filename && SvOK(filename)) { 14 1 15
179 STRLEN flen, i;
180 14 const char *fn = SvPVutf8(filename, flen);
181 14 int ascii = 1;
182 93 ▶ for (i = 0; i < flen; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < flen; i++) { 81 12 93
183 81 U8 c = (U8)fn[i];
184 81 ▶ if (c < 0x20 || c > 0x7E) { ascii = 0; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (c < 0x20 || c > 0x7E) { ascii = 0; break; } 81 0 81
if (c < 0x20 || c > 0x7E) { ascii = 0; break; } 2 79 81
185 }
186 /* the plain parameter always: non-ASCII bytes degrade to '_' so
187 * a client that ignores filename* still gets a usable name */
188 14 sv_catpvs(out, "; filename=\"");
189 113 ▶ for (i = 0; i < flen; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < flen; i++) { 99 14 113
190 99 U8 c = (U8)fn[i];
191 99 ▶ if (c < 0x20 || c > 0x7E) sv_catpvs(out, "_");
Branch: 2 branches
BranchTrueFalseTotal
if (c < 0x20 || c > 0x7E) sv_catpvs(out, "_"); 99 0 99
if (c < 0x20 || c > 0x7E) sv_catpvs(out, "_"); 4 95 99
192 else {
193 95 ▶ if (c == '"' || c == '\\') sv_catpvs(out, "\\");
Branch: 2 branches
BranchTrueFalseTotal
if (c == '"' || c == '\\') sv_catpvs(out, "\\"); 93 2 95
if (c == '"' || c == '\\') sv_catpvs(out, "\\"); 0 93 93
194 95 sv_catpvn(out, &fn[i], 1);
195 }
196 }
197 14 sv_catpvs(out, "\"");
198 14 ▶ if (!ascii) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ascii) { 2 12 14
199 static const char hex[] = "0123456789ABCDEF";
200 2 sv_catpvs(out, "; filename*=UTF-8''");
201 24 ▶ for (i = 0; i < flen; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < flen; i++) { 22 2 24
202 22 U8 c = (U8)fn[i];
203 22 ▶ if (isALNUM(c) || (c && strchr("!#$&+-.^_`|~", c) != NULL))
Branch: 3 branches
BranchTrueFalseTotal
if (isALNUM(c) || (c && strchr("!#$&+-.^_`|~", c) != NULL)) 6 16 22
if (isALNUM(c) || (c && strchr("!#$&+-.^_`|~", c) != NULL)) 6 0 6
if (isALNUM(c) || (c && strchr("!#$&+-.^_`|~", c) != NULL)) 2 4 6
204 18 sv_catpvn(out, &fn[i], 1);
205 else {
206 char pct[3];
207 4 pct[0] = '%';
208 4 pct[1] = hex[c >> 4];
209 4 pct[2] = hex[c & 0xF];
210 4 sv_catpvn(out, pct, 3);
211 }
212 }
213 }
214 }
215 16 return out;
216 }
217  
218 /* ---- Punk::SendFile::Reader ------------------------------------------------
219 * The bounded body for a 206 from a file: getline yields 64KB chunks until
220 * `remaining` is spent, close closes the PerlIO. Satisfies the PSGI body
221 * protocol everywhere (Hyperman's hm_slurp_body takes the getline branch);
222 * fileno is the streaming seam - a server holding it plus the response's
223 * Content-Length (Hyperman's hm_bsrc_lift) sends the window straight from
224 * the fd at its current position and never calls getline. */
225  
226 typedef struct psf_reader {
227 PerlIO *fp;
228 UV remaining;
229 } psf_reader;
230  
231 #define PSF_READER_CHUNK 65536
232 #define PSF_READER_CLASS "Punk::SendFile::Reader"
233  
234 12 static int psf_reader_free(pTHX_ SV *sv, MAGIC *mg) {
235 12 psf_reader *r = (psf_reader *)mg->mg_ptr;
236 PERL_UNUSED_ARG(sv);
237 12 ▶ if (r) {
Branch: 1 branch
BranchTrueFalseTotal
if (r) { 12 0 12
238 12 ▶ if (r->fp) PerlIO_close(r->fp);
Branch: 1 branch
BranchTrueFalseTotal
if (r->fp) PerlIO_close(r->fp); 2 10 12
239 12 Safefree(r);
240 }
241 12 return 0;
242 }
243 static MGVTBL psf_reader_vtbl = { NULL, NULL, NULL, NULL, psf_reader_free,
244 NULL, NULL, NULL };
245  
246 12 static SV *psf_reader_new(pTHX_ PerlIO *fp, UV remaining) {
247 12 SV *obj = newSV(0);
248 SV *rv;
249 psf_reader *r;
250 12 Newxz(r, 1, psf_reader);
251 12 r->fp = fp;
252 12 r->remaining = remaining;
253 12 sv_magicext(obj, NULL, PERL_MAGIC_ext, &psf_reader_vtbl, (char *)r, 0);
254 12 rv = newRV_noinc(obj);
255 12 return sv_bless(rv, gv_stashpvs(PSF_READER_CLASS, GV_ADD));
256 }
257  
258 32 static psf_reader *psf_reader_of(pTHX_ SV *self) {
259 MAGIC *mg;
260 32 ▶ if (SvROK(self)
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(self) 32 0 32
261 32 ▶ && (mg = mg_findext(SvRV(self), PERL_MAGIC_ext, &psf_reader_vtbl)))
Branch: 1 branch
BranchTrueFalseTotal
&& (mg = mg_findext(SvRV(self), PERL_MAGIC_ext, &psf_reader_vtbl))) 32 0 32
262 32 return (psf_reader *)mg->mg_ptr;
263 0 croak(PSF_READER_CLASS ": not a reader");
264 return NULL; /* not reached */
265 }
266  
267 /* ---- the decision core ----------------------------------------------------- */
268  
269 typedef struct psf_src {
270 const char *path; /* file source when non-NULL ... */
271 STRLEN plen;
272 const char *bytes; /* ... else the in-memory source */
273 UV size;
274 UV mtime;
275 UV mns; /* its nanoseconds, 0 when unknown */
276 UV ctime; /* 0 when unknown */
277 int has_mtime; /* scalar sources only via the option */
278 /* The rest of the caller's stat, so the descriptor cache can tell
279 * "the same path" from "the same FILE" without a syscall of its own.
280 * has_id is 0 for a caller that did not stat (an in-memory source, or
281 * one that built psf_src by hand), and then the cache is not consulted -
282 * an unverifiable descriptor is worse than an open. */
283 UV dev, ino;
284 int has_id;
285 /* Set on the way out when the file opened was not the size the caller's
286 * stat said: a caller whose stat came from a cache retries with a fresh
287 * one rather than send a Content-Length the body will not match. */
288 int changed;
289 /* the validators already formatted for this stat (the file cache keeps
290 * them per entry), or NULL to format them here */
291 const char *etag_pre;
292 const char *date_pre;
293 } psf_src;
294  
295 /* The ETag and Last-Modified for the file pfc_stat just answered for: from
296 * its cache entry when that entry still holds them for this stat, formatted
297 * into the entry otherwise. Copied out, so the caller holds no pointer into
298 * the cache. Returns 0 when the cache is off or the path is not cached. */
299 99 static int psf_cached_validators(pTHX_ const char *path, STRLEN plen,
300 const Stat_t *st, char *etag, size_t etagl,
301 char *date, size_t datel) {
302 99 punk_filecache *c = &PFC_CACHE;
303 pfc_entry *e;
304 99 ▶ if (!pfc_enabled() || c->disabled || plen == 0 || plen >= PFC_KEY_MAX)
Branch: 4 branches
BranchTrueFalseTotal
if (!pfc_enabled() || c->disabled || plen == 0 || plen >= PFC_KEY_MAX) 99 0 99
if (!pfc_enabled() || c->disabled || plen == 0 || plen >= PFC_KEY_MAX) 99 0 99
if (!pfc_enabled() || c->disabled || plen == 0 || plen >= PFC_KEY_MAX) 99 0 99
if (!pfc_enabled() || c->disabled || plen == 0 || plen >= PFC_KEY_MAX) 0 99 99
305 0 return 0;
306 99 e = pfc_lookup(c, path, plen, pfc_hash(path, plen));
307 99 ▶ if (!e || !e->exists) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !e->exists) return 0; 99 0 99
if (!e || !e->exists) return 0; 0 99 99
308 99 ▶ if (!e->hdr_ok || !pfc_same(st, &e->st)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!e->hdr_ok || !pfc_same(st, &e->st)) { 60 39 99
if (!e->hdr_ok || !pfc_same(st, &e->st)) { 0 60 60
309 39 psf_etag(e->hdr_etag, sizeof e->hdr_etag, (UV)st->st_mtime,
310 39 PFC_MTIME_NS(*st), (UV)st->st_size);
311 39 ps_http_date(e->hdr_date, sizeof e->hdr_date, (time_t)st->st_mtime);
312 39 e->hdr_ok = 1;
313 }
314 99 my_strlcpy(etag, e->hdr_etag, etagl);
315 99 my_strlcpy(date, e->hdr_date, datel);
316 99 return 1;
317 }
318  
319 typedef struct psf_opts {
320 SV *type; /* Content-Type, or NULL to infer */
321 SV *filename; /* Content-Disposition filename */
322 int inline_; /* disposition token */
323 int has_disp; /* emit Content-Disposition at all */
324 int ranges; /* honour Range / advertise bytes */
325 SV *etag; /* override: bare, quoted, or a weak
326 W/"..."; or NULL */
327 SV *cache_control; /* freshness lifetime, or NULL */
328 AV *extra; /* $c->header pairs (borrowed), or NULL */
329 } psf_opts;
330  
331 846 static void psf_hdr(pTHX_ AV *h, const char *k, SV *v) {
332 846 av_push(h, newSVpv(k, 0));
333 846 av_push(h, v);
334 846 }
335  
336 177 static void psf_hdr_extra(pTHX_ AV *h, AV *extra) {
337 SSize_t i, n;
338 177 ▶ if (!extra) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!extra) return; 66 111 177
339 111 n = av_len(extra) + 1;
340 355 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 244 111 355
341 244 SV **e = av_fetch(extra, i, 0);
342 244 ▶ av_push(h, e && *e ? newSVsv(*e) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(h, e && *e ? newSVsv(*e) : newSV(0)); 244 0 244
av_push(h, e && *e ? newSVsv(*e) : newSV(0)); 244 0 244
343 }
344 }
345  
346 /* Cache-Control, when one was asked for. It goes on the 304 as well as the
347 * 200: a 304 that omits it leaves the stored response with the freshness
348 * lifetime it already had, which has just run out - so the next load
349 * revalidates again, and the header buys nothing after the first hit. */
350 175 static void psf_hdr_cc(pTHX_ AV *hdr, psf_opts *opt) {
351 175 ▶ if (opt->cache_control && SvOK(opt->cache_control))
Branch: 2 branches
BranchTrueFalseTotal
if (opt->cache_control && SvOK(opt->cache_control)) 19 156 175
if (opt->cache_control && SvOK(opt->cache_control)) 19 0 19
352 19 psf_hdr(aTHX_ hdr, "Cache-Control", newSVsv(opt->cache_control));
353 175 }
354  
355 176 static SV *psf_wrap(pTHX_ IV status, AV *hdr, SV *body) {
356 176 AV *resp = newAV();
357 176 AV *bodyav = NULL;
358 176 av_extend(resp, 2);
359 176 av_push(resp, newSViv(status));
360 176 av_push(resp, newRV_noinc((SV *)hdr));
361 176 ▶ if (body && SvROK(body)) { /* glob or reader */
Branch: 2 branches
BranchTrueFalseTotal
if (body && SvROK(body)) { /* glob or reader */ 146 30 176
if (body && SvROK(body)) { /* glob or reader */ 58 88 146
362 58 av_push(resp, body);
363 }
364 else {
365 118 bodyav = newAV();
366 118 ▶ av_push(bodyav, body ? body : newSVpvs(""));
Branch: 1 branch
BranchTrueFalseTotal
av_push(bodyav, body ? body : newSVpvs("")); 30 88 118
367 118 av_push(resp, newRV_noinc((SV *)bodyav));
368 }
369 176 return newRV_noinc((SV *)resp);
370 }
371  
372 /* The finished triplet (+1 owned), or NULL when a file source vanished
373 * between the caller's stat and the open here - the caller decides what
374 * its missing-file answer looks like. */
375 178 static SV *psf_respond(pTHX_ HV *env, psf_src *src, psf_opts *opt) {
376 char etagbuf[PSF_ETAG_MAX], date[64];
377 178 const char *etag = NULL, *ldate = NULL;
378 178 STRLEN elen = 0;
379 const char *method;
380 178 STRLEN mlen = 3;
381 178 int is_get = 0, is_head = 0;
382 178 int rstat = PSF_RANGE_NONE;
383 178 UV off = 0, n = 0;
384 SV **e;
385 SV *ct;
386 AV *hdr;
387  
388 /* validators */
389 210 ▶ if (opt->etag && SvOK(opt->etag)) {
Branch: 2 branches
BranchTrueFalseTotal
if (opt->etag && SvOK(opt->etag)) { 33 145 178
if (opt->etag && SvOK(opt->etag)) { 33 0 33
390 /* Any length: a SHA-256 in hex is the natural thing to pass and is
391 * 64 characters. Given already quoted, or as a weak tag, it goes out
392 * as it came; given bare it is quoted here. */
393 STRLEN ol;
394 33 const char *ov = SvPV(opt->etag, ol);
395 SV *tag;
396 33 ▶ if ((ol >= 2 && ov[0] == '"')
Branch: 2 branches
BranchTrueFalseTotal
if ((ol >= 2 && ov[0] == '"') 32 1 33
if ((ol >= 2 && ov[0] == '"') 20 12 32
397 21 ▶ || (ol >= 4 && ov[0] == 'W' && ov[1] == '/' && ov[2] == '"'))
Branch: 4 branches
BranchTrueFalseTotal
|| (ol >= 4 && ov[0] == 'W' && ov[1] == '/' && ov[2] == '"')) 18 3 21
|| (ol >= 4 && ov[0] == 'W' && ov[1] == '/' && ov[2] == '"')) 7 11 18
|| (ol >= 4 && ov[0] == 'W' && ov[1] == '/' && ov[2] == '"')) 7 0 7
|| (ol >= 4 && ov[0] == 'W' && ov[1] == '/' && ov[2] == '"')) 7 0 7
398 19 tag = newSVpvn(ov, ol);
399 else
400 14 tag = newSVpvf("\"%" SVf "\"", SVfARG(opt->etag));
401 33 sv_2mortal(tag);
402 33 etag = SvPV(tag, elen);
403 {
404 STRLEN i;
405 976 ▶ for (i = 0; i < elen; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < elen; i++) 944 32 976
406 944 ▶ if ((U8)etag[i] < 0x20 || (U8)etag[i] == 0x7f)
Branch: 2 branches
BranchTrueFalseTotal
if ((U8)etag[i] < 0x20 || (U8)etag[i] == 0x7f) 943 1 944
if ((U8)etag[i] < 0x20 || (U8)etag[i] == 0x7f) 0 943 943
407 1 croak("Punk::Context::send_file: etag may not contain "
408 "a control character");
409 }
410 }
411 145 ▶ else if (src->has_mtime) {
Branch: 1 branch
BranchTrueFalseTotal
else if (src->has_mtime) { 143 2 145
412 143 ▶ if (src->etag_pre) etag = src->etag_pre;
Branch: 1 branch
BranchTrueFalseTotal
if (src->etag_pre) etag = src->etag_pre; 88 55 143
413 else {
414 55 psf_etag(etagbuf, sizeof etagbuf, src->mtime, src->mns, src->size);
415 55 etag = etagbuf;
416 }
417 143 elen = strlen(etag);
418 }
419 177 ▶ if (src->has_mtime) {
Branch: 1 branch
BranchTrueFalseTotal
if (src->has_mtime) { 175 2 177
420 175 ▶ if (src->date_pre) ldate = src->date_pre;
Branch: 1 branch
BranchTrueFalseTotal
if (src->date_pre) ldate = src->date_pre; 88 87 175
421 else {
422 87 ps_http_date(date, sizeof date, (time_t)src->mtime);
423 87 ldate = date;
424 }
425 }
426  
427 177 e = hv_fetchs(env, "REQUEST_METHOD", 0);
428 354 ▶ method = (e && *e && SvOK(*e)) ? SvPV(*e, mlen) : "GET";
Branch: 3 branches
BranchTrueFalseTotal
method = (e && *e && SvOK(*e)) ? SvPV(*e, mlen) : "GET"; 177 0 177
method = (e && *e && SvOK(*e)) ? SvPV(*e, mlen) : "GET"; 177 0 177
method = (e && *e && SvOK(*e)) ? SvPV(*e, mlen) : "GET"; 177 0 177
429 177 ▶ if (mlen == 3 && memEQ(method, "GET", 3)) is_get = 1;
Branch: 2 branches
BranchTrueFalseTotal
if (mlen == 3 && memEQ(method, "GET", 3)) is_get = 1; 170 7 177
if (mlen == 3 && memEQ(method, "GET", 3)) is_get = 1; 170 0 170
430 7 ▶ else if (mlen == 4 && memEQ(method, "HEAD", 4)) is_head = 1;
Branch: 2 branches
BranchTrueFalseTotal
else if (mlen == 4 && memEQ(method, "HEAD", 4)) is_head = 1; 7 0 7
else if (mlen == 4 && memEQ(method, "HEAD", 4)) is_head = 1; 4 3 7
431  
432 /* 304: a validator match on GET/HEAD (RFC 9110 13.1.3) */
433 177 ▶ if ((is_get || is_head)
Branch: 2 branches
BranchTrueFalseTotal
if ((is_get || is_head) 7 170 177
if ((is_get || is_head) 4 3 7
434 174 ▶ && psf_not_modified(aTHX_ env, etag, elen, ldate)) {
Branch: 1 branch
BranchTrueFalseTotal
&& psf_not_modified(aTHX_ env, etag, elen, ldate)) { 24 150 174
435 24 hdr = newAV();
436 24 ▶ if (etag) psf_hdr(aTHX_ hdr, "ETag", newSVpv(etag, elen));
Branch: 1 branch
BranchTrueFalseTotal
if (etag) psf_hdr(aTHX_ hdr, "ETag", newSVpv(etag, elen)); 24 0 24
437 24 ▶ if (ldate) psf_hdr(aTHX_ hdr, "Last-Modified", newSVpv(ldate, 0));
Branch: 1 branch
BranchTrueFalseTotal
if (ldate) psf_hdr(aTHX_ hdr, "Last-Modified", newSVpv(ldate, 0)); 24 0 24
438 24 psf_hdr_cc(aTHX_ hdr, opt);
439 24 psf_hdr_extra(aTHX_ hdr, opt->extra);
440 24 return psf_wrap(aTHX_ 304, hdr, NULL);
441 }
442  
443 /* Range applies to GET alone (RFC 9110 14.2) */
444 153 ▶ if (is_get && opt->ranges) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_get && opt->ranges) { 146 7 153
if (is_get && opt->ranges) { 144 2 146
445 144 e = hv_fetchs(env, "HTTP_RANGE", 0);
446 144 ▶ if (e && *e && SvOK(*e)) {
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) { 22 122 144
if (e && *e && SvOK(*e)) { 22 0 22
if (e && *e && SvOK(*e)) { 22 0 22
447 STRLEN l;
448 22 const char *h = SvPV(*e, l);
449 22 rstat = psf_parse_range(h, l, src->size, &off, &n);
450 22 ▶ if (rstat == PSF_RANGE_OK || rstat == PSF_RANGE_UNSAT) {
Branch: 2 branches
BranchTrueFalseTotal
if (rstat == PSF_RANGE_OK || rstat == PSF_RANGE_UNSAT) { 5 17 22
if (rstat == PSF_RANGE_OK || rstat == PSF_RANGE_UNSAT) { 2 3 5
451 19 SV **ir = hv_fetchs(env, "HTTP_IF_RANGE", 0);
452 19 ▶ if (ir && *ir && SvOK(*ir)) {
Branch: 3 branches
BranchTrueFalseTotal
if (ir && *ir && SvOK(*ir)) { 6 13 19
if (ir && *ir && SvOK(*ir)) { 6 0 6
if (ir && *ir && SvOK(*ir)) { 6 0 6
453 STRLEN il;
454 6 const char *iv = SvPV(*ir, il);
455 6 ▶ if (!psf_if_range_ok(iv, il, etag, elen, ldate))
Branch: 1 branch
BranchTrueFalseTotal
if (!psf_if_range_ok(iv, il, etag, elen, ldate)) 4 2 6
456 4 rstat = PSF_RANGE_IGNORE;
457 }
458 }
459 }
460 }
461  
462 153 ▶ if (rstat == PSF_RANGE_UNSAT) {
Branch: 1 branch
BranchTrueFalseTotal
if (rstat == PSF_RANGE_UNSAT) { 2 151 153
463 2 SV *cr = newSVpvs("bytes */");
464 2 sv_catpvf(cr, "%" UVuf, src->size);
465 2 hdr = newAV();
466 2 psf_hdr(aTHX_ hdr, "Content-Range", cr);
467 2 psf_hdr(aTHX_ hdr, "Content-Length", newSViv(0));
468 2 ▶ if (opt->ranges) psf_hdr(aTHX_ hdr, "Accept-Ranges", newSVpvs("bytes"));
Branch: 1 branch
BranchTrueFalseTotal
if (opt->ranges) psf_hdr(aTHX_ hdr, "Accept-Ranges", newSVpvs("bytes")); 2 0 2
469 2 psf_hdr_extra(aTHX_ hdr, opt->extra);
470 2 return psf_wrap(aTHX_ 416, hdr, NULL);
471 }
472  
473 /* content type: the option, else the path's extension, else the
474 * filename option's extension, else octet-stream */
475 151 ▶ if (opt->type && SvOK(opt->type)) ct = newSVsv(opt->type);
Branch: 2 branches
BranchTrueFalseTotal
if (opt->type && SvOK(opt->type)) ct = newSVsv(opt->type); 24 127 151
if (opt->type && SvOK(opt->type)) ct = newSVsv(opt->type); 24 0 24
476 127 ▶ else if (src->path)
Branch: 1 branch
BranchTrueFalseTotal
else if (src->path) 125 2 127
477 125 ct = newSVpv(ps_content_type(src->path, src->plen), 0);
478 2 ▶ else if (opt->filename && SvOK(opt->filename)) {
Branch: 2 branches
BranchTrueFalseTotal
else if (opt->filename && SvOK(opt->filename)) { 0 2 2
else if (opt->filename && SvOK(opt->filename)) { 0 0 0
479 STRLEN fl;
480 0 const char *fn = SvPV(opt->filename, fl);
481 0 ct = newSVpv(ps_content_type(fn, fl), 0);
482 }
483 2 else ct = newSVpvs("application/octet-stream");
484  
485 {
486 151 int partial = (rstat == PSF_RANGE_OK);
487 151 ▶ UV bl = partial ? n : src->size;
Branch: 1 branch
BranchTrueFalseTotal
UV bl = partial ? n : src->size; 138 13 151
488 151 SV *body = NULL;
489  
490 151 hdr = newAV();
491 151 psf_hdr(aTHX_ hdr, "Content-Type", ct);
492 151 psf_hdr(aTHX_ hdr, "Content-Length", newSVuv(bl));
493 151 ▶ if (partial) {
Branch: 1 branch
BranchTrueFalseTotal
if (partial) { 13 138 151
494 13 SV *cr = newSVpvs("bytes ");
495 13 sv_catpvf(cr, "%" UVuf "-%" UVuf "/%" UVuf,
496 off, off + n - 1, src->size);
497 13 psf_hdr(aTHX_ hdr, "Content-Range", cr);
498 }
499 151 ▶ if (opt->ranges) psf_hdr(aTHX_ hdr, "Accept-Ranges", newSVpvs("bytes"));
Branch: 1 branch
BranchTrueFalseTotal
if (opt->ranges) psf_hdr(aTHX_ hdr, "Accept-Ranges", newSVpvs("bytes")); 149 2 151
500 151 ▶ if (etag) psf_hdr(aTHX_ hdr, "ETag", newSVpv(etag, elen));
Branch: 1 branch
BranchTrueFalseTotal
if (etag) psf_hdr(aTHX_ hdr, "ETag", newSVpv(etag, elen)); 149 2 151
501 151 ▶ if (ldate) psf_hdr(aTHX_ hdr, "Last-Modified", newSVpv(ldate, 0));
Branch: 1 branch
BranchTrueFalseTotal
if (ldate) psf_hdr(aTHX_ hdr, "Last-Modified", newSVpv(ldate, 0)); 149 2 151
502 151 psf_hdr_cc(aTHX_ hdr, opt);
503 151 ▶ if (opt->has_disp)
Branch: 1 branch
BranchTrueFalseTotal
if (opt->has_disp) 11 140 151
504 11 psf_hdr(aTHX_ hdr, "Content-Disposition",
505 psf_disposition(aTHX_ opt->filename, opt->inline_));
506 151 psf_hdr_extra(aTHX_ hdr, opt->extra);
507  
508 151 ▶ if (is_head)
Branch: 1 branch
BranchTrueFalseTotal
if (is_head) 4 147 151
509 4 body = NULL; /* headers, no body */
510 147 ▶ else if (src->path) {
Branch: 1 branch
BranchTrueFalseTotal
else if (src->path) { 144 3 147
511 /* The content cache first: open + read + close is about two
512 * thirds of a small static request, and a hit does none of them.
513 * It validates against the stat the caller has already done, so
514 * consulting it costs no syscall. NULL means "read it yourself"
515 * - too large, unreadable, or not worth holding - never "the
516 * file is missing". */
517 PerlIO *fp;
518 /* Not for a RANGE. A 206 body is a Punk::SendFile::Reader - an
519 * object with getline/close - and callers read it as one. Slicing
520 * the cached bytes instead would hand back a plain arrayref and
521 * break that contract, for a request shape that is rare (seeking
522 * a video, resuming a download) and that streaming already suits.
523 * The whole-file 200 is what static traffic actually is, and what
524 * was measured. */
525 89 ▶ SV *cached = (src->has_id && !partial)
Branch: 1 branch
BranchTrueFalseTotal
SV *cached = (src->has_id && !partial) 87 2 89
526 87 ? pfc_get(aTHX_ src->path, src->plen,
527 src->dev, src->ino, src->mtime, src->mns,
528 src->ctime, src->size)
529 146 ▶ : NULL;
Branch: 1 branch
BranchTrueFalseTotal
: NULL; 89 55 144
530 144 ▶ if (cached) { body = cached; goto have_body; }
Branch: 1 branch
BranchTrueFalseTotal
if (cached) { body = cached; goto have_body; } 85 59 144
531 59 fp = PerlIO_open(src->path, "rb");
532 59 ▶ if (!fp) {
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) { 0 59 59
533 0 SvREFCNT_dec((SV *)hdr);
534 0 return NULL;
535 }
536 /* The headers above were built from the caller's stat, and that
537 * may be a second old. The handle is the file as it is now: if it
538 * is not the size that was promised, promise nothing. */
539 {
540 Stat_t fst;
541 59 ▶ if (PerlLIO_fstat(PerlIO_fileno(fp), &fst) == 0
Branch: 1 branch
BranchTrueFalseTotal
if (PerlLIO_fstat(PerlIO_fileno(fp), &fst) == 0 59 0 59
542 59 ▶ && (UV)fst.st_size != src->size) {
Branch: 1 branch
BranchTrueFalseTotal
&& (UV)fst.st_size != src->size) { 1 58 59
543 1 PerlIO_close(fp);
544 1 SvREFCNT_dec((SV *)hdr);
545 1 src->changed = 1;
546 1 return NULL;
547 }
548 }
549 58 ▶ if (partial) {
Branch: 1 branch
BranchTrueFalseTotal
if (partial) { 12 46 58
550 12 ▶ if (PerlIO_seek(fp, (Off_t)off, SEEK_SET) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (PerlIO_seek(fp, (Off_t)off, SEEK_SET) < 0) { 0 12 12
551 0 PerlIO_close(fp);
552 0 SvREFCNT_dec((SV *)hdr);
553 0 return NULL;
554 }
555 12 body = psf_reader_new(aTHX_ fp, n);
556 }
557 else {
558 /* a real filehandle, the Punk::Static convention */
559 46 GV *gv = newGVgen("Punk::SendFile");
560 46 ▶ IO *io = GvIOn(gv);
Branch: 5 branches
BranchTrueFalseTotal
IO *io = GvIOn(gv); 46 0 46
IO *io = GvIOn(gv); 0 46 46
IO *io = GvIOn(gv); 0 0 0
IO *io = GvIOn(gv); 46 0 46
IO *io = GvIOn(gv); 0 46 46
561 46 IoIFP(io) = fp;
562 46 IoTYPE(io) = IoTYPE_RDONLY;
563 46 body = newRV_inc((SV *)gv);
564 }
565 }
566 else
567 3 ▶ body = newSVpvn(src->bytes + (partial ? off : 0), bl);
Branch: 1 branch
BranchTrueFalseTotal
body = newSVpvn(src->bytes + (partial ? off : 0), bl); 1 2 3
568  
569 150 have_body:
570 150 ▶ return psf_wrap(aTHX_ partial ? 206 : 200, hdr, body);
Branch: 1 branch
BranchTrueFalseTotal
return psf_wrap(aTHX_ partial ? 206 : 200, hdr, body); 13 137 150
571 }
572 }
573  
574 /* ---- precompressed siblings -------------------------------------------------
575 *
576 * If `style.css.gz` sits next to `style.css` and the client accepts gzip, we
577 * serve the sibling's BYTES under the original's IDENTITY: its Content-Type,
578 * its URL, its cache entry keyed by an ETag of its own. Nothing is
579 * compressed at request time - the win is a build step's, paid once - so
580 * this needs no zlib and costs one stat.
581 *
582 * `.br` is listed first and preferred when the client offers both. Serving a
583 * brotli file needs no brotli library, only this table entry: the bytes are
584 * already encoded and we are choosing a file, not compressing one.
585 */
586 typedef struct { const char *suffix; STRLEN slen; const char *token; STRLEN tlen; }
587 psf_encoding;
588  
589 static const psf_encoding PSF_ENCODINGS[] = {
590 { ".br", 3, "br", 2 },
591 { ".gz", 3, "gzip", 4 },
592 };
593 #define PSF_NENCODINGS 2
594  
595 /* Is `token` an acceptable encoding per this Accept-Encoding header? A
596 * left-to-right walk: no split, no hash, no SV. `q=0` is an explicit refusal
597 * and loses to nothing; `*` matches anything not separately refused. */
598 31 static int psf_accepts(pTHX_ const char *ae, STRLEN len, const char *tok, STRLEN tlen) {
599 31 STRLEN i = 0;
600 31 int star = 0;
601 49 ▶ while (i < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < len) { 32 17 49
602 STRLEN start, end, j;
603 32 int refused = 0, is_star, is_tok;
604 34 ▶ while (i < len && (ae[i] == ' ' || ae[i] == '\t' || ae[i] == ',')) i++;
Branch: 4 branches
BranchTrueFalseTotal
while (i < len && (ae[i] == ' ' || ae[i] == '\t' || ae[i] == ',')) i++; 34 0 34
while (i < len && (ae[i] == ' ' || ae[i] == '\t' || ae[i] == ',')) i++; 1 33 34
while (i < len && (ae[i] == ' ' || ae[i] == '\t' || ae[i] == ',')) i++; 0 33 33
while (i < len && (ae[i] == ' ' || ae[i] == '\t' || ae[i] == ',')) i++; 1 32 33
605 32 start = i;
606 167 ▶ while (i < len && ae[i] != ',' && ae[i] != ';') i++;
Branch: 3 branches
BranchTrueFalseTotal
while (i < len && ae[i] != ',' && ae[i] != ';') i++; 143 24 167
while (i < len && ae[i] != ',' && ae[i] != ';') i++; 141 2 143
while (i < len && ae[i] != ',' && ae[i] != ';') i++; 135 6 141
607 32 end = i;
608 32 ▶ while (end > start && (ae[end - 1] == ' ' || ae[end - 1] == '\t')) end--;
Branch: 3 branches
BranchTrueFalseTotal
while (end > start && (ae[end - 1] == ' ' || ae[end - 1] == '\t')) end--; 32 0 32
while (end > start && (ae[end - 1] == ' ' || ae[end - 1] == '\t')) end--; 0 32 32
while (end > start && (ae[end - 1] == ' ' || ae[end - 1] == '\t')) end--; 0 32 32
609 /* parameters: only q matters, and only q=0 (with any zero spelling) */
610 32 ▶ if (i < len && ae[i] == ';') {
Branch: 2 branches
BranchTrueFalseTotal
if (i < len && ae[i] == ';') { 8 24 32
if (i < len && ae[i] == ';') { 6 2 8
611 6 STRLEN ps = i;
612 42 ▶ while (i < len && ae[i] != ',') i++;
Branch: 2 branches
BranchTrueFalseTotal
while (i < len && ae[i] != ',') i++; 36 6 42
while (i < len && ae[i] != ',') i++; 36 0 36
613 12 ▶ for (j = ps; j + 1 < i; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = ps; j + 1 < i; j++) { 12 0 12
614 12 ▶ if ((ae[j] | 32) != 'q') continue;
Branch: 1 branch
BranchTrueFalseTotal
if ((ae[j] | 32) != 'q') continue; 6 6 12
615 12 ▶ while (j + 1 < i && (ae[j + 1] == ' ' || ae[j + 1] == '=')) j++;
Branch: 3 branches
BranchTrueFalseTotal
while (j + 1 < i && (ae[j + 1] == ' ' || ae[j + 1] == '=')) j++; 12 0 12
while (j + 1 < i && (ae[j + 1] == ' ' || ae[j + 1] == '=')) j++; 0 12 12
while (j + 1 < i && (ae[j + 1] == ' ' || ae[j + 1] == '=')) j++; 6 6 12
616 6 ▶ if (j + 1 < i && ae[j + 1] == '0') {
Branch: 2 branches
BranchTrueFalseTotal
if (j + 1 < i && ae[j + 1] == '0') { 6 0 6
if (j + 1 < i && ae[j + 1] == '0') { 6 0 6
617 /* q=0, q=0.0, q=0.000 - anything that is not > 0 */
618 6 STRLEN k = j + 2;
619 6 int nonzero = 0;
620 6 ▶ if (k < i && ae[k] == '.')
Branch: 2 branches
BranchTrueFalseTotal
if (k < i && ae[k] == '.') 4 2 6
if (k < i && ae[k] == '.') 4 0 4
621 12 ▶ for (k++; k < i && ae[k] >= '0' && ae[k] <= '9'; k++)
Branch: 3 branches
BranchTrueFalseTotal
for (k++; k < i && ae[k] >= '0' && ae[k] <= '9'; k++) 8 4 12
for (k++; k < i && ae[k] >= '0' && ae[k] <= '9'; k++) 8 0 8
for (k++; k < i && ae[k] >= '0' && ae[k] <= '9'; k++) 8 0 8
622 8 ▶ if (ae[k] != '0') nonzero = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (ae[k] != '0') nonzero = 1; 2 6 8
623 6 ▶ if (!nonzero) refused = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!nonzero) refused = 1; 4 2 6
624 }
625 6 break;
626 }
627 }
628 32 ▶ is_star = (end - start == 1 && ae[start] == '*');
Branch: 2 branches
BranchTrueFalseTotal
is_star = (end - start == 1 && ae[start] == '*'); 1 31 32
is_star = (end - start == 1 && ae[start] == '*'); 1 0 1
629 32 ▶ is_tok = (end - start == tlen && foldEQ(ae + start, tok, (I32)tlen));
Branch: 2 branches
BranchTrueFalseTotal
is_tok = (end - start == tlen && foldEQ(ae + start, tok, (I32)tlen)); 14 18 32
is_tok = (end - start == tlen && foldEQ(ae + start, tok, (I32)tlen)); 14 0 14
630 32 ▶ if (is_tok) return !refused; /* named: it decides */
Branch: 1 branch
BranchTrueFalseTotal
if (is_tok) return !refused; /* named: it decides */ 14 18 32
631 18 ▶ if (is_star && !refused) star = 1;
Branch: 2 branches
BranchTrueFalseTotal
if (is_star && !refused) star = 1; 1 17 18
if (is_star && !refused) star = 1; 1 0 1
632 }
633 17 return star;
634 }
635  
636 /* The env's Accept-Encoding, or NULL. */
637 99 static const char *psf_accept_encoding(pTHX_ HV *env, STRLEN *len) {
638 99 SV **e = hv_fetchs(env, "HTTP_ACCEPT_ENCODING", 0);
639 99 ▶ if (!(e && *e && SvOK(*e))) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!(e && *e && SvOK(*e))) return NULL; 18 81 99
if (!(e && *e && SvOK(*e))) return NULL; 18 0 18
if (!(e && *e && SvOK(*e))) return NULL; 0 18 18
640 36 return SvPV_const(*e, *len);
641 }
642  
643 /* ---- ps_serve_file ----------------------------------------------------------
644 * The static/markdown "serve one file" (declared in punk_static.h): the
645 * decision core with a fixed option block - no disposition, ranges on,
646 * validators from the file itself. This is where a `static` mount's ETag,
647 * If-None-Match 304 and 206/416 answers come from. The is_head flag the
648 * callers computed is the same REQUEST_METHOD the core reads for itself.
649 *
650 * `fo` is the caller's freshness policy, or NULL: the mount decides what
651 * Cache-Control a file gets, because only the mount knows whether the URL
652 * that asked for it was content-addressed. */
653  
654 122 static SV *ps_serve_file_opt(pTHX_ HV *env, const char *file, STRLEN flen,
655 int is_head, ps_fopts *fo) {
656 Stat_t st, sst;
657 psf_src s;
658 psf_opts o;
659 char sib[MAXPATHLEN + 8];
660 char etagbuf[PSF_ETAG_MAX + 8], datebuf[40];
661 122 AV *extra = NULL;
662 const char *ae;
663 122 STRLEN ael = 0;
664 122 int i, retried = 0;
665 SV *resp;
666 PERL_UNUSED_ARG(is_head);
667 123 again:
668 123 ▶ if (!pfc_stat(aTHX_ file, flen, &st) || !S_ISREG(st.st_mode)) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (!pfc_stat(aTHX_ file, flen, &st) || !S_ISREG(st.st_mode)) return NULL; 102 21 123
if (!pfc_stat(aTHX_ file, flen, &st) || !S_ISREG(st.st_mode)) return NULL; 3 99 102
669 99 Zero(&s, 1, psf_src);
670 99 Zero(&o, 1, psf_opts);
671 99 s.path = file;
672 99 s.plen = flen;
673 99 s.size = (UV)st.st_size;
674 99 s.mtime = (UV)st.st_mtime;
675 99 s.mns = PFC_MTIME_NS(st);
676 99 s.ctime = (UV)st.st_ctime;
677 99 s.has_mtime = 1;
678 /* the rest of the stat we just did, for the descriptor cache to validate
679 * against - no extra syscall, this one was already paid for */
680 99 s.dev = (UV)st.st_dev;
681 99 s.ino = (UV)st.st_ino;
682 99 s.has_id = 1;
683 99 o.ranges = 1;
684 /* the validators the cache already formatted for this stat */
685 99 ▶ if (psf_cached_validators(aTHX_ file, flen, &st, etagbuf, sizeof etagbuf,
Branch: 1 branch
BranchTrueFalseTotal
if (psf_cached_validators(aTHX_ file, flen, &st, etagbuf, sizeof etagbuf, 99 0 99
686 datebuf, sizeof datebuf)) {
687 99 s.etag_pre = etagbuf;
688 99 s.date_pre = datebuf;
689 }
690 99 ▶ if (fo) o.cache_control = fo->cache_control;
Branch: 1 branch
BranchTrueFalseTotal
if (fo) o.cache_control = fo->cache_control; 94 5 99
691  
692 /* Vary goes on EVERY response from here, compressed or not: a shared
693 * cache that stored the identity bytes without it would hand them to a
694 * client that asked for gzip, and vice versa. It costs one header and
695 * it is the only spelling that is correct for both. */
696 99 extra = (AV *)sv_2mortal((SV *)newAV());
697 99 av_push(extra, newSVpvs("Vary"));
698 99 av_push(extra, newSVpvs("Accept-Encoding"));
699  
700 99 ae = psf_accept_encoding(aTHX_ env, &ael);
701 99 ▶ if (ae && ael && flen + 4 < sizeof(sib)) {
Branch: 3 branches
BranchTrueFalseTotal
if (ae && ael && flen + 4 < sizeof(sib)) { 18 81 99
if (ae && ael && flen + 4 < sizeof(sib)) { 17 1 18
if (ae && ael && flen + 4 < sizeof(sib)) { 17 0 17
702 37 ▶ for (i = 0; i < PSF_NENCODINGS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < PSF_NENCODINGS; i++) { 31 6 37
703 31 const psf_encoding *enc = &PSF_ENCODINGS[i];
704 31 ▶ if (!psf_accepts(aTHX_ ae, ael, enc->token, enc->tlen)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!psf_accepts(aTHX_ ae, ael, enc->token, enc->tlen)) continue; 18 13 31
705 13 memcpy(sib, file, flen);
706 13 memcpy(sib + flen, enc->suffix, enc->slen + 1);
707 /* Through the cache, which remembers ABSENCE too: every browser
708 * sends Accept-Encoding, so on a site with no build step this
709 * probe asks for a .br and a .gz that have never existed, on
710 * every single request. */
711 13 ▶ if (!pfc_stat(aTHX_ sib, flen + enc->slen, &sst)
Branch: 1 branch
BranchTrueFalseTotal
if (!pfc_stat(aTHX_ sib, flen + enc->slen, &sst) 12 1 13
712 13 ▶ || !S_ISREG(sst.st_mode)) continue;
Branch: 1 branch
BranchTrueFalseTotal
|| !S_ISREG(sst.st_mode)) continue; 0 12 12
713 /* A sibling older than its source is a stale build artefact.
714 * Serving it would ship last week's CSS forever, silently,
715 * which is the failure nobody thinks to look for. */
716 12 ▶ if ((UV)sst.st_mtime < (UV)st.st_mtime) continue;
Branch: 1 branch
BranchTrueFalseTotal
if ((UV)sst.st_mtime < (UV)st.st_mtime) continue; 1 11 12
717  
718 /* the bytes, the length and the validators are the sibling's;
719 * the Content-Type stays the original's, so ps_content_type
720 * must never see the .gz/.br suffix */
721 11 o.type = sv_2mortal(newSVpv(ps_content_type(file, flen), 0));
722 11 s.path = sib;
723 11 s.plen = flen + enc->slen;
724 11 s.size = (UV)sst.st_size;
725 11 s.mtime = (UV)sst.st_mtime;
726 11 s.mns = PFC_MTIME_NS(sst);
727 11 s.ctime = (UV)sst.st_ctime;
728 /* the sibling is a different file, so it carries its own identity
729 * - reusing the original's would key the cache on one path and
730 * validate it against another */
731 11 s.dev = (UV)sst.st_dev;
732 11 s.ino = (UV)sst.st_ino;
733 11 s.etag_pre = NULL; /* the original's, not this file's */
734 11 s.date_pre = NULL;
735  
736 /* an encoding-tagged ETag, so an identity client and this one
737 * never collide in a shared cache even if the two files should
738 * ever share an mtime and a size */
739 11 psf_etag(etagbuf, sizeof etagbuf, s.mtime, s.mns, s.size);
740 {
741 11 STRLEN el = strlen(etagbuf);
742 11 ▶ if (el > 1 && etagbuf[el - 1] == '"'
Branch: 2 branches
BranchTrueFalseTotal
if (el > 1 && etagbuf[el - 1] == '"' 11 0 11
if (el > 1 && etagbuf[el - 1] == '"' 11 0 11
743 11 ▶ && el + enc->tlen + 1 < sizeof etagbuf) {
Branch: 1 branch
BranchTrueFalseTotal
&& el + enc->tlen + 1 < sizeof etagbuf) { 11 0 11
744 11 etagbuf[el - 1] = '-';
745 11 memcpy(etagbuf + el, enc->token, enc->tlen);
746 11 etagbuf[el + enc->tlen] = '"';
747 11 etagbuf[el + enc->tlen + 1] = '\0';
748 }
749 11 o.etag = sv_2mortal(newSVpv(etagbuf, 0));
750 }
751 11 av_push(extra, newSVpvs("Content-Encoding"));
752 11 av_push(extra, newSVpvn(enc->token, enc->tlen));
753 11 break;
754 }
755 }
756 99 o.extra = extra;
757 99 resp = psf_respond(aTHX_ env, &s, &o);
758 99 ▶ if (!resp && s.changed && !retried) {
Branch: 3 branches
BranchTrueFalseTotal
if (!resp && s.changed && !retried) { 1 98 99
if (!resp && s.changed && !retried) { 1 0 1
if (!resp && s.changed && !retried) { 1 0 1
759 /* The file is not the one the stat cache remembers. Ask again, once:
760 * a second disagreement is a file being written as we look, and the
761 * caller's 404 is as good an answer as any to that. */
762 1 pfc_expire(aTHX_ file, flen);
763 1 ▶ if (s.path != file) pfc_expire(aTHX_ s.path, s.plen);
Branch: 1 branch
BranchTrueFalseTotal
if (s.path != file) pfc_expire(aTHX_ s.path, s.plen); 0 1 1
764 1 retried = 1;
765 1 goto again;
766 }
767 98 return resp;
768 }
769  
770 16 static SV *ps_serve_file(pTHX_ HV *env, const char *file, STRLEN flen,
771 int is_head) {
772 16 return ps_serve_file_opt(aTHX_ env, file, flen, is_head, NULL);
773 }
774  
775 #endif /* PUNK_SENDFILE_H */
« include/punk/punk_response.h ↑ Summary xs/log.xs »