xref: /lighttpd1.4/src/mod_cgi.c (revision 66698469)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "stat_cache.h"
5 #include "http_kv.h"
6 #include "fdlog.h"
7 #include "log.h"
8 #include "response.h"
9 #include "http_cgi.h"
10 #include "http_chunk.h"
11 #include "http_header.h"
12 
13 #include "plugin.h"
14 
15 #include <sys/types.h>
16 #include "sys-socket.h"
17 #ifdef HAVE_SYS_WAIT_H
18 #include <sys/wait.h>
19 #endif
20 
21 #include <unistd.h>
22 #include <errno.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <fdevent.h>
26 
27 #include <fcntl.h>
28 #include <signal.h>
29 
30 typedef struct {
31 	uintptr_t *offsets;
32 	size_t osize;
33 	size_t oused;
34 	buffer *b;
35 	buffer *boffsets;
36 	buffer *ld_preload;
37 	buffer *ld_library_path;
38       #ifdef __CYGWIN__
39 	buffer *systemroot;
40       #endif
41 } env_accum;
42 
43 typedef struct {
44 	unix_time64_t read_timeout;
45 	unix_time64_t write_timeout;
46 	int signal_fin;
47 } cgi_limits;
48 
49 typedef struct {
50 	const array *cgi;
51 	const cgi_limits *limits;
52 	unsigned short execute_x_only;
53 	unsigned short local_redir;
54 	unsigned short xsendfile_allow;
55 	unsigned short upgrade;
56 	const array *xsendfile_docroot;
57 } plugin_config;
58 
59 struct cgi_pid_t;
60 
61 typedef struct {
62 	PLUGIN_DATA;
63 	plugin_config defaults;
64 	plugin_config conf;
65 	int tempfile_accum;
66 	struct cgi_pid_t *cgi_pid;
67 	env_accum env;
68 } plugin_data;
69 
70 typedef struct {
71 	struct cgi_pid_t *cgi_pid;
72 	int fd;
73 	int fdtocgi;
74 	int rd_revents;
75 	int wr_revents;
76 	fdnode *fdn;
77 	fdnode *fdntocgi;
78 
79 	request_st *r;
80 	connection *con;          /* dumb pointer */
81 	struct fdevents *ev;      /* dumb pointer */
82 	plugin_data *plugin_data; /* dumb pointer */
83 
84 	buffer *response;
85 	unix_time64_t read_ts;
86 	unix_time64_t write_ts;
87 	buffer *cgi_handler;      /* dumb pointer */
88 	http_response_opts opts;
89 	plugin_config conf;
90 	off_t orig_reqbody_length;
91 } handler_ctx;
92 
93 typedef struct cgi_pid_t {
94 	pid_t pid;
95 	int signal_sent;
96 	handler_ctx *hctx;
97 	struct cgi_pid_t *next;
98 	struct cgi_pid_t *prev;
99 } cgi_pid_t;
100 
101 static handler_ctx * cgi_handler_ctx_init(void) {
102 	handler_ctx *hctx = calloc(1, sizeof(*hctx));
103 
104 	force_assert(hctx);
105 
106 	hctx->response = chunk_buffer_acquire();
107 	hctx->fd = -1;
108 	hctx->fdtocgi = -1;
109 
110 	return hctx;
111 }
112 
113 static void cgi_handler_ctx_free(handler_ctx *hctx) {
114 	chunk_buffer_release(hctx->response);
115 	free(hctx);
116 }
117 
118 INIT_FUNC(mod_cgi_init) {
119 	plugin_data *p;
120 	const char *s;
121 
122 	p = calloc(1, sizeof(*p));
123 
124 	force_assert(p);
125 
126 	/* for valgrind */
127 	s = getenv("LD_PRELOAD");
128 	if (s) buffer_copy_string((p->env.ld_preload = buffer_init()), s);
129 	s = getenv("LD_LIBRARY_PATH");
130 	if (s) buffer_copy_string((p->env.ld_library_path = buffer_init()), s);
131       #ifdef __CYGWIN__
132 	/* CYGWIN needs SYSTEMROOT */
133 	s = getenv("SYSTEMROOT");
134 	if (s) buffer_copy_string((p->env.systemroot = buffer_init()), s);
135       #endif
136 
137 	return p;
138 }
139 
140 
141 FREE_FUNC(mod_cgi_free) {
142 	plugin_data *p = p_d;
143 	buffer_free(p->env.ld_preload);
144 	buffer_free(p->env.ld_library_path);
145       #ifdef __CYGWIN__
146 	buffer_free(p->env.systemroot);
147       #endif
148 
149     for (cgi_pid_t *cgi_pid = p->cgi_pid, *next; cgi_pid; cgi_pid = next) {
150         next = cgi_pid->next;
151         free(cgi_pid);
152     }
153 
154     if (NULL == p->cvlist) return;
155     /* (init i to 0 if global context; to 1 to skip empty global context) */
156     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
157         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
158         for (; -1 != cpv->k_id; ++cpv) {
159             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
160             switch (cpv->k_id) {
161               case 6: /* cgi.limits */
162                 free(cpv->v.v);
163                 break;
164               default:
165                 break;
166             }
167         }
168     }
169 }
170 
171 static void mod_cgi_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
172     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
173       case 0: /* cgi.assign */
174         pconf->cgi = cpv->v.a;
175         break;
176       case 1: /* cgi.execute-x-only */
177         pconf->execute_x_only = (unsigned short)cpv->v.u;
178         break;
179       case 2: /* cgi.x-sendfile */
180         pconf->xsendfile_allow = (unsigned short)cpv->v.u;
181         break;
182       case 3: /* cgi.x-sendfile-docroot */
183         pconf->xsendfile_docroot = cpv->v.a;
184         break;
185       case 4: /* cgi.local-redir */
186         pconf->local_redir = (unsigned short)cpv->v.u;
187         break;
188       case 5: /* cgi.upgrade */
189         pconf->upgrade = (unsigned short)cpv->v.u;
190         break;
191       case 6: /* cgi.limits */
192         if (cpv->vtype != T_CONFIG_LOCAL) break;
193         pconf->limits = cpv->v.v;
194         break;
195       default:/* should not happen */
196         return;
197     }
198 }
199 
200 static void mod_cgi_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
201     do {
202         mod_cgi_merge_config_cpv(pconf, cpv);
203     } while ((++cpv)->k_id != -1);
204 }
205 
206 static void mod_cgi_patch_config(request_st * const r, plugin_data * const p) {
207     p->conf = p->defaults; /* copy small struct instead of memcpy() */
208     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
209     for (int i = 1, used = p->nconfig; i < used; ++i) {
210         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
211             mod_cgi_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
212     }
213 }
214 
215 __attribute_cold__
216 __attribute_pure__
217 static int mod_cgi_str_to_signal (const char *s, int default_sig) {
218     static const struct { const char *name; int sig; } sigs[] = {
219       { "HUP",  SIGHUP  }
220      ,{ "INT",  SIGINT  }
221      ,{ "QUIT", SIGQUIT }
222      ,{ "ILL",  SIGILL  }
223      ,{ "TRAP", SIGTRAP }
224      ,{ "ABRT", SIGABRT }
225      #ifdef SIGBUS
226      ,{ "BUS",  SIGBUS  }
227      #endif
228      ,{ "FPE",  SIGFPE  }
229      ,{ "KILL", SIGKILL }
230      #ifdef SIGUSR1
231      ,{ "USR1", SIGUSR1 }
232      #endif
233      ,{ "SEGV", SIGSEGV }
234      #ifdef SIGUSR2
235      ,{ "USR2", SIGUSR2 }
236      #endif
237      ,{ "PIPE", SIGPIPE }
238      ,{ "ALRM", SIGALRM }
239      ,{ "TERM", SIGTERM }
240      #ifdef SIGCHLD
241      ,{ "CHLD", SIGCHLD }
242      #endif
243      #ifdef SIGCONT
244      ,{ "CONT", SIGCONT }
245      #endif
246      #ifdef SIGURG
247      ,{ "URG",  SIGURG  }
248      #endif
249      #ifdef SIGXCPU
250      ,{ "XCPU", SIGXCPU }
251      #endif
252      #ifdef SIGXFSZ
253      ,{ "XFSZ", SIGXFSZ }
254      #endif
255      #ifdef SIGWINCH
256      ,{ "WINCH",SIGWINCH}
257      #endif
258      #ifdef SIGPOLL
259      ,{ "POLL", SIGPOLL }
260      #endif
261      #ifdef SIGIO
262      ,{ "IO",   SIGIO   }
263      #endif
264     };
265 
266     if (s[0] == 'S' && s[1] == 'I' && s[2] == 'G') s += 3; /*("SIG" prefix)*/
267     for (uint32_t i = 0; i < sizeof(sigs)/sizeof(*sigs); ++i) {
268         if (0 == strcmp(s, sigs[i].name)) return sigs[i].sig;
269     }
270     return default_sig;
271 }
272 
273 static cgi_limits * mod_cgi_parse_limits(const array * const a, log_error_st * const errh) {
274     cgi_limits * const limits = calloc(1, sizeof(cgi_limits));
275     force_assert(limits);
276     for (uint32_t i = 0; i < a->used; ++i) {
277         const data_unset * const du = a->data[i];
278         int32_t v = config_plugin_value_to_int32(du, -1);
279         if (buffer_eq_icase_slen(&du->key, CONST_STR_LEN("read-timeout"))) {
280             limits->read_timeout = (unix_time64_t)v;
281             continue;
282         }
283         if (buffer_eq_icase_slen(&du->key, CONST_STR_LEN("write-timeout"))) {
284             limits->write_timeout = (unix_time64_t)v;
285             continue;
286         }
287         if (buffer_eq_icase_slen(&du->key, CONST_STR_LEN("tcp-fin-propagate"))) {
288             if (-1 == v) {
289                 v = SIGTERM;
290                 if (du->type == TYPE_STRING) {
291                     buffer * const vstr = &((data_string *)du)->value;
292                     buffer_to_upper(vstr);
293                     v = mod_cgi_str_to_signal(vstr->ptr, SIGTERM);
294                 }
295             }
296             limits->signal_fin = v;
297             continue;
298         }
299         log_error(errh, __FILE__, __LINE__,
300                   "unrecognized cgi.limits param: %s", du->key.ptr);
301     }
302     return limits;
303 }
304 
305 SETDEFAULTS_FUNC(mod_cgi_set_defaults) {
306     static const config_plugin_keys_t cpk[] = {
307       { CONST_STR_LEN("cgi.assign"),
308         T_CONFIG_ARRAY_KVSTRING,
309         T_CONFIG_SCOPE_CONNECTION }
310      ,{ CONST_STR_LEN("cgi.execute-x-only"),
311         T_CONFIG_BOOL,
312         T_CONFIG_SCOPE_CONNECTION }
313      ,{ CONST_STR_LEN("cgi.x-sendfile"),
314         T_CONFIG_BOOL,
315         T_CONFIG_SCOPE_CONNECTION }
316      ,{ CONST_STR_LEN("cgi.x-sendfile-docroot"),
317         T_CONFIG_ARRAY_VLIST,
318         T_CONFIG_SCOPE_CONNECTION }
319      ,{ CONST_STR_LEN("cgi.local-redir"),
320         T_CONFIG_BOOL,
321         T_CONFIG_SCOPE_CONNECTION }
322      ,{ CONST_STR_LEN("cgi.upgrade"),
323         T_CONFIG_BOOL,
324         T_CONFIG_SCOPE_CONNECTION }
325      ,{ CONST_STR_LEN("cgi.limits"),
326         T_CONFIG_ARRAY_KVANY,
327         T_CONFIG_SCOPE_CONNECTION }
328      ,{ NULL, 0,
329         T_CONFIG_UNSET,
330         T_CONFIG_SCOPE_UNSET }
331     };
332 
333     plugin_data * const p = p_d;
334     if (!config_plugin_values_init(srv, p, cpk, "mod_cgi"))
335         return HANDLER_ERROR;
336 
337     /* process and validate config directives
338      * (init i to 0 if global context; to 1 to skip empty global context) */
339     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
340         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
341         for (; -1 != cpv->k_id; ++cpv) {
342             switch (cpv->k_id) {
343               case 0: /* cgi.assign */
344               case 1: /* cgi.execute-x-only */
345               case 2: /* cgi.x-sendfile */
346                 break;
347               case 3: /* cgi.x-sendfile-docroot */
348                 for (uint32_t j = 0; j < cpv->v.a->used; ++j) {
349                     data_string *ds = (data_string *)cpv->v.a->data[j];
350                     if (ds->value.ptr[0] != '/') {
351                         log_error(srv->errh, __FILE__, __LINE__,
352                           "%s paths must begin with '/'; invalid: \"%s\"",
353                           cpk[cpv->k_id].k, ds->value.ptr);
354                         return HANDLER_ERROR;
355                     }
356                     buffer_path_simplify(&ds->value);
357                     buffer_append_slash(&ds->value);
358                 }
359                 break;
360               case 4: /* cgi.local-redir */
361               case 5: /* cgi.upgrade */
362                 break;
363               case 6: /* cgi.limits */
364                 cpv->v.v = mod_cgi_parse_limits(cpv->v.a, srv->errh);
365                 if (NULL == cpv->v.v) return HANDLER_ERROR;
366                 cpv->vtype = T_CONFIG_LOCAL;
367                 break;
368               default:/* should not happen */
369                 break;
370             }
371         }
372     }
373 
374     /* initialize p->defaults from global config context */
375     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
376         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
377         if (-1 != cpv->k_id)
378             mod_cgi_merge_config(&p->defaults, cpv);
379     }
380 
381     p->tempfile_accum = config_feature_bool(srv, "cgi.tempfile-accum", 1);
382 
383     return HANDLER_GO_ON;
384 }
385 
386 
387 static cgi_pid_t * cgi_pid_add(plugin_data *p, pid_t pid, handler_ctx *hctx) {
388     cgi_pid_t *cgi_pid = malloc(sizeof(cgi_pid_t));
389     force_assert(cgi_pid);
390     cgi_pid->pid = pid;
391     cgi_pid->signal_sent = 0;
392     cgi_pid->hctx = hctx;
393     cgi_pid->prev = NULL;
394     cgi_pid->next = p->cgi_pid;
395     p->cgi_pid = cgi_pid;
396     return cgi_pid;
397 }
398 
399 static void cgi_pid_kill(cgi_pid_t *cgi_pid, int sig) {
400     cgi_pid->signal_sent = sig; /*(save last signal sent)*/
401     kill(cgi_pid->pid, sig);
402 }
403 
404 static void cgi_pid_del(plugin_data *p, cgi_pid_t *cgi_pid) {
405     if (cgi_pid->prev)
406         cgi_pid->prev->next = cgi_pid->next;
407     else
408         p->cgi_pid = cgi_pid->next;
409 
410     if (cgi_pid->next)
411         cgi_pid->next->prev = cgi_pid->prev;
412 
413     free(cgi_pid);
414 }
415 
416 
417 static void cgi_connection_close_fdtocgi(handler_ctx *hctx) {
418 	/*(closes only hctx->fdtocgi)*/
419 	if (-1 == hctx->fdtocgi) return;
420 	struct fdevents * const ev = hctx->ev;
421 	fdevent_fdnode_event_del(ev, hctx->fdntocgi);
422 	/*fdevent_unregister(ev, hctx->fdtocgi);*//*(handled below)*/
423 	fdevent_sched_close(ev, hctx->fdtocgi, 0);
424 	hctx->fdntocgi = NULL;
425 	hctx->fdtocgi = -1;
426 }
427 
428 static void cgi_connection_close(handler_ctx *hctx) {
429 	/* the connection to the browser went away, but we still have a connection
430 	 * to the CGI script
431 	 *
432 	 * close cgi-connection
433 	 */
434 
435 	if (hctx->fd != -1) {
436 		struct fdevents * const ev = hctx->ev;
437 		/* close connection to the cgi-script */
438 		fdevent_fdnode_event_del(ev, hctx->fdn);
439 		/*fdevent_unregister(ev, hctx->fd);*//*(handled below)*/
440 		fdevent_sched_close(ev, hctx->fd, 0);
441 		hctx->fdn = NULL;
442 	}
443 
444 	if (hctx->fdtocgi != -1) {
445 		cgi_connection_close_fdtocgi(hctx); /*(closes only hctx->fdtocgi)*/
446 	}
447 
448 	plugin_data * const p = hctx->plugin_data;
449 	request_st * const r = hctx->r;
450 	r->plugin_ctx[p->id] = NULL;
451 
452 	if (hctx->cgi_pid) {
453 		cgi_pid_kill(hctx->cgi_pid, SIGTERM);
454 		hctx->cgi_pid->hctx = NULL;
455 	}
456 	cgi_handler_ctx_free(hctx);
457 
458 	/* finish response (if not already r->resp_body_started, r->resp_body_finished) */
459 	if (r->handler_module == p->self) {
460 		http_response_backend_done(r);
461 	}
462 }
463 
464 static handler_t cgi_connection_close_callback(request_st * const r, void *p_d) {
465     handler_ctx *hctx = r->plugin_ctx[((plugin_data *)p_d)->id];
466     if (hctx) {
467         chunkqueue_set_tempdirs(&r->reqbody_queue, /* reset sz */
468                                 r->reqbody_queue.tempdirs, 0);
469         cgi_connection_close(hctx);
470     }
471     return HANDLER_GO_ON;
472 }
473 
474 
475 static int cgi_write_request(handler_ctx *hctx, int fd);
476 
477 
478 static handler_t cgi_handle_fdevent_send (void *ctx, int revents) {
479 	handler_ctx *hctx = ctx;
480 	hctx->wr_revents |= revents;
481 	joblist_append(hctx->con);
482 	return HANDLER_FINISHED;
483 }
484 
485 
486 static handler_t cgi_process_wr_revents (handler_ctx * const hctx, request_st * const r, int revents) {
487 	if (revents & FDEVENT_OUT) {
488 		if (0 != cgi_write_request(hctx, hctx->fdtocgi)) {
489 			cgi_connection_close(hctx);
490 			return HANDLER_ERROR;
491 		}
492 		/* more request body to be sent to CGI */
493 	}
494 
495 	if (revents & FDEVENT_HUP) {
496 		/* skip sending remaining data to CGI */
497 		if (r->reqbody_length) {
498 			chunkqueue *cq = &r->reqbody_queue;
499 			chunkqueue_mark_written(cq, chunkqueue_length(cq));
500 			if (cq->bytes_in != (off_t)r->reqbody_length) {
501 				r->keep_alive = 0;
502 			}
503 		}
504 
505 		cgi_connection_close_fdtocgi(hctx); /*(closes only hctx->fdtocgi)*/
506 	} else if (revents & FDEVENT_ERR) {
507 		/* kill all connections to the cgi process */
508 #if 1
509 		log_error(r->conf.errh, __FILE__, __LINE__, "cgi-FDEVENT_ERR");
510 #endif
511 		cgi_connection_close(hctx);
512 		return HANDLER_ERROR;
513 	}
514 
515 	return HANDLER_GO_ON;
516 }
517 
518 
519 static handler_t cgi_response_headers(request_st * const r, struct http_response_opts_t *opts) {
520     /* response headers just completed */
521     handler_ctx *hctx = (handler_ctx *)opts->pdata;
522 
523     if (light_btst(r->resp_htags, HTTP_HEADER_UPGRADE)) {
524         if (hctx->conf.upgrade && r->http_status == 101) {
525             /* 101 Switching Protocols; transition to transparent proxy */
526             if (r->h2_connect_ext) {
527                 r->http_status = 200; /* OK (response status for CONNECT) */
528                 http_header_response_unset(r, HTTP_HEADER_UPGRADE,
529                                            CONST_STR_LEN("Upgrade"));
530                 http_header_response_unset(r, HTTP_HEADER_OTHER,
531                                          CONST_STR_LEN("Sec-WebSocket-Accept"));
532             }
533             http_response_upgrade_read_body_unknown(r);
534         }
535         else {
536             light_bclr(r->resp_htags, HTTP_HEADER_UPGRADE);
537           #if 0
538             /* preserve prior questionable behavior; likely broken behavior
539              * anyway if backend thinks connection is being upgraded but client
540              * does not receive Connection: upgrade */
541             http_header_response_unset(r, HTTP_HEADER_UPGRADE,
542                                        CONST_STR_LEN("Upgrade"));
543           #endif
544         }
545     }
546     else if (__builtin_expect( (r->h2_connect_ext != 0), 0)
547              && r->http_status < 300) {
548         /*(not handling other 1xx intermediate responses here; not expected)*/
549         http_response_body_clear(r, 0);
550         r->handler_module = NULL;
551         r->http_status = 405; /* Method Not Allowed */
552         return HANDLER_FINISHED;
553     }
554 
555     if (hctx->conf.upgrade
556         && !light_btst(r->resp_htags, HTTP_HEADER_UPGRADE)) {
557         chunkqueue *cq = &r->reqbody_queue;
558         hctx->conf.upgrade = 0;
559         r->reqbody_length = hctx->orig_reqbody_length;
560         if (cq->bytes_out == (off_t)r->reqbody_length) {
561             cgi_connection_close_fdtocgi(hctx); /*(closes hctx->fdtocgi)*/
562         }
563     }
564 
565     return HANDLER_GO_ON;
566 }
567 
568 
569 __attribute_cold__
570 __attribute_noinline__
571 static handler_t cgi_local_redir(request_st * const r, handler_ctx * const hctx) {
572     buffer_clear(hctx->response);
573     chunk_buffer_yield(hctx->response);
574     http_response_reset(r); /*(includes r->http_status = 0)*/
575     r->con->srv->plugins_request_reset(r);
576     /*cgi_connection_close(hctx);*//*(already cleaned up and hctx is now invalid)*/
577     return HANDLER_COMEBACK;
578 }
579 
580 
581 static int cgi_recv_response(request_st * const r, handler_ctx * const hctx) {
582 		const off_t bytes_in = r->write_queue.bytes_in;
583 		switch (http_response_read(r, &hctx->opts,
584 					   hctx->response, hctx->fdn)) {
585 		default:
586 			if (r->write_queue.bytes_in > bytes_in)
587 				hctx->read_ts = log_monotonic_secs;
588 			return HANDLER_GO_ON;
589 		case HANDLER_ERROR:
590 			http_response_backend_error(r);
591 			__attribute_fallthrough__
592 		case HANDLER_FINISHED:
593 			cgi_connection_close(hctx);
594 			return HANDLER_FINISHED;
595 		case HANDLER_COMEBACK:
596 			return cgi_local_redir(r, hctx); /* HANDLER_COMEBACK */
597 		}
598 }
599 
600 
601 static handler_t cgi_handle_fdevent(void *ctx, int revents) {
602 	handler_ctx *hctx = ctx;
603 	hctx->rd_revents |= revents;
604 	joblist_append(hctx->con);
605 	return HANDLER_FINISHED;
606 }
607 
608 
609 static handler_t cgi_process_rd_revents(handler_ctx * const hctx, request_st * const r, int revents) {
610 	if (revents & FDEVENT_IN) {
611 		handler_t rc = cgi_recv_response(r, hctx); /*(might invalidate hctx)*/
612 		if (rc != HANDLER_GO_ON) return rc;         /*(unless HANDLER_GO_ON)*/
613 	}
614 
615 	/* perhaps this issue is already handled */
616 	if (revents & (FDEVENT_HUP|FDEVENT_RDHUP)) {
617 		if (r->resp_body_started) {
618 			/* drain any remaining data from kernel pipe buffers
619 			 * even if (r->conf.stream_response_body
620 			 *          & FDEVENT_STREAM_RESPONSE_BUFMIN)
621 			 * since event loop will spin on fd FDEVENT_HUP event
622 			 * until unregistered. */
623 			handler_t rc;
624 			const unsigned short flags = r->conf.stream_response_body;
625 			r->conf.stream_response_body &= ~FDEVENT_STREAM_RESPONSE_BUFMIN;
626 			r->conf.stream_response_body |= FDEVENT_STREAM_RESPONSE_POLLRDHUP;
627 			do {
628 				rc = cgi_recv_response(r,hctx); /*(might invalidate hctx)*/
629 			} while (rc == HANDLER_GO_ON);           /*(unless HANDLER_GO_ON)*/
630 			r->conf.stream_response_body = flags;
631 			return rc; /* HANDLER_FINISHED or HANDLER_COMEBACK or HANDLER_ERROR */
632 		} else if (!buffer_is_blank(hctx->response)) {
633 			/* unfinished header package which is a body in reality */
634 			r->resp_body_started = 1;
635 			if (0 != http_chunk_append_buffer(r, hctx->response)) {
636 				cgi_connection_close(hctx);
637 				return HANDLER_ERROR;
638 			}
639 			if (0 == r->http_status) r->http_status = 200; /* OK */
640 		}
641 		cgi_connection_close(hctx);
642 	} else if (revents & FDEVENT_ERR) {
643 		/* kill all connections to the cgi process */
644 		cgi_connection_close(hctx);
645 		return HANDLER_ERROR;
646 	}
647 
648 	return HANDLER_GO_ON;
649 }
650 
651 
652 __attribute_cold__
653 __attribute_noinline__
654 static void cgi_env_offset_resize(env_accum *env) {
655     chunk_buffer_prepare_append(env->boffsets, env->boffsets->size*2);
656     env->offsets = (uintptr_t *)(void *)env->boffsets->ptr;
657     env->osize = env->boffsets->size/sizeof(*env->offsets);
658 }
659 
660 static int cgi_env_add(void *venv, const char *key, size_t key_len, const char *val, size_t val_len) {
661 	env_accum *env = venv;
662 
663 	if (!key || (!val && val_len)) return -1;
664 
665 	if (__builtin_expect( (env->osize == env->oused), 0))
666 		cgi_env_offset_resize(env);
667 	env->offsets[env->oused++] = env->b->used-1;
668 
669 	char * const dst = buffer_extend(env->b, key_len + val_len + 2);
670 	memcpy(dst, key, key_len);
671 	dst[key_len] = '=';
672 	if (val_len) memcpy(dst + key_len + 1, val, val_len);
673 	dst[key_len + 1 + val_len] = '\0';
674 
675 	return 0;
676 }
677 
678 static int cgi_write_request(handler_ctx *hctx, int fd) {
679 	request_st * const r = hctx->r;
680 	chunkqueue *cq = &r->reqbody_queue;
681 	chunk *c;
682 
683 	chunkqueue_remove_finished_chunks(cq); /* unnecessary? */
684 
685 	/* old comment: windows doesn't support select() on pipes - wouldn't be easy to fix for all platforms.
686 	 */
687 
688 	for (c = cq->first; c; c = cq->first) {
689 		ssize_t wr = chunkqueue_write_chunk_to_pipe(fd, cq, r->conf.errh);
690 		if (wr > 0) {
691 			hctx->write_ts = log_monotonic_secs;
692 			chunkqueue_mark_written(cq, wr);
693 			/* continue if wrote whole chunk or wrote 16k block
694 			 * (see chunkqueue_write_chunk_file_intermed()) */
695 			if (c != cq->first || wr == 16384)
696 				continue;
697 			/*(else partial write)*/
698 		}
699 		else if (wr < 0) {
700 				switch(errno) {
701 				case EAGAIN:
702 				case EINTR:
703 					/* ignore and try again later */
704 					break;
705 				case EPIPE:
706 				case ECONNRESET:
707 					/* connection closed */
708 					log_error(r->conf.errh, __FILE__, __LINE__,
709 					  "failed to send post data to cgi, connection closed by CGI");
710 					/* skip all remaining data */
711 					chunkqueue_mark_written(cq, chunkqueue_length(cq));
712 					break;
713 				default:
714 					/* fatal error */
715 					log_perror(r->conf.errh, __FILE__, __LINE__, "write() failed");
716 					return -1;
717 				}
718 		}
719 		/*if (0 == wr) break;*/ /*(might block)*/
720 		break;
721 	}
722 
723 	if (cq->bytes_out == (off_t)r->reqbody_length && !hctx->conf.upgrade) {
724 		/* sent all request body input */
725 		/* close connection to the cgi-script */
726 		if (-1 == hctx->fdtocgi) { /*(received request body sent in initial send to pipe buffer)*/
727 			--r->con->srv->cur_fds;
728 			if (close(fd)) {
729 				log_perror(r->conf.errh, __FILE__, __LINE__, "cgi stdin close %d failed", fd);
730 			}
731 		} else {
732 			cgi_connection_close_fdtocgi(hctx); /*(closes only hctx->fdtocgi)*/
733 		}
734 	} else {
735 		off_t cqlen = chunkqueue_length(cq);
736 		if (cq->bytes_in != r->reqbody_length && cqlen < 65536 - 16384) {
737 			/*(r->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
738 			if (!(r->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN)) {
739 				r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
740 				r->con->is_readable = 1; /* trigger optimistic read from client */
741 			}
742 		}
743 		struct fdevents * const ev = hctx->ev;
744 		if (-1 == hctx->fdtocgi) { /*(not registered yet)*/
745 			hctx->fdtocgi = fd;
746 			hctx->fdntocgi = fdevent_register(ev, hctx->fdtocgi, cgi_handle_fdevent_send, hctx);
747 		}
748 		if (0 == cqlen) { /*(chunkqueue_is_empty(cq))*/
749 			if ((fdevent_fdnode_interest(hctx->fdntocgi) & FDEVENT_OUT)) {
750 				fdevent_fdnode_event_set(ev, hctx->fdntocgi, 0);
751 			}
752 		} else {
753 			/* more request body remains to be sent to CGI so register for fdevents */
754 			hctx->write_ts = log_monotonic_secs;
755 			fdevent_fdnode_event_set(ev, hctx->fdntocgi, FDEVENT_OUT);
756 		}
757 	}
758 
759 	return 0;
760 }
761 
762 static int cgi_create_env(request_st * const r, plugin_data * const p, handler_ctx * const hctx, buffer * const cgi_handler) {
763 	char *args[3];
764 	int to_cgi_fds[2];
765 	int from_cgi_fds[2];
766 	UNUSED(p);
767 
768 	if (!buffer_is_blank(cgi_handler)) {
769 		if (NULL == stat_cache_path_stat(cgi_handler)) {
770 			log_perror(r->conf.errh, __FILE__, __LINE__,
771 			  "stat for cgi-handler %s", cgi_handler->ptr);
772 			return -1;
773 		}
774 	}
775 
776 	to_cgi_fds[0] = -1;
777   #ifndef __CYGWIN__
778 	if (0 == r->reqbody_length) {
779 		/* future: might keep fd open in p->devnull for reuse
780 		 * and dup() here, or do not close() (later in this func) */
781 		to_cgi_fds[0] = fdevent_open_devnull();
782 		if (-1 == to_cgi_fds[0]) {
783 			log_perror(r->conf.errh, __FILE__, __LINE__, "open /dev/null");
784 			return -1;
785 		}
786 	}
787 	else if (!(r->conf.stream_request_body /*(if not streaming request body)*/
788 	           & (FDEVENT_STREAM_REQUEST|FDEVENT_STREAM_REQUEST_BUFMIN))
789 	         && !hctx->conf.upgrade) {
790 		chunkqueue * const cq = &r->reqbody_queue;
791 		chunk * const c = cq->first;
792 		if (c && c == cq->last && c->type == FILE_CHUNK && c->file.is_temp) {
793 			/* request body in single tempfile if not streaming req body */
794 			if (-1 == c->file.fd
795 			    && 0 != chunkqueue_open_file_chunk(cq, r->conf.errh))
796 				return -1;
797 		  #ifdef __COVERITY__
798 			force_assert(-1 != c->file.fd);
799 		  #endif
800 			if (-1 == lseek(c->file.fd, 0, SEEK_SET)) {
801 				log_perror(r->conf.errh, __FILE__, __LINE__,
802 				  "lseek %s", c->mem->ptr);
803 				return -1;
804 			}
805 			to_cgi_fds[0] = c->file.fd;
806 			to_cgi_fds[1] = -1;
807 		}
808 	}
809   #endif
810 
811 	unsigned int bufsz_hint = 16384;
812   #ifdef _WIN32
813 	if (r->reqbody_length <= 1048576 && r->reqbody_length > 0)
814 		bufsz_hint = (unsigned int)r->reqbody_length;
815   #endif
816 	if (-1 == to_cgi_fds[0] && fdevent_pipe_cloexec(to_cgi_fds, bufsz_hint)) {
817 		log_perror(r->conf.errh, __FILE__, __LINE__, "pipe failed");
818 		return -1;
819 	}
820 	if (fdevent_pipe_cloexec(from_cgi_fds, bufsz_hint)) {
821 		if (0 == r->reqbody_length) {
822 			close(to_cgi_fds[0]);
823 		}
824 		else if (-1 != to_cgi_fds[1]) {
825 			close(to_cgi_fds[0]);
826 			close(to_cgi_fds[1]);
827 		}
828 		log_perror(r->conf.errh, __FILE__, __LINE__, "pipe failed");
829 		return -1;
830 	}
831 
832 	env_accum * const env = &p->env;
833 	env->b = chunk_buffer_acquire();
834 	env->boffsets = chunk_buffer_acquire();
835 	buffer_truncate(env->b, 0);
836 	char **envp;
837 	{
838 		size_t i = 0;
839 		http_cgi_opts opts = { 0, 0, NULL, NULL };
840 		env->offsets = (uintptr_t *)(void *)env->boffsets->ptr;
841 		env->osize = env->boffsets->size/sizeof(*env->offsets);
842 		env->oused = 0;
843 
844 		/* create environment */
845 
846 		if (r->h2_connect_ext) {
847 			/*(SERVER_PROTOCOL=HTTP/1.1 instead of HTTP/2.0)*/
848 			r->http_version = HTTP_VERSION_1_1;
849 			r->http_method = HTTP_METHOD_GET;
850 		}
851 		if (hctx->conf.upgrade) {
852 			r->reqbody_length = hctx->orig_reqbody_length;
853 			if (r->reqbody_length < 0)
854 				r->reqbody_length = 0;
855 		}
856 
857 		http_cgi_headers(r, &opts, cgi_env_add, env);
858 
859 		if (hctx->conf.upgrade)
860 			r->reqbody_length = -1;
861 		if (r->h2_connect_ext) {
862 			r->http_version = HTTP_VERSION_2;
863 			r->http_method = HTTP_METHOD_CONNECT;
864 			/* https://datatracker.ietf.org/doc/html/rfc6455#section-4.1
865 			 * 7. The request MUST include a header field with the name
866 			 *    |Sec-WebSocket-Key|.  The value of this header field MUST be a
867 			 *    nonce consisting of a randomly selected 16-byte value that has
868 			 *    been base64-encoded (see Section 4 of [RFC4648]).  The nonce
869 			 *    MUST be selected randomly for each connection.
870 			 * Note: Sec-WebSocket-Key is not used in RFC8441;
871 			 *       include Sec-WebSocket-Key for HTTP/1.1 compatibility;
872 			 *       !!not random!! base64-encoded "0000000000000000" */
873 			if (!http_header_request_get(r, HTTP_HEADER_OTHER,
874 			                             CONST_STR_LEN("Sec-WebSocket-Key")))
875 				cgi_env_add(env, CONST_STR_LEN("HTTP_SEC_WEBSOCKET_KEY"),
876 				                 CONST_STR_LEN("MDAwMDAwMDAwMDAwMDAwMAo="));
877 			/*(Upgrade and Connection should not exist for HTTP/2 request)*/
878 			cgi_env_add(env, CONST_STR_LEN("HTTP_UPGRADE"), CONST_STR_LEN("websocket"));
879 			cgi_env_add(env, CONST_STR_LEN("HTTP_CONNECTION"), CONST_STR_LEN("upgrade"));
880 		}
881 
882 		/* for valgrind */
883 		if (p->env.ld_preload) {
884 			cgi_env_add(env, CONST_STR_LEN("LD_PRELOAD"), BUF_PTR_LEN(p->env.ld_preload));
885 		}
886 		if (p->env.ld_library_path) {
887 			cgi_env_add(env, CONST_STR_LEN("LD_LIBRARY_PATH"), BUF_PTR_LEN(p->env.ld_library_path));
888 		}
889 	      #ifdef __CYGWIN__
890 		/* CYGWIN needs SYSTEMROOT */
891 		if (p->env.systemroot) {
892 			cgi_env_add(env, CONST_STR_LEN("SYSTEMROOT"), BUF_PTR_LEN(p->env.systemroot));
893 		}
894 	      #endif
895 
896 		/* adjust (uintptr_t) offsets to (char *) ptr
897 		 * (stored as offsets while accumulating in buffer,
898 		 *  in case buffer is reallocated during env creation) */
899 		if (__builtin_expect( (env->osize == env->oused), 0))
900 			cgi_env_offset_resize(env);
901 		envp = (char **)env->offsets;
902 		envp[env->oused] = NULL;
903 		const uintptr_t baseptr = (uintptr_t)env->b->ptr;
904 		for (i = 0; i < env->oused; ++i)
905 			envp[i] += baseptr;
906 
907 		/* set up args */
908 		i = 0;
909 
910 		if (!buffer_is_blank(cgi_handler)) {
911 			args[i++] = cgi_handler->ptr;
912 		}
913 		args[i++] = r->physical.path.ptr;
914 		args[i  ] = NULL;
915 	}
916 
917 	int dfd = fdevent_open_dirname(r->physical.path.ptr,r->conf.follow_symlink);
918 	if (-1 == dfd) {
919 		log_perror(r->conf.errh, __FILE__, __LINE__, "open dirname %s failed", r->physical.path.ptr);
920 	}
921 
922 	int serrh_fd = r->conf.serrh ? r->conf.serrh->fd : -1;
923 	pid_t pid = (dfd >= 0)
924 	  ? fdevent_fork_execve(args[0], args, envp,
925 	                        to_cgi_fds[0], from_cgi_fds[1], serrh_fd, dfd)
926 	  : -1;
927 
928 	chunk_buffer_release(env->boffsets);
929 	chunk_buffer_release(env->b);
930 	env->boffsets = NULL;
931 	env->b = NULL;
932 
933 	if (-1 == pid) {
934 		/* log error with errno prior to calling close() (might change errno) */
935 		log_perror(r->conf.errh, __FILE__, __LINE__, "fork failed");
936 		if (-1 != dfd) close(dfd);
937 		close(from_cgi_fds[0]);
938 		close(from_cgi_fds[1]);
939 		if (0 == r->reqbody_length) {
940 			close(to_cgi_fds[0]);
941 		}
942 		else if (-1 != to_cgi_fds[1]) {
943 			close(to_cgi_fds[0]);
944 			close(to_cgi_fds[1]);
945 		}
946 		return -1;
947 	} else {
948 		if (-1 != dfd) close(dfd);
949 		close(from_cgi_fds[1]);
950 
951 		hctx->fd = from_cgi_fds[0];
952 		hctx->cgi_pid = cgi_pid_add(p, pid, hctx);
953 
954 		if (0 == r->reqbody_length) {
955 			close(to_cgi_fds[0]);
956 		}
957 		else if (-1 == to_cgi_fds[1]) {
958 			chunkqueue * const cq = &r->reqbody_queue;
959 			chunkqueue_mark_written(cq, chunkqueue_length(cq));
960 		}
961 		else if (0 == fdevent_fcntl_set_nb(to_cgi_fds[1])
962 		         && 0 == cgi_write_request(hctx, to_cgi_fds[1])) {
963 			close(to_cgi_fds[0]);
964 			++r->con->srv->cur_fds;
965 		}
966 		else {
967 			close(to_cgi_fds[0]);
968 			close(to_cgi_fds[1]);
969 			/*(hctx->fd not yet registered with fdevent, so manually
970 			 * cleanup here; see fdevent_register() further below)*/
971 			close(hctx->fd);
972 			hctx->fd = -1;
973 			cgi_connection_close(hctx);
974 			return -1;
975 		}
976 
977 		++r->con->srv->cur_fds;
978 
979 		struct fdevents * const ev = hctx->ev;
980 		hctx->fdn = fdevent_register(ev, hctx->fd, cgi_handle_fdevent, hctx);
981 		if (-1 == fdevent_fcntl_set_nb(hctx->fd)) {
982 			log_perror(r->conf.errh, __FILE__, __LINE__, "fcntl failed");
983 			cgi_connection_close(hctx);
984 			return -1;
985 		}
986 		hctx->read_ts = log_monotonic_secs;
987 		fdevent_fdnode_event_set(ev, hctx->fdn, FDEVENT_IN | FDEVENT_RDHUP);
988 
989 		return 0;
990 	}
991 }
992 
993 URIHANDLER_FUNC(cgi_is_handled) {
994 	plugin_data *p = p_d;
995 	const stat_cache_st *st;
996 	data_string *ds;
997 
998 	if (NULL != r->handler_module) return HANDLER_GO_ON;
999 	/* r->physical.path is non-empty for handle_subrequest_start */
1000 	/*if (buffer_is_blank(&r->physical.path)) return HANDLER_GO_ON;*/
1001 
1002 	mod_cgi_patch_config(r, p);
1003 	if (NULL == p->conf.cgi) return HANDLER_GO_ON;
1004 
1005 	ds = (data_string *)array_match_key_suffix(p->conf.cgi, &r->physical.path);
1006 	if (NULL == ds) return HANDLER_GO_ON;
1007 
1008 	/* r->tmp_sce is set in http_response_physical_path_check() and is valid
1009 	 * in handle_subrequest_start callback -- handle_subrequest_start callbacks
1010 	 * should not change r->physical.path (or should invalidate r->tmp_sce) */
1011 	st = r->tmp_sce && buffer_is_equal(&r->tmp_sce->name, &r->physical.path)
1012 	   ? &r->tmp_sce->st
1013 	   : stat_cache_path_stat(&r->physical.path);
1014 	if (NULL == st) return HANDLER_GO_ON;
1015 
1016 	/* (aside: CGI might be executable even if it is not readable) */
1017 	if (!S_ISREG(st->st_mode)) return HANDLER_GO_ON;
1018 	if (p->conf.execute_x_only == 1 && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) return HANDLER_GO_ON;
1019 
1020 	if (__builtin_expect( (r->h2_connect_ext != 0), 0) && !p->conf.upgrade) {
1021 		r->http_status = 405; /* Method Not Allowed */
1022 		return HANDLER_FINISHED;
1023 	}
1024 
1025 	if (r->reqbody_length
1026 	    && p->tempfile_accum
1027 	    && !(r->conf.stream_request_body /*(if not streaming request body)*/
1028 	         & (FDEVENT_STREAM_REQUEST|FDEVENT_STREAM_REQUEST_BUFMIN))) {
1029 		/* store request body in single tempfile if not streaming request body*/
1030 		r->reqbody_queue.upload_temp_file_size = INTMAX_MAX;
1031 	}
1032 
1033 	{
1034 		handler_ctx *hctx = cgi_handler_ctx_init();
1035 		hctx->ev = r->con->srv->ev;
1036 		hctx->r = r;
1037 		hctx->con = r->con;
1038 		hctx->plugin_data = p;
1039 		hctx->cgi_handler = &ds->value;
1040 		memcpy(&hctx->conf, &p->conf, sizeof(plugin_config));
1041 		if (__builtin_expect( (r->h2_connect_ext != 0), 0)) {
1042 		}
1043 		else if (!light_btst(r->rqst_htags, HTTP_HEADER_UPGRADE))
1044 			hctx->conf.upgrade = 0;
1045 		else if (!hctx->conf.upgrade || r->http_version != HTTP_VERSION_1_1) {
1046 			hctx->conf.upgrade = 0;
1047 			http_header_request_unset(r, HTTP_HEADER_UPGRADE,
1048 			                          CONST_STR_LEN("Upgrade"));
1049 		}
1050 		if (hctx->conf.upgrade) {
1051 			hctx->orig_reqbody_length = r->reqbody_length;
1052 			r->reqbody_length = -1;
1053 		}
1054 		hctx->opts.max_per_read =
1055 		  !(r->conf.stream_response_body /*(if not streaming response body)*/
1056 		    & (FDEVENT_STREAM_RESPONSE|FDEVENT_STREAM_RESPONSE_BUFMIN))
1057 		    ? 262144
1058 		    : (r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
1059 		      ? 16384  /* FDEVENT_STREAM_RESPONSE_BUFMIN */
1060 		      : 65536; /* FDEVENT_STREAM_RESPONSE */
1061 		hctx->opts.fdfmt = S_IFIFO;
1062 		hctx->opts.backend = BACKEND_CGI;
1063 		hctx->opts.authorizer = 0;
1064 		hctx->opts.local_redir = hctx->conf.local_redir;
1065 		hctx->opts.xsendfile_allow = hctx->conf.xsendfile_allow;
1066 		hctx->opts.xsendfile_docroot = hctx->conf.xsendfile_docroot;
1067 		hctx->opts.pdata = hctx;
1068 		hctx->opts.headers = cgi_response_headers;
1069 		r->plugin_ctx[p->id] = hctx;
1070 		r->handler_module = p->self;
1071 	}
1072 
1073 	return HANDLER_GO_ON;
1074 }
1075 
1076 /*
1077  * - HANDLER_GO_ON : not our job
1078  * - HANDLER_FINISHED: got response
1079  * - HANDLER_WAIT_FOR_EVENT: waiting for response
1080  */
1081 SUBREQUEST_FUNC(mod_cgi_handle_subrequest) {
1082 	plugin_data * const p = p_d;
1083 	handler_ctx * const hctx = r->plugin_ctx[p->id];
1084 	if (NULL == hctx) return HANDLER_GO_ON;
1085 
1086 	if (__builtin_expect(
1087 	     (r->conf.stream_request_body & FDEVENT_STREAM_REQUEST_TCP_FIN), 0)
1088 	    && hctx->conf.limits && hctx->conf.limits->signal_fin) {
1089 		/* XXX: consider setting r->http_status = 499 if (0 == r->http_status)
1090 		 * (499 is nginx custom status to indicate client closed connection) */
1091 		if (-1 == hctx->fd) return HANDLER_ERROR; /*(CGI not yet spawned)*/
1092 		if (hctx->cgi_pid) /* send signal to notify CGI about TCP FIN */
1093 			cgi_pid_kill(hctx->cgi_pid, hctx->conf.limits->signal_fin);
1094 	}
1095 
1096 	const int rd_revents = hctx->rd_revents;
1097 	const int wr_revents = hctx->wr_revents;
1098 	if (rd_revents) {
1099 		hctx->rd_revents = 0;
1100 		handler_t rc = cgi_process_rd_revents(hctx, r, rd_revents);
1101 		if (rc != HANDLER_GO_ON) return rc; /*(might invalidate hctx)*/
1102 	}
1103 	if (wr_revents) {
1104 		hctx->wr_revents = 0;
1105 		handler_t rc = cgi_process_wr_revents(hctx, r, wr_revents);
1106 		if (rc != HANDLER_GO_ON) return rc; /*(might invalidate hctx)*/
1107 	}
1108 
1109 	if ((r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
1110 	    && r->resp_body_started) {
1111 		if (chunkqueue_length(&r->write_queue) > 65536 - 4096) {
1112 			fdevent_fdnode_event_clr(hctx->ev, hctx->fdn, FDEVENT_IN);
1113 		} else if (!(fdevent_fdnode_interest(hctx->fdn) & FDEVENT_IN)) {
1114 			/* optimistic read from backend */
1115 			handler_t rc = cgi_recv_response(r, hctx);  /*(might invalidate hctx)*/
1116 			if (rc != HANDLER_GO_ON) return rc;          /*(unless HANDLER_GO_ON)*/
1117 			hctx->read_ts = log_monotonic_secs;
1118 			fdevent_fdnode_event_add(hctx->ev, hctx->fdn, FDEVENT_IN);
1119 		}
1120 	}
1121 
1122 	chunkqueue * const cq = &r->reqbody_queue;
1123 
1124 	if (cq->bytes_in != (off_t)r->reqbody_length) {
1125 		/*(64k - 4k to attempt to avoid temporary files
1126 		 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
1127 		if (chunkqueue_length(cq) > 65536 - 4096
1128 		    && (r->conf.stream_request_body & FDEVENT_STREAM_REQUEST_BUFMIN)){
1129 			r->conf.stream_request_body &= ~FDEVENT_STREAM_REQUEST_POLLIN;
1130 		} else {
1131 			handler_t rc = r->con->reqbody_read(r);
1132 			if (rc != HANDLER_GO_ON
1133 			    && !(hctx->conf.upgrade && -1 == hctx->fd
1134 			         && rc == HANDLER_WAIT_FOR_EVENT))
1135 				return rc;
1136 		}
1137 	}
1138 
1139 	if (-1 == hctx->fd) {
1140 			/* CGI environment requires that Content-Length be set.
1141 			 * Send 411 Length Required if Content-Length missing.
1142 			 * (occurs here if client sends Transfer-Encoding: chunked
1143 			 *  and module is flagged to stream request body to backend) */
1144 			if (-1 == r->reqbody_length && !hctx->conf.upgrade) {
1145 				return (r->conf.stream_request_body & FDEVENT_STREAM_REQUEST)
1146 				  ? http_response_reqbody_read_error(r, 411)
1147 				  : HANDLER_WAIT_FOR_EVENT;
1148 			}
1149 		if (cgi_create_env(r, p, hctx, hctx->cgi_handler)) {
1150 			r->http_status = 500;
1151 			r->handler_module = NULL;
1152 
1153 			return HANDLER_FINISHED;
1154 		}
1155 	} else if (!chunkqueue_is_empty(cq)) {
1156 		if (fdevent_fdnode_interest(hctx->fdntocgi) & FDEVENT_OUT)
1157 			return HANDLER_WAIT_FOR_EVENT;
1158 		if (0 != cgi_write_request(hctx, hctx->fdtocgi)) {
1159 			cgi_connection_close(hctx);
1160 			return HANDLER_ERROR;
1161 		}
1162 	}
1163 
1164 	/* if not done, wait for CGI to close stdout, so we read EOF on pipe */
1165 	return HANDLER_WAIT_FOR_EVENT;
1166 }
1167 
1168 
1169 __attribute_cold__
1170 __attribute_noinline__
1171 static void cgi_trigger_hctx_timeout(handler_ctx * const hctx, const char * const msg) {
1172     request_st * const r = hctx->r;
1173     joblist_append(r->con);
1174 
1175     log_error(r->conf.errh, __FILE__, __LINE__,
1176       "%s timeout on CGI: %s (pid: %lld)",
1177       msg, r->physical.path.ptr, (long long)hctx->cgi_pid->pid);
1178 
1179     if (*msg == 'w') { /* "write" */
1180         /* theoretically, response might be waiting on hctx->fdn pipe
1181          * if it arrived since we last checked for event, and if CGI
1182          * timeout out while reading (or did not read) request body */
1183         handler_t rc = cgi_recv_response(r, hctx); /*(might invalidate hctx)*/
1184         if (rc != HANDLER_GO_ON) return;            /*(unless HANDLER_GO_ON)*/
1185     }
1186 
1187     if (0 == r->http_status) r->http_status = 504; /* Gateway Timeout */
1188     cgi_connection_close(hctx);
1189 }
1190 
1191 
1192 static handler_t cgi_trigger_cb(server *srv, void *p_d) {
1193     UNUSED(srv);
1194     const unix_time64_t mono = log_monotonic_secs;
1195     plugin_data * const p = p_d;
1196     for (cgi_pid_t *cgi_pid = p->cgi_pid; cgi_pid; cgi_pid = cgi_pid->next) {
1197         /*(hctx stays in cgi_pid list until process pid is reaped,
1198          * so p->cgi_pid[] is not modified during this loop)*/
1199         handler_ctx * const hctx = cgi_pid->hctx;
1200         if (!hctx) continue; /*(already called cgi_pid_kill())*/
1201         const cgi_limits * const limits = hctx->conf.limits;
1202         if (NULL == limits) continue;
1203         if (limits->read_timeout && hctx->fdn
1204             && (fdevent_fdnode_interest(hctx->fdn) & FDEVENT_IN)
1205             && mono - hctx->read_ts > limits->read_timeout) {
1206             cgi_trigger_hctx_timeout(hctx, "read");
1207             continue;
1208         }
1209         if (limits->write_timeout && hctx->fdntocgi
1210             && (fdevent_fdnode_interest(hctx->fdntocgi) & FDEVENT_OUT)
1211             && mono - hctx->write_ts > limits->write_timeout) {
1212             cgi_trigger_hctx_timeout(hctx, "write");
1213             continue;
1214         }
1215     }
1216     return HANDLER_GO_ON;
1217 }
1218 
1219 
1220 static handler_t cgi_waitpid_cb(server *srv, void *p_d, pid_t pid, int status) {
1221     /*(XXX: if supporting a large number of CGI, might use a different algorithm
1222      * instead of linked list, e.g. splaytree indexed with pid)*/
1223     plugin_data *p = (plugin_data *)p_d;
1224     for (cgi_pid_t *cgi_pid = p->cgi_pid; cgi_pid; cgi_pid = cgi_pid->next) {
1225         if (pid != cgi_pid->pid) continue;
1226 
1227         handler_ctx * const hctx = cgi_pid->hctx;
1228         if (hctx) hctx->cgi_pid = NULL;
1229 
1230         if (WIFEXITED(status)) {
1231             /* (skip logging (non-zero) CGI exit; might be very noisy) */
1232         }
1233         else if (WIFSIGNALED(status)) {
1234             /* ignore SIGTERM if sent by cgi_connection_close() (NULL == hctx)*/
1235             if (WTERMSIG(status) != cgi_pid->signal_sent) {
1236                 log_error_st *errh = hctx ? hctx->r->conf.errh : srv->errh;
1237                 log_error(errh, __FILE__, __LINE__,
1238                   "CGI pid %d died with signal %d", pid, WTERMSIG(status));
1239             }
1240         }
1241         else {
1242             log_error_st *errh = hctx ? hctx->r->conf.errh : srv->errh;
1243             log_error(errh, __FILE__, __LINE__,
1244               "CGI pid %d ended unexpectedly", pid);
1245         }
1246 
1247         cgi_pid_del(p, cgi_pid);
1248         return HANDLER_FINISHED;
1249     }
1250 
1251     return HANDLER_GO_ON;
1252 }
1253 
1254 
1255 int mod_cgi_plugin_init(plugin *p);
1256 int mod_cgi_plugin_init(plugin *p) {
1257 	p->version     = LIGHTTPD_VERSION_ID;
1258 	p->name        = "cgi";
1259 
1260 	p->handle_request_reset = cgi_connection_close_callback;
1261 	p->handle_subrequest_start = cgi_is_handled;
1262 	p->handle_subrequest = mod_cgi_handle_subrequest;
1263 	p->handle_trigger = cgi_trigger_cb;
1264 	p->handle_waitpid = cgi_waitpid_cb;
1265 	p->init           = mod_cgi_init;
1266 	p->cleanup        = mod_cgi_free;
1267 	p->set_defaults   = mod_cgi_set_defaults;
1268 
1269 	return 0;
1270 }
1271