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 "proc.h"
38 #include "gotwebd.h"
40 size_t fcgi_parse_record(uint8_t *, size_t, struct request *);
41 void fcgi_parse_begin_request(uint8_t *, uint16_t, struct request *,
42 uint16_t);
43 void fcgi_parse_params(uint8_t *, uint16_t, struct request *, uint16_t);
44 int fcgi_send_response(struct request *, int, const void *, size_t);
46 void dump_fcgi_record_header(const char *, struct fcgi_record_header *);
47 void dump_fcgi_begin_request_body(const char *,
48 struct fcgi_begin_request_body *);
49 void dump_fcgi_end_request_body(const char *,
50 struct fcgi_end_request_body *);
52 extern int cgi_inflight;
53 extern volatile int client_cnt;
55 void
56 fcgi_request(int fd, short events, void *arg)
57 {
58 struct request *c = arg;
59 ssize_t n;
60 size_t parsed = 0;
62 n = read(fd, c->buf + c->buf_pos + c->buf_len,
63 FCGI_RECORD_SIZE - c->buf_pos-c->buf_len);
65 switch (n) {
66 case -1:
67 switch (errno) {
68 case EINTR:
69 case EAGAIN:
70 return;
71 default:
72 goto fail;
73 }
74 break;
76 case 0:
77 log_debug("closed connection");
78 goto fail;
79 default:
80 break;
81 }
83 c->buf_len += n;
85 /*
86 * Parse the records as they are received. Per the FastCGI
87 * specification, the server need only receive the FastCGI
88 * parameter records in full; it is free to begin execution
89 * at that point, which is what happens here.
90 */
91 do {
92 parsed = fcgi_parse_record(c->buf + c->buf_pos, c->buf_len, c);
93 if (parsed != 0) {
94 c->buf_pos += parsed;
95 c->buf_len -= parsed;
96 }
97 } while (parsed > 0 && c->buf_len > 0);
99 /* Make space for further reads */
100 if (parsed != 0)
101 if (c->buf_len > 0) {
102 bcopy(c->buf + c->buf_pos, c->buf, c->buf_len);
103 c->buf_pos = 0;
105 return;
106 fail:
107 fcgi_cleanup_request(c);
110 size_t
111 fcgi_parse_record(uint8_t *buf, size_t n, struct request *c)
113 struct fcgi_record_header *h;
115 if (n < sizeof(struct fcgi_record_header))
116 return 0;
118 h = (struct fcgi_record_header*) buf;
120 dump_fcgi_record("", h);
122 if (n < sizeof(struct fcgi_record_header) + ntohs(h->content_len)
123 + h->padding_len)
124 return 0;
126 if (h->version != 1)
127 log_warn("wrong version");
129 switch (h->type) {
130 case FCGI_BEGIN_REQUEST:
131 fcgi_parse_begin_request(buf +
132 sizeof(struct fcgi_record_header),
133 ntohs(h->content_len), c, ntohs(h->id));
134 break;
135 case FCGI_PARAMS:
136 fcgi_parse_params(buf + sizeof(struct fcgi_record_header),
137 ntohs(h->content_len), c, ntohs(h->id));
138 break;
139 case FCGI_STDIN:
140 case FCGI_ABORT_REQUEST:
141 if (c->sock->client_status != CLIENT_DISCONNECT &&
142 c->outbuf_len != 0) {
143 fcgi_send_response(c, FCGI_STDOUT, c->outbuf,
144 c->outbuf_len);
147 fcgi_create_end_record(c);
148 fcgi_cleanup_request(c);
149 return 0;
150 default:
151 log_warn("unimplemented type %d", h->type);
152 break;
155 return (sizeof(struct fcgi_record_header) + ntohs(h->content_len)
156 + h->padding_len);
159 void
160 fcgi_parse_begin_request(uint8_t *buf, uint16_t n,
161 struct request *c, uint16_t id)
163 /* XXX -- FCGI_CANT_MPX_CONN */
164 if (c->request_started) {
165 log_warn("unexpected FCGI_BEGIN_REQUEST, ignoring");
166 return;
169 if (n != sizeof(struct fcgi_begin_request_body)) {
170 log_warn("wrong size %d != %lu", n,
171 sizeof(struct fcgi_begin_request_body));
172 return;
175 c->request_started = 1;
176 c->id = id;
179 void
180 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
182 uint32_t name_len, val_len;
183 uint8_t *sd, *val;
185 if (!c->request_started) {
186 log_warn("FCGI_PARAMS without FCGI_BEGIN_REQUEST, ignoring");
187 return;
190 if (c->id != id) {
191 log_warn("unexpected id, ignoring");
192 return;
195 if (n == 0) {
196 gotweb_process_request(c);
197 return;
200 while (n > 0) {
201 if (buf[0] >> 7 == 0) {
202 name_len = buf[0];
203 n--;
204 buf++;
205 } else {
206 if (n > 3) {
207 name_len = ((buf[0] & 0x7f) << 24) +
208 (buf[1] << 16) + (buf[2] << 8) + buf[3];
209 n -= 4;
210 buf += 4;
211 } else
212 return;
215 if (n == 0)
216 return;
218 if (buf[0] >> 7 == 0) {
219 val_len = buf[0];
220 n--;
221 buf++;
222 } else {
223 if (n > 3) {
224 val_len = ((buf[0] & 0x7f) << 24) +
225 (buf[1] << 16) + (buf[2] << 8) +
226 buf[3];
227 n -= 4;
228 buf += 4;
229 } else
230 return;
233 if (n < name_len + val_len)
234 return;
236 val = buf + name_len;
238 if (c->querystring[0] == '\0' &&
239 val_len < MAX_QUERYSTRING &&
240 name_len == 12 &&
241 strncmp(buf, "QUERY_STRING", 12) == 0) {
242 memcpy(c->querystring, val, val_len);
243 c->querystring[val_len] = '\0';
246 if (c->http_host[0] == '\0' &&
247 val_len < GOTWEBD_MAXTEXT &&
248 name_len == 9 &&
249 strncmp(buf, "HTTP_HOST", 9) == 0) {
250 memcpy(c->http_host, val, val_len);
251 c->http_host[val_len] = '\0';
253 /*
254 * lazily get subdomain
255 * will only get domain if no subdomain exists
256 * this can still work if gotweb server name is the same
257 */
258 sd = strchr(c->http_host, '.');
259 if (sd)
260 *sd = '\0';
263 if (c->script_name[0] == '\0' &&
264 val_len < MAX_SCRIPT_NAME &&
265 name_len == 11 &&
266 strncmp(buf, "SCRIPT_NAME", 11) == 0) {
267 memcpy(c->script_name, val, val_len);
268 c->script_name[val_len] = '\0';
271 if (c->server_name[0] == '\0' &&
272 val_len < MAX_SERVER_NAME &&
273 name_len == 11 &&
274 strncmp(buf, "SERVER_NAME", 11) == 0) {
275 memcpy(c->server_name, val, val_len);
276 c->server_name[val_len] = '\0';
279 buf += name_len + val_len;
280 n -= name_len - val_len;
284 void
285 fcgi_timeout(int fd, short events, void *arg)
287 fcgi_cleanup_request((struct request*) arg);
290 int
291 fcgi_vprintf(struct request *c, const char *fmt, va_list ap)
293 char *str;
294 int r;
296 r = vasprintf(&str, fmt, ap);
297 if (r == -1) {
298 log_warn("%s: asprintf", __func__);
299 return -1;
302 r = fcgi_gen_binary_response(c, str, r);
303 free(str);
304 return r;
307 int
308 fcgi_printf(struct request *c, const char *fmt, ...)
310 va_list ap;
311 int r;
313 va_start(ap, fmt);
314 r = fcgi_vprintf(c, fmt, ap);
315 va_end(ap);
317 return r;
320 int
321 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
323 int r;
325 if (c->sock->client_status == CLIENT_DISCONNECT)
326 return -1;
328 if (data == NULL || len == 0)
329 return 0;
331 /*
332 * special case: send big replies -like blobs- directly
333 * without copying.
334 */
335 if (len > sizeof(c->outbuf)) {
336 if (c->outbuf_len > 0) {
337 fcgi_send_response(c, FCGI_STDOUT,
338 c->outbuf, c->outbuf_len);
339 c->outbuf_len = 0;
341 return fcgi_send_response(c, FCGI_STDOUT, data, len);
344 if (len < sizeof(c->outbuf) - c->outbuf_len) {
345 memcpy(c->outbuf + c->outbuf_len, data, len);
346 c->outbuf_len += len;
347 return 0;
350 r = fcgi_send_response(c, FCGI_STDOUT, c->outbuf, c->outbuf_len);
351 if (r == -1)
352 return -1;
354 memcpy(c->outbuf, data, len);
355 c->outbuf_len = len;
356 return 0;
359 static int
360 send_response(struct request *c, int type, const uint8_t *data,
361 size_t len)
363 static const uint8_t padding[FCGI_PADDING_SIZE];
364 struct fcgi_record_header header;
365 struct iovec iov[3];
366 struct timespec ts;
367 ssize_t nw;
368 size_t padded_len, tot;
369 int i, err = 0, th = 2000;
371 ts.tv_sec = 0;
372 ts.tv_nsec = 50;
374 memset(&header, 0, sizeof(header));
375 header.version = 1;
376 header.type = type;
377 header.id = htons(c->id);
378 header.content_len = htons(len);
380 /* The FastCGI spec suggests to align the output buffer */
381 tot = sizeof(header) + len;
382 padded_len = FCGI_ALIGN(tot);
383 if (padded_len > tot) {
384 header.padding_len = padded_len - tot;
385 tot += header.padding_len;
388 iov[0].iov_base = &header;
389 iov[0].iov_len = sizeof(header);
391 iov[1].iov_base = (void *)data;
392 iov[1].iov_len = len;
394 iov[2].iov_base = (void *)padding;
395 iov[2].iov_len = header.padding_len;
397 dump_fcgi_record("resp ", &header);
399 /*
400 * XXX: add some simple write heuristics here
401 * On slower VMs, spotty connections, etc., we don't want to go right to
402 * disconnect. Let's at least try to write the data a few times before
403 * giving up.
404 */
405 while (tot > 0) {
406 nw = writev(c->fd, iov, nitems(iov));
407 if (nw == 0) {
408 c->sock->client_status = CLIENT_DISCONNECT;
409 break;
411 if (nw == -1) {
412 err++;
413 if (errno == EAGAIN && err < th) {
414 nanosleep(&ts, NULL);
415 continue;
417 log_warn("%s: write failure", __func__);
418 c->sock->client_status = CLIENT_DISCONNECT;
419 return -1;
422 if (nw != tot)
423 log_debug("%s: partial write: %zu vs %zu", __func__,
424 nw, tot);
426 tot -= nw;
427 for (i = 0; i < nitems(iov); ++i) {
428 if (nw < iov[i].iov_len) {
429 iov[i].iov_base += nw;
430 iov[i].iov_len -= nw;
431 break;
433 nw -= iov[i].iov_len;
434 iov[i].iov_len = 0;
438 return 0;
441 int
442 fcgi_send_response(struct request *c, int type, const void *data,
443 size_t len)
445 if (c->sock->client_status == CLIENT_DISCONNECT)
446 return -1;
448 while (len > FCGI_CONTENT_SIZE) {
449 if (send_response(c, type, data, len) == -1)
450 return -1;
452 data += FCGI_CONTENT_SIZE;
453 len -= FCGI_CONTENT_SIZE;
456 if (len == 0)
457 return 0;
459 return send_response(c, type, data, len);
462 void
463 fcgi_create_end_record(struct request *c)
465 struct fcgi_end_request_body end_request;
467 memset(&end_request, 0, sizeof(end_request));
468 end_request.app_status = htonl(0); /* script status */
469 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
471 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
472 sizeof(end_request));
475 void
476 fcgi_cleanup_request(struct request *c)
478 cgi_inflight--;
479 client_cnt--;
481 evtimer_del(&c->tmo);
482 if (event_initialized(&c->ev))
483 event_del(&c->ev);
485 close(c->fd);
486 gotweb_free_transport(c->t);
487 free(c);
490 void
491 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
493 dump_fcgi_record_header(p, h);
495 if (h->type == FCGI_BEGIN_REQUEST)
496 dump_fcgi_begin_request_body(p,
497 (struct fcgi_begin_request_body *)(h + 1));
498 else if (h->type == FCGI_END_REQUEST)
499 dump_fcgi_end_request_body(p,
500 (struct fcgi_end_request_body *)(h + 1));
503 void
504 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
506 log_debug("%sversion: %d", p, h->version);
507 log_debug("%stype: %d", p, h->type);
508 log_debug("%srequestId: %d", p, ntohs(h->id));
509 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
510 log_debug("%spaddingLength: %d", p, h->padding_len);
511 log_debug("%sreserved: %d", p, h->reserved);
514 void
515 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
517 log_debug("%srole %d", p, ntohs(b->role));
518 log_debug("%sflags %d", p, b->flags);
521 void
522 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
524 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
525 log_debug("%sprotocolStatus: %d", p, b->protocol_status);