[core] support Transfer-Encoding: chunked req body (fixes #2156)
[lighttpd.git] / src / mod_cgi.c
blobe32db36073f95152cf1ab04c1681650ffa6b9bb0
1 #include "first.h"
3 #include "server.h"
4 #include "stat_cache.h"
5 #include "keyvalue.h"
6 #include "log.h"
7 #include "connections.h"
8 #include "joblist.h"
9 #include "response.h"
10 #include "http_chunk.h"
12 #include "plugin.h"
14 #include <sys/types.h>
15 #include "sys-mmap.h"
17 #ifdef __WIN32
18 # include <winsock2.h>
19 #else
20 # include <sys/socket.h>
21 # include <sys/wait.h>
22 # include <netinet/in.h>
23 # include <arpa/inet.h>
24 #endif
26 #include <unistd.h>
27 #include <errno.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <fdevent.h>
31 #include <signal.h>
32 #include <ctype.h>
33 #include <assert.h>
35 #include <stdio.h>
36 #include <fcntl.h>
38 #if defined(O_CLOEXEC) && (!defined(__FreeBSD__) || defined(SOCK_CLOEXEC)) \
39 && !(defined(__APPLE__) && defined(__MACH__))
40 #define pipe_cloexec(pipefd) pipe2((pipefd), O_CLOEXEC)
41 #elif defined FD_CLOEXEC
42 #define pipe_cloexec(pipefd) \
43 ( 0 == pipe(pipefd) \
44 && 0 == fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) \
45 && 0 == fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) \
46 ? 0 \
47 : -1)
48 #else
49 #define pipe_cloexec(pipefd) pipe(pipefd)
50 #endif
52 enum {EOL_UNSET, EOL_N, EOL_RN};
54 typedef struct {
55 char **ptr;
57 size_t size;
58 size_t used;
59 } char_array;
61 typedef struct {
62 pid_t *ptr;
63 size_t used;
64 size_t size;
65 } buffer_pid_t;
67 typedef struct {
68 array *cgi;
69 unsigned short execute_x_only;
70 unsigned short xsendfile_allow;
71 array *xsendfile_docroot;
72 } plugin_config;
74 typedef struct {
75 PLUGIN_DATA;
76 buffer_pid_t cgi_pid;
78 buffer *parse_response;
80 plugin_config **config_storage;
82 plugin_config conf;
83 } plugin_data;
85 typedef struct {
86 pid_t pid;
87 int fd;
88 int fdtocgi;
89 int fde_ndx; /* index into the fd-event buffer */
90 int fde_ndx_tocgi; /* index into the fd-event buffer */
92 connection *remote_conn; /* dumb pointer */
93 plugin_data *plugin_data; /* dumb pointer */
95 buffer *response;
96 buffer *response_header;
97 buffer *cgi_handler; /* dumb pointer */
98 plugin_config conf;
99 } handler_ctx;
101 static handler_ctx * cgi_handler_ctx_init(void) {
102 handler_ctx *hctx = calloc(1, sizeof(*hctx));
104 force_assert(hctx);
106 hctx->response = buffer_init();
107 hctx->response_header = buffer_init();
108 hctx->fd = -1;
109 hctx->fdtocgi = -1;
111 return hctx;
114 static void cgi_handler_ctx_free(handler_ctx *hctx) {
115 buffer_free(hctx->response);
116 buffer_free(hctx->response_header);
118 free(hctx);
121 enum {FDEVENT_HANDLED_UNSET, FDEVENT_HANDLED_FINISHED, FDEVENT_HANDLED_NOT_FINISHED, FDEVENT_HANDLED_COMEBACK, FDEVENT_HANDLED_ERROR};
123 INIT_FUNC(mod_cgi_init) {
124 plugin_data *p;
126 p = calloc(1, sizeof(*p));
128 force_assert(p);
130 p->parse_response = buffer_init();
132 return p;
136 FREE_FUNC(mod_cgi_free) {
137 plugin_data *p = p_d;
138 buffer_pid_t *r = &(p->cgi_pid);
140 UNUSED(srv);
142 if (p->config_storage) {
143 size_t i;
144 for (i = 0; i < srv->config_context->used; i++) {
145 plugin_config *s = p->config_storage[i];
147 if (NULL == s) continue;
149 array_free(s->cgi);
150 array_free(s->xsendfile_docroot);
152 free(s);
154 free(p->config_storage);
158 if (r->ptr) free(r->ptr);
160 buffer_free(p->parse_response);
162 free(p);
164 return HANDLER_GO_ON;
167 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults) {
168 plugin_data *p = p_d;
169 size_t i = 0;
171 config_values_t cv[] = {
172 { "cgi.assign", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
173 { "cgi.execute-x-only", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
174 { "cgi.x-sendfile", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
175 { "cgi.x-sendfile-docroot", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
176 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET}
179 if (!p) return HANDLER_ERROR;
181 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
182 force_assert(p->config_storage);
184 for (i = 0; i < srv->config_context->used; i++) {
185 data_config const* config = (data_config const*)srv->config_context->data[i];
186 plugin_config *s;
188 s = calloc(1, sizeof(plugin_config));
189 force_assert(s);
191 s->cgi = array_init();
192 s->execute_x_only = 0;
193 s->xsendfile_allow= 0;
194 s->xsendfile_docroot = array_init();
196 cv[0].destination = s->cgi;
197 cv[1].destination = &(s->execute_x_only);
198 cv[2].destination = &(s->xsendfile_allow);
199 cv[3].destination = s->xsendfile_docroot;
201 p->config_storage[i] = s;
203 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
204 return HANDLER_ERROR;
207 if (s->xsendfile_docroot->used) {
208 size_t j;
209 for (j = 0; j < s->xsendfile_docroot->used; ++j) {
210 data_string *ds = (data_string *)s->xsendfile_docroot->data[j];
211 if (ds->type != TYPE_STRING) {
212 log_error_write(srv, __FILE__, __LINE__, "s",
213 "unexpected type for key cgi.x-sendfile-docroot; expected: cgi.x-sendfile-docroot = ( \"/allowed/path\", ... )");
214 return HANDLER_ERROR;
216 if (ds->value->ptr[0] != '/') {
217 log_error_write(srv, __FILE__, __LINE__, "SBs",
218 "cgi.x-sendfile-docroot paths must begin with '/'; invalid: \"", ds->value, "\"");
219 return HANDLER_ERROR;
221 buffer_path_simplify(ds->value, ds->value);
222 buffer_append_slash(ds->value);
227 return HANDLER_GO_ON;
231 static int cgi_pid_add(server *srv, plugin_data *p, pid_t pid) {
232 int m = -1;
233 size_t i;
234 buffer_pid_t *r = &(p->cgi_pid);
236 UNUSED(srv);
238 for (i = 0; i < r->used; i++) {
239 if (r->ptr[i] > m) m = r->ptr[i];
242 if (r->size == 0) {
243 r->size = 16;
244 r->ptr = malloc(sizeof(*r->ptr) * r->size);
245 force_assert(r->ptr);
246 } else if (r->used == r->size) {
247 r->size += 16;
248 r->ptr = realloc(r->ptr, sizeof(*r->ptr) * r->size);
249 force_assert(r->ptr);
252 r->ptr[r->used++] = pid;
254 return m;
257 static int cgi_pid_del(server *srv, plugin_data *p, pid_t pid) {
258 size_t i;
259 buffer_pid_t *r = &(p->cgi_pid);
261 UNUSED(srv);
263 for (i = 0; i < r->used; i++) {
264 if (r->ptr[i] == pid) break;
267 if (i != r->used) {
268 /* found */
270 if (i != r->used - 1) {
271 r->ptr[i] = r->ptr[r->used - 1];
273 r->used--;
276 return 0;
279 static int cgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in) {
280 char *ns;
281 const char *s;
282 int line = 0;
284 UNUSED(srv);
286 buffer_copy_buffer(p->parse_response, in);
288 for (s = p->parse_response->ptr;
289 NULL != (ns = strchr(s, '\n'));
290 s = ns + 1, line++) {
291 const char *key, *value;
292 int key_len;
293 data_string *ds;
295 /* strip the \n */
296 ns[0] = '\0';
298 if (ns > s && ns[-1] == '\r') ns[-1] = '\0';
300 if (line == 0 &&
301 0 == strncmp(s, "HTTP/1.", 7)) {
302 /* non-parsed header ... we parse them anyway */
304 if ((s[7] == '1' ||
305 s[7] == '0') &&
306 s[8] == ' ') {
307 int status;
308 /* after the space should be a status code for us */
310 status = strtol(s+9, NULL, 10);
312 if (status >= 100 &&
313 status < 1000) {
314 /* we expected 3 digits and didn't got them */
315 con->parsed_response |= HTTP_STATUS;
316 con->http_status = status;
319 } else {
320 /* parse the headers */
321 key = s;
322 if (NULL == (value = strchr(s, ':'))) {
323 /* we expect: "<key>: <value>\r\n" */
324 continue;
327 key_len = value - key;
328 value += 1;
330 /* skip LWS */
331 while (*value == ' ' || *value == '\t') value++;
333 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
334 ds = data_response_init();
336 buffer_copy_string_len(ds->key, key, key_len);
337 buffer_copy_string(ds->value, value);
339 array_insert_unique(con->response.headers, (data_unset *)ds);
341 switch(key_len) {
342 case 4:
343 if (0 == strncasecmp(key, "Date", key_len)) {
344 con->parsed_response |= HTTP_DATE;
346 break;
347 case 6:
348 if (0 == strncasecmp(key, "Status", key_len)) {
349 int status = strtol(value, NULL, 10);
350 if (status >= 100 && status < 1000) {
351 con->http_status = status;
352 con->parsed_response |= HTTP_STATUS;
353 } else {
354 con->http_status = 502;
357 break;
358 case 8:
359 if (0 == strncasecmp(key, "Location", key_len)) {
360 con->parsed_response |= HTTP_LOCATION;
362 break;
363 case 10:
364 if (0 == strncasecmp(key, "Connection", key_len)) {
365 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
366 con->parsed_response |= HTTP_CONNECTION;
368 break;
369 case 14:
370 if (0 == strncasecmp(key, "Content-Length", key_len)) {
371 con->response.content_length = strtoul(value, NULL, 10);
372 con->parsed_response |= HTTP_CONTENT_LENGTH;
374 break;
375 default:
376 break;
381 /* CGI/1.1 rev 03 - 7.2.1.2 */
382 if ((con->parsed_response & HTTP_LOCATION) &&
383 !(con->parsed_response & HTTP_STATUS)) {
384 con->http_status = 302;
387 return 0;
391 static int cgi_demux_response(server *srv, handler_ctx *hctx) {
392 plugin_data *p = hctx->plugin_data;
393 connection *con = hctx->remote_conn;
395 while(1) {
396 int n;
397 int toread;
399 #if defined(__WIN32)
400 buffer_string_prepare_copy(hctx->response, 4 * 1024);
401 #else
402 if (ioctl(con->fd, FIONREAD, &toread) || toread <= 4*1024) {
403 buffer_string_prepare_copy(hctx->response, 4 * 1024);
404 } else {
405 if (toread > MAX_READ_LIMIT) toread = MAX_READ_LIMIT;
406 buffer_string_prepare_copy(hctx->response, toread);
408 #endif
410 if (-1 == (n = read(hctx->fd, hctx->response->ptr, hctx->response->size - 1))) {
411 if (errno == EAGAIN || errno == EINTR) {
412 /* would block, wait for signal */
413 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
414 return FDEVENT_HANDLED_NOT_FINISHED;
416 /* error */
417 log_error_write(srv, __FILE__, __LINE__, "sdd", strerror(errno), con->fd, hctx->fd);
418 return FDEVENT_HANDLED_ERROR;
421 if (n == 0) {
422 /* read finished */
423 return FDEVENT_HANDLED_FINISHED;
426 buffer_commit(hctx->response, n);
428 /* split header from body */
430 if (con->file_started == 0) {
431 int is_header = 0;
432 int is_header_end = 0;
433 size_t last_eol = 0;
434 size_t i, header_len;
436 buffer_append_string_buffer(hctx->response_header, hctx->response);
439 * we have to handle a few cases:
441 * nph:
443 * HTTP/1.0 200 Ok\n
444 * Header: Value\n
445 * \n
447 * CGI:
448 * Header: Value\n
449 * Status: 200\n
450 * \n
452 * and different mixes of \n and \r\n combinations
454 * Some users also forget about CGI and just send a response and hope
455 * we handle it. No headers, no header-content seperator
459 /* nph (non-parsed headers) */
460 if (0 == strncmp(hctx->response_header->ptr, "HTTP/1.", 7)) is_header = 1;
462 header_len = buffer_string_length(hctx->response_header);
463 for (i = 0; !is_header_end && i < header_len; i++) {
464 char c = hctx->response_header->ptr[i];
466 switch (c) {
467 case ':':
468 /* we found a colon
470 * looks like we have a normal header
472 is_header = 1;
473 break;
474 case '\n':
475 /* EOL */
476 if (is_header == 0) {
477 /* we got a EOL but we don't seem to got a HTTP header */
479 is_header_end = 1;
481 break;
485 * check if we saw a \n(\r)?\n sequence
487 if (last_eol > 0 &&
488 ((i - last_eol == 1) ||
489 (i - last_eol == 2 && hctx->response_header->ptr[i - 1] == '\r'))) {
490 is_header_end = 1;
491 break;
494 last_eol = i;
496 break;
500 if (is_header_end) {
501 if (!is_header) {
502 /* no header, but a body */
503 if (0 != http_chunk_append_buffer(srv, con, hctx->response_header)) {
504 return FDEVENT_HANDLED_ERROR;
506 } else {
507 const char *bstart;
508 size_t blen;
510 /* the body starts after the EOL */
511 bstart = hctx->response_header->ptr + i;
512 blen = header_len - i;
515 * i still points to the char after the terminating EOL EOL
517 * put it on the last \n again
519 i--;
521 /* string the last \r?\n */
522 if (i > 0 && (hctx->response_header->ptr[i - 1] == '\r')) {
523 i--;
526 buffer_string_set_length(hctx->response_header, i);
528 /* parse the response header */
529 cgi_response_parse(srv, con, p, hctx->response_header);
531 if (con->http_status >= 300 && con->http_status < 400) {
532 /*(con->parsed_response & HTTP_LOCATION)*/
533 data_string *ds;
534 if (NULL != (ds = (data_string *) array_get_element(con->response.headers, "Location"))
535 && ds->value->ptr[0] == '/') {
536 if (++con->loops_per_request > 5) {
537 log_error_write(srv, __FILE__, __LINE__, "sb", "too many internal loops while processing request:", con->request.orig_uri);
538 con->http_status = 500; /* Internal Server Error */
539 con->mode = DIRECT;
540 return FDEVENT_HANDLED_FINISHED;
543 buffer_copy_buffer(con->request.uri, ds->value);
545 if (con->request.content_length) {
546 if (con->request.content_length != con->request_content_queue->bytes_in) {
547 con->keep_alive = 0;
549 con->request.content_length = 0;
550 chunkqueue_reset(con->request_content_queue);
553 if (con->http_status != 307 && con->http_status != 308) {
554 /* Note: request body (if any) sent to initial dynamic handler
555 * and is not available to the internal redirect */
556 con->request.http_method = HTTP_METHOD_GET;
559 connection_response_reset(srv, con); /*(includes con->http_status = 0)*/
561 con->mode = DIRECT;
562 return FDEVENT_HANDLED_COMEBACK;
566 if (hctx->conf.xsendfile_allow) {
567 data_string *ds;
568 if (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile"))) {
569 http_response_xsendfile(srv, con, ds->value, hctx->conf.xsendfile_docroot);
570 return FDEVENT_HANDLED_FINISHED;
574 if (blen > 0) {
575 if (0 != http_chunk_append_mem(srv, con, bstart, blen)) {
576 return FDEVENT_HANDLED_ERROR;
581 con->file_started = 1;
582 } else {
583 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
584 if (header_len > MAX_HTTP_REQUEST_HEADER) {
585 log_error_write(srv, __FILE__, __LINE__, "sb", "response headers too large for", con->uri.path);
586 con->http_status = 502; /* Bad Gateway */
587 con->mode = DIRECT;
588 return FDEVENT_HANDLED_FINISHED;
591 } else {
592 if (0 != http_chunk_append_buffer(srv, con, hctx->response)) {
593 return FDEVENT_HANDLED_ERROR;
595 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
596 && chunkqueue_length(con->write_queue) > 65536 - 4096) {
597 if (!con->is_writable) {
598 /*(defer removal of FDEVENT_IN interest since
599 * connection_state_machine() might be able to send data
600 * immediately, unless !con->is_writable, where
601 * connection_state_machine() might not loop back to call
602 * mod_cgi_handle_subrequest())*/
603 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
605 break;
609 #if 0
610 log_error_write(srv, __FILE__, __LINE__, "ddss", con->fd, hctx->fd, connection_get_state(con->state), b->ptr);
611 #endif
614 return FDEVENT_HANDLED_NOT_FINISHED;
617 static void cgi_connection_close_fdtocgi(server *srv, handler_ctx *hctx) {
618 /*(closes only hctx->fdtocgi)*/
619 fdevent_event_del(srv->ev, &(hctx->fde_ndx_tocgi), hctx->fdtocgi);
620 fdevent_unregister(srv->ev, hctx->fdtocgi);
621 fdevent_sched_close(srv->ev, hctx->fdtocgi, 0);
622 hctx->fdtocgi = -1;
625 static void cgi_connection_close(server *srv, handler_ctx *hctx) {
626 int status;
627 pid_t pid;
628 plugin_data *p = hctx->plugin_data;
629 connection *con = hctx->remote_conn;
631 #ifndef __WIN32
633 /* the connection to the browser went away, but we still have a connection
634 * to the CGI script
636 * close cgi-connection
639 if (hctx->fd != -1) {
640 /* close connection to the cgi-script */
641 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
642 fdevent_unregister(srv->ev, hctx->fd);
643 fdevent_sched_close(srv->ev, hctx->fd, 0);
646 if (hctx->fdtocgi != -1) {
647 cgi_connection_close_fdtocgi(srv, hctx); /*(closes only hctx->fdtocgi)*/
650 pid = hctx->pid;
652 con->plugin_ctx[p->id] = NULL;
654 cgi_handler_ctx_free(hctx);
656 /* if waitpid hasn't been called by response.c yet, do it here */
657 if (pid) {
658 /* check if the CGI-script is already gone */
659 switch(waitpid(pid, &status, WNOHANG)) {
660 case 0:
661 /* not finished yet */
662 #if 0
663 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", pid);
664 #endif
665 break;
666 case -1:
667 /* */
668 if (errno == EINTR) break;
671 * errno == ECHILD happens if _subrequest catches the process-status before
672 * we have read the response of the cgi process
674 * -> catch status
675 * -> WAIT_FOR_EVENT
676 * -> read response
677 * -> we get here with waitpid == ECHILD
680 if (errno != ECHILD) {
681 log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno));
683 /* anyway: don't wait for it anymore */
684 pid = 0;
685 break;
686 default:
687 if (WIFEXITED(status)) {
688 #if 0
689 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", pid);
690 #endif
691 } else {
692 log_error_write(srv, __FILE__, __LINE__, "sd", "cgi died, pid:", pid);
695 pid = 0;
696 break;
699 if (pid) {
700 kill(pid, SIGTERM);
702 /* cgi-script is still alive, queue the PID for removal */
703 cgi_pid_add(srv, p, pid);
706 #endif
708 /* finish response (if not already con->file_started, con->file_finished) */
709 if (con->mode == p->id) {
710 http_response_backend_done(srv, con);
714 static handler_t cgi_connection_close_callback(server *srv, connection *con, void *p_d) {
715 plugin_data *p = p_d;
716 handler_ctx *hctx = con->plugin_ctx[p->id];
717 if (hctx) cgi_connection_close(srv, hctx);
719 return HANDLER_GO_ON;
723 static int cgi_write_request(server *srv, handler_ctx *hctx, int fd);
726 static handler_t cgi_handle_fdevent_send (server *srv, void *ctx, int revents) {
727 handler_ctx *hctx = ctx;
728 connection *con = hctx->remote_conn;
730 /*(joblist only actually necessary here in mod_cgi fdevent send if returning HANDLER_ERROR)*/
731 joblist_append(srv, con);
733 if (revents & FDEVENT_OUT) {
734 if (0 != cgi_write_request(srv, hctx, hctx->fdtocgi)) {
735 cgi_connection_close(srv, hctx);
736 return HANDLER_ERROR;
738 /* more request body to be sent to CGI */
741 if (revents & FDEVENT_HUP) {
742 /* skip sending remaining data to CGI */
743 if (con->request.content_length) {
744 chunkqueue *cq = con->request_content_queue;
745 chunkqueue_mark_written(cq, chunkqueue_length(cq));
746 if (cq->bytes_in != (off_t)con->request.content_length) {
747 con->keep_alive = 0;
751 cgi_connection_close_fdtocgi(srv, hctx); /*(closes only hctx->fdtocgi)*/
752 } else if (revents & FDEVENT_ERR) {
753 /* kill all connections to the cgi process */
754 #if 1
755 log_error_write(srv, __FILE__, __LINE__, "s", "cgi-FDEVENT_ERR");
756 #endif
757 cgi_connection_close(srv, hctx);
758 return HANDLER_ERROR;
761 return HANDLER_FINISHED;
765 static int cgi_recv_response(server *srv, handler_ctx *hctx) {
766 switch (cgi_demux_response(srv, hctx)) {
767 case FDEVENT_HANDLED_NOT_FINISHED:
768 break;
769 case FDEVENT_HANDLED_FINISHED:
770 /* we are done */
772 #if 0
773 log_error_write(srv, __FILE__, __LINE__, "ddss", con->fd, hctx->fd, connection_get_state(con->state), "finished");
774 #endif
775 cgi_connection_close(srv, hctx);
777 /* if we get a IN|HUP and have read everything don't exec the close twice */
778 return HANDLER_FINISHED;
779 case FDEVENT_HANDLED_COMEBACK:
780 cgi_connection_close(srv, hctx);
781 return HANDLER_COMEBACK;
782 case FDEVENT_HANDLED_ERROR:
783 log_error_write(srv, __FILE__, __LINE__, "s", "demuxer failed: ");
785 cgi_connection_close(srv, hctx);
786 return HANDLER_FINISHED;
789 return HANDLER_GO_ON;
793 static handler_t cgi_handle_fdevent(server *srv, void *ctx, int revents) {
794 handler_ctx *hctx = ctx;
795 connection *con = hctx->remote_conn;
797 joblist_append(srv, con);
799 if (revents & FDEVENT_IN) {
800 handler_t rc = cgi_recv_response(srv, hctx);/*(might invalidate hctx)*/
801 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
804 /* perhaps this issue is already handled */
805 if (revents & FDEVENT_HUP) {
806 if (con->file_started) {
807 /* drain any remaining data from kernel pipe buffers
808 * even if (con->conf.stream_response_body
809 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
810 * since event loop will spin on fd FDEVENT_HUP event
811 * until unregistered. */
812 handler_t rc;
813 do {
814 rc = cgi_recv_response(srv,hctx);/*(might invalidate hctx)*/
815 } while (rc == HANDLER_GO_ON); /*(unless HANDLER_GO_ON)*/
816 return rc; /* HANDLER_FINISHED or HANDLER_COMEBACK or HANDLER_ERROR */
817 } else if (!buffer_string_is_empty(hctx->response_header)) {
818 /* unfinished header package which is a body in reality */
819 con->file_started = 1;
820 if (0 != http_chunk_append_buffer(srv, con, hctx->response_header)) {
821 cgi_connection_close(srv, hctx);
822 return HANDLER_ERROR;
824 } else {
825 # if 0
826 log_error_write(srv, __FILE__, __LINE__, "sddd", "got HUP from cgi", con->fd, hctx->fd, revents);
827 # endif
829 cgi_connection_close(srv, hctx);
830 } else if (revents & FDEVENT_ERR) {
831 /* kill all connections to the cgi process */
832 cgi_connection_close(srv, hctx);
833 #if 1
834 log_error_write(srv, __FILE__, __LINE__, "s", "cgi-FDEVENT_ERR");
835 #endif
836 return HANDLER_ERROR;
839 return HANDLER_FINISHED;
843 static int cgi_env_add(void *venv, const char *key, size_t key_len, const char *val, size_t val_len) {
844 char_array *env = venv;
845 char *dst;
847 if (!key || !val) return -1;
849 dst = malloc(key_len + val_len + 2);
850 force_assert(dst);
851 memcpy(dst, key, key_len);
852 dst[key_len] = '=';
853 memcpy(dst + key_len + 1, val, val_len);
854 dst[key_len + 1 + val_len] = '\0';
856 if (env->size == 0) {
857 env->size = 16;
858 env->ptr = malloc(env->size * sizeof(*env->ptr));
859 force_assert(env->ptr);
860 } else if (env->size == env->used) {
861 env->size += 16;
862 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
863 force_assert(env->ptr);
866 env->ptr[env->used++] = dst;
868 return 0;
871 /*(improved from network_write_mmap.c)*/
872 static off_t mmap_align_offset(off_t start) {
873 static off_t pagemask = 0;
874 if (0 == pagemask) {
875 long pagesize = sysconf(_SC_PAGESIZE);
876 if (-1 == pagesize) pagesize = 4096;
877 pagemask = ~((off_t)pagesize - 1); /* pagesize always power-of-2 */
879 return (start & pagemask);
882 /* returns: 0: continue, -1: fatal error, -2: connection reset */
883 /* similar to network_write_file_chunk_mmap, but doesn't use send on windows (because we're on pipes),
884 * also mmaps and sends complete chunk instead of only small parts - the files
885 * are supposed to be temp files with reasonable chunk sizes.
887 * Also always use mmap; the files are "trusted", as we created them.
889 static ssize_t cgi_write_file_chunk_mmap(server *srv, connection *con, int fd, chunkqueue *cq) {
890 chunk* const c = cq->first;
891 off_t offset, toSend, file_end;
892 ssize_t r;
893 size_t mmap_offset, mmap_avail;
894 char *data;
896 force_assert(NULL != c);
897 force_assert(FILE_CHUNK == c->type);
898 force_assert(c->offset >= 0 && c->offset <= c->file.length);
900 offset = c->file.start + c->offset;
901 toSend = c->file.length - c->offset;
902 file_end = c->file.start + c->file.length; /* offset to file end in this chunk */
904 if (0 == toSend) {
905 chunkqueue_remove_finished_chunks(cq);
906 return 0;
909 /*(simplified from network_write_no_mmap.c:network_open_file_chunk())*/
910 UNUSED(con);
911 if (-1 == c->file.fd) {
912 if (-1 == (c->file.fd = fdevent_open_cloexec(c->file.name->ptr, O_RDONLY, 0))) {
913 log_error_write(srv, __FILE__, __LINE__, "ssb", "open failed:", strerror(errno), c->file.name);
914 return -1;
918 /* (re)mmap the buffer if range is not covered completely */
919 if (MAP_FAILED == c->file.mmap.start
920 || offset < c->file.mmap.offset
921 || file_end > (off_t)(c->file.mmap.offset + c->file.mmap.length)) {
923 if (MAP_FAILED != c->file.mmap.start) {
924 munmap(c->file.mmap.start, c->file.mmap.length);
925 c->file.mmap.start = MAP_FAILED;
928 c->file.mmap.offset = mmap_align_offset(offset);
929 c->file.mmap.length = file_end - c->file.mmap.offset;
931 if (MAP_FAILED == (c->file.mmap.start = mmap(NULL, c->file.mmap.length, PROT_READ, MAP_PRIVATE, c->file.fd, c->file.mmap.offset))) {
932 if (toSend > 65536) toSend = 65536;
933 data = malloc(toSend);
934 force_assert(data);
935 if (-1 == lseek(c->file.fd, offset, SEEK_SET)
936 || 0 >= (toSend = read(c->file.fd, data, toSend))) {
937 if (-1 == toSend) {
938 log_error_write(srv, __FILE__, __LINE__, "ssbdo", "lseek/read failed:",
939 strerror(errno), c->file.name, c->file.fd, offset);
940 } else { /*(0 == toSend)*/
941 log_error_write(srv, __FILE__, __LINE__, "sbdo", "unexpected EOF (input truncated?):",
942 c->file.name, c->file.fd, offset);
944 free(data);
945 return -1;
950 if (MAP_FAILED != c->file.mmap.start) {
951 force_assert(offset >= c->file.mmap.offset);
952 mmap_offset = offset - c->file.mmap.offset;
953 force_assert(c->file.mmap.length > mmap_offset);
954 mmap_avail = c->file.mmap.length - mmap_offset;
955 force_assert(toSend <= (off_t) mmap_avail);
957 data = c->file.mmap.start + mmap_offset;
960 r = write(fd, data, toSend);
962 if (MAP_FAILED == c->file.mmap.start) free(data);
964 if (r < 0) {
965 switch (errno) {
966 case EAGAIN:
967 case EINTR:
968 return 0;
969 case EPIPE:
970 case ECONNRESET:
971 return -2;
972 default:
973 log_error_write(srv, __FILE__, __LINE__, "ssd",
974 "write failed:", strerror(errno), fd);
975 return -1;
979 if (r >= 0) {
980 chunkqueue_mark_written(cq, r);
983 return r;
986 static int cgi_write_request(server *srv, handler_ctx *hctx, int fd) {
987 connection *con = hctx->remote_conn;
988 chunkqueue *cq = con->request_content_queue;
989 chunk *c;
991 /* old comment: windows doesn't support select() on pipes - wouldn't be easy to fix for all platforms.
992 * solution: if this is still a problem on windows, then substitute
993 * socketpair() for pipe() and closesocket() for close() on windows.
996 for (c = cq->first; c; c = cq->first) {
997 ssize_t r = -1;
999 switch(c->type) {
1000 case FILE_CHUNK:
1001 r = cgi_write_file_chunk_mmap(srv, con, fd, cq);
1002 break;
1004 case MEM_CHUNK:
1005 if ((r = write(fd, c->mem->ptr + c->offset, buffer_string_length(c->mem) - c->offset)) < 0) {
1006 switch(errno) {
1007 case EAGAIN:
1008 case EINTR:
1009 /* ignore and try again */
1010 r = 0;
1011 break;
1012 case EPIPE:
1013 case ECONNRESET:
1014 /* connection closed */
1015 r = -2;
1016 break;
1017 default:
1018 /* fatal error */
1019 log_error_write(srv, __FILE__, __LINE__, "ss", "write failed due to: ", strerror(errno));
1020 r = -1;
1021 break;
1023 } else if (r > 0) {
1024 chunkqueue_mark_written(cq, r);
1026 break;
1029 if (0 == r) break; /*(might block)*/
1031 switch (r) {
1032 case -1:
1033 /* fatal error */
1034 return -1;
1035 case -2:
1036 /* connection reset */
1037 log_error_write(srv, __FILE__, __LINE__, "s", "failed to send post data to cgi, connection closed by CGI");
1038 /* skip all remaining data */
1039 chunkqueue_mark_written(cq, chunkqueue_length(cq));
1040 break;
1041 default:
1042 break;
1046 if (cq->bytes_out == (off_t)con->request.content_length) {
1047 /* sent all request body input */
1048 /* close connection to the cgi-script */
1049 if (-1 == hctx->fdtocgi) { /*(received request body sent in initial send to pipe buffer)*/
1050 --srv->cur_fds;
1051 if (close(fd)) {
1052 log_error_write(srv, __FILE__, __LINE__, "sds", "cgi stdin close failed ", fd, strerror(errno));
1054 } else {
1055 cgi_connection_close_fdtocgi(srv, hctx); /*(closes only hctx->fdtocgi)*/
1057 } else {
1058 off_t cqlen = cq->bytes_in - cq->bytes_out;
1059 if (cq->bytes_in != con->request.content_length && cqlen < 65536 - 16384) {
1060 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
1061 if (!(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN)) {
1062 con->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
1063 con->is_readable = 1; /* trigger optimistic read from client */
1066 if (-1 == hctx->fdtocgi) { /*(not registered yet)*/
1067 hctx->fdtocgi = fd;
1068 hctx->fde_ndx_tocgi = -1;
1069 fdevent_register(srv->ev, hctx->fdtocgi, cgi_handle_fdevent_send, hctx);
1071 if (0 == cqlen) { /*(chunkqueue_is_empty(cq))*/
1072 if ((fdevent_event_get_interest(srv->ev, hctx->fdtocgi) & FDEVENT_OUT)) {
1073 fdevent_event_set(srv->ev, &(hctx->fde_ndx_tocgi), hctx->fdtocgi, 0);
1075 } else {
1076 /* more request body remains to be sent to CGI so register for fdevents */
1077 fdevent_event_set(srv->ev, &(hctx->fde_ndx_tocgi), hctx->fdtocgi, FDEVENT_OUT);
1081 return 0;
1084 static int cgi_create_env(server *srv, connection *con, plugin_data *p, handler_ctx *hctx, buffer *cgi_handler) {
1085 pid_t pid;
1087 int to_cgi_fds[2];
1088 int from_cgi_fds[2];
1089 struct stat st;
1090 UNUSED(p);
1092 #ifndef __WIN32
1094 if (!buffer_string_is_empty(cgi_handler)) {
1095 /* stat the exec file */
1096 if (-1 == (stat(cgi_handler->ptr, &st))) {
1097 log_error_write(srv, __FILE__, __LINE__, "sbss",
1098 "stat for cgi-handler", cgi_handler,
1099 "failed:", strerror(errno));
1100 return -1;
1104 if (pipe_cloexec(to_cgi_fds)) {
1105 log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno));
1106 return -1;
1109 if (pipe_cloexec(from_cgi_fds)) {
1110 close(to_cgi_fds[0]);
1111 close(to_cgi_fds[1]);
1112 log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno));
1113 return -1;
1116 /* fork, execve */
1117 switch (pid = fork()) {
1118 case 0: {
1119 /* child */
1120 char **args;
1121 int argc;
1122 int i = 0;
1123 char_array env;
1124 char *c;
1125 const char *s;
1126 http_cgi_opts opts = { 0, 0, NULL, NULL };
1128 /* move stdout to from_cgi_fd[1] */
1129 dup2(from_cgi_fds[1], STDOUT_FILENO);
1130 #ifndef FD_CLOEXEC
1131 close(from_cgi_fds[1]);
1132 /* not needed */
1133 close(from_cgi_fds[0]);
1134 #endif
1136 /* move the stdin to to_cgi_fd[0] */
1137 dup2(to_cgi_fds[0], STDIN_FILENO);
1138 #ifndef FD_CLOEXEC
1139 close(to_cgi_fds[0]);
1140 /* not needed */
1141 close(to_cgi_fds[1]);
1142 #endif
1144 /* create environment */
1145 env.ptr = NULL;
1146 env.size = 0;
1147 env.used = 0;
1149 http_cgi_headers(srv, con, &opts, cgi_env_add, &env);
1151 /* for valgrind */
1152 if (NULL != (s = getenv("LD_PRELOAD"))) {
1153 cgi_env_add(&env, CONST_STR_LEN("LD_PRELOAD"), s, strlen(s));
1156 if (NULL != (s = getenv("LD_LIBRARY_PATH"))) {
1157 cgi_env_add(&env, CONST_STR_LEN("LD_LIBRARY_PATH"), s, strlen(s));
1159 #ifdef __CYGWIN__
1160 /* CYGWIN needs SYSTEMROOT */
1161 if (NULL != (s = getenv("SYSTEMROOT"))) {
1162 cgi_env_add(&env, CONST_STR_LEN("SYSTEMROOT"), s, strlen(s));
1164 #endif
1166 if (env.size == env.used) {
1167 env.size += 16;
1168 env.ptr = realloc(env.ptr, env.size * sizeof(*env.ptr));
1171 env.ptr[env.used] = NULL;
1173 /* set up args */
1174 argc = 3;
1175 args = malloc(sizeof(*args) * argc);
1176 force_assert(args);
1177 i = 0;
1179 if (!buffer_string_is_empty(cgi_handler)) {
1180 args[i++] = cgi_handler->ptr;
1182 args[i++] = con->physical.path->ptr;
1183 args[i ] = NULL;
1185 /* search for the last / */
1186 if (NULL != (c = strrchr(con->physical.path->ptr, '/'))) {
1187 /* handle special case of file in root directory */
1188 const char* physdir = (c == con->physical.path->ptr) ? "/" : con->physical.path->ptr;
1190 /* temporarily shorten con->physical.path to directory without terminating '/' */
1191 *c = '\0';
1192 /* change to the physical directory */
1193 if (-1 == chdir(physdir)) {
1194 log_error_write(srv, __FILE__, __LINE__, "ssb", "chdir failed:", strerror(errno), con->physical.path);
1196 *c = '/';
1199 /* we don't need the client socket */
1200 for (i = 3; i < 256; i++) {
1201 if (i != srv->errorlog_fd) close(i);
1204 /* exec the cgi */
1205 execve(args[0], args, env.ptr);
1207 /* most log files may have been closed/redirected by this point,
1208 * though stderr might still point to lighttpd.breakage.log */
1209 perror(args[0]);
1210 _exit(1);
1212 case -1:
1213 /* error */
1214 log_error_write(srv, __FILE__, __LINE__, "ss", "fork failed:", strerror(errno));
1215 close(from_cgi_fds[0]);
1216 close(from_cgi_fds[1]);
1217 close(to_cgi_fds[0]);
1218 close(to_cgi_fds[1]);
1219 return -1;
1220 default: {
1221 /* parent process */
1223 close(from_cgi_fds[1]);
1224 close(to_cgi_fds[0]);
1226 /* register PID and wait for them asynchronously */
1228 hctx->pid = pid;
1229 hctx->fd = from_cgi_fds[0];
1230 hctx->fde_ndx = -1;
1232 ++srv->cur_fds;
1234 if (0 == con->request.content_length) {
1235 close(to_cgi_fds[1]);
1236 } else {
1237 /* there is content to send */
1238 if (-1 == fdevent_fcntl_set_nb(srv->ev, to_cgi_fds[1])) {
1239 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
1240 close(to_cgi_fds[1]);
1241 cgi_connection_close(srv, hctx);
1242 return -1;
1245 if (0 != cgi_write_request(srv, hctx, to_cgi_fds[1])) {
1246 close(to_cgi_fds[1]);
1247 cgi_connection_close(srv, hctx);
1248 return -1;
1251 ++srv->cur_fds;
1254 fdevent_register(srv->ev, hctx->fd, cgi_handle_fdevent, hctx);
1255 if (-1 == fdevent_fcntl_set_nb(srv->ev, hctx->fd)) {
1256 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
1257 cgi_connection_close(srv, hctx);
1258 return -1;
1260 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
1262 break;
1266 return 0;
1267 #else
1268 return -1;
1269 #endif
1272 static buffer * cgi_get_handler(array *a, buffer *fn) {
1273 size_t k, s_len = buffer_string_length(fn);
1274 for (k = 0; k < a->used; ++k) {
1275 data_string *ds = (data_string *)a->data[k];
1276 size_t ct_len = buffer_string_length(ds->key);
1278 if (buffer_is_empty(ds->key)) continue;
1279 if (s_len < ct_len) continue;
1281 if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) {
1282 return ds->value;
1286 return NULL;
1289 #define PATCH(x) \
1290 p->conf.x = s->x;
1291 static int mod_cgi_patch_connection(server *srv, connection *con, plugin_data *p) {
1292 size_t i, j;
1293 plugin_config *s = p->config_storage[0];
1295 PATCH(cgi);
1296 PATCH(execute_x_only);
1297 PATCH(xsendfile_allow);
1298 PATCH(xsendfile_docroot);
1300 /* skip the first, the global context */
1301 for (i = 1; i < srv->config_context->used; i++) {
1302 data_config *dc = (data_config *)srv->config_context->data[i];
1303 s = p->config_storage[i];
1305 /* condition didn't match */
1306 if (!config_check_cond(srv, con, dc)) continue;
1308 /* merge config */
1309 for (j = 0; j < dc->value->used; j++) {
1310 data_unset *du = dc->value->data[j];
1312 if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.assign"))) {
1313 PATCH(cgi);
1314 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.execute-x-only"))) {
1315 PATCH(execute_x_only);
1316 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.x-sendfile"))) {
1317 PATCH(xsendfile_allow);
1318 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.x-sendfile-docroot"))) {
1319 PATCH(xsendfile_docroot);
1324 return 0;
1326 #undef PATCH
1328 URIHANDLER_FUNC(cgi_is_handled) {
1329 plugin_data *p = p_d;
1330 buffer *fn = con->physical.path;
1331 stat_cache_entry *sce = NULL;
1332 struct stat stbuf;
1333 struct stat *st;
1334 buffer *cgi_handler;
1336 if (con->mode != DIRECT) return HANDLER_GO_ON;
1338 if (buffer_is_empty(fn)) return HANDLER_GO_ON;
1340 mod_cgi_patch_connection(srv, con, p);
1342 if (HANDLER_ERROR != stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
1343 st = &sce->st;
1344 } else {
1345 /* CGI might be executable even if it is not readable
1346 * (stat_cache_get_entry() currently checks file is readable)*/
1347 if (0 != stat(con->physical.path->ptr, &stbuf)) return HANDLER_GO_ON;
1348 st = &stbuf;
1351 if (!S_ISREG(st->st_mode)) return HANDLER_GO_ON;
1352 if (p->conf.execute_x_only == 1 && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) return HANDLER_GO_ON;
1354 if (NULL != (cgi_handler = cgi_get_handler(p->conf.cgi, fn))) {
1355 handler_ctx *hctx = cgi_handler_ctx_init();
1356 hctx->remote_conn = con;
1357 hctx->plugin_data = p;
1358 hctx->cgi_handler = cgi_handler;
1359 memcpy(&hctx->conf, &p->conf, sizeof(plugin_config));
1360 con->plugin_ctx[p->id] = hctx;
1361 con->mode = p->id;
1364 return HANDLER_GO_ON;
1367 TRIGGER_FUNC(cgi_trigger) {
1368 plugin_data *p = p_d;
1369 size_t ndx;
1370 /* the trigger handle only cares about lonely PID which we have to wait for */
1371 #ifndef __WIN32
1373 for (ndx = 0; ndx < p->cgi_pid.used; ndx++) {
1374 int status;
1376 switch(waitpid(p->cgi_pid.ptr[ndx], &status, WNOHANG)) {
1377 case 0:
1378 /* not finished yet */
1379 #if 0
1380 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", p->cgi_pid.ptr[ndx]);
1381 #endif
1382 break;
1383 case -1:
1384 if (errno == ECHILD) {
1385 /* someone else called waitpid... remove the pid to stop looping the error each time */
1386 log_error_write(srv, __FILE__, __LINE__, "s", "cgi child vanished, probably someone else called waitpid");
1388 cgi_pid_del(srv, p, p->cgi_pid.ptr[ndx]);
1389 ndx--;
1390 continue;
1393 log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno));
1395 return HANDLER_ERROR;
1396 default:
1398 if (WIFEXITED(status)) {
1399 #if 0
1400 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", p->cgi_pid.ptr[ndx]);
1401 #endif
1402 } else if (WIFSIGNALED(status)) {
1403 /* FIXME: what if we killed the CGI script with a kill(..., SIGTERM) ?
1405 if (WTERMSIG(status) != SIGTERM) {
1406 log_error_write(srv, __FILE__, __LINE__, "sd", "cleaning up CGI: process died with signal", WTERMSIG(status));
1408 } else {
1409 log_error_write(srv, __FILE__, __LINE__, "s", "cleaning up CGI: ended unexpectedly");
1412 cgi_pid_del(srv, p, p->cgi_pid.ptr[ndx]);
1413 /* del modified the buffer structure
1414 * and copies the last entry to the current one
1415 * -> recheck the current index
1417 ndx--;
1420 #endif
1421 return HANDLER_GO_ON;
1425 * - HANDLER_GO_ON : not our job
1426 * - HANDLER_FINISHED: got response
1427 * - HANDLER_WAIT_FOR_EVENT: waiting for response
1429 SUBREQUEST_FUNC(mod_cgi_handle_subrequest) {
1430 plugin_data *p = p_d;
1431 handler_ctx *hctx = con->plugin_ctx[p->id];
1432 chunkqueue *cq = con->request_content_queue;
1434 if (con->mode != p->id) return HANDLER_GO_ON;
1435 if (NULL == hctx) return HANDLER_GO_ON;
1437 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
1438 && con->file_started) {
1439 if (chunkqueue_length(con->write_queue) > 65536 - 4096) {
1440 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
1441 } else if (!(fdevent_event_get_interest(srv->ev, hctx->fd) & FDEVENT_IN)) {
1442 /* optimistic read from backend, which might re-enable FDEVENT_IN */
1443 handler_t rc = cgi_recv_response(srv, hctx); /*(might invalidate hctx)*/
1444 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
1448 if (cq->bytes_in != (off_t)con->request.content_length) {
1449 /*(64k - 4k to attempt to avoid temporary files
1450 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
1451 if (cq->bytes_in - cq->bytes_out > 65536 - 4096
1452 && (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_BUFMIN)){
1453 con->conf.stream_request_body &= ~FDEVENT_STREAM_REQUEST_POLLIN;
1454 if (-1 != hctx->fd) return HANDLER_WAIT_FOR_EVENT;
1455 } else {
1456 handler_t r = connection_handle_read_post_state(srv, con);
1457 if (!chunkqueue_is_empty(cq)) {
1458 if (fdevent_event_get_interest(srv->ev, hctx->fdtocgi) & FDEVENT_OUT) {
1459 return (r == HANDLER_GO_ON) ? HANDLER_WAIT_FOR_EVENT : r;
1462 if (r != HANDLER_GO_ON) return r;
1464 /* CGI environment requires that Content-Length be set.
1465 * Send 411 Length Required if Content-Length missing.
1466 * (occurs here if client sends Transfer-Encoding: chunked
1467 * and module is flagged to stream request body to backend) */
1468 if (-1 == con->request.content_length) {
1469 return connection_handle_read_post_error(srv, con, 411);
1474 if (-1 == hctx->fd) {
1475 if (cgi_create_env(srv, con, p, hctx, hctx->cgi_handler)) {
1476 con->http_status = 500;
1477 con->mode = DIRECT;
1479 return HANDLER_FINISHED;
1481 #if 0
1482 log_error_write(srv, __FILE__, __LINE__, "sdd", "subrequest, pid =", hctx, hctx->pid);
1483 #endif
1484 } else if (!chunkqueue_is_empty(con->request_content_queue)) {
1485 if (0 != cgi_write_request(srv, hctx, hctx->fdtocgi)) {
1486 cgi_connection_close(srv, hctx);
1487 return HANDLER_ERROR;
1491 /* if not done, wait for CGI to close stdout, so we read EOF on pipe */
1492 return HANDLER_WAIT_FOR_EVENT;
1496 int mod_cgi_plugin_init(plugin *p);
1497 int mod_cgi_plugin_init(plugin *p) {
1498 p->version = LIGHTTPD_VERSION_ID;
1499 p->name = buffer_init_string("cgi");
1501 p->connection_reset = cgi_connection_close_callback;
1502 p->handle_subrequest_start = cgi_is_handled;
1503 p->handle_subrequest = mod_cgi_handle_subrequest;
1504 p->handle_trigger = cgi_trigger;
1505 p->init = mod_cgi_init;
1506 p->cleanup = mod_cgi_free;
1507 p->set_defaults = mod_fastcgi_set_defaults;
1509 p->data = NULL;
1511 return 0;