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 <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <time.h>
32 #include <unistd.h>
34 #include "got_error.h"
36 #include "proc.h"
37 #include "gotwebd.h"
39 size_t fcgi_parse_record(uint8_t *, size_t, struct request *);
40 void fcgi_parse_begin_request(uint8_t *, uint16_t, struct request *,
41 uint16_t);
42 void fcgi_parse_params(uint8_t *, uint16_t, struct request *, uint16_t);
43 int fcgi_send_response(struct request *, int, const void *, size_t);
45 void dump_fcgi_record_header(const char *, struct fcgi_record_header *);
46 void dump_fcgi_begin_request_body(const char *,
47 struct fcgi_begin_request_body *);
48 void dump_fcgi_end_request_body(const char *,
49 struct fcgi_end_request_body *);
51 extern int cgi_inflight;
52 extern volatile int client_cnt;
54 void
55 fcgi_request(int fd, short events, void *arg)
56 {
57 struct request *c = arg;
58 ssize_t n;
59 size_t parsed = 0;
61 n = read(fd, c->buf + c->buf_pos + c->buf_len,
62 FCGI_RECORD_SIZE - c->buf_pos-c->buf_len);
64 switch (n) {
65 case -1:
66 switch (errno) {
67 case EINTR:
68 case EAGAIN:
69 return;
70 default:
71 goto fail;
72 }
73 break;
75 case 0:
76 log_debug("closed connection");
77 goto fail;
78 default:
79 break;
80 }
82 c->buf_len += n;
84 /*
85 * Parse the records as they are received. Per the FastCGI
86 * specification, the server need only receive the FastCGI
87 * parameter records in full; it is free to begin execution
88 * at that point, which is what happens here.
89 */
90 do {
91 parsed = fcgi_parse_record(c->buf + c->buf_pos, c->buf_len, c);
92 if (parsed != 0) {
93 c->buf_pos += parsed;
94 c->buf_len -= parsed;
95 }
96 } while (parsed > 0 && c->buf_len > 0);
98 /* Make space for further reads */
99 if (parsed != 0)
100 if (c->buf_len > 0) {
101 bcopy(c->buf + c->buf_pos, c->buf, c->buf_len);
102 c->buf_pos = 0;
104 return;
105 fail:
106 fcgi_cleanup_request(c);
109 size_t
110 fcgi_parse_record(uint8_t *buf, size_t n, struct request *c)
112 struct fcgi_record_header *h;
114 if (n < sizeof(struct fcgi_record_header))
115 return 0;
117 h = (struct fcgi_record_header*) buf;
119 dump_fcgi_record("", h);
121 if (n < sizeof(struct fcgi_record_header) + ntohs(h->content_len)
122 + h->padding_len)
123 return 0;
125 if (h->version != 1)
126 log_warn("wrong version");
128 switch (h->type) {
129 case FCGI_BEGIN_REQUEST:
130 fcgi_parse_begin_request(buf +
131 sizeof(struct fcgi_record_header),
132 ntohs(h->content_len), c, ntohs(h->id));
133 break;
134 case FCGI_PARAMS:
135 fcgi_parse_params(buf + sizeof(struct fcgi_record_header),
136 ntohs(h->content_len), c, ntohs(h->id));
137 break;
138 case FCGI_STDIN:
139 case FCGI_ABORT_REQUEST:
140 if (c->sock->client_status != CLIENT_DISCONNECT &&
141 c->outbuf_len != 0) {
142 fcgi_send_response(c, FCGI_STDOUT, c->outbuf,
143 c->outbuf_len);
146 fcgi_create_end_record(c);
147 fcgi_cleanup_request(c);
148 return 0;
149 default:
150 log_warn("unimplemented type %d", h->type);
151 break;
154 return (sizeof(struct fcgi_record_header) + ntohs(h->content_len)
155 + h->padding_len);
158 void
159 fcgi_parse_begin_request(uint8_t *buf, uint16_t n,
160 struct request *c, uint16_t id)
162 /* XXX -- FCGI_CANT_MPX_CONN */
163 if (c->request_started) {
164 log_warn("unexpected FCGI_BEGIN_REQUEST, ignoring");
165 return;
168 if (n != sizeof(struct fcgi_begin_request_body)) {
169 log_warn("wrong size %d != %lu", n,
170 sizeof(struct fcgi_begin_request_body));
171 return;
174 c->request_started = 1;
176 c->id = id;
177 SLIST_INIT(&c->env);
178 c->env_count = 0;
181 void
182 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
184 struct env_val *env_entry;
185 uint32_t name_len, val_len;
186 uint8_t *sd, *dr_buf;
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 if (buf[0] >> 7 == 0) {
220 val_len = buf[0];
221 n--;
222 buf++;
223 } else {
224 if (n > 3) {
225 val_len = ((buf[0] & 0x7f) << 24) +
226 (buf[1] << 16) + (buf[2] << 8) +
227 buf[3];
228 n -= 4;
229 buf += 4;
230 } else
231 return;
233 } else
234 return;
236 if (n < name_len + val_len)
237 return;
239 if ((env_entry = malloc(sizeof(struct env_val))) == NULL) {
240 log_warn("cannot malloc env_entry");
241 return;
244 if ((env_entry->val = calloc(sizeof(char), name_len + val_len +
245 2)) == NULL) {
246 log_warn("cannot allocate env_entry->val");
247 free(env_entry);
248 return;
251 bcopy(buf, env_entry->val, name_len);
252 buf += name_len;
253 n -= name_len;
255 env_entry->val[name_len] = '\0';
256 if (val_len < MAX_QUERYSTRING && strcmp(env_entry->val,
257 "QUERY_STRING") == 0 && c->querystring[0] == '\0') {
258 bcopy(buf, c->querystring, val_len);
259 c->querystring[val_len] = '\0';
261 if (val_len < GOTWEBD_MAXTEXT && strcmp(env_entry->val,
262 "HTTP_HOST") == 0 && c->http_host[0] == '\0') {
264 /*
265 * lazily get subdomain
266 * will only get domain if no subdomain exists
267 * this can still work if gotweb server name is the same
268 */
269 sd = strchr(buf, '.');
270 if (sd)
271 *sd = '\0';
273 bcopy(buf, c->http_host, val_len);
274 c->http_host[val_len] = '\0';
276 if (val_len < MAX_DOCUMENT_ROOT && strcmp(env_entry->val,
277 "DOCUMENT_ROOT") == 0 && c->document_root[0] == '\0') {
279 /* drop first char, as it's always / */
280 dr_buf = &buf[1];
282 bcopy(dr_buf, c->document_root, val_len - 1);
283 c->document_root[val_len] = '\0';
285 if (val_len < MAX_SERVER_NAME && strcmp(env_entry->val,
286 "SERVER_NAME") == 0 && c->server_name[0] == '\0') {
287 /* drop first char, as it's always / */
289 bcopy(buf, c->server_name, val_len);
290 c->server_name[val_len] = '\0';
292 env_entry->val[name_len] = '=';
294 bcopy(buf, (env_entry->val) + name_len + 1, val_len);
295 buf += val_len;
296 n -= val_len;
298 SLIST_INSERT_HEAD(&c->env, env_entry, entry);
299 log_debug("env[%d], %s", c->env_count, env_entry->val);
300 c->env_count++;
304 void
305 fcgi_timeout(int fd, short events, void *arg)
307 fcgi_cleanup_request((struct request*) arg);
310 int
311 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
313 int r;
315 if (c->sock->client_status == CLIENT_DISCONNECT)
316 return -1;
318 if (data == NULL || len == 0)
319 return 0;
321 /*
322 * special case: send big replies -like blobs- directly
323 * without copying.
324 */
325 if (len > sizeof(c->outbuf)) {
326 if (c->outbuf_len > 0) {
327 fcgi_send_response(c, FCGI_STDOUT,
328 c->outbuf, c->outbuf_len);
329 c->outbuf_len = 0;
331 return fcgi_send_response(c, FCGI_STDOUT, data, len);
334 if (len < sizeof(c->outbuf) - c->outbuf_len) {
335 memcpy(c->outbuf + c->outbuf_len, data, len);
336 c->outbuf_len += len;
337 return 0;
340 r = fcgi_send_response(c, FCGI_STDOUT, c->outbuf, c->outbuf_len);
341 if (r == -1)
342 return -1;
344 memcpy(c->outbuf, data, len);
345 c->outbuf_len = len;
346 return 0;
349 int
350 fcgi_gen_response(struct request *c, const char *data)
352 if (data == NULL || *data == '\0')
353 return 0;
354 return fcgi_gen_binary_response(c, data, strlen(data));
357 static int
358 send_response(struct request *c, int type, const uint8_t *data,
359 size_t len)
361 static const uint8_t padding[FCGI_PADDING_SIZE];
362 struct fcgi_record_header header;
363 struct iovec iov[3];
364 struct timespec ts;
365 ssize_t nw;
366 size_t padded_len, tot;
367 int i, err = 0, th = 2000;
369 ts.tv_sec = 0;
370 ts.tv_nsec = 50;
372 memset(&header, 0, sizeof(header));
373 header.version = 1;
374 header.type = type;
375 header.id = htons(c->id);
376 header.content_len = htons(len);
378 /* The FastCGI spec suggests to align the output buffer */
379 tot = sizeof(header) + len;
380 padded_len = FCGI_ALIGN(tot);
381 if (padded_len > tot) {
382 header.padding_len = padded_len - tot;
383 tot += header.padding_len;
386 iov[0].iov_base = &header;
387 iov[0].iov_len = sizeof(header);
389 iov[1].iov_base = (void *)data;
390 iov[1].iov_len = len;
392 iov[2].iov_base = (void *)padding;
393 iov[2].iov_len = header.padding_len;
395 dump_fcgi_record("resp ", &header);
397 /*
398 * XXX: add some simple write heuristics here
399 * On slower VMs, spotty connections, etc., we don't want to go right to
400 * disconnect. Let's at least try to write the data a few times before
401 * giving up.
402 */
403 while (tot > 0) {
404 nw = writev(c->fd, iov, nitems(iov));
405 if (nw == 0) {
406 c->sock->client_status = CLIENT_DISCONNECT;
407 break;
409 if (nw == -1) {
410 err++;
411 if (errno == EAGAIN && err < th) {
412 nanosleep(&ts, NULL);
413 continue;
415 log_warn("%s: write failure", __func__);
416 c->sock->client_status = CLIENT_DISCONNECT;
417 return -1;
420 if (nw != tot)
421 log_debug("%s: partial write: %zu vs %zu", __func__,
422 nw, tot);
424 tot -= nw;
425 for (i = 0; i < nitems(iov); ++i) {
426 if (nw < iov[i].iov_len) {
427 iov[i].iov_base += nw;
428 iov[i].iov_len -= nw;
429 break;
431 nw -= iov[i].iov_len;
432 iov[i].iov_len = 0;
436 return 0;
439 int
440 fcgi_send_response(struct request *c, int type, const void *data,
441 size_t len)
443 if (c->sock->client_status == CLIENT_DISCONNECT)
444 return -1;
446 while (len > FCGI_CONTENT_SIZE) {
447 if (send_response(c, type, data, len) == -1)
448 return -1;
450 data += FCGI_CONTENT_SIZE;
451 len -= FCGI_CONTENT_SIZE;
454 if (len == 0)
455 return 0;
457 return send_response(c, type, data, len);
460 void
461 fcgi_create_end_record(struct request *c)
463 struct fcgi_end_request_body end_request;
465 memset(&end_request, 0, sizeof(end_request));
466 end_request.app_status = htonl(0); /* script status */
467 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
469 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
470 sizeof(end_request));
473 void
474 fcgi_cleanup_request(struct request *c)
476 cgi_inflight--;
477 client_cnt--;
479 evtimer_del(&c->tmo);
480 if (event_initialized(&c->ev))
481 event_del(&c->ev);
483 close(c->fd);
484 gotweb_free_transport(c->t);
485 free(c);
488 void
489 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
491 dump_fcgi_record_header(p, h);
493 if (h->type == FCGI_BEGIN_REQUEST)
494 dump_fcgi_begin_request_body(p,
495 (struct fcgi_begin_request_body *)(h + 1));
496 else if (h->type == FCGI_END_REQUEST)
497 dump_fcgi_end_request_body(p,
498 (struct fcgi_end_request_body *)(h + 1));
501 void
502 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
504 log_debug("%sversion: %d", p, h->version);
505 log_debug("%stype: %d", p, h->type);
506 log_debug("%srequestId: %d", p, ntohs(h->id));
507 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
508 log_debug("%spaddingLength: %d", p, h->padding_len);
509 log_debug("%sreserved: %d", p, h->reserved);
512 void
513 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
515 log_debug("%srole %d", p, ntohs(b->role));
516 log_debug("%sflags %d", p, b->flags);
519 void
520 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
522 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
523 log_debug("%sprotocolStatus: %d", p, b->protocol_status);