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 void 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 fcgi_create_end_record(c);
141 fcgi_cleanup_request(c);
142 return 0;
143 default:
144 log_warn("unimplemented type %d", h->type);
145 break;
148 return (sizeof(struct fcgi_record_header) + ntohs(h->content_len)
149 + h->padding_len);
152 void
153 fcgi_parse_begin_request(uint8_t *buf, uint16_t n,
154 struct request *c, uint16_t id)
156 /* XXX -- FCGI_CANT_MPX_CONN */
157 if (c->request_started) {
158 log_warn("unexpected FCGI_BEGIN_REQUEST, ignoring");
159 return;
162 if (n != sizeof(struct fcgi_begin_request_body)) {
163 log_warn("wrong size %d != %lu", n,
164 sizeof(struct fcgi_begin_request_body));
165 return;
168 c->request_started = 1;
170 c->id = id;
171 SLIST_INIT(&c->env);
172 c->env_count = 0;
175 void
176 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
178 struct env_val *env_entry;
179 uint32_t name_len, val_len;
180 uint8_t *sd, *dr_buf;
182 if (!c->request_started) {
183 log_warn("FCGI_PARAMS without FCGI_BEGIN_REQUEST, ignoring");
184 return;
187 if (c->id != id) {
188 log_warn("unexpected id, ignoring");
189 return;
192 if (n == 0) {
193 gotweb_process_request(c);
194 return;
197 while (n > 0) {
198 if (buf[0] >> 7 == 0) {
199 name_len = buf[0];
200 n--;
201 buf++;
202 } else {
203 if (n > 3) {
204 name_len = ((buf[0] & 0x7f) << 24) +
205 (buf[1] << 16) + (buf[2] << 8) + buf[3];
206 n -= 4;
207 buf += 4;
208 } else
209 return;
212 if (n > 0) {
213 if (buf[0] >> 7 == 0) {
214 val_len = buf[0];
215 n--;
216 buf++;
217 } else {
218 if (n > 3) {
219 val_len = ((buf[0] & 0x7f) << 24) +
220 (buf[1] << 16) + (buf[2] << 8) +
221 buf[3];
222 n -= 4;
223 buf += 4;
224 } else
225 return;
227 } else
228 return;
230 if (n < name_len + val_len)
231 return;
233 if ((env_entry = malloc(sizeof(struct env_val))) == NULL) {
234 log_warn("cannot malloc env_entry");
235 return;
238 if ((env_entry->val = calloc(sizeof(char), name_len + val_len +
239 2)) == NULL) {
240 log_warn("cannot allocate env_entry->val");
241 free(env_entry);
242 return;
245 bcopy(buf, env_entry->val, name_len);
246 buf += name_len;
247 n -= name_len;
249 env_entry->val[name_len] = '\0';
250 if (val_len < MAX_QUERYSTRING && strcmp(env_entry->val,
251 "QUERY_STRING") == 0 && c->querystring[0] == '\0') {
252 bcopy(buf, c->querystring, val_len);
253 c->querystring[val_len] = '\0';
255 if (val_len < GOTWEBD_MAXTEXT && strcmp(env_entry->val,
256 "HTTP_HOST") == 0 && c->http_host[0] == '\0') {
258 /*
259 * lazily get subdomain
260 * will only get domain if no subdomain exists
261 * this can still work if gotweb server name is the same
262 */
263 sd = strchr(buf, '.');
264 if (sd)
265 *sd = '\0';
267 bcopy(buf, c->http_host, val_len);
268 c->http_host[val_len] = '\0';
270 if (val_len < MAX_DOCUMENT_ROOT && strcmp(env_entry->val,
271 "DOCUMENT_ROOT") == 0 && c->document_root[0] == '\0') {
273 /* drop first char, as it's always / */
274 dr_buf = &buf[1];
276 bcopy(dr_buf, c->document_root, val_len - 1);
277 c->document_root[val_len] = '\0';
279 if (val_len < MAX_SERVER_NAME && strcmp(env_entry->val,
280 "SERVER_NAME") == 0 && c->server_name[0] == '\0') {
281 /* drop first char, as it's always / */
283 bcopy(buf, c->server_name, val_len);
284 c->server_name[val_len] = '\0';
286 env_entry->val[name_len] = '=';
288 bcopy(buf, (env_entry->val) + name_len + 1, val_len);
289 buf += val_len;
290 n -= val_len;
292 SLIST_INSERT_HEAD(&c->env, env_entry, entry);
293 log_debug("env[%d], %s", c->env_count, env_entry->val);
294 c->env_count++;
298 void
299 fcgi_timeout(int fd, short events, void *arg)
301 fcgi_cleanup_request((struct request*) arg);
304 int
305 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
307 if (c->sock->client_status == CLIENT_DISCONNECT)
308 return -1;
310 if (data == NULL || len == 0)
311 return 0;
313 fcgi_send_response(c, FCGI_STDOUT, data, len);
314 return 0;
317 int
318 fcgi_gen_response(struct request *c, const char *data)
320 if (data == NULL || *data == '\0')
321 return 0;
322 return fcgi_gen_binary_response(c, data, strlen(data));
325 static void
326 send_response(struct request *c, int type, const uint8_t *data,
327 size_t len)
329 static const uint8_t padding[FCGI_PADDING_SIZE];
330 struct fcgi_record_header header;
331 struct iovec iov[3];
332 struct timespec ts;
333 ssize_t nw;
334 size_t padded_len, tot;
335 int i, err = 0, th = 2000;
337 ts.tv_sec = 0;
338 ts.tv_nsec = 50;
340 memset(&header, 0, sizeof(header));
341 header.version = 1;
342 header.type = type;
343 header.id = htons(c->id);
344 header.content_len = htons(len);
346 /* The FastCGI spec suggests to align the output buffer */
347 tot = sizeof(header) + len;
348 padded_len = FCGI_ALIGN(tot);
349 if (padded_len > tot) {
350 header.padding_len = padded_len - tot;
351 tot += header.padding_len;
354 iov[0].iov_base = &header;
355 iov[0].iov_len = sizeof(header);
357 iov[1].iov_base = (void *)data;
358 iov[1].iov_len = len;
360 iov[2].iov_base = (void *)padding;
361 iov[2].iov_len = header.padding_len;
363 dump_fcgi_record("resp ", &header);
365 /*
366 * XXX: add some simple write heuristics here
367 * On slower VMs, spotty connections, etc., we don't want to go right to
368 * disconnect. Let's at least try to write the data a few times before
369 * giving up.
370 */
371 while (tot > 0) {
372 nw = writev(c->fd, iov, nitems(iov));
373 if (nw == 0) {
374 c->sock->client_status = CLIENT_DISCONNECT;
375 break;
377 if (nw == -1) {
378 err++;
379 if (errno == EAGAIN && err < th) {
380 nanosleep(&ts, NULL);
381 continue;
383 log_warn("%s: write failure", __func__);
384 c->sock->client_status = CLIENT_DISCONNECT;
385 break;
388 if (nw != tot)
389 log_debug("%s: partial write: %zu vs %zu", __func__,
390 nw, tot);
392 tot -= nw;
393 for (i = 0; i < nitems(iov); ++i) {
394 if (nw < iov[i].iov_len) {
395 iov[i].iov_base += nw;
396 iov[i].iov_len -= nw;
397 break;
399 nw -= iov[i].iov_len;
400 iov[i].iov_len = 0;
405 void
406 fcgi_send_response(struct request *c, int type, const void *data,
407 size_t len)
409 while (len > FCGI_CONTENT_SIZE) {
410 send_response(c, type, data, len);
411 if (c->sock->client_status == CLIENT_DISCONNECT)
412 return;
414 data += FCGI_CONTENT_SIZE;
415 len -= FCGI_CONTENT_SIZE;
418 if (len == 0)
419 return;
421 send_response(c, type, data, len);
424 void
425 fcgi_create_end_record(struct request *c)
427 struct fcgi_end_request_body end_request;
429 memset(&end_request, 0, sizeof(end_request));
430 end_request.app_status = htonl(0); /* script status */
431 end_request.protocol_status = FCGI_REQUEST_COMPLETE;
433 fcgi_send_response(c, FCGI_END_REQUEST, &end_request,
434 sizeof(end_request));
437 void
438 fcgi_cleanup_request(struct request *c)
440 cgi_inflight--;
441 client_cnt--;
443 evtimer_del(&c->tmo);
444 if (event_initialized(&c->ev))
445 event_del(&c->ev);
447 close(c->fd);
448 gotweb_free_transport(c->t);
449 free(c);
452 void
453 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
455 dump_fcgi_record_header(p, h);
457 if (h->type == FCGI_BEGIN_REQUEST)
458 dump_fcgi_begin_request_body(p,
459 (struct fcgi_begin_request_body *)(h + 1));
460 else if (h->type == FCGI_END_REQUEST)
461 dump_fcgi_end_request_body(p,
462 (struct fcgi_end_request_body *)(h + 1));
465 void
466 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
468 log_debug("%sversion: %d", p, h->version);
469 log_debug("%stype: %d", p, h->type);
470 log_debug("%srequestId: %d", p, ntohs(h->id));
471 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
472 log_debug("%spaddingLength: %d", p, h->padding_len);
473 log_debug("%sreserved: %d", p, h->reserved);
476 void
477 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
479 log_debug("%srole %d", p, ntohs(b->role));
480 log_debug("%sflags %d", p, b->flags);
483 void
484 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
486 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
487 log_debug("%sprotocolStatus: %d", p, b->protocol_status);