Blob


1 /*
2 * Copyright (c) 2020-2022 Tracey Emery <tracey@traceyemery.net>
3 * Copyright (c) 2013 David Gwynne <dlg@openbsd.org>
4 * Copyright (c) 2013 Florian Obser <florian@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <arpa/inet.h>
20 #include <sys/queue.h>
21 #include <sys/socket.h>
22 #include <sys/types.h>
23 #include <sys/uio.h>
25 #include <errno.h>
26 #include <event.h>
27 #include <imsg.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <time.h>
33 #include <unistd.h>
35 #include "got_error.h"
36 #include "got_reference.h"
38 #include "proc.h"
39 #include "gotwebd.h"
40 #include "tmpl.h"
42 size_t fcgi_parse_record(uint8_t *, size_t, struct request *);
43 void fcgi_parse_begin_request(uint8_t *, uint16_t, struct request *,
44 uint16_t);
45 void fcgi_parse_params(uint8_t *, uint16_t, struct request *, uint16_t);
46 int fcgi_send_response(struct request *, int, const void *, size_t);
48 void dump_fcgi_record_header(const char *, struct fcgi_record_header *);
49 void dump_fcgi_begin_request_body(const char *,
50 struct fcgi_begin_request_body *);
51 void dump_fcgi_end_request_body(const char *,
52 struct fcgi_end_request_body *);
54 extern int cgi_inflight;
55 extern volatile int client_cnt;
57 void
58 fcgi_request(int fd, short events, void *arg)
59 {
60 struct request *c = arg;
61 ssize_t n;
62 size_t parsed = 0;
64 n = read(fd, c->buf + c->buf_pos + c->buf_len,
65 FCGI_RECORD_SIZE - c->buf_pos-c->buf_len);
67 switch (n) {
68 case -1:
69 switch (errno) {
70 case EINTR:
71 case EAGAIN:
72 return;
73 default:
74 goto fail;
75 }
76 break;
78 case 0:
79 log_debug("closed connection");
80 goto fail;
81 default:
82 break;
83 }
85 c->buf_len += n;
87 /*
88 * Parse the records as they are received. Per the FastCGI
89 * specification, the server need only receive the FastCGI
90 * parameter records in full; it is free to begin execution
91 * at that point, which is what happens here.
92 */
93 do {
94 parsed = fcgi_parse_record(c->buf + c->buf_pos, c->buf_len, c);
95 if (parsed != 0) {
96 c->buf_pos += parsed;
97 c->buf_len -= parsed;
98 }
100 /* drop the parsed record */
101 if (parsed != 0 && c->buf_len > 0) {
102 bcopy(c->buf + c->buf_pos, c->buf, c->buf_len);
103 c->buf_pos = 0;
105 } while (parsed > 0 && c->buf_len > 0);
107 return;
108 fail:
109 fcgi_cleanup_request(c);
112 size_t
113 fcgi_parse_record(uint8_t *buf, size_t n, struct request *c)
115 struct fcgi_record_header *h;
117 if (n < sizeof(struct fcgi_record_header))
118 return 0;
120 h = (struct fcgi_record_header*) buf;
122 dump_fcgi_record("", h);
124 if (n < sizeof(struct fcgi_record_header) + ntohs(h->content_len)
125 + h->padding_len)
126 return 0;
128 if (h->version != 1)
129 log_warn("wrong version");
131 switch (h->type) {
132 case FCGI_BEGIN_REQUEST:
133 fcgi_parse_begin_request(buf +
134 sizeof(struct fcgi_record_header),
135 ntohs(h->content_len), c, ntohs(h->id));
136 break;
137 case FCGI_PARAMS:
138 fcgi_parse_params(buf + sizeof(struct fcgi_record_header),
139 ntohs(h->content_len), c, ntohs(h->id));
140 break;
141 case FCGI_STDIN:
142 case FCGI_ABORT_REQUEST:
143 if (c->sock->client_status != CLIENT_DISCONNECT &&
144 c->outbuf_len != 0) {
145 fcgi_send_response(c, FCGI_STDOUT, c->outbuf,
146 c->outbuf_len);
149 fcgi_create_end_record(c);
150 fcgi_cleanup_request(c);
151 return 0;
152 default:
153 log_warn("unimplemented type %d", h->type);
154 break;
157 return (sizeof(struct fcgi_record_header) + ntohs(h->content_len)
158 + h->padding_len);
161 void
162 fcgi_parse_begin_request(uint8_t *buf, uint16_t n,
163 struct request *c, uint16_t id)
165 /* XXX -- FCGI_CANT_MPX_CONN */
166 if (c->request_started) {
167 log_warn("unexpected FCGI_BEGIN_REQUEST, ignoring");
168 return;
171 if (n != sizeof(struct fcgi_begin_request_body)) {
172 log_warn("wrong size %d != %lu", n,
173 sizeof(struct fcgi_begin_request_body));
174 return;
177 c->request_started = 1;
178 c->id = id;
181 void
182 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
184 uint32_t name_len, val_len;
185 uint8_t *val;
187 if (!c->request_started) {
188 log_warn("FCGI_PARAMS without FCGI_BEGIN_REQUEST, ignoring");
189 return;
192 if (c->id != id) {
193 log_warn("unexpected id, ignoring");
194 return;
197 if (n == 0) {
198 gotweb_process_request(c);
199 return;
202 while (n > 0) {
203 if (buf[0] >> 7 == 0) {
204 name_len = buf[0];
205 n--;
206 buf++;
207 } else {
208 if (n > 3) {
209 name_len = ((buf[0] & 0x7f) << 24) +
210 (buf[1] << 16) + (buf[2] << 8) + buf[3];
211 n -= 4;
212 buf += 4;
213 } else
214 return;
217 if (n == 0)
218 return;
220 if (buf[0] >> 7 == 0) {
221 val_len = buf[0];
222 n--;
223 buf++;
224 } else {
225 if (n > 3) {
226 val_len = ((buf[0] & 0x7f) << 24) +
227 (buf[1] << 16) + (buf[2] << 8) +
228 buf[3];
229 n -= 4;
230 buf += 4;
231 } else
232 return;
235 if (n < name_len + val_len)
236 return;
238 val = buf + name_len;
240 if (c->querystring[0] == '\0' &&
241 val_len < MAX_QUERYSTRING &&
242 name_len == 12 &&
243 strncmp(buf, "QUERY_STRING", 12) == 0) {
244 memcpy(c->querystring, val, val_len);
245 c->querystring[val_len] = '\0';
248 if (c->document_uri[0] == '\0' &&
249 val_len < MAX_DOCUMENT_URI &&
250 name_len == 12 &&
251 strncmp(buf, "DOCUMENT_URI", 12) == 0) {
252 memcpy(c->document_uri, val, val_len);
253 c->document_uri[val_len] = '\0';
256 if (c->server_name[0] == '\0' &&
257 val_len < MAX_SERVER_NAME &&
258 name_len == 11 &&
259 strncmp(buf, "SERVER_NAME", 11) == 0) {
260 memcpy(c->server_name, val, val_len);
261 c->server_name[val_len] = '\0';
264 if (name_len == 5 &&
265 strncmp(buf, "HTTPS", 5) == 0)
266 c->https = 1;
268 buf += name_len + val_len;
269 n -= name_len - val_len;
273 void
274 fcgi_timeout(int fd, short events, void *arg)
276 fcgi_cleanup_request((struct request*) arg);
279 int
280 fcgi_puts(struct template *tp, const char *str)
282 if (str == NULL)
283 return 0;
284 return fcgi_gen_binary_response(tp->tp_arg, str, strlen(str));
287 int
288 fcgi_putc(struct template *tp, int ch)
290 uint8_t c = ch;
291 return fcgi_gen_binary_response(tp->tp_arg, &c, 1);
294 int
295 fcgi_vprintf(struct request *c, const char *fmt, va_list ap)
297 char *str;
298 int r;
300 r = vasprintf(&str, fmt, ap);
301 if (r == -1) {
302 log_warn("%s: asprintf", __func__);
303 return -1;
306 r = fcgi_gen_binary_response(c, str, r);
307 free(str);
308 return r;
311 int
312 fcgi_printf(struct request *c, const char *fmt, ...)
314 va_list ap;
315 int r;
317 va_start(ap, fmt);
318 r = fcgi_vprintf(c, fmt, ap);
319 va_end(ap);
321 return r;
324 int
325 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
327 int r;
329 if (c->sock->client_status == CLIENT_DISCONNECT)
330 return -1;
332 if (data == NULL || len == 0)
333 return 0;
335 /*
336 * special case: send big replies -like blobs- directly
337 * without copying.
338 */
339 if (len > sizeof(c->outbuf)) {
340 if (c->outbuf_len > 0) {
341 fcgi_send_response(c, FCGI_STDOUT,
342 c->outbuf, c->outbuf_len);
343 c->outbuf_len = 0;
345 return fcgi_send_response(c, FCGI_STDOUT, data, len);
348 if (len < sizeof(c->outbuf) - c->outbuf_len) {
349 memcpy(c->outbuf + c->outbuf_len, data, len);
350 c->outbuf_len += len;
351 return 0;
354 r = fcgi_send_response(c, FCGI_STDOUT, c->outbuf, c->outbuf_len);
355 if (r == -1)
356 return -1;
358 memcpy(c->outbuf, data, len);
359 c->outbuf_len = len;
360 return 0;
363 static int
364 send_response(struct request *c, int type, const uint8_t *data,
365 size_t len)
367 static const uint8_t padding[FCGI_PADDING_SIZE];
368 struct fcgi_record_header header;
369 struct iovec iov[3];
370 struct timespec ts;
371 ssize_t nw;
372 size_t padded_len, tot;
373 int i, err = 0, th = 2000;
375 ts.tv_sec = 0;
376 ts.tv_nsec = 50;
378 memset(&header, 0, sizeof(header));
379 header.version = 1;
380 header.type = type;
381 header.id = htons(c->id);
382 header.content_len = htons(len);
384 /* The FastCGI spec suggests to align the output buffer */
385 tot = sizeof(header) + len;
386 padded_len = FCGI_ALIGN(tot);
387 if (padded_len > tot) {
388 header.padding_len = padded_len - tot;
389 tot += header.padding_len;
392 iov[0].iov_base = &header;
393 iov[0].iov_len = sizeof(header);
395 iov[1].iov_base = (void *)data;
396 iov[1].iov_len = len;
398 iov[2].iov_base = (void *)padding;
399 iov[2].iov_len = header.padding_len;
401 dump_fcgi_record("resp ", &header);
403 /*
404 * XXX: add some simple write heuristics here
405 * On slower VMs, spotty connections, etc., we don't want to go right to
406 * disconnect. Let's at least try to write the data a few times before
407 * giving up.
408 */
409 while (tot > 0) {
410 nw = writev(c->fd, iov, nitems(iov));
411 if (nw == 0) {
412 c->sock->client_status = CLIENT_DISCONNECT;
413 break;
415 if (nw == -1) {
416 err++;
417 if (errno == EAGAIN && err < th) {
418 nanosleep(&ts, NULL);
419 continue;
421 log_debug("%s: write failure: %s", __func__,
422 strerror(errno));
423 c->sock->client_status = CLIENT_DISCONNECT;
424 return -1;
427 if (nw != tot)
428 log_debug("%s: partial write: %zu vs %zu", __func__,
429 nw, tot);
431 tot -= nw;
432 for (i = 0; i < nitems(iov); ++i) {
433 if (nw < iov[i].iov_len) {
434 iov[i].iov_base += nw;
435 iov[i].iov_len -= nw;
436 break;
438 nw -= iov[i].iov_len;
439 iov[i].iov_len = 0;
443 return 0;
446 int
447 fcgi_send_response(struct request *c, int type, const void *data,
448 size_t len)
450 if (c->sock->client_status == CLIENT_DISCONNECT)
451 return -1;
453 while (len > FCGI_CONTENT_SIZE) {
454 if (send_response(c, type, data, len) == -1)
455 return -1;
457 data += FCGI_CONTENT_SIZE;
458 len -= FCGI_CONTENT_SIZE;
461 if (len == 0)
462 return 0;
464 return send_response(c, type, data, len);
467 void
468 fcgi_create_end_record(struct request *c)
470 struct fcgi_end_request_body end_request;
472 memset(&end_request, 0, sizeof(end_request));
473 end_request.app_status = htonl(0); /* script status */
474 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
476 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
477 sizeof(end_request));
480 void
481 fcgi_cleanup_request(struct request *c)
483 cgi_inflight--;
484 client_cnt--;
486 evtimer_del(&c->tmo);
487 if (event_initialized(&c->ev))
488 event_del(&c->ev);
490 close(c->fd);
491 template_free(c->tp);
492 if (c->t != NULL)
493 gotweb_free_transport(c->t);
494 free(c);
497 void
498 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
500 dump_fcgi_record_header(p, h);
502 if (h->type == FCGI_BEGIN_REQUEST)
503 dump_fcgi_begin_request_body(p,
504 (struct fcgi_begin_request_body *)(h + 1));
505 else if (h->type == FCGI_END_REQUEST)
506 dump_fcgi_end_request_body(p,
507 (struct fcgi_end_request_body *)(h + 1));
510 void
511 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
513 log_debug("%sversion: %d", p, h->version);
514 log_debug("%stype: %d", p, h->type);
515 log_debug("%srequestId: %d", p, ntohs(h->id));
516 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
517 log_debug("%spaddingLength: %d", p, h->padding_len);
518 log_debug("%sreserved: %d", p, h->reserved);
521 void
522 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
524 log_debug("%srole %d", p, ntohs(b->role));
525 log_debug("%sflags %d", p, b->flags);
528 void
529 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
531 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
532 log_debug("%sprotocolStatus: %d", p, b->protocol_status);