[mod_ssi] produce content in subrequest hook
[lighttpd.git] / src / connections.c
blob2ef88d5b12eee7a255d8e4e2c53a2f930375862f
1 #include "first.h"
3 #include "buffer.h"
4 #include "server.h"
5 #include "log.h"
6 #include "connections.h"
7 #include "fdevent.h"
9 #include "configfile.h"
10 #include "request.h"
11 #include "response.h"
12 #include "network.h"
13 #include "http_chunk.h"
14 #include "stat_cache.h"
15 #include "joblist.h"
17 #include "plugin.h"
19 #include "inet_ntop_cache.h"
21 #include <sys/stat.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <fcntl.h>
29 #include <assert.h>
31 #ifdef USE_OPENSSL
32 # include <openssl/ssl.h>
33 # include <openssl/err.h>
34 #endif
36 #ifdef HAVE_SYS_FILIO_H
37 # include <sys/filio.h>
38 #endif
40 #include "sys-socket.h"
42 typedef struct {
43 PLUGIN_DATA;
44 } plugin_data;
46 static connection *connections_get_new_connection(server *srv) {
47 connections *conns = srv->conns;
48 size_t i;
50 if (conns->size == 0) {
51 conns->size = 128;
52 conns->ptr = NULL;
53 conns->ptr = malloc(sizeof(*conns->ptr) * conns->size);
54 force_assert(NULL != conns->ptr);
55 for (i = 0; i < conns->size; i++) {
56 conns->ptr[i] = connection_init(srv);
58 } else if (conns->size == conns->used) {
59 conns->size += 128;
60 conns->ptr = realloc(conns->ptr, sizeof(*conns->ptr) * conns->size);
61 force_assert(NULL != conns->ptr);
63 for (i = conns->used; i < conns->size; i++) {
64 conns->ptr[i] = connection_init(srv);
68 connection_reset(srv, conns->ptr[conns->used]);
69 #if 0
70 fprintf(stderr, "%s.%d: add: ", __FILE__, __LINE__);
71 for (i = 0; i < conns->used + 1; i++) {
72 fprintf(stderr, "%d ", conns->ptr[i]->fd);
74 fprintf(stderr, "\n");
75 #endif
77 conns->ptr[conns->used]->ndx = conns->used;
78 return conns->ptr[conns->used++];
81 static int connection_del(server *srv, connection *con) {
82 size_t i;
83 connections *conns = srv->conns;
84 connection *temp;
86 if (con == NULL) return -1;
88 if (-1 == con->ndx) return -1;
90 buffer_reset(con->uri.authority);
91 buffer_reset(con->uri.path);
92 buffer_reset(con->uri.query);
93 buffer_reset(con->request.orig_uri);
95 i = con->ndx;
97 /* not last element */
99 if (i != conns->used - 1) {
100 temp = conns->ptr[i];
101 conns->ptr[i] = conns->ptr[conns->used - 1];
102 conns->ptr[conns->used - 1] = temp;
104 conns->ptr[i]->ndx = i;
105 conns->ptr[conns->used - 1]->ndx = -1;
108 conns->used--;
110 con->ndx = -1;
111 #if 0
112 fprintf(stderr, "%s.%d: del: (%d)", __FILE__, __LINE__, conns->used);
113 for (i = 0; i < conns->used; i++) {
114 fprintf(stderr, "%d ", conns->ptr[i]->fd);
116 fprintf(stderr, "\n");
117 #endif
118 return 0;
121 static int connection_close(server *srv, connection *con) {
122 #ifdef USE_OPENSSL
123 server_socket *srv_sock = con->srv_socket;
124 if (srv_sock->is_ssl) {
125 if (con->ssl) SSL_free(con->ssl);
126 con->ssl = NULL;
128 #endif
130 fdevent_event_del(srv->ev, &(con->fde_ndx), con->fd);
131 fdevent_unregister(srv->ev, con->fd);
132 #ifdef __WIN32
133 if (closesocket(con->fd)) {
134 log_error_write(srv, __FILE__, __LINE__, "sds",
135 "(warning) close:", con->fd, strerror(errno));
137 #else
138 if (close(con->fd)) {
139 log_error_write(srv, __FILE__, __LINE__, "sds",
140 "(warning) close:", con->fd, strerror(errno));
142 #endif
143 else {
144 srv->cur_fds--;
147 con->fd = -1;
148 connection_del(srv, con);
149 connection_set_state(srv, con, CON_STATE_CONNECT);
151 return 0;
154 static void connection_handle_close_state(server *srv, connection *con) {
155 /* we have to do the linger_on_close stuff regardless
156 * of con->keep_alive; even non-keepalive sockets may
157 * still have unread data, and closing before reading
158 * it will make the client not see all our output.
160 int len;
161 char buf[1024];
163 len = read(con->fd, buf, sizeof(buf));
164 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
165 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
168 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
169 connection_close(srv, con);
171 if (srv->srvconf.log_state_handling) {
172 log_error_write(srv, __FILE__, __LINE__, "sd",
173 "connection closed for fd", con->fd);
178 static void connection_handle_shutdown(server *srv, connection *con) {
179 int r;
181 #ifdef USE_OPENSSL
182 server_socket *srv_sock = con->srv_socket;
183 if (srv_sock->is_ssl && SSL_is_init_finished(con->ssl)) {
184 int ret, ssl_r;
185 unsigned long err;
186 ERR_clear_error();
187 switch ((ret = SSL_shutdown(con->ssl))) {
188 case 1:
189 /* ok */
190 break;
191 case 0:
192 /* wait for fd-event
194 * FIXME: wait for fdevent and call SSL_shutdown again
197 ERR_clear_error();
198 if (-1 != (ret = SSL_shutdown(con->ssl))) break;
200 /* fall through */
201 default:
203 switch ((ssl_r = SSL_get_error(con->ssl, ret))) {
204 case SSL_ERROR_ZERO_RETURN:
205 break;
206 case SSL_ERROR_WANT_WRITE:
207 /*con->is_writable = -1;*//*(no effect; shutdown() called below)*/
208 case SSL_ERROR_WANT_READ:
209 break;
210 case SSL_ERROR_SYSCALL:
211 /* perhaps we have error waiting in our error-queue */
212 if (0 != (err = ERR_get_error())) {
213 do {
214 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
215 ssl_r, ret,
216 ERR_error_string(err, NULL));
217 } while((err = ERR_get_error()));
218 } else if (errno != 0) { /* ssl bug (see lighttpd ticket #2213): sometimes errno == 0 */
219 switch(errno) {
220 case EPIPE:
221 case ECONNRESET:
222 break;
223 default:
224 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL (error):",
225 ssl_r, ret, errno,
226 strerror(errno));
227 break;
231 break;
232 default:
233 while((err = ERR_get_error())) {
234 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
235 ssl_r, ret,
236 ERR_error_string(err, NULL));
239 break;
242 ERR_clear_error();
244 #endif
246 switch(r = plugins_call_handle_connection_close(srv, con)) {
247 case HANDLER_GO_ON:
248 case HANDLER_FINISHED:
249 break;
250 default:
251 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
252 break;
255 srv->con_closed++;
256 connection_reset(srv, con);
258 /* close the connection */
259 if ((0 == shutdown(con->fd, SHUT_WR))) {
260 con->close_timeout_ts = srv->cur_ts;
261 connection_set_state(srv, con, CON_STATE_CLOSE);
263 if (srv->srvconf.log_state_handling) {
264 log_error_write(srv, __FILE__, __LINE__, "sd",
265 "shutdown for fd", con->fd);
267 } else {
268 connection_close(srv, con);
272 static void connection_handle_response_end_state(server *srv, connection *con) {
273 /* log the request */
274 /* (even if error, connection dropped, still write to access log if http_status) */
275 if (con->http_status) {
276 plugins_call_handle_request_done(srv, con);
279 if (con->state != CON_STATE_ERROR) srv->con_written++;
281 if ((con->request.content_length
282 && (off_t)con->request.content_length > con->request_content_queue->bytes_in)
283 || con->state == CON_STATE_ERROR) {
284 /* request body is present and has not been read completely */
285 con->keep_alive = 0;
288 if (con->keep_alive) {
289 connection_reset(srv, con);
290 #if 0
291 con->request_start = srv->cur_ts;
292 con->read_idle_ts = srv->cur_ts;
293 #endif
294 connection_set_state(srv, con, CON_STATE_REQUEST_START);
295 } else {
296 connection_handle_shutdown(srv, con);
300 static void connection_handle_errdoc_init(server *srv, connection *con) {
301 /* modules that produce headers required with error response should
302 * typically also produce an error document. Make an exception for
303 * mod_auth WWW-Authenticate response header. */
304 buffer *www_auth = NULL;
305 if (401 == con->http_status) {
306 data_string *ds = (data_string *)array_get_element(con->response.headers, "WWW-Authenticate");
307 if (NULL != ds) {
308 www_auth = buffer_init_buffer(ds->value);
312 con->response.transfer_encoding = 0;
313 buffer_reset(con->physical.path);
314 array_reset(con->response.headers);
315 chunkqueue_reset(con->write_queue);
317 if (NULL != www_auth) {
318 response_header_insert(srv, con, CONST_STR_LEN("WWW-Authenticate"), CONST_BUF_LEN(www_auth));
319 buffer_free(www_auth);
323 static int connection_handle_write_prepare(server *srv, connection *con) {
324 if (con->mode == DIRECT) {
325 /* static files */
326 switch(con->request.http_method) {
327 case HTTP_METHOD_GET:
328 case HTTP_METHOD_POST:
329 case HTTP_METHOD_HEAD:
330 break;
331 case HTTP_METHOD_OPTIONS:
333 * 400 is coming from the request-parser BEFORE uri.path is set
334 * 403 is from the response handler when noone else catched it
336 * */
337 if ((!con->http_status || con->http_status == 200) && !buffer_string_is_empty(con->uri.path) &&
338 con->uri.path->ptr[0] != '*') {
339 response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST"));
341 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
342 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
344 con->http_status = 200;
345 con->file_finished = 1;
347 chunkqueue_reset(con->write_queue);
349 break;
350 default:
351 if (0 == con->http_status) {
352 con->http_status = 501;
354 break;
358 if (con->http_status == 0) {
359 con->http_status = 403;
362 switch(con->http_status) {
363 case 204: /* class: header only */
364 case 205:
365 case 304:
366 /* disable chunked encoding again as we have no body */
367 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
368 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
369 chunkqueue_reset(con->write_queue);
371 con->file_finished = 1;
372 break;
373 default: /* class: header + body */
374 if (con->mode != DIRECT) break;
376 /* only custom body for 4xx and 5xx */
377 if (con->http_status < 400 || con->http_status >= 600) break;
379 con->file_finished = 0;
381 connection_handle_errdoc_init(srv, con);
383 /* try to send static errorfile */
384 if (!buffer_string_is_empty(con->conf.errorfile_prefix)) {
385 stat_cache_entry *sce = NULL;
387 buffer_copy_buffer(con->physical.path, con->conf.errorfile_prefix);
388 buffer_append_int(con->physical.path, con->http_status);
389 buffer_append_string_len(con->physical.path, CONST_STR_LEN(".html"));
391 if (0 == http_chunk_append_file(srv, con, con->physical.path)) {
392 con->file_finished = 1;
393 if (HANDLER_ERROR != stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
394 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce->content_type));
399 if (!con->file_finished) {
400 buffer *b;
402 buffer_reset(con->physical.path);
404 con->file_finished = 1;
405 b = buffer_init();
407 /* build default error-page */
408 buffer_copy_string_len(b, CONST_STR_LEN(
409 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
410 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
411 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
412 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
413 " <head>\n"
414 " <title>"));
415 buffer_append_int(b, con->http_status);
416 buffer_append_string_len(b, CONST_STR_LEN(" - "));
417 buffer_append_string(b, get_http_status_name(con->http_status));
419 buffer_append_string_len(b, CONST_STR_LEN(
420 "</title>\n"
421 " </head>\n"
422 " <body>\n"
423 " <h1>"));
424 buffer_append_int(b, con->http_status);
425 buffer_append_string_len(b, CONST_STR_LEN(" - "));
426 buffer_append_string(b, get_http_status_name(con->http_status));
428 buffer_append_string_len(b, CONST_STR_LEN("</h1>\n"
429 " </body>\n"
430 "</html>\n"
433 (void)http_chunk_append_buffer(srv, con, b);
434 buffer_free(b);
436 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
438 break;
441 /* Allow filter plugins to change response headers before they are written. */
442 switch(plugins_call_handle_response_start(srv, con)) {
443 case HANDLER_GO_ON:
444 case HANDLER_FINISHED:
445 break;
446 default:
447 log_error_write(srv, __FILE__, __LINE__, "s", "response_start plugin failed");
448 return -1;
451 if (con->file_finished) {
452 /* we have all the content and chunked encoding is not used, set a content-length */
454 if ((!(con->parsed_response & HTTP_CONTENT_LENGTH)) &&
455 (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0) {
456 off_t qlen = chunkqueue_length(con->write_queue);
459 * The Content-Length header only can be sent if we have content:
460 * - HEAD doesn't have a content-body (but have a content-length)
461 * - 1xx, 204 and 304 don't have a content-body (RFC 2616 Section 4.3)
463 * Otherwise generate a Content-Length header as chunked encoding is not
464 * available
466 if ((con->http_status >= 100 && con->http_status < 200) ||
467 con->http_status == 204 ||
468 con->http_status == 304) {
469 data_string *ds;
470 /* no Content-Body, no Content-Length */
471 if (NULL != (ds = (data_string*) array_get_element(con->response.headers, "Content-Length"))) {
472 buffer_reset(ds->value); /* Headers with empty values are ignored for output */
474 } else if (qlen > 0 || con->request.http_method != HTTP_METHOD_HEAD) {
475 /* qlen = 0 is important for Redirects (301, ...) as they MAY have
476 * a content. Browsers are waiting for a Content otherwise
478 buffer_copy_int(srv->tmp_buf, qlen);
480 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Length"), CONST_BUF_LEN(srv->tmp_buf));
483 } else {
485 * the file isn't finished yet, but we have all headers
487 * to get keep-alive we either need:
488 * - Content-Length: ... (HTTP/1.0 and HTTP/1.0) or
489 * - Transfer-Encoding: chunked (HTTP/1.1)
492 if (((con->parsed_response & HTTP_CONTENT_LENGTH) == 0) &&
493 ((con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0)) {
494 if (con->request.http_version == HTTP_VERSION_1_1) {
495 off_t qlen = chunkqueue_length(con->write_queue);
496 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
497 if (qlen) {
498 /* create initial Transfer-Encoding: chunked segment */
499 buffer *b = srv->tmp_chunk_len;
500 buffer_string_set_length(b, 0);
501 buffer_append_uint_hex(b, (uintmax_t)qlen);
502 buffer_append_string_len(b, CONST_STR_LEN("\r\n"));
503 chunkqueue_prepend_buffer(con->write_queue, b);
504 chunkqueue_append_mem(con->write_queue, CONST_STR_LEN("\r\n"));
506 } else {
507 con->keep_alive = 0;
512 * if the backend sent a Connection: close, follow the wish
514 * NOTE: if the backend sent Connection: Keep-Alive, but no Content-Length, we
515 * will close the connection. That's fine. We can always decide the close
516 * the connection
518 * FIXME: to be nice we should remove the Connection: ...
520 if (con->parsed_response & HTTP_CONNECTION) {
521 /* a subrequest disable keep-alive although the client wanted it */
522 if (con->keep_alive && !con->response.keep_alive) {
523 con->keep_alive = 0;
528 if (con->request.http_method == HTTP_METHOD_HEAD) {
530 * a HEAD request has the same as a GET
531 * without the content
533 con->file_finished = 1;
535 chunkqueue_reset(con->write_queue);
536 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
539 http_response_write_header(srv, con);
541 return 0;
544 static int connection_handle_write(server *srv, connection *con) {
545 switch(network_write_chunkqueue(srv, con, con->write_queue, MAX_WRITE_LIMIT)) {
546 case 0:
547 con->write_request_ts = srv->cur_ts;
548 if (con->file_finished) {
549 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
551 break;
552 case -1: /* error on our side */
553 log_error_write(srv, __FILE__, __LINE__, "sd",
554 "connection closed: write failed on fd", con->fd);
555 connection_set_state(srv, con, CON_STATE_ERROR);
556 break;
557 case -2: /* remote close */
558 connection_set_state(srv, con, CON_STATE_ERROR);
559 break;
560 case 1:
561 con->write_request_ts = srv->cur_ts;
562 con->is_writable = 0;
564 /* not finished yet -> WRITE */
565 break;
568 return 0;
573 connection *connection_init(server *srv) {
574 connection *con;
576 UNUSED(srv);
578 con = calloc(1, sizeof(*con));
579 force_assert(NULL != con);
581 con->fd = 0;
582 con->ndx = -1;
583 con->fde_ndx = -1;
584 con->bytes_written = 0;
585 con->bytes_read = 0;
586 con->bytes_header = 0;
587 con->loops_per_request = 0;
589 #define CLEAN(x) \
590 con->x = buffer_init();
592 CLEAN(request.uri);
593 CLEAN(request.request_line);
594 CLEAN(request.request);
595 CLEAN(request.pathinfo);
597 CLEAN(request.orig_uri);
599 CLEAN(uri.scheme);
600 CLEAN(uri.authority);
601 CLEAN(uri.path);
602 CLEAN(uri.path_raw);
603 CLEAN(uri.query);
605 CLEAN(physical.doc_root);
606 CLEAN(physical.path);
607 CLEAN(physical.basedir);
608 CLEAN(physical.rel_path);
609 CLEAN(physical.etag);
610 CLEAN(parse_request);
612 CLEAN(server_name);
613 CLEAN(dst_addr_buf);
614 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
615 CLEAN(tlsext_server_name);
616 #endif
618 #undef CLEAN
619 con->write_queue = chunkqueue_init();
620 con->read_queue = chunkqueue_init();
621 con->request_content_queue = chunkqueue_init();
623 con->request.headers = array_init();
624 con->response.headers = array_init();
625 con->environment = array_init();
627 /* init plugin specific connection structures */
629 con->plugin_ctx = calloc(1, (srv->plugins.used + 1) * sizeof(void *));
630 force_assert(NULL != con->plugin_ctx);
632 con->cond_cache = calloc(srv->config_context->used, sizeof(cond_cache_t));
633 force_assert(NULL != con->cond_cache);
634 config_setup_connection(srv, con);
636 return con;
639 void connections_free(server *srv) {
640 connections *conns = srv->conns;
641 size_t i;
643 for (i = 0; i < conns->size; i++) {
644 connection *con = conns->ptr[i];
646 connection_reset(srv, con);
648 chunkqueue_free(con->write_queue);
649 chunkqueue_free(con->read_queue);
650 chunkqueue_free(con->request_content_queue);
651 array_free(con->request.headers);
652 array_free(con->response.headers);
653 array_free(con->environment);
655 #define CLEAN(x) \
656 buffer_free(con->x);
658 CLEAN(request.uri);
659 CLEAN(request.request_line);
660 CLEAN(request.request);
661 CLEAN(request.pathinfo);
663 CLEAN(request.orig_uri);
665 CLEAN(uri.scheme);
666 CLEAN(uri.authority);
667 CLEAN(uri.path);
668 CLEAN(uri.path_raw);
669 CLEAN(uri.query);
671 CLEAN(physical.doc_root);
672 CLEAN(physical.path);
673 CLEAN(physical.basedir);
674 CLEAN(physical.etag);
675 CLEAN(physical.rel_path);
676 CLEAN(parse_request);
678 CLEAN(server_name);
679 CLEAN(dst_addr_buf);
680 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
681 CLEAN(tlsext_server_name);
682 #endif
683 #undef CLEAN
684 free(con->plugin_ctx);
685 free(con->cond_cache);
687 free(con);
690 free(conns->ptr);
694 int connection_reset(server *srv, connection *con) {
695 size_t i;
697 plugins_call_connection_reset(srv, con);
699 connection_response_reset(srv, con);
700 con->is_readable = 1;
702 con->bytes_written = 0;
703 con->bytes_written_cur_second = 0;
704 con->bytes_read = 0;
705 con->bytes_header = 0;
706 con->loops_per_request = 0;
708 con->request.http_method = HTTP_METHOD_UNSET;
709 con->request.http_version = HTTP_VERSION_UNSET;
711 con->request.http_if_modified_since = NULL;
712 con->request.http_if_none_match = NULL;
714 #define CLEAN(x) \
715 if (con->x) buffer_reset(con->x);
717 CLEAN(request.uri);
718 CLEAN(request.request_line);
719 CLEAN(request.pathinfo);
720 CLEAN(request.request);
722 /* CLEAN(request.orig_uri); */
724 CLEAN(uri.scheme);
725 /* CLEAN(uri.authority); */
726 /* CLEAN(uri.path); */
727 CLEAN(uri.path_raw);
728 /* CLEAN(uri.query); */
730 CLEAN(parse_request);
732 CLEAN(server_name);
733 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
734 CLEAN(tlsext_server_name);
735 #endif
736 #undef CLEAN
738 #define CLEAN(x) \
739 if (con->x) con->x->used = 0;
741 #undef CLEAN
743 #define CLEAN(x) \
744 con->request.x = NULL;
746 CLEAN(http_host);
747 CLEAN(http_range);
748 CLEAN(http_content_type);
749 #undef CLEAN
750 con->request.content_length = 0;
752 array_reset(con->request.headers);
753 array_reset(con->environment);
755 chunkqueue_reset(con->request_content_queue);
757 /* the plugins should cleanup themself */
758 for (i = 0; i < srv->plugins.used; i++) {
759 plugin *p = ((plugin **)(srv->plugins.ptr))[i];
760 plugin_data *pd = p->data;
762 if (!pd) continue;
764 if (con->plugin_ctx[pd->id] != NULL) {
765 log_error_write(srv, __FILE__, __LINE__, "sb", "missing cleanup in", p->name);
768 con->plugin_ctx[pd->id] = NULL;
771 /* The cond_cache gets reset in response.c */
772 /* config_cond_cache_reset(srv, con); */
774 con->header_len = 0;
775 con->error_handler_saved_status = 0;
776 /*con->error_handler_saved_method = HTTP_METHOD_UNSET;*/
777 /*(error_handler_saved_method value is not valid unless error_handler_saved_status is set)*/
779 config_setup_connection(srv, con);
781 return 0;
785 * handle all header and content read
787 * we get called by the state-engine and by the fdevent-handler
789 static int connection_handle_read_state(server *srv, connection *con) {
790 chunk *c, *last_chunk;
791 off_t last_offset;
792 chunkqueue *cq = con->read_queue;
793 int is_closed = 0; /* the connection got closed, if we don't have a complete header, -> error */
794 /* when in CON_STATE_READ: about to receive first byte for a request: */
795 int is_request_start = chunkqueue_is_empty(cq);
797 if (con->is_readable) {
798 con->read_idle_ts = srv->cur_ts;
800 switch(connection_handle_read(srv, con)) {
801 case -1:
802 return -1;
803 case -2:
804 is_closed = 1;
805 break;
806 default:
807 break;
811 chunkqueue_remove_finished_chunks(cq);
813 /* we might have got several packets at once
816 /* update request_start timestamp when first byte of
817 * next request is received on a keep-alive connection */
818 if (con->request_count > 1 && is_request_start) {
819 con->request_start = srv->cur_ts;
820 if (con->conf.high_precision_timestamps)
821 log_clock_gettime_realtime(&con->request_start_hp);
824 /* if there is a \r\n\r\n in the chunkqueue
826 * scan the chunk-queue twice
827 * 1. to find the \r\n\r\n
828 * 2. to copy the header-packet
832 last_chunk = NULL;
833 last_offset = 0;
835 for (c = cq->first; c; c = c->next) {
836 size_t i;
837 size_t len = buffer_string_length(c->mem) - c->offset;
838 const char *b = c->mem->ptr + c->offset;
840 for (i = 0; i < len; ++i) {
841 char ch = b[i];
843 if ('\r' == ch) {
844 /* chec if \n\r\n follows */
845 size_t j = i+1;
846 chunk *cc = c;
847 const char header_end[] = "\r\n\r\n";
848 int header_end_match_pos = 1;
850 for ( ; cc; cc = cc->next, j = 0 ) {
851 size_t bblen = buffer_string_length(cc->mem) - cc->offset;
852 const char *bb = cc->mem->ptr + cc->offset;
854 for ( ; j < bblen; j++) {
855 ch = bb[j];
857 if (ch == header_end[header_end_match_pos]) {
858 header_end_match_pos++;
859 if (4 == header_end_match_pos) {
860 last_chunk = cc;
861 last_offset = j+1;
862 goto found_header_end;
864 } else {
865 goto reset_search;
870 reset_search: ;
873 found_header_end:
875 /* found */
876 if (last_chunk) {
877 buffer_reset(con->request.request);
879 for (c = cq->first; c; c = c->next) {
880 size_t len = buffer_string_length(c->mem) - c->offset;
882 if (c == last_chunk) {
883 len = last_offset;
886 buffer_append_string_len(con->request.request, c->mem->ptr + c->offset, len);
887 c->offset += len;
888 cq->bytes_out += len;
890 if (c == last_chunk) break;
893 connection_set_state(srv, con, CON_STATE_REQUEST_END);
894 } else if (is_closed) {
895 /* the connection got closed and we didn't got enough data to leave CON_STATE_READ;
896 * the only way is to leave here */
897 connection_set_state(srv, con, CON_STATE_ERROR);
900 if ((last_chunk ? buffer_string_length(con->request.request) : (size_t)chunkqueue_length(cq))
901 > srv->srvconf.max_request_field_size) {
902 log_error_write(srv, __FILE__, __LINE__, "s", "oversized request-header -> sending Status 431");
903 con->http_status = 431; /* Request Header Fields Too Large */
904 con->keep_alive = 0;
905 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
908 chunkqueue_remove_finished_chunks(cq);
910 return 0;
913 static handler_t connection_handle_fdevent(server *srv, void *context, int revents) {
914 connection *con = context;
916 joblist_append(srv, con);
918 if (con->srv_socket->is_ssl) {
919 /* ssl may read and write for both reads and writes */
920 if (revents & (FDEVENT_IN | FDEVENT_OUT)) {
921 con->is_readable = 1;
922 con->is_writable = 1;
924 } else {
925 if (revents & FDEVENT_IN) {
926 con->is_readable = 1;
928 if (revents & FDEVENT_OUT) {
929 con->is_writable = 1;
930 /* we don't need the event twice */
935 if (con->state == CON_STATE_READ) {
936 connection_handle_read_state(srv, con);
939 if (con->state == CON_STATE_WRITE &&
940 !chunkqueue_is_empty(con->write_queue) &&
941 con->is_writable) {
943 if (-1 == connection_handle_write(srv, con)) {
944 connection_set_state(srv, con, CON_STATE_ERROR);
946 log_error_write(srv, __FILE__, __LINE__, "ds",
947 con->fd,
948 "handle write failed.");
952 if (con->state == CON_STATE_CLOSE) {
953 /* flush the read buffers */
954 int len;
955 char buf[1024];
957 len = read(con->fd, buf, sizeof(buf));
958 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
959 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
964 /* attempt (above) to read data in kernel socket buffers
965 * prior to handling FDEVENT_HUP and FDEVENT_ERR */
967 if ((revents & ~(FDEVENT_IN | FDEVENT_OUT)) && con->state != CON_STATE_ERROR) {
968 if (con->state == CON_STATE_CLOSE) {
969 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
970 } else if (revents & FDEVENT_HUP) {
971 if (fdevent_is_tcp_half_closed(con->fd)) {
972 con->keep_alive = 0;
973 } else {
974 connection_set_state(srv, con, CON_STATE_ERROR);
976 } else if (revents & FDEVENT_ERR) { /* error, connection reset */
977 connection_set_state(srv, con, CON_STATE_ERROR);
978 } else {
979 log_error_write(srv, __FILE__, __LINE__, "sd",
980 "connection closed: poll() -> ???", revents);
984 return HANDLER_FINISHED;
988 connection *connection_accept(server *srv, server_socket *srv_socket) {
989 /* accept everything */
991 /* search an empty place */
992 int cnt;
993 sock_addr cnt_addr;
994 socklen_t cnt_len;
995 /* accept it and register the fd */
998 * check if we can still open a new connections
1000 * see #1216
1003 if (srv->conns->used >= srv->max_conns) {
1004 return NULL;
1007 cnt_len = sizeof(cnt_addr);
1009 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1010 #if defined(__NetBSD__)
1011 cnt = paccept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);
1012 #else
1013 cnt = accept4(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len, SOCK_CLOEXEC | SOCK_NONBLOCK);
1014 #endif
1015 #else
1016 cnt = accept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len);
1017 #endif
1018 if (-1 == cnt) {
1019 switch (errno) {
1020 case EAGAIN:
1021 #if EWOULDBLOCK != EAGAIN
1022 case EWOULDBLOCK:
1023 #endif
1024 case EINTR:
1025 /* we were stopped _before_ we had a connection */
1026 case ECONNABORTED: /* this is a FreeBSD thingy */
1027 /* we were stopped _after_ we had a connection */
1028 break;
1029 case EMFILE:
1030 /* out of fds */
1031 break;
1032 default:
1033 log_error_write(srv, __FILE__, __LINE__, "ssd", "accept failed:", strerror(errno), errno);
1035 return NULL;
1036 } else {
1037 if (cnt_addr.plain.sa_family != AF_UNIX) {
1038 network_accept_tcp_nagle_disable(cnt);
1040 return connection_accepted(srv, srv_socket, &cnt_addr, cnt);
1044 connection *connection_accepted(server *srv, server_socket *srv_socket, sock_addr *cnt_addr, int cnt) {
1045 connection *con;
1047 srv->cur_fds++;
1049 /* ok, we have the connection, register it */
1050 #if 0
1051 log_error_write(srv, __FILE__, __LINE__, "sd",
1052 "appected()", cnt);
1053 #endif
1054 srv->con_opened++;
1056 con = connections_get_new_connection(srv);
1058 con->fd = cnt;
1059 con->fde_ndx = -1;
1060 fdevent_register(srv->ev, con->fd, connection_handle_fdevent, con);
1062 connection_set_state(srv, con, CON_STATE_REQUEST_START);
1064 con->connection_start = srv->cur_ts;
1065 con->dst_addr = *cnt_addr;
1066 buffer_copy_string(con->dst_addr_buf, inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
1067 con->srv_socket = srv_socket;
1069 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv->ev, con->fd)) {
1070 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
1071 connection_close(srv, con);
1072 return NULL;
1074 #ifdef USE_OPENSSL
1075 /* connect FD to SSL */
1076 if (srv_socket->is_ssl) {
1077 if (NULL == (con->ssl = SSL_new(srv_socket->ssl_ctx))) {
1078 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1079 ERR_error_string(ERR_get_error(), NULL));
1081 connection_close(srv, con);
1082 return NULL;
1085 con->renegotiations = 0;
1086 SSL_set_app_data(con->ssl, con);
1087 SSL_set_accept_state(con->ssl);
1089 if (1 != (SSL_set_fd(con->ssl, cnt))) {
1090 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1091 ERR_error_string(ERR_get_error(), NULL));
1092 connection_close(srv, con);
1093 return NULL;
1096 #endif
1097 return con;
1101 int connection_state_machine(server *srv, connection *con) {
1102 int done = 0, r;
1104 if (srv->srvconf.log_state_handling) {
1105 log_error_write(srv, __FILE__, __LINE__, "sds",
1106 "state at start",
1107 con->fd,
1108 connection_get_state(con->state));
1111 while (done == 0) {
1112 size_t ostate = con->state;
1114 if (srv->srvconf.log_state_handling) {
1115 log_error_write(srv, __FILE__, __LINE__, "sds",
1116 "state for fd", con->fd, connection_get_state(con->state));
1119 switch (con->state) {
1120 case CON_STATE_REQUEST_START: /* transient */
1121 con->request_start = srv->cur_ts;
1122 con->read_idle_ts = srv->cur_ts;
1123 if (con->conf.high_precision_timestamps)
1124 log_clock_gettime_realtime(&con->request_start_hp);
1126 con->request_count++;
1127 con->loops_per_request = 0;
1129 connection_set_state(srv, con, CON_STATE_READ);
1131 break;
1132 case CON_STATE_REQUEST_END: /* transient */
1133 buffer_reset(con->uri.authority);
1134 buffer_reset(con->uri.path);
1135 buffer_reset(con->uri.query);
1136 buffer_reset(con->request.orig_uri);
1138 if (http_request_parse(srv, con)) {
1139 /* we have to read some data from the POST request */
1141 connection_set_state(srv, con, CON_STATE_READ_POST);
1143 break;
1146 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
1148 break;
1149 case CON_STATE_READ_POST:
1150 case CON_STATE_HANDLE_REQUEST:
1152 * the request is parsed
1154 * decided what to do with the request
1160 switch (r = http_response_prepare(srv, con)) {
1161 case HANDLER_WAIT_FOR_EVENT:
1162 if (!con->file_finished && (!con->file_started || 0 == con->conf.stream_response_body)) {
1163 break; /* come back here */
1165 /* response headers received from backend; fall through to start response */
1166 case HANDLER_FINISHED:
1167 if (con->error_handler_saved_status > 0) {
1168 con->request.http_method = con->error_handler_saved_method;
1170 if (con->mode == DIRECT) {
1171 if (con->error_handler_saved_status) {
1172 if (con->error_handler_saved_status > 0) {
1173 con->http_status = con->error_handler_saved_status;
1174 } else if (con->http_status == 404 || con->http_status == 403) {
1175 /* error-handler-404 is a 404 */
1176 con->http_status = -con->error_handler_saved_status;
1177 } else {
1178 /* error-handler-404 is back and has generated content */
1179 /* if Status: was set, take it otherwise use 200 */
1181 } else if (con->http_status >= 400) {
1182 buffer *error_handler = NULL;
1183 if (!buffer_string_is_empty(con->conf.error_handler)) {
1184 error_handler = con->conf.error_handler;
1185 } else if ((con->http_status == 404 || con->http_status == 403)
1186 && !buffer_string_is_empty(con->conf.error_handler_404)) {
1187 error_handler = con->conf.error_handler_404;
1190 if (error_handler) {
1191 /* call error-handler */
1193 /* set REDIRECT_STATUS to save current HTTP status code
1194 * for access by dynamic handlers
1195 * https://redmine.lighttpd.net/issues/1828 */
1196 data_string *ds;
1197 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
1198 ds = data_string_init();
1200 buffer_copy_string_len(ds->key, CONST_STR_LEN("REDIRECT_STATUS"));
1201 buffer_append_int(ds->value, con->http_status);
1202 array_insert_unique(con->environment, (data_unset *)ds);
1204 if (error_handler == con->conf.error_handler) {
1205 plugins_call_connection_reset(srv, con);
1207 if (con->request.content_length) {
1208 if ((off_t)con->request.content_length != chunkqueue_length(con->request_content_queue)) {
1209 con->keep_alive = 0;
1211 con->request.content_length = 0;
1212 chunkqueue_reset(con->request_content_queue);
1215 con->is_writable = 1;
1216 con->file_finished = 0;
1217 con->file_started = 0;
1218 con->got_response = 0;
1219 con->parsed_response = 0;
1220 con->response.keep_alive = 0;
1221 con->response.content_length = -1;
1222 con->response.transfer_encoding = 0;
1224 con->error_handler_saved_status = con->http_status;
1225 con->error_handler_saved_method = con->request.http_method;
1227 con->request.http_method = HTTP_METHOD_GET;
1228 } else { /*(preserve behavior for server.error-handler-404)*/
1229 con->error_handler_saved_status = -con->http_status; /*(negative to flag old behavior)*/
1232 buffer_copy_buffer(con->request.uri, error_handler);
1233 connection_handle_errdoc_init(srv, con);
1234 con->http_status = 0; /*(after connection_handle_errdoc_init())*/
1236 done = -1;
1237 break;
1241 if (con->http_status == 0) con->http_status = 200;
1243 /* we have something to send, go on */
1244 connection_set_state(srv, con, CON_STATE_RESPONSE_START);
1245 break;
1246 case HANDLER_WAIT_FOR_FD:
1247 srv->want_fds++;
1249 fdwaitqueue_append(srv, con);
1251 break;
1252 case HANDLER_COMEBACK:
1253 done = -1;
1254 break;
1255 case HANDLER_ERROR:
1256 /* something went wrong */
1257 connection_set_state(srv, con, CON_STATE_ERROR);
1258 break;
1259 default:
1260 log_error_write(srv, __FILE__, __LINE__, "sdd", "unknown ret-value: ", con->fd, r);
1261 break;
1264 if (con->state == CON_STATE_HANDLE_REQUEST && ostate == CON_STATE_READ_POST) {
1265 ostate = CON_STATE_HANDLE_REQUEST;
1267 break;
1268 case CON_STATE_RESPONSE_START:
1270 * the decision is done
1271 * - create the HTTP-Response-Header
1275 if (-1 == connection_handle_write_prepare(srv, con)) {
1276 connection_set_state(srv, con, CON_STATE_ERROR);
1278 break;
1281 connection_set_state(srv, con, CON_STATE_WRITE);
1282 break;
1283 case CON_STATE_RESPONSE_END: /* transient */
1284 case CON_STATE_ERROR: /* transient */
1285 connection_handle_response_end_state(srv, con);
1286 break;
1287 case CON_STATE_CONNECT:
1288 chunkqueue_reset(con->read_queue);
1290 con->request_count = 0;
1292 break;
1293 case CON_STATE_CLOSE:
1294 connection_handle_close_state(srv, con);
1295 break;
1296 case CON_STATE_READ:
1297 connection_handle_read_state(srv, con);
1298 break;
1299 case CON_STATE_WRITE:
1300 do {
1301 /* only try to write if we have something in the queue */
1302 if (!chunkqueue_is_empty(con->write_queue)) {
1303 if (con->is_writable) {
1304 if (-1 == connection_handle_write(srv, con)) {
1305 log_error_write(srv, __FILE__, __LINE__, "ds",
1306 con->fd,
1307 "handle write failed.");
1308 connection_set_state(srv, con, CON_STATE_ERROR);
1309 break;
1311 if (con->state != CON_STATE_WRITE) break;
1313 } else if (con->file_finished) {
1314 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
1315 break;
1318 if (con->mode != DIRECT && !con->file_finished) {
1319 switch(r = plugins_call_handle_subrequest(srv, con)) {
1320 case HANDLER_WAIT_FOR_EVENT:
1321 case HANDLER_FINISHED:
1322 case HANDLER_GO_ON:
1323 break;
1324 case HANDLER_WAIT_FOR_FD:
1325 srv->want_fds++;
1326 fdwaitqueue_append(srv, con);
1327 break;
1328 case HANDLER_COMEBACK:
1329 default:
1330 log_error_write(srv, __FILE__, __LINE__, "sdd", "unexpected subrequest handler ret-value: ", con->fd, r);
1331 /* fall through */
1332 case HANDLER_ERROR:
1333 connection_set_state(srv, con, CON_STATE_ERROR);
1334 break;
1337 } while (con->state == CON_STATE_WRITE && (!chunkqueue_is_empty(con->write_queue) ? con->is_writable : con->file_finished));
1339 break;
1340 default:
1341 log_error_write(srv, __FILE__, __LINE__, "sdd",
1342 "unknown state:", con->fd, con->state);
1344 break;
1347 if (done == -1) {
1348 done = 0;
1349 } else if (ostate == con->state) {
1350 done = 1;
1354 if (srv->srvconf.log_state_handling) {
1355 log_error_write(srv, __FILE__, __LINE__, "sds",
1356 "state at exit:",
1357 con->fd,
1358 connection_get_state(con->state));
1361 r = 0;
1362 switch(con->state) {
1363 case CON_STATE_READ:
1364 case CON_STATE_CLOSE:
1365 r = FDEVENT_IN;
1366 break;
1367 case CON_STATE_WRITE:
1368 /* request write-fdevent only if we really need it
1369 * - if we have data to write
1370 * - if the socket is not writable yet
1372 if (!chunkqueue_is_empty(con->write_queue) &&
1373 (con->is_writable == 0) &&
1374 (con->traffic_limit_reached == 0)) {
1375 r |= FDEVENT_OUT;
1377 /* fall through */
1378 case CON_STATE_READ_POST:
1379 if (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN) {
1380 r |= FDEVENT_IN;
1382 break;
1383 default:
1384 break;
1386 if (-1 != con->fd) {
1387 const int events = fdevent_event_get_interest(srv->ev, con->fd);
1388 if (con->is_readable < 0) {
1389 con->is_readable = 0;
1390 r |= FDEVENT_IN;
1392 if (con->is_writable < 0) {
1393 con->is_writable = 0;
1394 r |= FDEVENT_OUT;
1396 if (r != events) {
1397 /* update timestamps when enabling interest in events */
1398 if ((r & FDEVENT_IN) && !(events & FDEVENT_IN)) {
1399 con->read_idle_ts = srv->cur_ts;
1401 if ((r & FDEVENT_OUT) && !(events & FDEVENT_OUT)) {
1402 con->write_request_ts = srv->cur_ts;
1404 fdevent_event_set(srv->ev, &con->fde_ndx, con->fd, r);
1408 return 0;