4 #include "stat_cache.h"
7 #include "connections.h"
10 #include "http_chunk.h"
14 #include <sys/types.h>
16 #include "sys-socket.h"
17 # include <sys/wait.h>
29 static int pipe_cloexec(int pipefd
[2]) {
31 if (0 == pipe2(pipefd
, O_CLOEXEC
)) return 0;
33 return 0 == pipe(pipefd
)
35 && 0 == fcntl(pipefd
[0], F_SETFD
, FD_CLOEXEC
)
36 && 0 == fcntl(pipefd
[1], F_SETFD
, FD_CLOEXEC
)
42 enum {EOL_UNSET
, EOL_N
, EOL_RN
};
59 unsigned short execute_x_only
;
60 unsigned short local_redir
;
61 unsigned short xsendfile_allow
;
62 array
*xsendfile_docroot
;
69 plugin_config
**config_storage
;
78 int fde_ndx
; /* index into the fd-event buffer */
79 int fde_ndx_tocgi
; /* index into the fd-event buffer */
81 connection
*remote_conn
; /* dumb pointer */
82 plugin_data
*plugin_data
; /* dumb pointer */
85 buffer
*cgi_handler
; /* dumb pointer */
86 http_response_opts opts
;
90 static handler_ctx
* cgi_handler_ctx_init(void) {
91 handler_ctx
*hctx
= calloc(1, sizeof(*hctx
));
95 hctx
->response
= buffer_init();
102 static void cgi_handler_ctx_free(handler_ctx
*hctx
) {
103 buffer_free(hctx
->response
);
107 INIT_FUNC(mod_cgi_init
) {
110 p
= calloc(1, sizeof(*p
));
118 FREE_FUNC(mod_cgi_free
) {
119 plugin_data
*p
= p_d
;
120 buffer_pid_t
*r
= &(p
->cgi_pid
);
124 if (p
->config_storage
) {
126 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
127 plugin_config
*s
= p
->config_storage
[i
];
129 if (NULL
== s
) continue;
132 array_free(s
->xsendfile_docroot
);
136 free(p
->config_storage
);
140 if (r
->ptr
) free(r
->ptr
);
144 return HANDLER_GO_ON
;
147 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults
) {
148 plugin_data
*p
= p_d
;
151 config_values_t cv
[] = {
152 { "cgi.assign", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
153 { "cgi.execute-x-only", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
154 { "cgi.x-sendfile", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
155 { "cgi.x-sendfile-docroot", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 3 */
156 { "cgi.local-redir", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 4 */
157 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
160 if (!p
) return HANDLER_ERROR
;
162 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
163 force_assert(p
->config_storage
);
165 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
166 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
169 s
= calloc(1, sizeof(plugin_config
));
172 s
->cgi
= array_init();
173 s
->execute_x_only
= 0;
175 s
->xsendfile_allow
= 0;
176 s
->xsendfile_docroot
= array_init();
178 cv
[0].destination
= s
->cgi
;
179 cv
[1].destination
= &(s
->execute_x_only
);
180 cv
[2].destination
= &(s
->xsendfile_allow
);
181 cv
[3].destination
= s
->xsendfile_docroot
;
182 cv
[4].destination
= &(s
->local_redir
);
184 p
->config_storage
[i
] = s
;
186 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
187 return HANDLER_ERROR
;
190 if (!array_is_kvstring(s
->cgi
)) {
191 log_error_write(srv
, __FILE__
, __LINE__
, "s",
192 "unexpected value for cgi.assign; expected list of \"ext\" => \"exepath\"");
193 return HANDLER_ERROR
;
196 if (s
->xsendfile_docroot
->used
) {
198 for (j
= 0; j
< s
->xsendfile_docroot
->used
; ++j
) {
199 data_string
*ds
= (data_string
*)s
->xsendfile_docroot
->data
[j
];
200 if (ds
->type
!= TYPE_STRING
) {
201 log_error_write(srv
, __FILE__
, __LINE__
, "s",
202 "unexpected type for key cgi.x-sendfile-docroot; expected: cgi.x-sendfile-docroot = ( \"/allowed/path\", ... )");
203 return HANDLER_ERROR
;
205 if (ds
->value
->ptr
[0] != '/') {
206 log_error_write(srv
, __FILE__
, __LINE__
, "SBs",
207 "cgi.x-sendfile-docroot paths must begin with '/'; invalid: \"", ds
->value
, "\"");
208 return HANDLER_ERROR
;
210 buffer_path_simplify(ds
->value
, ds
->value
);
211 buffer_append_slash(ds
->value
);
216 return HANDLER_GO_ON
;
220 static int cgi_pid_add(server
*srv
, plugin_data
*p
, pid_t pid
) {
223 buffer_pid_t
*r
= &(p
->cgi_pid
);
227 for (i
= 0; i
< r
->used
; i
++) {
228 if (r
->ptr
[i
] > m
) m
= r
->ptr
[i
];
233 r
->ptr
= malloc(sizeof(*r
->ptr
) * r
->size
);
234 force_assert(r
->ptr
);
235 } else if (r
->used
== r
->size
) {
237 r
->ptr
= realloc(r
->ptr
, sizeof(*r
->ptr
) * r
->size
);
238 force_assert(r
->ptr
);
241 r
->ptr
[r
->used
++] = pid
;
246 static int cgi_pid_del(server
*srv
, plugin_data
*p
, pid_t pid
) {
248 buffer_pid_t
*r
= &(p
->cgi_pid
);
252 for (i
= 0; i
< r
->used
; i
++) {
253 if (r
->ptr
[i
] == pid
) break;
259 if (i
!= r
->used
- 1) {
260 r
->ptr
[i
] = r
->ptr
[r
->used
- 1];
269 static void cgi_connection_close_fdtocgi(server
*srv
, handler_ctx
*hctx
) {
270 /*(closes only hctx->fdtocgi)*/
271 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx_tocgi
), hctx
->fdtocgi
);
272 fdevent_unregister(srv
->ev
, hctx
->fdtocgi
);
273 fdevent_sched_close(srv
->ev
, hctx
->fdtocgi
, 0);
277 static void cgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
280 plugin_data
*p
= hctx
->plugin_data
;
281 connection
*con
= hctx
->remote_conn
;
285 /* the connection to the browser went away, but we still have a connection
288 * close cgi-connection
291 if (hctx
->fd
!= -1) {
292 /* close connection to the cgi-script */
293 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
294 fdevent_unregister(srv
->ev
, hctx
->fd
);
295 fdevent_sched_close(srv
->ev
, hctx
->fd
, 0);
298 if (hctx
->fdtocgi
!= -1) {
299 cgi_connection_close_fdtocgi(srv
, hctx
); /*(closes only hctx->fdtocgi)*/
304 con
->plugin_ctx
[p
->id
] = NULL
;
306 cgi_handler_ctx_free(hctx
);
308 /* if waitpid hasn't been called by response.c yet, do it here */
310 /* check if the CGI-script is already gone */
311 switch(waitpid(pid
, &status
, WNOHANG
)) {
313 /* not finished yet */
315 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "(debug) child isn't done yet, pid:", pid
);
320 if (errno
== EINTR
) break;
323 * errno == ECHILD happens if _subrequest catches the process-status before
324 * we have read the response of the cgi process
329 * -> we get here with waitpid == ECHILD
332 if (errno
!= ECHILD
) {
333 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "waitpid failed: ", strerror(errno
));
335 /* anyway: don't wait for it anymore */
339 if (WIFEXITED(status
)) {
341 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "(debug) cgi exited fine, pid:", pid
);
344 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "cgi died, pid:", pid
);
354 /* cgi-script is still alive, queue the PID for removal */
355 cgi_pid_add(srv
, p
, pid
);
360 /* finish response (if not already con->file_started, con->file_finished) */
361 if (con
->mode
== p
->id
) {
362 http_response_backend_done(srv
, con
);
366 static handler_t
cgi_connection_close_callback(server
*srv
, connection
*con
, void *p_d
) {
367 plugin_data
*p
= p_d
;
368 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
369 if (hctx
) cgi_connection_close(srv
, hctx
);
371 return HANDLER_GO_ON
;
375 static int cgi_write_request(server
*srv
, handler_ctx
*hctx
, int fd
);
378 static handler_t
cgi_handle_fdevent_send (server
*srv
, void *ctx
, int revents
) {
379 handler_ctx
*hctx
= ctx
;
380 connection
*con
= hctx
->remote_conn
;
382 /*(joblist only actually necessary here in mod_cgi fdevent send if returning HANDLER_ERROR)*/
383 joblist_append(srv
, con
);
385 if (revents
& FDEVENT_OUT
) {
386 if (0 != cgi_write_request(srv
, hctx
, hctx
->fdtocgi
)) {
387 cgi_connection_close(srv
, hctx
);
388 return HANDLER_ERROR
;
390 /* more request body to be sent to CGI */
393 if (revents
& FDEVENT_HUP
) {
394 /* skip sending remaining data to CGI */
395 if (con
->request
.content_length
) {
396 chunkqueue
*cq
= con
->request_content_queue
;
397 chunkqueue_mark_written(cq
, chunkqueue_length(cq
));
398 if (cq
->bytes_in
!= (off_t
)con
->request
.content_length
) {
403 cgi_connection_close_fdtocgi(srv
, hctx
); /*(closes only hctx->fdtocgi)*/
404 } else if (revents
& FDEVENT_ERR
) {
405 /* kill all connections to the cgi process */
407 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cgi-FDEVENT_ERR");
409 cgi_connection_close(srv
, hctx
);
410 return HANDLER_ERROR
;
413 return HANDLER_FINISHED
;
417 static int cgi_recv_response(server
*srv
, handler_ctx
*hctx
) {
418 switch (http_response_read(srv
, hctx
->remote_conn
, &hctx
->opts
,
419 hctx
->response
, hctx
->fd
, &hctx
->fde_ndx
)) {
421 return HANDLER_GO_ON
;
423 http_response_backend_error(srv
, hctx
->remote_conn
);
425 case HANDLER_FINISHED
:
426 cgi_connection_close(srv
, hctx
);
427 return HANDLER_FINISHED
;
428 case HANDLER_COMEBACK
:
429 /* hctx->conf.local_redir */
430 connection_response_reset(srv
, hctx
->remote_conn
); /*(includes con->http_status = 0)*/
431 plugins_call_connection_reset(srv
, hctx
->remote_conn
);
432 /*cgi_connection_close(srv, hctx);*//*(already cleaned up and hctx is now invalid)*/
433 return HANDLER_COMEBACK
;
438 static handler_t
cgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
439 handler_ctx
*hctx
= ctx
;
440 connection
*con
= hctx
->remote_conn
;
442 joblist_append(srv
, con
);
444 if (revents
& FDEVENT_IN
) {
445 handler_t rc
= cgi_recv_response(srv
, hctx
);/*(might invalidate hctx)*/
446 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
449 /* perhaps this issue is already handled */
450 if (revents
& FDEVENT_HUP
) {
451 if (con
->file_started
) {
452 /* drain any remaining data from kernel pipe buffers
453 * even if (con->conf.stream_response_body
454 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
455 * since event loop will spin on fd FDEVENT_HUP event
456 * until unregistered. */
459 rc
= cgi_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
460 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
461 return rc
; /* HANDLER_FINISHED or HANDLER_COMEBACK or HANDLER_ERROR */
462 } else if (!buffer_string_is_empty(hctx
->response
)) {
463 /* unfinished header package which is a body in reality */
464 con
->file_started
= 1;
465 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response
)) {
466 cgi_connection_close(srv
, hctx
);
467 return HANDLER_ERROR
;
469 if (0 == con
->http_status
) con
->http_status
= 200; /* OK */
472 log_error_write(srv
, __FILE__
, __LINE__
, "sddd", "got HUP from cgi", con
->fd
, hctx
->fd
, revents
);
475 cgi_connection_close(srv
, hctx
);
476 } else if (revents
& FDEVENT_ERR
) {
477 /* kill all connections to the cgi process */
478 cgi_connection_close(srv
, hctx
);
480 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cgi-FDEVENT_ERR");
482 return HANDLER_ERROR
;
485 return HANDLER_FINISHED
;
489 static int cgi_env_add(void *venv
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
490 char_array
*env
= venv
;
493 if (!key
|| !val
) return -1;
495 dst
= malloc(key_len
+ val_len
+ 2);
497 memcpy(dst
, key
, key_len
);
499 memcpy(dst
+ key_len
+ 1, val
, val_len
);
500 dst
[key_len
+ 1 + val_len
] = '\0';
502 if (env
->size
== 0) {
504 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
505 force_assert(env
->ptr
);
506 } else if (env
->size
== env
->used
) {
508 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
509 force_assert(env
->ptr
);
512 env
->ptr
[env
->used
++] = dst
;
517 /*(improved from network_write_mmap.c)*/
518 static off_t
mmap_align_offset(off_t start
) {
519 static off_t pagemask
= 0;
521 long pagesize
= sysconf(_SC_PAGESIZE
);
522 if (-1 == pagesize
) pagesize
= 4096;
523 pagemask
= ~((off_t
)pagesize
- 1); /* pagesize always power-of-2 */
525 return (start
& pagemask
);
528 /* returns: 0: continue, -1: fatal error, -2: connection reset */
529 /* similar to network_write_file_chunk_mmap, but doesn't use send on windows (because we're on pipes),
530 * also mmaps and sends complete chunk instead of only small parts - the files
531 * are supposed to be temp files with reasonable chunk sizes.
533 * Also always use mmap; the files are "trusted", as we created them.
535 static ssize_t
cgi_write_file_chunk_mmap(server
*srv
, connection
*con
, int fd
, chunkqueue
*cq
) {
536 chunk
* const c
= cq
->first
;
537 off_t offset
, toSend
, file_end
;
539 size_t mmap_offset
, mmap_avail
;
542 force_assert(NULL
!= c
);
543 force_assert(FILE_CHUNK
== c
->type
);
544 force_assert(c
->offset
>= 0 && c
->offset
<= c
->file
.length
);
546 offset
= c
->file
.start
+ c
->offset
;
547 toSend
= c
->file
.length
- c
->offset
;
548 file_end
= c
->file
.start
+ c
->file
.length
; /* offset to file end in this chunk */
551 chunkqueue_remove_finished_chunks(cq
);
555 /*(simplified from chunk.c:chunkqueue_open_file_chunk())*/
557 if (-1 == c
->file
.fd
) {
558 if (-1 == (c
->file
.fd
= fdevent_open_cloexec(c
->file
.name
->ptr
, O_RDONLY
, 0))) {
559 log_error_write(srv
, __FILE__
, __LINE__
, "ssb", "open failed:", strerror(errno
), c
->file
.name
);
564 /* (re)mmap the buffer if range is not covered completely */
565 if (MAP_FAILED
== c
->file
.mmap
.start
566 || offset
< c
->file
.mmap
.offset
567 || file_end
> (off_t
)(c
->file
.mmap
.offset
+ c
->file
.mmap
.length
)) {
569 if (MAP_FAILED
!= c
->file
.mmap
.start
) {
570 munmap(c
->file
.mmap
.start
, c
->file
.mmap
.length
);
571 c
->file
.mmap
.start
= MAP_FAILED
;
574 c
->file
.mmap
.offset
= mmap_align_offset(offset
);
575 c
->file
.mmap
.length
= file_end
- c
->file
.mmap
.offset
;
577 if (MAP_FAILED
== (c
->file
.mmap
.start
= mmap(NULL
, c
->file
.mmap
.length
, PROT_READ
, MAP_PRIVATE
, c
->file
.fd
, c
->file
.mmap
.offset
))) {
578 if (toSend
> 65536) toSend
= 65536;
579 data
= malloc(toSend
);
581 if (-1 == lseek(c
->file
.fd
, offset
, SEEK_SET
)
582 || 0 >= (toSend
= read(c
->file
.fd
, data
, toSend
))) {
584 log_error_write(srv
, __FILE__
, __LINE__
, "ssbdo", "lseek/read failed:",
585 strerror(errno
), c
->file
.name
, c
->file
.fd
, offset
);
586 } else { /*(0 == toSend)*/
587 log_error_write(srv
, __FILE__
, __LINE__
, "sbdo", "unexpected EOF (input truncated?):",
588 c
->file
.name
, c
->file
.fd
, offset
);
596 if (MAP_FAILED
!= c
->file
.mmap
.start
) {
597 force_assert(offset
>= c
->file
.mmap
.offset
);
598 mmap_offset
= offset
- c
->file
.mmap
.offset
;
599 force_assert(c
->file
.mmap
.length
> mmap_offset
);
600 mmap_avail
= c
->file
.mmap
.length
- mmap_offset
;
601 force_assert(toSend
<= (off_t
) mmap_avail
);
603 data
= c
->file
.mmap
.start
+ mmap_offset
;
606 r
= write(fd
, data
, toSend
);
608 if (MAP_FAILED
== c
->file
.mmap
.start
) free(data
);
619 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
620 "write failed:", strerror(errno
), fd
);
626 chunkqueue_mark_written(cq
, r
);
632 static int cgi_write_request(server
*srv
, handler_ctx
*hctx
, int fd
) {
633 connection
*con
= hctx
->remote_conn
;
634 chunkqueue
*cq
= con
->request_content_queue
;
637 /* old comment: windows doesn't support select() on pipes - wouldn't be easy to fix for all platforms.
638 * solution: if this is still a problem on windows, then substitute
639 * socketpair() for pipe() and closesocket() for close() on windows.
642 for (c
= cq
->first
; c
; c
= cq
->first
) {
647 r
= cgi_write_file_chunk_mmap(srv
, con
, fd
, cq
);
651 if ((r
= write(fd
, c
->mem
->ptr
+ c
->offset
, buffer_string_length(c
->mem
) - c
->offset
)) < 0) {
655 /* ignore and try again */
660 /* connection closed */
665 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "write failed due to: ", strerror(errno
));
670 chunkqueue_mark_written(cq
, r
);
675 if (0 == r
) break; /*(might block)*/
682 /* connection reset */
683 log_error_write(srv
, __FILE__
, __LINE__
, "s", "failed to send post data to cgi, connection closed by CGI");
684 /* skip all remaining data */
685 chunkqueue_mark_written(cq
, chunkqueue_length(cq
));
692 if (cq
->bytes_out
== (off_t
)con
->request
.content_length
) {
693 /* sent all request body input */
694 /* close connection to the cgi-script */
695 if (-1 == hctx
->fdtocgi
) { /*(received request body sent in initial send to pipe buffer)*/
698 log_error_write(srv
, __FILE__
, __LINE__
, "sds", "cgi stdin close failed ", fd
, strerror(errno
));
701 cgi_connection_close_fdtocgi(srv
, hctx
); /*(closes only hctx->fdtocgi)*/
704 off_t cqlen
= cq
->bytes_in
- cq
->bytes_out
;
705 if (cq
->bytes_in
!= con
->request
.content_length
&& cqlen
< 65536 - 16384) {
706 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
707 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
708 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
709 con
->is_readable
= 1; /* trigger optimistic read from client */
712 if (-1 == hctx
->fdtocgi
) { /*(not registered yet)*/
714 hctx
->fde_ndx_tocgi
= -1;
715 fdevent_register(srv
->ev
, hctx
->fdtocgi
, cgi_handle_fdevent_send
, hctx
);
717 if (0 == cqlen
) { /*(chunkqueue_is_empty(cq))*/
718 if ((fdevent_event_get_interest(srv
->ev
, hctx
->fdtocgi
) & FDEVENT_OUT
)) {
719 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx_tocgi
), hctx
->fdtocgi
, 0);
722 /* more request body remains to be sent to CGI so register for fdevents */
723 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx_tocgi
), hctx
->fdtocgi
, FDEVENT_OUT
);
730 static int cgi_create_env(server
*srv
, connection
*con
, plugin_data
*p
, handler_ctx
*hctx
, buffer
*cgi_handler
) {
740 if (!buffer_string_is_empty(cgi_handler
)) {
741 /* stat the exec file */
742 if (-1 == (stat(cgi_handler
->ptr
, &st
))) {
743 log_error_write(srv
, __FILE__
, __LINE__
, "sbss",
744 "stat for cgi-handler", cgi_handler
,
745 "failed:", strerror(errno
));
750 if (pipe_cloexec(to_cgi_fds
)) {
751 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "pipe failed:", strerror(errno
));
755 if (pipe_cloexec(from_cgi_fds
)) {
756 close(to_cgi_fds
[0]);
757 close(to_cgi_fds
[1]);
758 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "pipe failed:", strerror(errno
));
763 switch (pid
= fork()) {
772 http_cgi_opts opts
= { 0, 0, NULL
, NULL
};
774 /* move stdout to from_cgi_fd[1] */
775 dup2(from_cgi_fds
[1], STDOUT_FILENO
);
777 close(from_cgi_fds
[1]);
779 close(from_cgi_fds
[0]);
782 /* move the stdin to to_cgi_fd[0] */
783 dup2(to_cgi_fds
[0], STDIN_FILENO
);
785 close(to_cgi_fds
[0]);
787 close(to_cgi_fds
[1]);
790 /* create environment */
795 http_cgi_headers(srv
, con
, &opts
, cgi_env_add
, &env
);
798 if (NULL
!= (s
= getenv("LD_PRELOAD"))) {
799 cgi_env_add(&env
, CONST_STR_LEN("LD_PRELOAD"), s
, strlen(s
));
802 if (NULL
!= (s
= getenv("LD_LIBRARY_PATH"))) {
803 cgi_env_add(&env
, CONST_STR_LEN("LD_LIBRARY_PATH"), s
, strlen(s
));
806 /* CYGWIN needs SYSTEMROOT */
807 if (NULL
!= (s
= getenv("SYSTEMROOT"))) {
808 cgi_env_add(&env
, CONST_STR_LEN("SYSTEMROOT"), s
, strlen(s
));
812 if (env
.size
== env
.used
) {
814 env
.ptr
= realloc(env
.ptr
, env
.size
* sizeof(*env
.ptr
));
817 env
.ptr
[env
.used
] = NULL
;
821 args
= malloc(sizeof(*args
) * argc
);
825 if (!buffer_string_is_empty(cgi_handler
)) {
826 args
[i
++] = cgi_handler
->ptr
;
828 args
[i
++] = con
->physical
.path
->ptr
;
831 /* search for the last / */
832 if (NULL
!= (c
= strrchr(con
->physical
.path
->ptr
, '/'))) {
833 /* handle special case of file in root directory */
834 const char* physdir
= (c
== con
->physical
.path
->ptr
) ? "/" : con
->physical
.path
->ptr
;
836 /* temporarily shorten con->physical.path to directory without terminating '/' */
838 /* change to the physical directory */
839 if (-1 == chdir(physdir
)) {
840 log_error_write(srv
, __FILE__
, __LINE__
, "ssb", "chdir failed:", strerror(errno
), con
->physical
.path
);
845 /* we don't need the client socket */
846 for (i
= 3; i
< 256; i
++) {
847 if (i
!= srv
->errorlog_fd
) close(i
);
851 execve(args
[0], args
, env
.ptr
);
853 /* most log files may have been closed/redirected by this point,
854 * though stderr might still point to lighttpd.breakage.log */
860 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fork failed:", strerror(errno
));
861 close(from_cgi_fds
[0]);
862 close(from_cgi_fds
[1]);
863 close(to_cgi_fds
[0]);
864 close(to_cgi_fds
[1]);
869 close(from_cgi_fds
[1]);
870 close(to_cgi_fds
[0]);
872 /* register PID and wait for them asynchronously */
875 hctx
->fd
= from_cgi_fds
[0];
880 if (0 == con
->request
.content_length
) {
881 close(to_cgi_fds
[1]);
883 /* there is content to send */
884 if (-1 == fdevent_fcntl_set_nb(srv
->ev
, to_cgi_fds
[1])) {
885 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl failed: ", strerror(errno
));
886 close(to_cgi_fds
[1]);
887 cgi_connection_close(srv
, hctx
);
891 if (0 != cgi_write_request(srv
, hctx
, to_cgi_fds
[1])) {
892 close(to_cgi_fds
[1]);
893 cgi_connection_close(srv
, hctx
);
900 fdevent_register(srv
->ev
, hctx
->fd
, cgi_handle_fdevent
, hctx
);
901 if (-1 == fdevent_fcntl_set_nb(srv
->ev
, hctx
->fd
)) {
902 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl failed: ", strerror(errno
));
903 cgi_connection_close(srv
, hctx
);
906 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
918 static buffer
* cgi_get_handler(array
*a
, buffer
*fn
) {
919 size_t k
, s_len
= buffer_string_length(fn
);
920 for (k
= 0; k
< a
->used
; ++k
) {
921 data_string
*ds
= (data_string
*)a
->data
[k
];
922 size_t ct_len
= buffer_string_length(ds
->key
);
924 if (buffer_is_empty(ds
->key
)) continue;
925 if (s_len
< ct_len
) continue;
927 if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ds
->key
->ptr
, ct_len
)) {
937 static int mod_cgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
939 plugin_config
*s
= p
->config_storage
[0];
942 PATCH(execute_x_only
);
944 PATCH(xsendfile_allow
);
945 PATCH(xsendfile_docroot
);
947 /* skip the first, the global context */
948 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
949 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
950 s
= p
->config_storage
[i
];
952 /* condition didn't match */
953 if (!config_check_cond(srv
, con
, dc
)) continue;
956 for (j
= 0; j
< dc
->value
->used
; j
++) {
957 data_unset
*du
= dc
->value
->data
[j
];
959 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("cgi.assign"))) {
961 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("cgi.execute-x-only"))) {
962 PATCH(execute_x_only
);
963 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("cgi.local-redir"))) {
965 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("cgi.x-sendfile"))) {
966 PATCH(xsendfile_allow
);
967 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("cgi.x-sendfile-docroot"))) {
968 PATCH(xsendfile_docroot
);
977 URIHANDLER_FUNC(cgi_is_handled
) {
978 plugin_data
*p
= p_d
;
979 buffer
*fn
= con
->physical
.path
;
980 stat_cache_entry
*sce
= NULL
;
985 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
987 if (buffer_is_empty(fn
)) return HANDLER_GO_ON
;
989 mod_cgi_patch_connection(srv
, con
, p
);
991 if (HANDLER_ERROR
!= stat_cache_get_entry(srv
, con
, con
->physical
.path
, &sce
)) {
994 /* CGI might be executable even if it is not readable
995 * (stat_cache_get_entry() currently checks file is readable)*/
996 if (0 != stat(con
->physical
.path
->ptr
, &stbuf
)) return HANDLER_GO_ON
;
1000 if (!S_ISREG(st
->st_mode
)) return HANDLER_GO_ON
;
1001 if (p
->conf
.execute_x_only
== 1 && (st
->st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)) == 0) return HANDLER_GO_ON
;
1003 if (NULL
!= (cgi_handler
= cgi_get_handler(p
->conf
.cgi
, fn
))) {
1004 handler_ctx
*hctx
= cgi_handler_ctx_init();
1005 hctx
->remote_conn
= con
;
1006 hctx
->plugin_data
= p
;
1007 hctx
->cgi_handler
= cgi_handler
;
1008 memcpy(&hctx
->conf
, &p
->conf
, sizeof(plugin_config
));
1009 hctx
->opts
.fdfmt
= S_IFIFO
;
1010 hctx
->opts
.backend
= BACKEND_CGI
;
1011 hctx
->opts
.authorizer
= 0;
1012 hctx
->opts
.local_redir
= hctx
->conf
.local_redir
;
1013 hctx
->opts
.xsendfile_allow
= hctx
->conf
.xsendfile_allow
;
1014 hctx
->opts
.xsendfile_docroot
= hctx
->conf
.xsendfile_docroot
;
1015 con
->plugin_ctx
[p
->id
] = hctx
;
1019 return HANDLER_GO_ON
;
1022 TRIGGER_FUNC(cgi_trigger
) {
1023 plugin_data
*p
= p_d
;
1025 /* the trigger handle only cares about lonely PID which we have to wait for */
1028 for (ndx
= 0; ndx
< p
->cgi_pid
.used
; ndx
++) {
1031 switch(waitpid(p
->cgi_pid
.ptr
[ndx
], &status
, WNOHANG
)) {
1033 /* not finished yet */
1035 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "(debug) child isn't done yet, pid:", p
->cgi_pid
.ptr
[ndx
]);
1039 if (errno
== ECHILD
) {
1040 /* someone else called waitpid... remove the pid to stop looping the error each time */
1041 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cgi child vanished, probably someone else called waitpid");
1043 cgi_pid_del(srv
, p
, p
->cgi_pid
.ptr
[ndx
]);
1048 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "waitpid failed: ", strerror(errno
));
1050 return HANDLER_ERROR
;
1053 if (WIFEXITED(status
)) {
1055 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "(debug) cgi exited fine, pid:", p
->cgi_pid
.ptr
[ndx
]);
1057 } else if (WIFSIGNALED(status
)) {
1058 /* FIXME: what if we killed the CGI script with a kill(..., SIGTERM) ?
1060 if (WTERMSIG(status
) != SIGTERM
) {
1061 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "cleaning up CGI: process died with signal", WTERMSIG(status
));
1064 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cleaning up CGI: ended unexpectedly");
1067 cgi_pid_del(srv
, p
, p
->cgi_pid
.ptr
[ndx
]);
1068 /* del modified the buffer structure
1069 * and copies the last entry to the current one
1070 * -> recheck the current index
1076 return HANDLER_GO_ON
;
1080 * - HANDLER_GO_ON : not our job
1081 * - HANDLER_FINISHED: got response
1082 * - HANDLER_WAIT_FOR_EVENT: waiting for response
1084 SUBREQUEST_FUNC(mod_cgi_handle_subrequest
) {
1085 plugin_data
*p
= p_d
;
1086 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1087 chunkqueue
*cq
= con
->request_content_queue
;
1089 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
1090 if (NULL
== hctx
) return HANDLER_GO_ON
;
1092 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
1093 && con
->file_started
) {
1094 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
1095 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
1096 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
1097 /* optimistic read from backend */
1098 handler_t rc
= cgi_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
1099 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
1100 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
1104 if (cq
->bytes_in
!= (off_t
)con
->request
.content_length
) {
1105 /*(64k - 4k to attempt to avoid temporary files
1106 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
1107 if (cq
->bytes_in
- cq
->bytes_out
> 65536 - 4096
1108 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
1109 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
1110 if (-1 != hctx
->fd
) return HANDLER_WAIT_FOR_EVENT
;
1112 handler_t r
= connection_handle_read_post_state(srv
, con
);
1113 if (!chunkqueue_is_empty(cq
)) {
1114 if (fdevent_event_get_interest(srv
->ev
, hctx
->fdtocgi
) & FDEVENT_OUT
) {
1115 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
1118 if (r
!= HANDLER_GO_ON
) return r
;
1120 /* CGI environment requires that Content-Length be set.
1121 * Send 411 Length Required if Content-Length missing.
1122 * (occurs here if client sends Transfer-Encoding: chunked
1123 * and module is flagged to stream request body to backend) */
1124 if (-1 == con
->request
.content_length
) {
1125 return connection_handle_read_post_error(srv
, con
, 411);
1130 if (-1 == hctx
->fd
) {
1131 if (cgi_create_env(srv
, con
, p
, hctx
, hctx
->cgi_handler
)) {
1132 con
->http_status
= 500;
1135 return HANDLER_FINISHED
;
1138 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "subrequest, pid =", hctx
, hctx
->pid
);
1140 } else if (!chunkqueue_is_empty(con
->request_content_queue
)) {
1141 if (0 != cgi_write_request(srv
, hctx
, hctx
->fdtocgi
)) {
1142 cgi_connection_close(srv
, hctx
);
1143 return HANDLER_ERROR
;
1147 /* if not done, wait for CGI to close stdout, so we read EOF on pipe */
1148 return HANDLER_WAIT_FOR_EVENT
;
1152 int mod_cgi_plugin_init(plugin
*p
);
1153 int mod_cgi_plugin_init(plugin
*p
) {
1154 p
->version
= LIGHTTPD_VERSION_ID
;
1155 p
->name
= buffer_init_string("cgi");
1157 p
->connection_reset
= cgi_connection_close_callback
;
1158 p
->handle_subrequest_start
= cgi_is_handled
;
1159 p
->handle_subrequest
= mod_cgi_handle_subrequest
;
1160 p
->handle_trigger
= cgi_trigger
;
1161 p
->init
= mod_cgi_init
;
1162 p
->cleanup
= mod_cgi_free
;
1163 p
->set_defaults
= mod_fastcgi_set_defaults
;