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;
177 c->id = id;
178 SLIST_INIT(&c->env);
179 c->env_count = 0;
182 void
183 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
185 struct env_val *env_entry;
186 uint32_t name_len, val_len;
187 uint8_t *sd, *dr_buf;
189 if (!c->request_started) {
190 log_warn("FCGI_PARAMS without FCGI_BEGIN_REQUEST, ignoring");
191 return;
194 if (c->id != id) {
195 log_warn("unexpected id, ignoring");
196 return;
199 if (n == 0) {
200 gotweb_process_request(c);
201 return;
204 while (n > 0) {
205 if (buf[0] >> 7 == 0) {
206 name_len = buf[0];
207 n--;
208 buf++;
209 } else {
210 if (n > 3) {
211 name_len = ((buf[0] & 0x7f) << 24) +
212 (buf[1] << 16) + (buf[2] << 8) + buf[3];
213 n -= 4;
214 buf += 4;
215 } else
216 return;
219 if (n > 0) {
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;
234 } else
235 return;
237 if (n < name_len + val_len)
238 return;
240 if ((env_entry = malloc(sizeof(struct env_val))) == NULL) {
241 log_warn("cannot malloc env_entry");
242 return;
245 if ((env_entry->val = calloc(sizeof(char), name_len + val_len +
246 2)) == NULL) {
247 log_warn("cannot allocate env_entry->val");
248 free(env_entry);
249 return;
252 bcopy(buf, env_entry->val, name_len);
253 buf += name_len;
254 n -= name_len;
256 env_entry->val[name_len] = '\0';
257 if (val_len < MAX_QUERYSTRING && strcmp(env_entry->val,
258 "QUERY_STRING") == 0 && c->querystring[0] == '\0') {
259 bcopy(buf, c->querystring, val_len);
260 c->querystring[val_len] = '\0';
262 if (val_len < GOTWEBD_MAXTEXT && strcmp(env_entry->val,
263 "HTTP_HOST") == 0 && c->http_host[0] == '\0') {
265 /*
266 * lazily get subdomain
267 * will only get domain if no subdomain exists
268 * this can still work if gotweb server name is the same
269 */
270 sd = strchr(buf, '.');
271 if (sd)
272 *sd = '\0';
274 bcopy(buf, c->http_host, val_len);
275 c->http_host[val_len] = '\0';
277 if (val_len < MAX_SCRIPT_NAME && strcmp(env_entry->val,
278 "SCRIPT_NAME") == 0 && c->script_name[0] == '\0') {
279 bcopy(dr_buf, c->script_name, val_len);
280 c->script_name[val_len] = '\0';
282 if (val_len < MAX_SERVER_NAME && strcmp(env_entry->val,
283 "SERVER_NAME") == 0 && c->server_name[0] == '\0') {
284 bcopy(buf, c->server_name, val_len);
285 c->server_name[val_len] = '\0';
287 env_entry->val[name_len] = '=';
289 bcopy(buf, (env_entry->val) + name_len + 1, val_len);
290 buf += val_len;
291 n -= val_len;
293 SLIST_INSERT_HEAD(&c->env, env_entry, entry);
294 log_debug("env[%d], %s", c->env_count, env_entry->val);
295 c->env_count++;
299 void
300 fcgi_timeout(int fd, short events, void *arg)
302 fcgi_cleanup_request((struct request*) arg);
305 int
306 fcgi_printf(struct request *c, const char *fmt, ...)
308 va_list ap;
309 char *str;
310 int r;
312 va_start(ap, fmt);
313 r = vasprintf(&str, fmt, ap);
314 va_end(ap);
316 if (r == -1) {
317 log_warn("%s: asprintf", __func__);
318 return -1;
321 r = fcgi_gen_binary_response(c, str, r);
322 free(str);
323 return r;
326 int
327 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
329 int r;
331 if (c->sock->client_status == CLIENT_DISCONNECT)
332 return -1;
334 if (data == NULL || len == 0)
335 return 0;
337 /*
338 * special case: send big replies -like blobs- directly
339 * without copying.
340 */
341 if (len > sizeof(c->outbuf)) {
342 if (c->outbuf_len > 0) {
343 fcgi_send_response(c, FCGI_STDOUT,
344 c->outbuf, c->outbuf_len);
345 c->outbuf_len = 0;
347 return fcgi_send_response(c, FCGI_STDOUT, data, len);
350 if (len < sizeof(c->outbuf) - c->outbuf_len) {
351 memcpy(c->outbuf + c->outbuf_len, data, len);
352 c->outbuf_len += len;
353 return 0;
356 r = fcgi_send_response(c, FCGI_STDOUT, c->outbuf, c->outbuf_len);
357 if (r == -1)
358 return -1;
360 memcpy(c->outbuf, data, len);
361 c->outbuf_len = len;
362 return 0;
365 static int
366 send_response(struct request *c, int type, const uint8_t *data,
367 size_t len)
369 static const uint8_t padding[FCGI_PADDING_SIZE];
370 struct fcgi_record_header header;
371 struct iovec iov[3];
372 struct timespec ts;
373 ssize_t nw;
374 size_t padded_len, tot;
375 int i, err = 0, th = 2000;
377 ts.tv_sec = 0;
378 ts.tv_nsec = 50;
380 memset(&header, 0, sizeof(header));
381 header.version = 1;
382 header.type = type;
383 header.id = htons(c->id);
384 header.content_len = htons(len);
386 /* The FastCGI spec suggests to align the output buffer */
387 tot = sizeof(header) + len;
388 padded_len = FCGI_ALIGN(tot);
389 if (padded_len > tot) {
390 header.padding_len = padded_len - tot;
391 tot += header.padding_len;
394 iov[0].iov_base = &header;
395 iov[0].iov_len = sizeof(header);
397 iov[1].iov_base = (void *)data;
398 iov[1].iov_len = len;
400 iov[2].iov_base = (void *)padding;
401 iov[2].iov_len = header.padding_len;
403 dump_fcgi_record("resp ", &header);
405 /*
406 * XXX: add some simple write heuristics here
407 * On slower VMs, spotty connections, etc., we don't want to go right to
408 * disconnect. Let's at least try to write the data a few times before
409 * giving up.
410 */
411 while (tot > 0) {
412 nw = writev(c->fd, iov, nitems(iov));
413 if (nw == 0) {
414 c->sock->client_status = CLIENT_DISCONNECT;
415 break;
417 if (nw == -1) {
418 err++;
419 if (errno == EAGAIN && err < th) {
420 nanosleep(&ts, NULL);
421 continue;
423 log_warn("%s: write failure", __func__);
424 c->sock->client_status = CLIENT_DISCONNECT;
425 return -1;
428 if (nw != tot)
429 log_debug("%s: partial write: %zu vs %zu", __func__,
430 nw, tot);
432 tot -= nw;
433 for (i = 0; i < nitems(iov); ++i) {
434 if (nw < iov[i].iov_len) {
435 iov[i].iov_base += nw;
436 iov[i].iov_len -= nw;
437 break;
439 nw -= iov[i].iov_len;
440 iov[i].iov_len = 0;
444 return 0;
447 int
448 fcgi_send_response(struct request *c, int type, const void *data,
449 size_t len)
451 if (c->sock->client_status == CLIENT_DISCONNECT)
452 return -1;
454 while (len > FCGI_CONTENT_SIZE) {
455 if (send_response(c, type, data, len) == -1)
456 return -1;
458 data += FCGI_CONTENT_SIZE;
459 len -= FCGI_CONTENT_SIZE;
462 if (len == 0)
463 return 0;
465 return send_response(c, type, data, len);
468 void
469 fcgi_create_end_record(struct request *c)
471 struct fcgi_end_request_body end_request;
473 memset(&end_request, 0, sizeof(end_request));
474 end_request.app_status = htonl(0); /* script status */
475 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
477 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
478 sizeof(end_request));
481 void
482 fcgi_cleanup_request(struct request *c)
484 cgi_inflight--;
485 client_cnt--;
487 evtimer_del(&c->tmo);
488 if (event_initialized(&c->ev))
489 event_del(&c->ev);
491 close(c->fd);
492 gotweb_free_transport(c->t);
493 free(c);
496 void
497 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
499 dump_fcgi_record_header(p, h);
501 if (h->type == FCGI_BEGIN_REQUEST)
502 dump_fcgi_begin_request_body(p,
503 (struct fcgi_begin_request_body *)(h + 1));
504 else if (h->type == FCGI_END_REQUEST)
505 dump_fcgi_end_request_body(p,
506 (struct fcgi_end_request_body *)(h + 1));
509 void
510 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
512 log_debug("%sversion: %d", p, h->version);
513 log_debug("%stype: %d", p, h->type);
514 log_debug("%srequestId: %d", p, ntohs(h->id));
515 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
516 log_debug("%spaddingLength: %d", p, h->padding_len);
517 log_debug("%sreserved: %d", p, h->reserved);
520 void
521 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
523 log_debug("%srole %d", p, ntohs(b->role));
524 log_debug("%sflags %d", p, b->flags);
527 void
528 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
530 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
531 log_debug("%sprotocolStatus: %d", p, b->protocol_status);