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 *sd, *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->http_host[0] == '\0' &&
249 val_len < GOTWEBD_MAXTEXT &&
250 name_len == 9 &&
251 strncmp(buf, "HTTP_HOST", 9) == 0) {
252 memcpy(c->http_host, val, val_len);
253 c->http_host[val_len] = '\0';
255 /*
256 * lazily get subdomain
257 * will only get domain if no subdomain exists
258 * this can still work if gotweb server name is the same
259 */
260 sd = strchr(c->http_host, '.');
261 if (sd)
262 *sd = '\0';
265 if (c->document_uri[0] == '\0' &&
266 val_len < MAX_DOCUMENT_URI &&
267 name_len == 12 &&
268 strncmp(buf, "DOCUMENT_URI", 12) == 0) {
269 memcpy(c->document_uri, val, val_len);
270 c->document_uri[val_len] = '\0';
273 if (c->server_name[0] == '\0' &&
274 val_len < MAX_SERVER_NAME &&
275 name_len == 11 &&
276 strncmp(buf, "SERVER_NAME", 11) == 0) {
277 memcpy(c->server_name, val, val_len);
278 c->server_name[val_len] = '\0';
281 if (name_len == 5 &&
282 strncmp(buf, "HTTPS", 5) == 0)
283 c->https = 1;
285 buf += name_len + val_len;
286 n -= name_len - val_len;
290 void
291 fcgi_timeout(int fd, short events, void *arg)
293 fcgi_cleanup_request((struct request*) arg);
296 int
297 fcgi_puts(struct template *tp, const char *str)
299 if (str == NULL)
300 return 0;
301 return fcgi_gen_binary_response(tp->tp_arg, str, strlen(str));
304 int
305 fcgi_putc(struct template *tp, int ch)
307 uint8_t c = ch;
308 return fcgi_gen_binary_response(tp->tp_arg, &c, 1);
311 int
312 fcgi_vprintf(struct request *c, const char *fmt, va_list ap)
314 char *str;
315 int r;
317 r = vasprintf(&str, fmt, ap);
318 if (r == -1) {
319 log_warn("%s: asprintf", __func__);
320 return -1;
323 r = fcgi_gen_binary_response(c, str, r);
324 free(str);
325 return r;
328 int
329 fcgi_printf(struct request *c, const char *fmt, ...)
331 va_list ap;
332 int r;
334 va_start(ap, fmt);
335 r = fcgi_vprintf(c, fmt, ap);
336 va_end(ap);
338 return r;
341 int
342 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
344 int r;
346 if (c->sock->client_status == CLIENT_DISCONNECT)
347 return -1;
349 if (data == NULL || len == 0)
350 return 0;
352 /*
353 * special case: send big replies -like blobs- directly
354 * without copying.
355 */
356 if (len > sizeof(c->outbuf)) {
357 if (c->outbuf_len > 0) {
358 fcgi_send_response(c, FCGI_STDOUT,
359 c->outbuf, c->outbuf_len);
360 c->outbuf_len = 0;
362 return fcgi_send_response(c, FCGI_STDOUT, data, len);
365 if (len < sizeof(c->outbuf) - c->outbuf_len) {
366 memcpy(c->outbuf + c->outbuf_len, data, len);
367 c->outbuf_len += len;
368 return 0;
371 r = fcgi_send_response(c, FCGI_STDOUT, c->outbuf, c->outbuf_len);
372 if (r == -1)
373 return -1;
375 memcpy(c->outbuf, data, len);
376 c->outbuf_len = len;
377 return 0;
380 static int
381 send_response(struct request *c, int type, const uint8_t *data,
382 size_t len)
384 static const uint8_t padding[FCGI_PADDING_SIZE];
385 struct fcgi_record_header header;
386 struct iovec iov[3];
387 struct timespec ts;
388 ssize_t nw;
389 size_t padded_len, tot;
390 int i, err = 0, th = 2000;
392 ts.tv_sec = 0;
393 ts.tv_nsec = 50;
395 memset(&header, 0, sizeof(header));
396 header.version = 1;
397 header.type = type;
398 header.id = htons(c->id);
399 header.content_len = htons(len);
401 /* The FastCGI spec suggests to align the output buffer */
402 tot = sizeof(header) + len;
403 padded_len = FCGI_ALIGN(tot);
404 if (padded_len > tot) {
405 header.padding_len = padded_len - tot;
406 tot += header.padding_len;
409 iov[0].iov_base = &header;
410 iov[0].iov_len = sizeof(header);
412 iov[1].iov_base = (void *)data;
413 iov[1].iov_len = len;
415 iov[2].iov_base = (void *)padding;
416 iov[2].iov_len = header.padding_len;
418 dump_fcgi_record("resp ", &header);
420 /*
421 * XXX: add some simple write heuristics here
422 * On slower VMs, spotty connections, etc., we don't want to go right to
423 * disconnect. Let's at least try to write the data a few times before
424 * giving up.
425 */
426 while (tot > 0) {
427 nw = writev(c->fd, iov, nitems(iov));
428 if (nw == 0) {
429 c->sock->client_status = CLIENT_DISCONNECT;
430 break;
432 if (nw == -1) {
433 err++;
434 if (errno == EAGAIN && err < th) {
435 nanosleep(&ts, NULL);
436 continue;
438 log_warn("%s: write failure", __func__);
439 c->sock->client_status = CLIENT_DISCONNECT;
440 return -1;
443 if (nw != tot)
444 log_debug("%s: partial write: %zu vs %zu", __func__,
445 nw, tot);
447 tot -= nw;
448 for (i = 0; i < nitems(iov); ++i) {
449 if (nw < iov[i].iov_len) {
450 iov[i].iov_base += nw;
451 iov[i].iov_len -= nw;
452 break;
454 nw -= iov[i].iov_len;
455 iov[i].iov_len = 0;
459 return 0;
462 int
463 fcgi_send_response(struct request *c, int type, const void *data,
464 size_t len)
466 if (c->sock->client_status == CLIENT_DISCONNECT)
467 return -1;
469 while (len > FCGI_CONTENT_SIZE) {
470 if (send_response(c, type, data, len) == -1)
471 return -1;
473 data += FCGI_CONTENT_SIZE;
474 len -= FCGI_CONTENT_SIZE;
477 if (len == 0)
478 return 0;
480 return send_response(c, type, data, len);
483 void
484 fcgi_create_end_record(struct request *c)
486 struct fcgi_end_request_body end_request;
488 memset(&end_request, 0, sizeof(end_request));
489 end_request.app_status = htonl(0); /* script status */
490 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
492 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
493 sizeof(end_request));
496 void
497 fcgi_cleanup_request(struct request *c)
499 cgi_inflight--;
500 client_cnt--;
502 evtimer_del(&c->tmo);
503 if (event_initialized(&c->ev))
504 event_del(&c->ev);
506 close(c->fd);
507 template_free(c->tp);
508 if (c->t != NULL)
509 gotweb_free_transport(c->t);
510 free(c);
513 void
514 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
516 dump_fcgi_record_header(p, h);
518 if (h->type == FCGI_BEGIN_REQUEST)
519 dump_fcgi_begin_request_body(p,
520 (struct fcgi_begin_request_body *)(h + 1));
521 else if (h->type == FCGI_END_REQUEST)
522 dump_fcgi_end_request_body(p,
523 (struct fcgi_end_request_body *)(h + 1));
526 void
527 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
529 log_debug("%sversion: %d", p, h->version);
530 log_debug("%stype: %d", p, h->type);
531 log_debug("%srequestId: %d", p, ntohs(h->id));
532 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
533 log_debug("%spaddingLength: %d", p, h->padding_len);
534 log_debug("%sreserved: %d", p, h->reserved);
537 void
538 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
540 log_debug("%srole %d", p, ntohs(b->role));
541 log_debug("%sflags %d", p, b->flags);
544 void
545 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
547 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
548 log_debug("%sprotocolStatus: %d", p, b->protocol_status);