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"
37 #include "got_compat.h"
39 #include "proc.h"
40 #include "gotwebd.h"
41 #include "tmpl.h"
43 size_t fcgi_parse_record(uint8_t *, size_t, struct request *);
44 void fcgi_parse_begin_request(uint8_t *, uint16_t, struct request *,
45 uint16_t);
46 void fcgi_parse_params(uint8_t *, uint16_t, struct request *, uint16_t);
47 int fcgi_send_response(struct request *, int, const void *, size_t);
49 void dump_fcgi_record_header(const char *, struct fcgi_record_header *);
50 void dump_fcgi_begin_request_body(const char *,
51 struct fcgi_begin_request_body *);
52 void dump_fcgi_end_request_body(const char *,
53 struct fcgi_end_request_body *);
55 extern int cgi_inflight;
56 extern volatile int client_cnt;
58 void
59 fcgi_request(int fd, short events, void *arg)
60 {
61 struct request *c = arg;
62 ssize_t n;
63 size_t parsed = 0;
65 n = read(fd, c->buf + c->buf_pos + c->buf_len,
66 FCGI_RECORD_SIZE - c->buf_pos-c->buf_len);
68 switch (n) {
69 case -1:
70 switch (errno) {
71 case EINTR:
72 case EAGAIN:
73 return;
74 default:
75 goto fail;
76 }
77 break;
79 case 0:
80 log_debug("closed connection");
81 goto fail;
82 default:
83 break;
84 }
86 c->buf_len += n;
88 /*
89 * Parse the records as they are received. Per the FastCGI
90 * specification, the server need only receive the FastCGI
91 * parameter records in full; it is free to begin execution
92 * at that point, which is what happens here.
93 */
94 do {
95 parsed = fcgi_parse_record(c->buf + c->buf_pos, c->buf_len, c);
96 if (parsed != 0) {
97 c->buf_pos += parsed;
98 c->buf_len -= parsed;
99 }
100 } while (parsed > 0 && c->buf_len > 0);
102 /* Make space for further reads */
103 if (parsed != 0)
104 if (c->buf_len > 0) {
105 bcopy(c->buf + c->buf_pos, c->buf, c->buf_len);
106 c->buf_pos = 0;
108 return;
109 fail:
110 fcgi_cleanup_request(c);
113 size_t
114 fcgi_parse_record(uint8_t *buf, size_t n, struct request *c)
116 struct fcgi_record_header *h;
118 if (n < sizeof(struct fcgi_record_header))
119 return 0;
121 h = (struct fcgi_record_header*) buf;
123 dump_fcgi_record("", h);
125 if (n < sizeof(struct fcgi_record_header) + ntohs(h->content_len)
126 + h->padding_len)
127 return 0;
129 if (h->version != 1)
130 log_warn("wrong version");
132 switch (h->type) {
133 case FCGI_BEGIN_REQUEST:
134 fcgi_parse_begin_request(buf +
135 sizeof(struct fcgi_record_header),
136 ntohs(h->content_len), c, ntohs(h->id));
137 break;
138 case FCGI_PARAMS:
139 fcgi_parse_params(buf + sizeof(struct fcgi_record_header),
140 ntohs(h->content_len), c, ntohs(h->id));
141 break;
142 case FCGI_STDIN:
143 case FCGI_ABORT_REQUEST:
144 if (c->sock->client_status != CLIENT_DISCONNECT &&
145 c->outbuf_len != 0) {
146 fcgi_send_response(c, FCGI_STDOUT, c->outbuf,
147 c->outbuf_len);
150 fcgi_create_end_record(c);
151 fcgi_cleanup_request(c);
152 return 0;
153 default:
154 log_warn("unimplemented type %d", h->type);
155 break;
158 return (sizeof(struct fcgi_record_header) + ntohs(h->content_len)
159 + h->padding_len);
162 void
163 fcgi_parse_begin_request(uint8_t *buf, uint16_t n,
164 struct request *c, uint16_t id)
166 /* XXX -- FCGI_CANT_MPX_CONN */
167 if (c->request_started) {
168 log_warn("unexpected FCGI_BEGIN_REQUEST, ignoring");
169 return;
172 if (n != sizeof(struct fcgi_begin_request_body)) {
173 log_warn("wrong size %d != %lu", n,
174 sizeof(struct fcgi_begin_request_body));
175 return;
178 c->request_started = 1;
179 c->id = id;
182 void
183 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
185 uint32_t name_len, val_len;
186 uint8_t *sd, *val;
188 if (!c->request_started) {
189 log_warn("FCGI_PARAMS without FCGI_BEGIN_REQUEST, ignoring");
190 return;
193 if (c->id != id) {
194 log_warn("unexpected id, ignoring");
195 return;
198 if (n == 0) {
199 gotweb_process_request(c);
200 return;
203 while (n > 0) {
204 if (buf[0] >> 7 == 0) {
205 name_len = buf[0];
206 n--;
207 buf++;
208 } else {
209 if (n > 3) {
210 name_len = ((buf[0] & 0x7f) << 24) +
211 (buf[1] << 16) + (buf[2] << 8) + buf[3];
212 n -= 4;
213 buf += 4;
214 } else
215 return;
218 if (n == 0)
219 return;
221 if (buf[0] >> 7 == 0) {
222 val_len = buf[0];
223 n--;
224 buf++;
225 } else {
226 if (n > 3) {
227 val_len = ((buf[0] & 0x7f) << 24) +
228 (buf[1] << 16) + (buf[2] << 8) +
229 buf[3];
230 n -= 4;
231 buf += 4;
232 } else
233 return;
236 if (n < name_len + val_len)
237 return;
239 val = buf + name_len;
241 if (c->querystring[0] == '\0' &&
242 val_len < MAX_QUERYSTRING &&
243 name_len == 12 &&
244 strncmp(buf, "QUERY_STRING", 12) == 0) {
245 memcpy(c->querystring, val, val_len);
246 c->querystring[val_len] = '\0';
249 if (c->http_host[0] == '\0' &&
250 val_len < GOTWEBD_MAXTEXT &&
251 name_len == 9 &&
252 strncmp(buf, "HTTP_HOST", 9) == 0) {
253 memcpy(c->http_host, val, val_len);
254 c->http_host[val_len] = '\0';
256 /*
257 * lazily get subdomain
258 * will only get domain if no subdomain exists
259 * this can still work if gotweb server name is the same
260 */
261 sd = strchr(c->http_host, '.');
262 if (sd)
263 *sd = '\0';
266 if (c->document_uri[0] == '\0' &&
267 val_len < MAX_DOCUMENT_URI &&
268 name_len == 12 &&
269 strncmp(buf, "DOCUMENT_URI", 12) == 0) {
270 memcpy(c->document_uri, val, val_len);
271 c->document_uri[val_len] = '\0';
274 if (c->server_name[0] == '\0' &&
275 val_len < MAX_SERVER_NAME &&
276 name_len == 11 &&
277 strncmp(buf, "SERVER_NAME", 11) == 0) {
278 memcpy(c->server_name, val, val_len);
279 c->server_name[val_len] = '\0';
282 buf += name_len + val_len;
283 n -= name_len - val_len;
287 void
288 fcgi_timeout(int fd, short events, void *arg)
290 fcgi_cleanup_request((struct request*) arg);
293 int
294 fcgi_puts(struct template *tp, const char *str)
296 if (str == NULL)
297 return 0;
298 return fcgi_gen_binary_response(tp->tp_arg, str, strlen(str));
301 int
302 fcgi_putc(struct template *tp, int ch)
304 uint8_t c = ch;
305 return fcgi_gen_binary_response(tp->tp_arg, &c, 1);
308 int
309 fcgi_vprintf(struct request *c, const char *fmt, va_list ap)
311 char *str;
312 int r;
314 r = vasprintf(&str, fmt, ap);
315 if (r == -1) {
316 log_warn("%s: asprintf", __func__);
317 return -1;
320 r = fcgi_gen_binary_response(c, str, r);
321 free(str);
322 return r;
325 int
326 fcgi_printf(struct request *c, const char *fmt, ...)
328 va_list ap;
329 int r;
331 va_start(ap, fmt);
332 r = fcgi_vprintf(c, fmt, ap);
333 va_end(ap);
335 return r;
338 int
339 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
341 int r;
343 if (c->sock->client_status == CLIENT_DISCONNECT)
344 return -1;
346 if (data == NULL || len == 0)
347 return 0;
349 /*
350 * special case: send big replies -like blobs- directly
351 * without copying.
352 */
353 if (len > sizeof(c->outbuf)) {
354 if (c->outbuf_len > 0) {
355 fcgi_send_response(c, FCGI_STDOUT,
356 c->outbuf, c->outbuf_len);
357 c->outbuf_len = 0;
359 return fcgi_send_response(c, FCGI_STDOUT, data, len);
362 if (len < sizeof(c->outbuf) - c->outbuf_len) {
363 memcpy(c->outbuf + c->outbuf_len, data, len);
364 c->outbuf_len += len;
365 return 0;
368 r = fcgi_send_response(c, FCGI_STDOUT, c->outbuf, c->outbuf_len);
369 if (r == -1)
370 return -1;
372 memcpy(c->outbuf, data, len);
373 c->outbuf_len = len;
374 return 0;
377 static int
378 send_response(struct request *c, int type, const uint8_t *data,
379 size_t len)
381 static const uint8_t padding[FCGI_PADDING_SIZE];
382 struct fcgi_record_header header;
383 struct iovec iov[3];
384 struct timespec ts;
385 ssize_t nw;
386 size_t padded_len, tot;
387 int i, err = 0, th = 2000;
389 ts.tv_sec = 0;
390 ts.tv_nsec = 50;
392 memset(&header, 0, sizeof(header));
393 header.version = 1;
394 header.type = type;
395 header.id = htons(c->id);
396 header.content_len = htons(len);
398 /* The FastCGI spec suggests to align the output buffer */
399 tot = sizeof(header) + len;
400 padded_len = FCGI_ALIGN(tot);
401 if (padded_len > tot) {
402 header.padding_len = padded_len - tot;
403 tot += header.padding_len;
406 iov[0].iov_base = &header;
407 iov[0].iov_len = sizeof(header);
409 iov[1].iov_base = (void *)data;
410 iov[1].iov_len = len;
412 iov[2].iov_base = (void *)padding;
413 iov[2].iov_len = header.padding_len;
415 dump_fcgi_record("resp ", &header);
417 /*
418 * XXX: add some simple write heuristics here
419 * On slower VMs, spotty connections, etc., we don't want to go right to
420 * disconnect. Let's at least try to write the data a few times before
421 * giving up.
422 */
423 while (tot > 0) {
424 nw = writev(c->fd, iov, nitems(iov));
425 if (nw == 0) {
426 c->sock->client_status = CLIENT_DISCONNECT;
427 break;
429 if (nw == -1) {
430 err++;
431 if (errno == EAGAIN && err < th) {
432 nanosleep(&ts, NULL);
433 continue;
435 log_warn("%s: write failure", __func__);
436 c->sock->client_status = CLIENT_DISCONNECT;
437 return -1;
440 if (nw != tot)
441 log_debug("%s: partial write: %zu vs %zu", __func__,
442 nw, tot);
444 tot -= nw;
445 for (i = 0; i < nitems(iov); ++i) {
446 if (nw < iov[i].iov_len) {
447 iov[i].iov_base += nw;
448 iov[i].iov_len -= nw;
449 break;
451 nw -= iov[i].iov_len;
452 iov[i].iov_len = 0;
456 return 0;
459 int
460 fcgi_send_response(struct request *c, int type, const void *data,
461 size_t len)
463 if (c->sock->client_status == CLIENT_DISCONNECT)
464 return -1;
466 while (len > FCGI_CONTENT_SIZE) {
467 if (send_response(c, type, data, len) == -1)
468 return -1;
470 data += FCGI_CONTENT_SIZE;
471 len -= FCGI_CONTENT_SIZE;
474 if (len == 0)
475 return 0;
477 return send_response(c, type, data, len);
480 void
481 fcgi_create_end_record(struct request *c)
483 struct fcgi_end_request_body end_request;
485 memset(&end_request, 0, sizeof(end_request));
486 end_request.app_status = htonl(0); /* script status */
487 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
489 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
490 sizeof(end_request));
493 void
494 fcgi_cleanup_request(struct request *c)
496 cgi_inflight--;
497 client_cnt--;
499 evtimer_del(&c->tmo);
500 if (event_initialized(&c->ev))
501 event_del(&c->ev);
503 close(c->fd);
504 template_free(c->tp);
505 gotweb_free_transport(c->t);
506 free(c);
509 void
510 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
512 dump_fcgi_record_header(p, h);
514 if (h->type == FCGI_BEGIN_REQUEST)
515 dump_fcgi_begin_request_body(p,
516 (struct fcgi_begin_request_body *)(h + 1));
517 else if (h->type == FCGI_END_REQUEST)
518 dump_fcgi_end_request_body(p,
519 (struct fcgi_end_request_body *)(h + 1));
522 void
523 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
525 log_debug("%sversion: %d", p, h->version);
526 log_debug("%stype: %d", p, h->type);
527 log_debug("%srequestId: %d", p, ntohs(h->id));
528 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
529 log_debug("%spaddingLength: %d", p, h->padding_len);
530 log_debug("%sreserved: %d", p, h->reserved);
533 void
534 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
536 log_debug("%srole %d", p, ntohs(b->role));
537 log_debug("%sflags %d", p, b->flags);
540 void
541 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
543 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
544 log_debug("%sprotocolStatus: %d", p, b->protocol_status);