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>
24 #include <errno.h>
25 #include <event.h>
26 #include <imsg.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <time.h>
31 #include <unistd.h>
33 #include "got_error.h"
35 #include "proc.h"
36 #include "gotwebd.h"
38 size_t fcgi_parse_record(uint8_t *, size_t, struct request *);
39 void fcgi_parse_begin_request(uint8_t *, uint16_t, struct request *,
40 uint16_t);
41 void fcgi_parse_params(uint8_t *, uint16_t, struct request *, uint16_t);
42 void fcgi_send_response(struct request *, struct fcgi_response *);
44 void dump_fcgi_record_header(const char *, struct fcgi_record_header *);
45 void dump_fcgi_begin_request_body(const char *,
46 struct fcgi_begin_request_body *);
47 void dump_fcgi_end_request_body(const char *,
48 struct fcgi_end_request_body *);
50 extern int cgi_inflight;
51 extern volatile int client_cnt;
53 void
54 fcgi_request(int fd, short events, void *arg)
55 {
56 struct request *c = arg;
57 ssize_t n;
58 size_t parsed = 0;
60 n = read(fd, c->buf + c->buf_pos + c->buf_len,
61 FCGI_RECORD_SIZE - c->buf_pos-c->buf_len);
63 switch (n) {
64 case -1:
65 switch (errno) {
66 case EINTR:
67 case EAGAIN:
68 return;
69 default:
70 goto fail;
71 }
72 break;
74 case 0:
75 log_debug("closed connection");
76 goto fail;
77 default:
78 break;
79 }
81 c->buf_len += n;
83 /*
84 * Parse the records as they are received. Per the FastCGI
85 * specification, the server need only receive the FastCGI
86 * parameter records in full; it is free to begin execution
87 * at that point, which is what happens here.
88 */
89 do {
90 parsed = fcgi_parse_record(c->buf + c->buf_pos, c->buf_len, c);
91 if (parsed != 0) {
92 c->buf_pos += parsed;
93 c->buf_len -= parsed;
94 }
95 } while (parsed > 0 && c->buf_len > 0);
97 /* Make space for further reads */
98 if (parsed != 0)
99 if (c->buf_len > 0) {
100 bcopy(c->buf + c->buf_pos, c->buf, c->buf_len);
101 c->buf_pos = 0;
103 return;
104 fail:
105 fcgi_cleanup_request(c);
108 size_t
109 fcgi_parse_record(uint8_t *buf, size_t n, struct request *c)
111 struct fcgi_record_header *h;
113 if (n < sizeof(struct fcgi_record_header))
114 return 0;
116 h = (struct fcgi_record_header*) buf;
118 dump_fcgi_record("", h);
120 if (n < sizeof(struct fcgi_record_header) + ntohs(h->content_len)
121 + h->padding_len)
122 return 0;
124 if (h->version != 1)
125 log_warn("wrong version");
127 switch (h->type) {
128 case FCGI_BEGIN_REQUEST:
129 fcgi_parse_begin_request(buf +
130 sizeof(struct fcgi_record_header),
131 ntohs(h->content_len), c, ntohs(h->id));
132 break;
133 case FCGI_PARAMS:
134 fcgi_parse_params(buf + sizeof(struct fcgi_record_header),
135 ntohs(h->content_len), c, ntohs(h->id));
136 break;
137 case FCGI_STDIN:
138 case FCGI_ABORT_REQUEST:
139 fcgi_create_end_record(c);
140 fcgi_cleanup_request(c);
141 return 0;
142 default:
143 log_warn("unimplemented type %d", h->type);
144 break;
147 return (sizeof(struct fcgi_record_header) + ntohs(h->content_len)
148 + h->padding_len);
151 void
152 fcgi_parse_begin_request(uint8_t *buf, uint16_t n,
153 struct request *c, uint16_t id)
155 /* XXX -- FCGI_CANT_MPX_CONN */
156 if (c->request_started) {
157 log_warn("unexpected FCGI_BEGIN_REQUEST, ignoring");
158 return;
161 if (n != sizeof(struct fcgi_begin_request_body)) {
162 log_warn("wrong size %d != %lu", n,
163 sizeof(struct fcgi_begin_request_body));
164 return;
167 c->request_started = 1;
169 c->id = id;
170 SLIST_INIT(&c->env);
171 c->env_count = 0;
174 void
175 fcgi_parse_params(uint8_t *buf, uint16_t n, struct request *c, uint16_t id)
177 struct env_val *env_entry;
178 uint32_t name_len, val_len;
179 uint8_t *sd, *dr_buf;
181 if (!c->request_started) {
182 log_warn("FCGI_PARAMS without FCGI_BEGIN_REQUEST, ignoring");
183 return;
186 if (c->id != id) {
187 log_warn("unexpected id, ignoring");
188 return;
191 if (n == 0) {
192 gotweb_process_request(c);
193 return;
196 while (n > 0) {
197 if (buf[0] >> 7 == 0) {
198 name_len = buf[0];
199 n--;
200 buf++;
201 } else {
202 if (n > 3) {
203 name_len = ((buf[0] & 0x7f) << 24) +
204 (buf[1] << 16) + (buf[2] << 8) + buf[3];
205 n -= 4;
206 buf += 4;
207 } else
208 return;
211 if (n > 0) {
212 if (buf[0] >> 7 == 0) {
213 val_len = buf[0];
214 n--;
215 buf++;
216 } else {
217 if (n > 3) {
218 val_len = ((buf[0] & 0x7f) << 24) +
219 (buf[1] << 16) + (buf[2] << 8) +
220 buf[3];
221 n -= 4;
222 buf += 4;
223 } else
224 return;
226 } else
227 return;
229 if (n < name_len + val_len)
230 return;
232 if ((env_entry = malloc(sizeof(struct env_val))) == NULL) {
233 log_warn("cannot malloc env_entry");
234 return;
237 if ((env_entry->val = calloc(sizeof(char), name_len + val_len +
238 2)) == NULL) {
239 log_warn("cannot allocate env_entry->val");
240 free(env_entry);
241 return;
244 bcopy(buf, env_entry->val, name_len);
245 buf += name_len;
246 n -= name_len;
248 env_entry->val[name_len] = '\0';
249 if (val_len < MAX_QUERYSTRING && strcmp(env_entry->val,
250 "QUERY_STRING") == 0 && c->querystring[0] == '\0') {
251 bcopy(buf, c->querystring, val_len);
252 c->querystring[val_len] = '\0';
254 if (val_len < GOTWEBD_MAXTEXT && strcmp(env_entry->val,
255 "HTTP_HOST") == 0 && c->http_host[0] == '\0') {
257 /*
258 * lazily get subdomain
259 * will only get domain if no subdomain exists
260 * this can still work if gotweb server name is the same
261 */
262 sd = strchr(buf, '.');
263 if (sd)
264 *sd = '\0';
266 bcopy(buf, c->http_host, val_len);
267 c->http_host[val_len] = '\0';
269 if (val_len < MAX_DOCUMENT_ROOT && strcmp(env_entry->val,
270 "DOCUMENT_ROOT") == 0 && c->document_root[0] == '\0') {
272 /* drop first char, as it's always / */
273 dr_buf = &buf[1];
275 bcopy(dr_buf, c->document_root, val_len - 1);
276 c->document_root[val_len] = '\0';
278 if (val_len < MAX_SERVER_NAME && strcmp(env_entry->val,
279 "SERVER_NAME") == 0 && c->server_name[0] == '\0') {
280 /* drop first char, as it's always / */
282 bcopy(buf, c->server_name, val_len);
283 c->server_name[val_len] = '\0';
285 env_entry->val[name_len] = '=';
287 bcopy(buf, (env_entry->val) + name_len + 1, val_len);
288 buf += val_len;
289 n -= val_len;
291 SLIST_INSERT_HEAD(&c->env, env_entry, entry);
292 log_debug("env[%d], %s", c->env_count, env_entry->val);
293 c->env_count++;
297 void
298 fcgi_timeout(int fd, short events, void *arg)
300 fcgi_cleanup_request((struct request*) arg);
303 int
304 fcgi_gen_binary_response(struct request *c, const uint8_t *data, int len)
306 struct fcgi_response *resp;
307 struct fcgi_record_header *header;
308 ssize_t n = 0;
309 int i;
311 if (c->sock->client_status == CLIENT_DISCONNECT)
312 return -1;
314 if (data == NULL || len == 0)
315 return 0;
317 if ((resp = calloc(1, sizeof(struct fcgi_response))) == NULL) {
318 log_warn("%s: cannot calloc fcgi_response", __func__);
319 return -1;
322 header = (struct fcgi_record_header*) resp->data;
323 header->version = 1;
324 header->type = FCGI_STDOUT;
325 header->id = htons(c->id);
326 header->padding_len = 0;
327 header->reserved = 0;
329 for (i = 0; i < len; i++) {
330 resp->data[i+8] = data[i];
331 n++;
334 header->content_len = htons(n);
335 resp->data_pos = 0;
336 resp->data_len = n + sizeof(struct fcgi_record_header);
337 fcgi_send_response(c, resp);
339 return 0;
342 int
343 fcgi_gen_response(struct request *c, const char *data)
345 if (data == NULL || *data == '\0')
346 return 0;
347 return fcgi_gen_binary_response(c, data, strlen(data));
350 void
351 fcgi_send_response(struct request *c, struct fcgi_response *resp)
353 struct fcgi_record_header *header;
354 struct timespec ts;
355 size_t padded_len, off;
356 ssize_t nw;
357 int err = 0, th = 2000;
359 ts.tv_sec = 0;
360 ts.tv_nsec = 50;
362 header = (struct fcgi_record_header*)resp->data;
364 /* The FastCGI spec suggests to align the output buffer */
365 padded_len = FCGI_ALIGN(resp->data_len);
366 if (padded_len > resp->data_len) {
367 /* There should always be FCGI_PADDING_SIZE bytes left */
368 if (padded_len > FCGI_RECORD_SIZE)
369 log_warn("response too long");
370 header->padding_len = padded_len - resp->data_len;
371 resp->data_len = padded_len;
374 dump_fcgi_record("resp ", header);
376 /*
377 * XXX: add some simple write heuristics here
378 * On slower VMs, spotty connections, etc., we don't want to go right to
379 * disconnect. Let's at least try to write the data a few times before
380 * giving up.
381 */
382 for (off = 0; off < resp->data_len; off += nw) {
383 nw = write(c->fd, resp->data + off, resp->data_len - off);
384 if (nw == 0) {
385 c->sock->client_status = CLIENT_DISCONNECT;
386 break;
388 if (nw == -1) {
389 err++;
390 if (errno == EAGAIN && err < th) {
391 nw = 0;
392 nanosleep(&ts, NULL);
393 continue;
395 log_warn("write");
396 c->sock->client_status = CLIENT_DISCONNECT;
397 break;
400 if (nw != resp->data_len - off)
401 log_debug("partial write: %zu vs %zu", nw,
402 resp->data_len - off);
405 free(resp);
408 void
409 fcgi_create_end_record(struct request *c)
411 struct fcgi_response *resp;
412 struct fcgi_record_header *header;
413 struct fcgi_end_request_body *end_request;
415 if ((resp = calloc(1, sizeof(struct fcgi_response))) == NULL) {
416 log_warn("cannot calloc fcgi_response");
417 return;
419 header = (struct fcgi_record_header*) resp->data;
420 header->version = 1;
421 header->type = FCGI_END_REQUEST;
422 header->id = htons(c->id);
423 header->content_len = htons(sizeof(struct
424 fcgi_end_request_body));
425 header->padding_len = 0;
426 header->reserved = 0;
427 end_request = (struct fcgi_end_request_body *) (resp->data +
428 sizeof(struct fcgi_record_header));
429 end_request->app_status = htonl(0); /* script_status */
430 end_request->protocol_status = FCGI_REQUEST_COMPLETE;
431 end_request->reserved[0] = 0;
432 end_request->reserved[1] = 0;
433 end_request->reserved[2] = 0;
434 resp->data_pos = 0;
435 resp->data_len = sizeof(struct fcgi_end_request_body) +
436 sizeof(struct fcgi_record_header);
437 fcgi_send_response(c, resp);
440 void
441 fcgi_cleanup_request(struct request *c)
443 cgi_inflight--;
444 client_cnt--;
446 evtimer_del(&c->tmo);
447 if (event_initialized(&c->ev))
448 event_del(&c->ev);
450 close(c->fd);
451 gotweb_free_transport(c->t);
452 free(c);
455 void
456 dump_fcgi_record(const char *p, struct fcgi_record_header *h)
458 dump_fcgi_record_header(p, h);
460 if (h->type == FCGI_BEGIN_REQUEST)
461 dump_fcgi_begin_request_body(p,
462 (struct fcgi_begin_request_body *)(h + 1));
463 else if (h->type == FCGI_END_REQUEST)
464 dump_fcgi_end_request_body(p,
465 (struct fcgi_end_request_body *)(h + 1));
468 void
469 dump_fcgi_record_header(const char* p, struct fcgi_record_header *h)
471 log_debug("%sversion: %d", p, h->version);
472 log_debug("%stype: %d", p, h->type);
473 log_debug("%srequestId: %d", p, ntohs(h->id));
474 log_debug("%scontentLength: %d", p, ntohs(h->content_len));
475 log_debug("%spaddingLength: %d", p, h->padding_len);
476 log_debug("%sreserved: %d", p, h->reserved);
479 void
480 dump_fcgi_begin_request_body(const char *p, struct fcgi_begin_request_body *b)
482 log_debug("%srole %d", p, ntohs(b->role));
483 log_debug("%sflags %d", p, b->flags);
486 void
487 dump_fcgi_end_request_body(const char *p, struct fcgi_end_request_body *b)
489 log_debug("%sappStatus: %d", p, ntohl(b->app_status));
490 log_debug("%sprotocolStatus: %d", p, b->protocol_status);