[core] option to stream request body to backend (fixes #376)
[lighttpd.git] / src / mod_cgi.c
blob8f630fa5e87fadcbd4a7611d76ec56ed7f9ac711
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"
11 #include "network_backends.h"
13 #include "plugin.h"
15 #include <sys/types.h>
16 #include "sys-mmap.h"
18 #ifdef __WIN32
19 # include <winsock2.h>
20 #else
21 # include <sys/socket.h>
22 # include <sys/wait.h>
23 # include <netinet/in.h>
24 # include <arpa/inet.h>
25 #endif
27 #include <unistd.h>
28 #include <errno.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <fdevent.h>
32 #include <signal.h>
33 #include <ctype.h>
34 #include <assert.h>
36 #include <stdio.h>
37 #include <fcntl.h>
39 #include "version.h"
41 enum {EOL_UNSET, EOL_N, EOL_RN};
43 typedef struct {
44 char **ptr;
46 size_t size;
47 size_t used;
48 } char_array;
50 typedef struct {
51 pid_t *ptr;
52 size_t used;
53 size_t size;
54 } buffer_pid_t;
56 typedef struct {
57 array *cgi;
58 unsigned short execute_x_only;
59 unsigned short xsendfile_allow;
60 array *xsendfile_docroot;
61 } plugin_config;
63 typedef struct {
64 PLUGIN_DATA;
65 buffer_pid_t cgi_pid;
67 buffer *tmp_buf;
68 buffer *parse_response;
70 plugin_config **config_storage;
72 plugin_config conf;
73 } plugin_data;
75 typedef struct {
76 pid_t pid;
77 int fd;
78 int fdtocgi;
79 int fde_ndx; /* index into the fd-event buffer */
80 int fde_ndx_tocgi; /* index into the fd-event buffer */
82 connection *remote_conn; /* dumb pointer */
83 plugin_data *plugin_data; /* dumb pointer */
85 buffer *response;
86 buffer *response_header;
87 } handler_ctx;
89 static handler_ctx * cgi_handler_ctx_init(void) {
90 handler_ctx *hctx = calloc(1, sizeof(*hctx));
92 force_assert(hctx);
94 hctx->response = buffer_init();
95 hctx->response_header = buffer_init();
96 hctx->fd = -1;
97 hctx->fdtocgi = -1;
99 return hctx;
102 static void cgi_handler_ctx_free(handler_ctx *hctx) {
103 buffer_free(hctx->response);
104 buffer_free(hctx->response_header);
106 free(hctx);
109 enum {FDEVENT_HANDLED_UNSET, FDEVENT_HANDLED_FINISHED, FDEVENT_HANDLED_NOT_FINISHED, FDEVENT_HANDLED_ERROR};
111 INIT_FUNC(mod_cgi_init) {
112 plugin_data *p;
114 p = calloc(1, sizeof(*p));
116 force_assert(p);
118 p->tmp_buf = buffer_init();
119 p->parse_response = buffer_init();
121 return p;
125 FREE_FUNC(mod_cgi_free) {
126 plugin_data *p = p_d;
127 buffer_pid_t *r = &(p->cgi_pid);
129 UNUSED(srv);
131 if (p->config_storage) {
132 size_t i;
133 for (i = 0; i < srv->config_context->used; i++) {
134 plugin_config *s = p->config_storage[i];
136 if (NULL == s) continue;
138 array_free(s->cgi);
139 array_free(s->xsendfile_docroot);
141 free(s);
143 free(p->config_storage);
147 if (r->ptr) free(r->ptr);
149 buffer_free(p->tmp_buf);
150 buffer_free(p->parse_response);
152 free(p);
154 return HANDLER_GO_ON;
157 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults) {
158 plugin_data *p = p_d;
159 size_t i = 0;
161 config_values_t cv[] = {
162 { "cgi.assign", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
163 { "cgi.execute-x-only", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
164 { "cgi.x-sendfile", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
165 { "cgi.x-sendfile-docroot", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
166 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET}
169 if (!p) return HANDLER_ERROR;
171 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
172 force_assert(p->config_storage);
174 for (i = 0; i < srv->config_context->used; i++) {
175 data_config const* config = (data_config const*)srv->config_context->data[i];
176 plugin_config *s;
178 s = calloc(1, sizeof(plugin_config));
179 force_assert(s);
181 s->cgi = array_init();
182 s->execute_x_only = 0;
183 s->xsendfile_allow= 0;
184 s->xsendfile_docroot = array_init();
186 cv[0].destination = s->cgi;
187 cv[1].destination = &(s->execute_x_only);
188 cv[2].destination = &(s->xsendfile_allow);
189 cv[3].destination = s->xsendfile_docroot;
191 p->config_storage[i] = s;
193 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
194 return HANDLER_ERROR;
197 if (s->xsendfile_docroot->used) {
198 size_t j;
199 for (j = 0; j < s->xsendfile_docroot->used; ++j) {
200 data_string *ds = (data_string *)s->xsendfile_docroot->data[j];
201 if (ds->type != TYPE_STRING) {
202 log_error_write(srv, __FILE__, __LINE__, "s",
203 "unexpected type for key cgi.x-sendfile-docroot; expected: cgi.x-sendfile-docroot = ( \"/allowed/path\", ... )");
204 return HANDLER_ERROR;
206 if (ds->value->ptr[0] != '/') {
207 log_error_write(srv, __FILE__, __LINE__, "SBs",
208 "cgi.x-sendfile-docroot paths must begin with '/'; invalid: \"", ds->value, "\"");
209 return HANDLER_ERROR;
211 buffer_path_simplify(ds->value, ds->value);
212 buffer_append_slash(ds->value);
217 return HANDLER_GO_ON;
221 static int cgi_pid_add(server *srv, plugin_data *p, pid_t pid) {
222 int m = -1;
223 size_t i;
224 buffer_pid_t *r = &(p->cgi_pid);
226 UNUSED(srv);
228 for (i = 0; i < r->used; i++) {
229 if (r->ptr[i] > m) m = r->ptr[i];
232 if (r->size == 0) {
233 r->size = 16;
234 r->ptr = malloc(sizeof(*r->ptr) * r->size);
235 force_assert(r->ptr);
236 } else if (r->used == r->size) {
237 r->size += 16;
238 r->ptr = realloc(r->ptr, sizeof(*r->ptr) * r->size);
239 force_assert(r->ptr);
242 r->ptr[r->used++] = pid;
244 return m;
247 static int cgi_pid_del(server *srv, plugin_data *p, pid_t pid) {
248 size_t i;
249 buffer_pid_t *r = &(p->cgi_pid);
251 UNUSED(srv);
253 for (i = 0; i < r->used; i++) {
254 if (r->ptr[i] == pid) break;
257 if (i != r->used) {
258 /* found */
260 if (i != r->used - 1) {
261 r->ptr[i] = r->ptr[r->used - 1];
263 r->used--;
266 return 0;
269 static int cgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in) {
270 char *ns;
271 const char *s;
272 int line = 0;
274 UNUSED(srv);
276 buffer_copy_buffer(p->parse_response, in);
278 for (s = p->parse_response->ptr;
279 NULL != (ns = strchr(s, '\n'));
280 s = ns + 1, line++) {
281 const char *key, *value;
282 int key_len;
283 data_string *ds;
285 /* strip the \n */
286 ns[0] = '\0';
288 if (ns > s && ns[-1] == '\r') ns[-1] = '\0';
290 if (line == 0 &&
291 0 == strncmp(s, "HTTP/1.", 7)) {
292 /* non-parsed header ... we parse them anyway */
294 if ((s[7] == '1' ||
295 s[7] == '0') &&
296 s[8] == ' ') {
297 int status;
298 /* after the space should be a status code for us */
300 status = strtol(s+9, NULL, 10);
302 if (status >= 100 &&
303 status < 1000) {
304 /* we expected 3 digits and didn't got them */
305 con->parsed_response |= HTTP_STATUS;
306 con->http_status = status;
309 } else {
310 /* parse the headers */
311 key = s;
312 if (NULL == (value = strchr(s, ':'))) {
313 /* we expect: "<key>: <value>\r\n" */
314 continue;
317 key_len = value - key;
318 value += 1;
320 /* skip LWS */
321 while (*value == ' ' || *value == '\t') value++;
323 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
324 ds = data_response_init();
326 buffer_copy_string_len(ds->key, key, key_len);
327 buffer_copy_string(ds->value, value);
329 array_insert_unique(con->response.headers, (data_unset *)ds);
331 switch(key_len) {
332 case 4:
333 if (0 == strncasecmp(key, "Date", key_len)) {
334 con->parsed_response |= HTTP_DATE;
336 break;
337 case 6:
338 if (0 == strncasecmp(key, "Status", key_len)) {
339 int status = strtol(value, NULL, 10);
340 if (status >= 100 && status < 1000) {
341 con->http_status = status;
342 con->parsed_response |= HTTP_STATUS;
343 } else {
344 con->http_status = 502;
347 break;
348 case 8:
349 if (0 == strncasecmp(key, "Location", key_len)) {
350 con->parsed_response |= HTTP_LOCATION;
352 break;
353 case 10:
354 if (0 == strncasecmp(key, "Connection", key_len)) {
355 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
356 con->parsed_response |= HTTP_CONNECTION;
358 break;
359 case 14:
360 if (0 == strncasecmp(key, "Content-Length", key_len)) {
361 con->response.content_length = strtoul(value, NULL, 10);
362 con->parsed_response |= HTTP_CONTENT_LENGTH;
364 break;
365 default:
366 break;
371 /* CGI/1.1 rev 03 - 7.2.1.2 */
372 if ((con->parsed_response & HTTP_LOCATION) &&
373 !(con->parsed_response & HTTP_STATUS)) {
374 con->http_status = 302;
377 return 0;
381 static int cgi_demux_response(server *srv, handler_ctx *hctx) {
382 plugin_data *p = hctx->plugin_data;
383 connection *con = hctx->remote_conn;
385 while(1) {
386 int n;
387 int toread;
389 #if defined(__WIN32)
390 buffer_string_prepare_copy(hctx->response, 4 * 1024);
391 #else
392 if (ioctl(con->fd, FIONREAD, &toread) || toread == 0 || toread <= 4*1024) {
393 buffer_string_prepare_copy(hctx->response, 4 * 1024);
394 } else {
395 if (toread > MAX_READ_LIMIT) toread = MAX_READ_LIMIT;
396 buffer_string_prepare_copy(hctx->response, toread);
398 #endif
400 if (-1 == (n = read(hctx->fd, hctx->response->ptr, hctx->response->size - 1))) {
401 if (errno == EAGAIN || errno == EINTR) {
402 /* would block, wait for signal */
403 return FDEVENT_HANDLED_NOT_FINISHED;
405 /* error */
406 log_error_write(srv, __FILE__, __LINE__, "sdd", strerror(errno), con->fd, hctx->fd);
407 return FDEVENT_HANDLED_ERROR;
410 if (n == 0) {
411 /* read finished */
413 con->file_finished = 1;
415 /* send final chunk */
416 http_chunk_close(srv, con);
418 return FDEVENT_HANDLED_FINISHED;
421 buffer_commit(hctx->response, n);
423 /* split header from body */
425 if (con->file_started == 0) {
426 int is_header = 0;
427 int is_header_end = 0;
428 size_t last_eol = 0;
429 size_t i, header_len;
431 buffer_append_string_buffer(hctx->response_header, hctx->response);
434 * we have to handle a few cases:
436 * nph:
438 * HTTP/1.0 200 Ok\n
439 * Header: Value\n
440 * \n
442 * CGI:
443 * Header: Value\n
444 * Status: 200\n
445 * \n
447 * and different mixes of \n and \r\n combinations
449 * Some users also forget about CGI and just send a response and hope
450 * we handle it. No headers, no header-content seperator
454 /* nph (non-parsed headers) */
455 if (0 == strncmp(hctx->response_header->ptr, "HTTP/1.", 7)) is_header = 1;
457 header_len = buffer_string_length(hctx->response_header);
458 for (i = 0; !is_header_end && i < header_len; i++) {
459 char c = hctx->response_header->ptr[i];
461 switch (c) {
462 case ':':
463 /* we found a colon
465 * looks like we have a normal header
467 is_header = 1;
468 break;
469 case '\n':
470 /* EOL */
471 if (is_header == 0) {
472 /* we got a EOL but we don't seem to got a HTTP header */
474 is_header_end = 1;
476 break;
480 * check if we saw a \n(\r)?\n sequence
482 if (last_eol > 0 &&
483 ((i - last_eol == 1) ||
484 (i - last_eol == 2 && hctx->response_header->ptr[i - 1] == '\r'))) {
485 is_header_end = 1;
486 break;
489 last_eol = i;
491 break;
495 if (is_header_end) {
496 if (!is_header) {
497 /* no header, but a body */
499 if (con->request.http_version == HTTP_VERSION_1_1) {
500 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
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 (p->conf.xsendfile_allow) {
532 data_string *ds;
533 if (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile"))) {
534 http_response_xsendfile(srv, con, ds->value, p->conf.xsendfile_docroot);
535 return FDEVENT_HANDLED_FINISHED;
539 /* enable chunked-transfer-encoding */
540 if (con->request.http_version == HTTP_VERSION_1_1 &&
541 !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
542 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
545 if (blen > 0) {
546 if (0 != http_chunk_append_mem(srv, con, bstart, blen)) {
547 return FDEVENT_HANDLED_ERROR;
552 con->file_started = 1;
554 } else {
555 if (0 != http_chunk_append_buffer(srv, con, hctx->response)) {
556 return FDEVENT_HANDLED_ERROR;
560 #if 0
561 log_error_write(srv, __FILE__, __LINE__, "ddss", con->fd, hctx->fd, connection_get_state(con->state), b->ptr);
562 #endif
565 return FDEVENT_HANDLED_NOT_FINISHED;
568 static void cgi_connection_close_fdtocgi(server *srv, handler_ctx *hctx) {
569 /*(closes only hctx->fdtocgi)*/
570 fdevent_event_del(srv->ev, &(hctx->fde_ndx_tocgi), hctx->fdtocgi);
571 fdevent_unregister(srv->ev, hctx->fdtocgi);
573 if (close(hctx->fdtocgi)) {
574 log_error_write(srv, __FILE__, __LINE__, "sds", "cgi stdin close failed ", hctx->fdtocgi, strerror(errno));
576 hctx->fdtocgi = -1;
579 static void cgi_connection_close(server *srv, handler_ctx *hctx) {
580 int status;
581 pid_t pid;
582 plugin_data *p = hctx->plugin_data;
583 connection *con = hctx->remote_conn;
585 #ifndef __WIN32
587 /* the connection to the browser went away, but we still have a connection
588 * to the CGI script
590 * close cgi-connection
593 if (hctx->fd != -1) {
594 /* close connection to the cgi-script */
595 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
596 fdevent_unregister(srv->ev, hctx->fd);
598 if (close(hctx->fd)) {
599 log_error_write(srv, __FILE__, __LINE__, "sds", "cgi close failed ", hctx->fd, strerror(errno));
603 if (hctx->fdtocgi != -1) {
604 cgi_connection_close_fdtocgi(srv, hctx); /*(closes only hctx->fdtocgi)*/
607 pid = hctx->pid;
609 con->plugin_ctx[p->id] = NULL;
611 cgi_handler_ctx_free(hctx);
613 /* if waitpid hasn't been called by response.c yet, do it here */
614 if (pid) {
615 /* check if the CGI-script is already gone */
616 switch(waitpid(pid, &status, WNOHANG)) {
617 case 0:
618 /* not finished yet */
619 #if 0
620 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", pid);
621 #endif
622 break;
623 case -1:
624 /* */
625 if (errno == EINTR) break;
628 * errno == ECHILD happens if _subrequest catches the process-status before
629 * we have read the response of the cgi process
631 * -> catch status
632 * -> WAIT_FOR_EVENT
633 * -> read response
634 * -> we get here with waitpid == ECHILD
637 if (errno != ECHILD) {
638 log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno));
640 /* anyway: don't wait for it anymore */
641 pid = 0;
642 break;
643 default:
644 if (WIFEXITED(status)) {
645 #if 0
646 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", pid);
647 #endif
648 } else {
649 log_error_write(srv, __FILE__, __LINE__, "sd", "cgi died, pid:", pid);
652 pid = 0;
653 break;
656 if (pid) {
657 kill(pid, SIGTERM);
659 /* cgi-script is still alive, queue the PID for removal */
660 cgi_pid_add(srv, p, pid);
663 #endif
665 /* finish response (if not already con->file_started, con->file_finished) */
666 if (con->mode == p->id) {
667 http_response_backend_done(srv, con);
671 static handler_t cgi_connection_close_callback(server *srv, connection *con, void *p_d) {
672 plugin_data *p = p_d;
673 handler_ctx *hctx = con->plugin_ctx[p->id];
674 if (hctx) cgi_connection_close(srv, hctx);
676 return HANDLER_GO_ON;
680 static int cgi_write_request(server *srv, handler_ctx *hctx, int fd);
683 static handler_t cgi_handle_fdevent_send (server *srv, void *ctx, int revents) {
684 handler_ctx *hctx = ctx;
685 connection *con = hctx->remote_conn;
687 /*(joblist only actually necessary here in mod_cgi fdevent send if returning HANDLER_ERROR)*/
688 joblist_append(srv, con);
690 if (revents & FDEVENT_OUT) {
691 if (0 != cgi_write_request(srv, hctx, hctx->fdtocgi)) {
692 cgi_connection_close(srv, hctx);
693 return HANDLER_ERROR;
695 /* more request body to be sent to CGI */
698 if (revents & FDEVENT_HUP) {
699 /* skip sending remaining data to CGI */
700 if (con->request.content_length) {
701 chunkqueue *cq = con->request_content_queue;
702 chunkqueue_mark_written(cq, chunkqueue_length(cq));
703 if (cq->bytes_in != (off_t)con->request.content_length) {
704 con->keep_alive = 0;
708 cgi_connection_close_fdtocgi(srv, hctx); /*(closes only hctx->fdtocgi)*/
709 } else if (revents & FDEVENT_ERR) {
710 /* kill all connections to the cgi process */
711 #if 1
712 log_error_write(srv, __FILE__, __LINE__, "s", "cgi-FDEVENT_ERR");
713 #endif
714 cgi_connection_close(srv, hctx);
715 return HANDLER_ERROR;
718 return HANDLER_FINISHED;
722 static handler_t cgi_handle_fdevent(server *srv, void *ctx, int revents) {
723 handler_ctx *hctx = ctx;
724 connection *con = hctx->remote_conn;
726 joblist_append(srv, con);
728 if (revents & FDEVENT_IN) {
729 switch (cgi_demux_response(srv, hctx)) {
730 case FDEVENT_HANDLED_NOT_FINISHED:
731 break;
732 case FDEVENT_HANDLED_FINISHED:
733 /* we are done */
735 #if 0
736 log_error_write(srv, __FILE__, __LINE__, "ddss", con->fd, hctx->fd, connection_get_state(con->state), "finished");
737 #endif
738 cgi_connection_close(srv, hctx);
740 /* if we get a IN|HUP and have read everything don't exec the close twice */
741 return HANDLER_FINISHED;
742 case FDEVENT_HANDLED_ERROR:
743 log_error_write(srv, __FILE__, __LINE__, "s", "demuxer failed: ");
745 cgi_connection_close(srv, hctx);
746 return HANDLER_FINISHED;
750 /* perhaps this issue is already handled */
751 if (revents & FDEVENT_HUP) {
752 /* check if we still have a unfinished header package which is a body in reality */
753 if (con->file_started == 0 && !buffer_string_is_empty(hctx->response_header)) {
754 con->file_started = 1;
755 if (0 != http_chunk_append_buffer(srv, con, hctx->response_header)) {
756 cgi_connection_close(srv, hctx);
757 return HANDLER_ERROR;
761 # if 0
762 log_error_write(srv, __FILE__, __LINE__, "sddd", "got HUP from cgi", con->fd, hctx->fd, revents);
763 # endif
765 /* rtsigs didn't liked the close */
766 cgi_connection_close(srv, hctx);
767 } else if (revents & FDEVENT_ERR) {
768 /* kill all connections to the cgi process */
769 cgi_connection_close(srv, hctx);
770 #if 1
771 log_error_write(srv, __FILE__, __LINE__, "s", "cgi-FDEVENT_ERR");
772 #endif
773 return HANDLER_ERROR;
776 return HANDLER_FINISHED;
780 static int cgi_env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
781 char *dst;
783 if (!key || !val) return -1;
785 dst = malloc(key_len + val_len + 2);
786 force_assert(dst);
787 memcpy(dst, key, key_len);
788 dst[key_len] = '=';
789 memcpy(dst + key_len + 1, val, val_len);
790 dst[key_len + 1 + val_len] = '\0';
792 if (env->size == 0) {
793 env->size = 16;
794 env->ptr = malloc(env->size * sizeof(*env->ptr));
795 force_assert(env->ptr);
796 } else if (env->size == env->used) {
797 env->size += 16;
798 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
799 force_assert(env->ptr);
802 env->ptr[env->used++] = dst;
804 return 0;
807 /* returns: 0: continue, -1: fatal error, -2: connection reset */
808 /* similar to network_write_file_chunk_mmap, but doesn't use send on windows (because we're on pipes),
809 * also mmaps and sends complete chunk instead of only small parts - the files
810 * are supposed to be temp files with reasonable chunk sizes.
812 * Also always use mmap; the files are "trusted", as we created them.
814 static ssize_t cgi_write_file_chunk_mmap(server *srv, connection *con, int fd, chunkqueue *cq) {
815 chunk* const c = cq->first;
816 off_t offset, toSend, file_end;
817 ssize_t r;
818 size_t mmap_offset, mmap_avail;
819 char *data;
821 force_assert(NULL != c);
822 force_assert(FILE_CHUNK == c->type);
823 force_assert(c->offset >= 0 && c->offset <= c->file.length);
825 offset = c->file.start + c->offset;
826 toSend = c->file.length - c->offset;
827 file_end = c->file.start + c->file.length; /* offset to file end in this chunk */
829 if (0 == toSend) {
830 chunkqueue_remove_finished_chunks(cq);
831 return 0;
834 if (0 != network_open_file_chunk(srv, con, cq)) return -1;
836 /* (re)mmap the buffer if range is not covered completely */
837 if (MAP_FAILED == c->file.mmap.start
838 || offset < c->file.mmap.offset
839 || file_end > (off_t)(c->file.mmap.offset + c->file.mmap.length)) {
841 if (MAP_FAILED != c->file.mmap.start) {
842 munmap(c->file.mmap.start, c->file.mmap.length);
843 c->file.mmap.start = MAP_FAILED;
846 c->file.mmap.offset = mmap_align_offset(offset);
847 c->file.mmap.length = file_end - c->file.mmap.offset;
849 if (MAP_FAILED == (c->file.mmap.start = mmap(NULL, c->file.mmap.length, PROT_READ, MAP_PRIVATE, c->file.fd, c->file.mmap.offset))) {
850 if (toSend > 65536) toSend = 65536;
851 data = malloc(toSend);
852 force_assert(data);
853 if (-1 == lseek(c->file.fd, offset, SEEK_SET)
854 || 0 >= (toSend = read(c->file.fd, data, toSend))) {
855 if (-1 == toSend) {
856 log_error_write(srv, __FILE__, __LINE__, "ssbdo", "lseek/read failed:",
857 strerror(errno), c->file.name, c->file.fd, offset);
858 } else { /*(0 == toSend)*/
859 log_error_write(srv, __FILE__, __LINE__, "sbdo", "unexpected EOF (input truncated?):",
860 c->file.name, c->file.fd, offset);
862 free(data);
863 return -1;
868 if (MAP_FAILED != c->file.mmap.start) {
869 force_assert(offset >= c->file.mmap.offset);
870 mmap_offset = offset - c->file.mmap.offset;
871 force_assert(c->file.mmap.length > mmap_offset);
872 mmap_avail = c->file.mmap.length - mmap_offset;
873 force_assert(toSend <= (off_t) mmap_avail);
875 data = c->file.mmap.start + mmap_offset;
878 r = write(fd, data, toSend);
880 if (MAP_FAILED == c->file.mmap.start) free(data);
882 if (r < 0) {
883 switch (errno) {
884 case EAGAIN:
885 case EINTR:
886 return 0;
887 case EPIPE:
888 case ECONNRESET:
889 return -2;
890 default:
891 log_error_write(srv, __FILE__, __LINE__, "ssd",
892 "write failed:", strerror(errno), fd);
893 return -1;
897 if (r >= 0) {
898 chunkqueue_mark_written(cq, r);
901 return r;
904 static int cgi_write_request(server *srv, handler_ctx *hctx, int fd) {
905 connection *con = hctx->remote_conn;
906 chunkqueue *cq = con->request_content_queue;
907 chunk *c;
909 /* old comment: windows doesn't support select() on pipes - wouldn't be easy to fix for all platforms.
910 * solution: if this is still a problem on windows, then substitute
911 * socketpair() for pipe() and closesocket() for close() on windows.
914 for (c = cq->first; c; c = cq->first) {
915 ssize_t r = -1;
917 switch(c->type) {
918 case FILE_CHUNK:
919 r = cgi_write_file_chunk_mmap(srv, con, fd, cq);
920 break;
922 case MEM_CHUNK:
923 if ((r = write(fd, c->mem->ptr + c->offset, buffer_string_length(c->mem) - c->offset)) < 0) {
924 switch(errno) {
925 case EAGAIN:
926 case EINTR:
927 /* ignore and try again */
928 r = 0;
929 break;
930 case EPIPE:
931 case ECONNRESET:
932 /* connection closed */
933 r = -2;
934 break;
935 default:
936 /* fatal error */
937 log_error_write(srv, __FILE__, __LINE__, "ss", "write failed due to: ", strerror(errno));
938 r = -1;
939 break;
941 } else if (r > 0) {
942 chunkqueue_mark_written(cq, r);
944 break;
947 if (0 == r) break; /*(might block)*/
949 switch (r) {
950 case -1:
951 /* fatal error */
952 return -1;
953 case -2:
954 /* connection reset */
955 log_error_write(srv, __FILE__, __LINE__, "s", "failed to send post data to cgi, connection closed by CGI");
956 /* skip all remaining data */
957 chunkqueue_mark_written(cq, chunkqueue_length(cq));
958 break;
959 default:
960 break;
964 if (cq->bytes_out == (off_t)con->request.content_length) {
965 /* sent all request body input */
966 /* close connection to the cgi-script */
967 if (-1 == hctx->fdtocgi) { /*(received request body sent in initial send to pipe buffer)*/
968 if (close(fd)) {
969 log_error_write(srv, __FILE__, __LINE__, "sds", "cgi stdin close failed ", fd, strerror(errno));
971 } else {
972 cgi_connection_close_fdtocgi(srv, hctx); /*(closes only hctx->fdtocgi)*/
974 } else {
975 off_t cqlen = cq->bytes_in - cq->bytes_out;
976 if (cq->bytes_in < (off_t)con->request.content_length && cqlen < 65536 - 16384) {
977 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
978 if (!(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN)) {
979 con->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
980 con->is_readable = 1; /* trigger optimistic read from client */
983 if (-1 == hctx->fdtocgi) { /*(not registered yet)*/
984 hctx->fdtocgi = fd;
985 hctx->fde_ndx_tocgi = -1;
986 fdevent_register(srv->ev, hctx->fdtocgi, cgi_handle_fdevent_send, hctx);
988 if (0 == cqlen) { /*(chunkqueue_is_empty(cq))*/
989 if ((fdevent_event_get_interest(srv->ev, hctx->fdtocgi) & FDEVENT_OUT)) {
990 fdevent_event_set(srv->ev, &(hctx->fde_ndx_tocgi), hctx->fdtocgi, 0);
992 } else {
993 /* more request body remains to be sent to CGI so register for fdevents */
994 fdevent_event_set(srv->ev, &(hctx->fde_ndx_tocgi), hctx->fdtocgi, FDEVENT_OUT);
998 return 0;
1001 static int cgi_create_env(server *srv, connection *con, plugin_data *p, handler_ctx *hctx, buffer *cgi_handler) {
1002 pid_t pid;
1004 #ifdef HAVE_IPV6
1005 char b2[INET6_ADDRSTRLEN + 1];
1006 #endif
1008 int to_cgi_fds[2];
1009 int from_cgi_fds[2];
1010 struct stat st;
1012 #ifndef __WIN32
1014 if (!buffer_string_is_empty(cgi_handler)) {
1015 /* stat the exec file */
1016 if (-1 == (stat(cgi_handler->ptr, &st))) {
1017 log_error_write(srv, __FILE__, __LINE__, "sbss",
1018 "stat for cgi-handler", cgi_handler,
1019 "failed:", strerror(errno));
1020 return -1;
1024 if (pipe(to_cgi_fds)) {
1025 log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno));
1026 return -1;
1029 if (pipe(from_cgi_fds)) {
1030 close(to_cgi_fds[0]);
1031 close(to_cgi_fds[1]);
1032 log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno));
1033 return -1;
1036 /* fork, execve */
1037 switch (pid = fork()) {
1038 case 0: {
1039 /* child */
1040 char **args;
1041 int argc;
1042 int i = 0;
1043 char buf[LI_ITOSTRING_LENGTH];
1044 size_t n;
1045 char_array env;
1046 char *c;
1047 const char *s;
1048 server_socket *srv_sock = con->srv_socket;
1050 /* move stdout to from_cgi_fd[1] */
1051 close(STDOUT_FILENO);
1052 dup2(from_cgi_fds[1], STDOUT_FILENO);
1053 close(from_cgi_fds[1]);
1054 /* not needed */
1055 close(from_cgi_fds[0]);
1057 /* move the stdin to to_cgi_fd[0] */
1058 close(STDIN_FILENO);
1059 dup2(to_cgi_fds[0], STDIN_FILENO);
1060 close(to_cgi_fds[0]);
1061 /* not needed */
1062 close(to_cgi_fds[1]);
1064 /* create environment */
1065 env.ptr = NULL;
1066 env.size = 0;
1067 env.used = 0;
1069 if (buffer_is_empty(con->conf.server_tag)) {
1070 cgi_env_add(&env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC));
1071 } else {
1072 cgi_env_add(&env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con->conf.server_tag));
1075 if (!buffer_string_is_empty(con->server_name)) {
1076 size_t len = buffer_string_length(con->server_name);
1078 if (con->server_name->ptr[0] == '[') {
1079 const char *colon = strstr(con->server_name->ptr, "]:");
1080 if (colon) len = (colon + 1) - con->server_name->ptr;
1081 } else {
1082 const char *colon = strchr(con->server_name->ptr, ':');
1083 if (colon) len = colon - con->server_name->ptr;
1086 cgi_env_add(&env, CONST_STR_LEN("SERVER_NAME"), con->server_name->ptr, len);
1087 } else {
1088 #ifdef HAVE_IPV6
1089 s = inet_ntop(
1090 srv_sock->addr.plain.sa_family,
1091 srv_sock->addr.plain.sa_family == AF_INET6 ?
1092 (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
1093 (const void *) &(srv_sock->addr.ipv4.sin_addr),
1094 b2, sizeof(b2)-1);
1095 #else
1096 s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1097 #endif
1098 force_assert(s);
1099 cgi_env_add(&env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
1101 cgi_env_add(&env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1103 s = get_http_version_name(con->request.http_version);
1104 force_assert(s);
1105 cgi_env_add(&env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
1107 li_utostrn(buf, sizeof(buf),
1108 #ifdef HAVE_IPV6
1109 ntohs(srv_sock->addr.plain.sa_family == AF_INET6 ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
1110 #else
1111 ntohs(srv_sock->addr.ipv4.sin_port)
1112 #endif
1114 cgi_env_add(&env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf));
1116 switch (srv_sock->addr.plain.sa_family) {
1117 #ifdef HAVE_IPV6
1118 case AF_INET6:
1119 s = inet_ntop(
1120 srv_sock->addr.plain.sa_family,
1121 (const void *) &(srv_sock->addr.ipv6.sin6_addr),
1122 b2, sizeof(b2)-1);
1123 break;
1124 case AF_INET:
1125 s = inet_ntop(
1126 srv_sock->addr.plain.sa_family,
1127 (const void *) &(srv_sock->addr.ipv4.sin_addr),
1128 b2, sizeof(b2)-1);
1129 break;
1130 #else
1131 case AF_INET:
1132 s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1133 break;
1134 #endif
1135 default:
1136 s = "";
1137 break;
1139 force_assert(s);
1140 cgi_env_add(&env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));
1142 s = get_http_method_name(con->request.http_method);
1143 force_assert(s);
1144 cgi_env_add(&env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
1146 if (!buffer_string_is_empty(con->request.pathinfo)) {
1147 cgi_env_add(&env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo));
1149 if (!buffer_string_is_empty(con->uri.query)) {
1150 cgi_env_add(&env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query));
1151 } else {
1152 cgi_env_add(&env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1154 if (con->error_handler_saved_status >= 0) {
1155 cgi_env_add(&env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.uri));
1156 } else {
1157 cgi_env_add(&env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri));
1159 /* set REDIRECT_STATUS for php compiled with --force-redirect
1160 * (if REDIRECT_STATUS has not already been set by error handler) */
1161 if (0 == con->error_handler_saved_status) {
1162 cgi_env_add(&env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200"));
1166 switch (con->dst_addr.plain.sa_family) {
1167 #ifdef HAVE_IPV6
1168 case AF_INET6:
1169 s = inet_ntop(
1170 con->dst_addr.plain.sa_family,
1171 (const void *) &(con->dst_addr.ipv6.sin6_addr),
1172 b2, sizeof(b2)-1);
1173 break;
1174 case AF_INET:
1175 s = inet_ntop(
1176 con->dst_addr.plain.sa_family,
1177 (const void *) &(con->dst_addr.ipv4.sin_addr),
1178 b2, sizeof(b2)-1);
1179 break;
1180 #else
1181 case AF_INET:
1182 s = inet_ntoa(con->dst_addr.ipv4.sin_addr);
1183 break;
1184 #endif
1185 default:
1186 s = "";
1187 break;
1189 force_assert(s);
1190 cgi_env_add(&env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s));
1192 li_utostrn(buf, sizeof(buf),
1193 #ifdef HAVE_IPV6
1194 ntohs(con->dst_addr.plain.sa_family == AF_INET6 ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
1195 #else
1196 ntohs(con->dst_addr.ipv4.sin_port)
1197 #endif
1199 cgi_env_add(&env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf));
1201 if (buffer_is_equal_caseless_string(con->uri.scheme, CONST_STR_LEN("https"))) {
1202 cgi_env_add(&env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1205 li_itostrn(buf, sizeof(buf), con->request.content_length);
1206 cgi_env_add(&env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf));
1207 cgi_env_add(&env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path));
1208 cgi_env_add(&env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path));
1209 cgi_env_add(&env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir));
1211 /* for valgrind */
1212 if (NULL != (s = getenv("LD_PRELOAD"))) {
1213 cgi_env_add(&env, CONST_STR_LEN("LD_PRELOAD"), s, strlen(s));
1216 if (NULL != (s = getenv("LD_LIBRARY_PATH"))) {
1217 cgi_env_add(&env, CONST_STR_LEN("LD_LIBRARY_PATH"), s, strlen(s));
1219 #ifdef __CYGWIN__
1220 /* CYGWIN needs SYSTEMROOT */
1221 if (NULL != (s = getenv("SYSTEMROOT"))) {
1222 cgi_env_add(&env, CONST_STR_LEN("SYSTEMROOT"), s, strlen(s));
1224 #endif
1226 for (n = 0; n < con->request.headers->used; n++) {
1227 data_string *ds;
1229 ds = (data_string *)con->request.headers->data[n];
1231 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1232 buffer_copy_string_encoded_cgi_varnames(p->tmp_buf, CONST_BUF_LEN(ds->key), 1);
1234 cgi_env_add(&env, CONST_BUF_LEN(p->tmp_buf), CONST_BUF_LEN(ds->value));
1238 for (n = 0; n < con->environment->used; n++) {
1239 data_string *ds;
1241 ds = (data_string *)con->environment->data[n];
1243 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1244 buffer_copy_string_encoded_cgi_varnames(p->tmp_buf, CONST_BUF_LEN(ds->key), 0);
1246 cgi_env_add(&env, CONST_BUF_LEN(p->tmp_buf), CONST_BUF_LEN(ds->value));
1250 if (env.size == env.used) {
1251 env.size += 16;
1252 env.ptr = realloc(env.ptr, env.size * sizeof(*env.ptr));
1255 env.ptr[env.used] = NULL;
1257 /* set up args */
1258 argc = 3;
1259 args = malloc(sizeof(*args) * argc);
1260 force_assert(args);
1261 i = 0;
1263 if (!buffer_string_is_empty(cgi_handler)) {
1264 args[i++] = cgi_handler->ptr;
1266 args[i++] = con->physical.path->ptr;
1267 args[i ] = NULL;
1269 /* search for the last / */
1270 if (NULL != (c = strrchr(con->physical.path->ptr, '/'))) {
1271 /* handle special case of file in root directory */
1272 const char* physdir = (c == con->physical.path->ptr) ? "/" : con->physical.path->ptr;
1274 /* temporarily shorten con->physical.path to directory without terminating '/' */
1275 *c = '\0';
1276 /* change to the physical directory */
1277 if (-1 == chdir(physdir)) {
1278 log_error_write(srv, __FILE__, __LINE__, "ssb", "chdir failed:", strerror(errno), con->physical.path);
1280 *c = '/';
1283 /* we don't need the client socket */
1284 for (i = 3; i < 256; i++) {
1285 if (i != srv->errorlog_fd) close(i);
1288 /* exec the cgi */
1289 execve(args[0], args, env.ptr);
1291 /* most log files may have been closed/redirected by this point,
1292 * though stderr might still point to lighttpd.breakage.log */
1293 perror(args[0]);
1294 _exit(1);
1296 case -1:
1297 /* error */
1298 log_error_write(srv, __FILE__, __LINE__, "ss", "fork failed:", strerror(errno));
1299 close(from_cgi_fds[0]);
1300 close(from_cgi_fds[1]);
1301 close(to_cgi_fds[0]);
1302 close(to_cgi_fds[1]);
1303 return -1;
1304 default: {
1305 /* parent process */
1307 close(from_cgi_fds[1]);
1308 close(to_cgi_fds[0]);
1310 /* register PID and wait for them asynchronously */
1312 hctx->pid = pid;
1313 hctx->fd = from_cgi_fds[0];
1314 hctx->fde_ndx = -1;
1316 if (0 == con->request.content_length) {
1317 close(to_cgi_fds[1]);
1318 } else {
1319 /* there is content to send */
1320 if (-1 == fdevent_fcntl_set(srv->ev, to_cgi_fds[1])) {
1321 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
1322 close(to_cgi_fds[1]);
1323 cgi_connection_close(srv, hctx);
1324 return -1;
1327 if (0 != cgi_write_request(srv, hctx, to_cgi_fds[1])) {
1328 close(to_cgi_fds[1]);
1329 cgi_connection_close(srv, hctx);
1330 return -1;
1334 fdevent_register(srv->ev, hctx->fd, cgi_handle_fdevent, hctx);
1335 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
1337 if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
1338 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
1339 cgi_connection_close(srv, hctx);
1340 return -1;
1343 break;
1347 return 0;
1348 #else
1349 return -1;
1350 #endif
1353 static buffer * cgi_get_handler(array *a, buffer *fn) {
1354 size_t k, s_len = buffer_string_length(fn);
1355 for (k = 0; k < a->used; ++k) {
1356 data_string *ds = (data_string *)a->data[k];
1357 size_t ct_len = buffer_string_length(ds->key);
1359 if (buffer_is_empty(ds->key)) continue;
1360 if (s_len < ct_len) continue;
1362 if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) {
1363 return ds->value;
1367 return NULL;
1370 #define PATCH(x) \
1371 p->conf.x = s->x;
1372 static int mod_cgi_patch_connection(server *srv, connection *con, plugin_data *p) {
1373 size_t i, j;
1374 plugin_config *s = p->config_storage[0];
1376 PATCH(cgi);
1377 PATCH(execute_x_only);
1378 PATCH(xsendfile_allow);
1379 PATCH(xsendfile_docroot);
1381 /* skip the first, the global context */
1382 for (i = 1; i < srv->config_context->used; i++) {
1383 data_config *dc = (data_config *)srv->config_context->data[i];
1384 s = p->config_storage[i];
1386 /* condition didn't match */
1387 if (!config_check_cond(srv, con, dc)) continue;
1389 /* merge config */
1390 for (j = 0; j < dc->value->used; j++) {
1391 data_unset *du = dc->value->data[j];
1393 if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.assign"))) {
1394 PATCH(cgi);
1395 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.execute-x-only"))) {
1396 PATCH(execute_x_only);
1397 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.x-sendfile"))) {
1398 PATCH(xsendfile_allow);
1399 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("cgi.x-sendfile-docroot"))) {
1400 PATCH(xsendfile_docroot);
1405 return 0;
1407 #undef PATCH
1409 URIHANDLER_FUNC(cgi_is_handled) {
1410 plugin_data *p = p_d;
1411 buffer *fn = con->physical.path;
1412 stat_cache_entry *sce = NULL;
1414 if (con->mode != DIRECT) return HANDLER_GO_ON;
1416 if (buffer_is_empty(fn)) return HANDLER_GO_ON;
1418 mod_cgi_patch_connection(srv, con, p);
1420 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, con->physical.path, &sce)) return HANDLER_GO_ON;
1421 if (!S_ISREG(sce->st.st_mode)) return HANDLER_GO_ON;
1422 if (p->conf.execute_x_only == 1 && (sce->st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) return HANDLER_GO_ON;
1424 if (NULL != cgi_get_handler(p->conf.cgi, fn)) {
1425 handler_ctx *hctx = cgi_handler_ctx_init();
1426 hctx->remote_conn = con;
1427 hctx->plugin_data = p;
1428 con->plugin_ctx[p->id] = hctx;
1429 con->mode = p->id;
1432 return HANDLER_GO_ON;
1435 TRIGGER_FUNC(cgi_trigger) {
1436 plugin_data *p = p_d;
1437 size_t ndx;
1438 /* the trigger handle only cares about lonely PID which we have to wait for */
1439 #ifndef __WIN32
1441 for (ndx = 0; ndx < p->cgi_pid.used; ndx++) {
1442 int status;
1444 switch(waitpid(p->cgi_pid.ptr[ndx], &status, WNOHANG)) {
1445 case 0:
1446 /* not finished yet */
1447 #if 0
1448 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", p->cgi_pid.ptr[ndx]);
1449 #endif
1450 break;
1451 case -1:
1452 if (errno == ECHILD) {
1453 /* someone else called waitpid... remove the pid to stop looping the error each time */
1454 log_error_write(srv, __FILE__, __LINE__, "s", "cgi child vanished, probably someone else called waitpid");
1456 cgi_pid_del(srv, p, p->cgi_pid.ptr[ndx]);
1457 ndx--;
1458 continue;
1461 log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno));
1463 return HANDLER_ERROR;
1464 default:
1466 if (WIFEXITED(status)) {
1467 #if 0
1468 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", p->cgi_pid.ptr[ndx]);
1469 #endif
1470 } else if (WIFSIGNALED(status)) {
1471 /* FIXME: what if we killed the CGI script with a kill(..., SIGTERM) ?
1473 if (WTERMSIG(status) != SIGTERM) {
1474 log_error_write(srv, __FILE__, __LINE__, "sd", "cleaning up CGI: process died with signal", WTERMSIG(status));
1476 } else {
1477 log_error_write(srv, __FILE__, __LINE__, "s", "cleaning up CGI: ended unexpectedly");
1480 cgi_pid_del(srv, p, p->cgi_pid.ptr[ndx]);
1481 /* del modified the buffer structure
1482 * and copies the last entry to the current one
1483 * -> recheck the current index
1485 ndx--;
1488 #endif
1489 return HANDLER_GO_ON;
1493 * - HANDLER_GO_ON : not our job
1494 * - HANDLER_FINISHED: got response
1495 * - HANDLER_WAIT_FOR_EVENT: waiting for response
1497 SUBREQUEST_FUNC(mod_cgi_handle_subrequest) {
1498 plugin_data *p = p_d;
1499 handler_ctx *hctx = con->plugin_ctx[p->id];
1500 chunkqueue *cq = con->request_content_queue;
1502 if (con->mode != p->id) return HANDLER_GO_ON;
1503 if (NULL == hctx) return HANDLER_GO_ON;
1505 if (cq->bytes_in != (off_t)con->request.content_length) {
1506 /*(64k - 4k to attempt to avoid temporary files
1507 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
1508 if (cq->bytes_in - cq->bytes_out > 65536 - 4096
1509 && (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_BUFMIN)){
1510 con->conf.stream_request_body &= ~FDEVENT_STREAM_REQUEST_POLLIN;
1511 if (-1 != hctx->fd) return HANDLER_WAIT_FOR_EVENT;
1512 } else {
1513 handler_t r = connection_handle_read_post_state(srv, con);
1514 if (!chunkqueue_is_empty(cq)) {
1515 if (fdevent_event_get_interest(srv->ev, hctx->fdtocgi) & FDEVENT_OUT) {
1516 return (r == HANDLER_GO_ON) ? HANDLER_WAIT_FOR_EVENT : r;
1519 if (r != HANDLER_GO_ON) return r;
1523 if (-1 == hctx->fd) {
1524 buffer *handler = cgi_get_handler(p->conf.cgi, con->physical.path);
1525 if (!handler) return HANDLER_GO_ON; /*(should not happen; checked in cgi_is_handled())*/
1526 if (cgi_create_env(srv, con, p, hctx, handler)) {
1527 con->http_status = 500;
1528 con->mode = DIRECT;
1530 return HANDLER_FINISHED;
1532 #if 0
1533 log_error_write(srv, __FILE__, __LINE__, "sdd", "subrequest, pid =", hctx, hctx->pid);
1534 #endif
1535 } else if (!chunkqueue_is_empty(con->request_content_queue)) {
1536 if (0 != cgi_write_request(srv, hctx, hctx->fdtocgi)) {
1537 cgi_connection_close(srv, hctx);
1538 return HANDLER_ERROR;
1542 /* if not done, wait for CGI to close stdout, so we read EOF on pipe */
1543 return con->file_finished ? HANDLER_FINISHED : HANDLER_WAIT_FOR_EVENT;
1547 int mod_cgi_plugin_init(plugin *p);
1548 int mod_cgi_plugin_init(plugin *p) {
1549 p->version = LIGHTTPD_VERSION_ID;
1550 p->name = buffer_init_string("cgi");
1552 p->connection_reset = cgi_connection_close_callback;
1553 p->handle_subrequest_start = cgi_is_handled;
1554 p->handle_subrequest = mod_cgi_handle_subrequest;
1555 p->handle_trigger = cgi_trigger;
1556 p->init = mod_cgi_init;
1557 p->cleanup = mod_cgi_free;
1558 p->set_defaults = mod_fastcgi_set_defaults;
1560 p->data = NULL;
1562 return 0;