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"
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 }
99 } while (parsed > 0 && c->buf_len > 0);
101 /* Make space for further reads */
102 if (parsed != 0)
103 if (c->buf_len > 0) {
104 bcopy(c->buf + c->buf_pos, c->buf, c->buf_len);
105 c->buf_pos = 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;
179 c->id = id;
180 SLIST_INIT(&c->env);
181 c->env_count = 0;
184 void
185 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
187 struct env_val *env_entry;
188 uint32_t name_len, val_len;
189 uint8_t *sd, *dr_buf;
191 if (!c->request_started) {
192 log_warn("FCGI_PARAMS without FCGI_BEGIN_REQUEST, ignoring");
193 return;
196 if (c->id != id) {
197 log_warn("unexpected id, ignoring");
198 return;
201 if (n == 0) {
202 gotweb_process_request(c);
203 return;
206 while (n > 0) {
207 if (buf[0] >> 7 == 0) {
208 name_len = buf[0];
209 n--;
210 buf++;
211 } else {
212 if (n > 3) {
213 name_len = ((buf[0] & 0x7f) << 24) +
214 (buf[1] << 16) + (buf[2] << 8) + buf[3];
215 n -= 4;
216 buf += 4;
217 } else
218 return;
221 if (n > 0) {
222 if (buf[0] >> 7 == 0) {
223 val_len = buf[0];
224 n--;
225 buf++;
226 } else {
227 if (n > 3) {
228 val_len = ((buf[0] & 0x7f) << 24) +
229 (buf[1] << 16) + (buf[2] << 8) +
230 buf[3];
231 n -= 4;
232 buf += 4;
233 } else
234 return;
236 } else
237 return;
239 if (n < name_len + val_len)
240 return;
242 if ((env_entry = malloc(sizeof(struct env_val))) == NULL) {
243 log_warn("cannot malloc env_entry");
244 return;
247 if ((env_entry->val = calloc(sizeof(char), name_len + val_len +
248 2)) == NULL) {
249 log_warn("cannot allocate env_entry->val");
250 free(env_entry);
251 return;
254 bcopy(buf, env_entry->val, name_len);
255 buf += name_len;
256 n -= name_len;
258 env_entry->val[name_len] = '\0';
259 if (val_len < MAX_QUERYSTRING && strcmp(env_entry->val,
260 "QUERY_STRING") == 0 && c->querystring[0] == '\0') {
261 bcopy(buf, c->querystring, val_len);
262 c->querystring[val_len] = '\0';
264 if (val_len < GOTWEBD_MAXTEXT && strcmp(env_entry->val,
265 "HTTP_HOST") == 0 && c->http_host[0] == '\0') {
267 /*
268 * lazily get subdomain
269 * will only get domain if no subdomain exists
270 * this can still work if gotweb server name is the same
271 */
272 sd = strchr(buf, '.');
273 if (sd)
274 *sd = '\0';
276 bcopy(buf, c->http_host, val_len);
277 c->http_host[val_len] = '\0';
279 if (val_len < MAX_DOCUMENT_ROOT && strcmp(env_entry->val,
280 "DOCUMENT_ROOT") == 0 && c->document_root[0] == '\0') {
282 /* drop first char, as it's always / */
283 dr_buf = &buf[1];
285 bcopy(dr_buf, c->document_root, val_len - 1);
286 c->document_root[val_len] = '\0';
288 if (val_len < MAX_SERVER_NAME && strcmp(env_entry->val,
289 "SERVER_NAME") == 0 && c->server_name[0] == '\0') {
290 /* drop first char, as it's always / */
292 bcopy(buf, c->server_name, val_len);
293 c->server_name[val_len] = '\0';
295 env_entry->val[name_len] = '=';
297 bcopy(buf, (env_entry->val) + name_len + 1, val_len);
298 buf += val_len;
299 n -= val_len;
301 SLIST_INSERT_HEAD(&c->env, env_entry, entry);
302 log_debug("env[%d], %s", c->env_count, env_entry->val);
303 c->env_count++;
307 void
308 fcgi_timeout(int fd, short events, void *arg)
310 fcgi_cleanup_request((struct request*) arg);
313 int
314 fcgi_printf(struct request *c, const char *fmt, ...)
316 va_list ap;
317 char *str;
318 int r;
320 va_start(ap, fmt);
321 r = vasprintf(&str, fmt, ap);
322 va_end(ap);
324 if (r == -1) {
325 log_warn("%s: asprintf", __func__);
326 return -1;
329 r = fcgi_gen_binary_response(c, str, r);
330 free(str);
331 return r;
334 int
335 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
337 int r;
339 if (c->sock->client_status == CLIENT_DISCONNECT)
340 return -1;
342 if (data == NULL || len == 0)
343 return 0;
345 /*
346 * special case: send big replies -like blobs- directly
347 * without copying.
348 */
349 if (len > sizeof(c->outbuf)) {
350 if (c->outbuf_len > 0) {
351 fcgi_send_response(c, FCGI_STDOUT,
352 c->outbuf, c->outbuf_len);
353 c->outbuf_len = 0;
355 return fcgi_send_response(c, FCGI_STDOUT, data, len);
358 if (len < sizeof(c->outbuf) - c->outbuf_len) {
359 memcpy(c->outbuf + c->outbuf_len, data, len);
360 c->outbuf_len += len;
361 return 0;
364 r = fcgi_send_response(c, FCGI_STDOUT, c->outbuf, c->outbuf_len);
365 if (r == -1)
366 return -1;
368 memcpy(c->outbuf, data, len);
369 c->outbuf_len = len;
370 return 0;
373 static int
374 send_response(struct request *c, int type, const uint8_t *data,
375 size_t len)
377 static const uint8_t padding[FCGI_PADDING_SIZE];
378 struct fcgi_record_header header;
379 struct iovec iov[3];
380 struct timespec ts;
381 ssize_t nw;
382 size_t padded_len, tot;
383 int i, err = 0, th = 2000;
385 ts.tv_sec = 0;
386 ts.tv_nsec = 50;
388 memset(&header, 0, sizeof(header));
389 header.version = 1;
390 header.type = type;
391 header.id = htons(c->id);
392 header.content_len = htons(len);
394 /* The FastCGI spec suggests to align the output buffer */
395 tot = sizeof(header) + len;
396 padded_len = FCGI_ALIGN(tot);
397 if (padded_len > tot) {
398 header.padding_len = padded_len - tot;
399 tot += header.padding_len;
402 iov[0].iov_base = &header;
403 iov[0].iov_len = sizeof(header);
405 iov[1].iov_base = (void *)data;
406 iov[1].iov_len = len;
408 iov[2].iov_base = (void *)padding;
409 iov[2].iov_len = header.padding_len;
411 dump_fcgi_record("resp ", &header);
413 /*
414 * XXX: add some simple write heuristics here
415 * On slower VMs, spotty connections, etc., we don't want to go right to
416 * disconnect. Let's at least try to write the data a few times before
417 * giving up.
418 */
419 while (tot > 0) {
420 nw = writev(c->fd, iov, nitems(iov));
421 if (nw == 0) {
422 c->sock->client_status = CLIENT_DISCONNECT;
423 break;
425 if (nw == -1) {
426 err++;
427 if (errno == EAGAIN && err < th) {
428 nanosleep(&ts, NULL);
429 continue;
431 log_warn("%s: write failure", __func__);
432 c->sock->client_status = CLIENT_DISCONNECT;
433 return -1;
436 if (nw != tot)
437 log_debug("%s: partial write: %zu vs %zu", __func__,
438 nw, tot);
440 tot -= nw;
441 for (i = 0; i < nitems(iov); ++i) {
442 if (nw < iov[i].iov_len) {
443 iov[i].iov_base += nw;
444 iov[i].iov_len -= nw;
445 break;
447 nw -= iov[i].iov_len;
448 iov[i].iov_len = 0;
452 return 0;
455 int
456 fcgi_send_response(struct request *c, int type, const void *data,
457 size_t len)
459 if (c->sock->client_status == CLIENT_DISCONNECT)
460 return -1;
462 while (len > FCGI_CONTENT_SIZE) {
463 if (send_response(c, type, data, len) == -1)
464 return -1;
466 data += FCGI_CONTENT_SIZE;
467 len -= FCGI_CONTENT_SIZE;
470 if (len == 0)
471 return 0;
473 return send_response(c, type, data, len);
476 void
477 fcgi_create_end_record(struct request *c)
479 struct fcgi_end_request_body end_request;
481 memset(&end_request, 0, sizeof(end_request));
482 end_request.app_status = htonl(0); /* script status */
483 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
485 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
486 sizeof(end_request));
489 void
490 fcgi_cleanup_request(struct request *c)
492 cgi_inflight--;
493 client_cnt--;
495 evtimer_del(&c->tmo);
496 if (event_initialized(&c->ev))
497 event_del(&c->ev);
499 close(c->fd);
500 gotweb_free_transport(c->t);
501 free(c);
504 void
505 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
507 dump_fcgi_record_header(p, h);
509 if (h->type == FCGI_BEGIN_REQUEST)
510 dump_fcgi_begin_request_body(p,
511 (struct fcgi_begin_request_body *)(h + 1));
512 else if (h->type == FCGI_END_REQUEST)
513 dump_fcgi_end_request_body(p,
514 (struct fcgi_end_request_body *)(h + 1));
517 void
518 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
520 log_debug("%sversion: %d", p, h->version);
521 log_debug("%stype: %d", p, h->type);
522 log_debug("%srequestId: %d", p, ntohs(h->id));
523 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
524 log_debug("%spaddingLength: %d", p, h->padding_len);
525 log_debug("%sreserved: %d", p, h->reserved);
528 void
529 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
531 log_debug("%srole %d", p, ntohs(b->role));
532 log_debug("%sflags %d", p, b->flags);
535 void
536 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
538 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
539 log_debug("%sprotocolStatus: %d", p, b->protocol_status);