[mod_cgi] skip local-redir handling if to self (fixes #2779, #2108)
[lighttpd.git] / src / connections.c
blob4b4c94a21fdebf77b37f2a4258cfa0c66e5def3f
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 if (srv->srvconf.log_state_handling) {
148 log_error_write(srv, __FILE__, __LINE__, "sd",
149 "connection closed for fd", con->fd);
151 con->fd = -1;
152 connection_del(srv, con);
153 connection_set_state(srv, con, CON_STATE_CONNECT);
155 return 0;
158 static void connection_read_for_eos(server *srv, connection *con) {
159 /* we have to do the linger_on_close stuff regardless
160 * of con->keep_alive; even non-keepalive sockets may
161 * still have unread data, and closing before reading
162 * it will make the client not see all our output.
164 ssize_t len;
165 char buf[4096];
167 do {
168 len = read(con->fd, buf, sizeof(buf));
169 } while (len > 0 || (len < 0 && errno == EINTR));
171 if (len < 0 && errno == EAGAIN) return;
172 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
173 if (len < 0 && errno == EWOULDBLOCK) return;
174 #endif
176 /* 0 == len || (len < 0 && (errno is a non-recoverable error)) */
177 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
180 static void connection_handle_close_state(server *srv, connection *con) {
181 connection_read_for_eos(srv, con);
183 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
184 connection_close(srv, con);
188 static void connection_handle_shutdown(server *srv, connection *con) {
189 int r;
191 #ifdef USE_OPENSSL
192 server_socket *srv_sock = con->srv_socket;
193 if (srv_sock->is_ssl && SSL_is_init_finished(con->ssl)) {
194 int ret, ssl_r;
195 unsigned long err;
196 ERR_clear_error();
197 switch ((ret = SSL_shutdown(con->ssl))) {
198 case 1:
199 /* ok */
200 break;
201 case 0:
202 /* wait for fd-event
204 * FIXME: wait for fdevent and call SSL_shutdown again
207 ERR_clear_error();
208 if (-1 != (ret = SSL_shutdown(con->ssl))) break;
210 /* fall through */
211 default:
213 switch ((ssl_r = SSL_get_error(con->ssl, ret))) {
214 case SSL_ERROR_ZERO_RETURN:
215 break;
216 case SSL_ERROR_WANT_WRITE:
217 /*con->is_writable = -1;*//*(no effect; shutdown() called below)*/
218 case SSL_ERROR_WANT_READ:
219 break;
220 case SSL_ERROR_SYSCALL:
221 /* perhaps we have error waiting in our error-queue */
222 if (0 != (err = ERR_get_error())) {
223 do {
224 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
225 ssl_r, ret,
226 ERR_error_string(err, NULL));
227 } while((err = ERR_get_error()));
228 } else if (errno != 0) { /* ssl bug (see lighttpd ticket #2213): sometimes errno == 0 */
229 switch(errno) {
230 case EPIPE:
231 case ECONNRESET:
232 break;
233 default:
234 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL (error):",
235 ssl_r, ret, errno,
236 strerror(errno));
237 break;
241 break;
242 default:
243 while((err = ERR_get_error())) {
244 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
245 ssl_r, ret,
246 ERR_error_string(err, NULL));
249 break;
252 ERR_clear_error();
254 #endif
256 switch(r = plugins_call_handle_connection_close(srv, con)) {
257 case HANDLER_GO_ON:
258 case HANDLER_FINISHED:
259 break;
260 default:
261 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
262 break;
265 srv->con_closed++;
266 connection_reset(srv, con);
268 /* plugins should have cleaned themselves up */
269 for (size_t i = 0; i < srv->plugins.used; ++i) {
270 plugin *p = ((plugin **)(srv->plugins.ptr))[i];
271 plugin_data *pd = p->data;
272 if (!pd || NULL == con->plugin_ctx[pd->id]) continue;
273 log_error_write(srv, __FILE__, __LINE__, "sb",
274 "missing cleanup in", p->name);
275 con->plugin_ctx[pd->id] = NULL;
278 /* close the connection */
279 if ((0 == shutdown(con->fd, SHUT_WR))) {
280 con->close_timeout_ts = srv->cur_ts;
281 connection_set_state(srv, con, CON_STATE_CLOSE);
283 if (srv->srvconf.log_state_handling) {
284 log_error_write(srv, __FILE__, __LINE__, "sd",
285 "shutdown for fd", con->fd);
287 } else {
288 connection_close(srv, con);
292 static void connection_handle_response_end_state(server *srv, connection *con) {
293 /* log the request */
294 /* (even if error, connection dropped, still write to access log if http_status) */
295 if (con->http_status) {
296 plugins_call_handle_request_done(srv, con);
299 if (con->state != CON_STATE_ERROR) srv->con_written++;
301 if (con->request.content_length != con->request_content_queue->bytes_in
302 || con->state == CON_STATE_ERROR) {
303 /* request body is present and has not been read completely */
304 con->keep_alive = 0;
307 if (con->keep_alive) {
308 connection_reset(srv, con);
309 #if 0
310 con->request_start = srv->cur_ts;
311 con->read_idle_ts = srv->cur_ts;
312 #endif
313 connection_set_state(srv, con, CON_STATE_REQUEST_START);
314 } else {
315 connection_handle_shutdown(srv, con);
319 static void connection_handle_errdoc_init(server *srv, connection *con) {
320 /* modules that produce headers required with error response should
321 * typically also produce an error document. Make an exception for
322 * mod_auth WWW-Authenticate response header. */
323 buffer *www_auth = NULL;
324 if (401 == con->http_status) {
325 data_string *ds = (data_string *)array_get_element(con->response.headers, "WWW-Authenticate");
326 if (NULL != ds) {
327 www_auth = buffer_init_buffer(ds->value);
331 con->response.transfer_encoding = 0;
332 buffer_reset(con->physical.path);
333 array_reset(con->response.headers);
334 chunkqueue_reset(con->write_queue);
336 if (NULL != www_auth) {
337 response_header_insert(srv, con, CONST_STR_LEN("WWW-Authenticate"), CONST_BUF_LEN(www_auth));
338 buffer_free(www_auth);
342 static int connection_handle_write_prepare(server *srv, connection *con) {
343 if (con->mode == DIRECT) {
344 /* static files */
345 switch(con->request.http_method) {
346 case HTTP_METHOD_GET:
347 case HTTP_METHOD_POST:
348 case HTTP_METHOD_HEAD:
349 break;
350 case HTTP_METHOD_OPTIONS:
352 * 400 is coming from the request-parser BEFORE uri.path is set
353 * 403 is from the response handler when noone else catched it
355 * */
356 if ((!con->http_status || con->http_status == 200) && !buffer_string_is_empty(con->uri.path) &&
357 con->uri.path->ptr[0] != '*') {
358 response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST"));
360 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
361 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
363 con->http_status = 200;
364 con->file_finished = 1;
366 chunkqueue_reset(con->write_queue);
368 break;
369 default:
370 if (0 == con->http_status) {
371 con->http_status = 501;
373 break;
377 if (con->http_status == 0) {
378 con->http_status = 403;
381 switch(con->http_status) {
382 case 204: /* class: header only */
383 case 205:
384 case 304:
385 /* disable chunked encoding again as we have no body */
386 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
387 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
388 chunkqueue_reset(con->write_queue);
390 con->file_finished = 1;
391 break;
392 default: /* class: header + body */
393 if (con->mode != DIRECT) break;
395 /* only custom body for 4xx and 5xx */
396 if (con->http_status < 400 || con->http_status >= 600) break;
398 con->file_finished = 0;
400 connection_handle_errdoc_init(srv, con);
402 /* try to send static errorfile */
403 if (!buffer_string_is_empty(con->conf.errorfile_prefix)) {
404 stat_cache_entry *sce = NULL;
406 buffer_copy_buffer(con->physical.path, con->conf.errorfile_prefix);
407 buffer_append_int(con->physical.path, con->http_status);
408 buffer_append_string_len(con->physical.path, CONST_STR_LEN(".html"));
410 if (0 == http_chunk_append_file(srv, con, con->physical.path)) {
411 con->file_finished = 1;
412 if (HANDLER_ERROR != stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
413 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce->content_type));
418 if (!con->file_finished) {
419 buffer *b;
421 buffer_reset(con->physical.path);
423 con->file_finished = 1;
424 b = buffer_init();
426 /* build default error-page */
427 buffer_copy_string_len(b, CONST_STR_LEN(
428 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
429 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
430 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
431 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
432 " <head>\n"
433 " <title>"));
434 buffer_append_int(b, con->http_status);
435 buffer_append_string_len(b, CONST_STR_LEN(" - "));
436 buffer_append_string(b, get_http_status_name(con->http_status));
438 buffer_append_string_len(b, CONST_STR_LEN(
439 "</title>\n"
440 " </head>\n"
441 " <body>\n"
442 " <h1>"));
443 buffer_append_int(b, con->http_status);
444 buffer_append_string_len(b, CONST_STR_LEN(" - "));
445 buffer_append_string(b, get_http_status_name(con->http_status));
447 buffer_append_string_len(b, CONST_STR_LEN("</h1>\n"
448 " </body>\n"
449 "</html>\n"
452 (void)http_chunk_append_buffer(srv, con, b);
453 buffer_free(b);
455 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
457 break;
460 /* Allow filter plugins to change response headers before they are written. */
461 switch(plugins_call_handle_response_start(srv, con)) {
462 case HANDLER_GO_ON:
463 case HANDLER_FINISHED:
464 break;
465 default:
466 log_error_write(srv, __FILE__, __LINE__, "s", "response_start plugin failed");
467 return -1;
470 if (con->file_finished) {
471 /* we have all the content and chunked encoding is not used, set a content-length */
473 if ((!(con->parsed_response & HTTP_CONTENT_LENGTH)) &&
474 (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0) {
475 off_t qlen = chunkqueue_length(con->write_queue);
478 * The Content-Length header only can be sent if we have content:
479 * - HEAD doesn't have a content-body (but have a content-length)
480 * - 1xx, 204 and 304 don't have a content-body (RFC 2616 Section 4.3)
482 * Otherwise generate a Content-Length header as chunked encoding is not
483 * available
485 if ((con->http_status >= 100 && con->http_status < 200) ||
486 con->http_status == 204 ||
487 con->http_status == 304) {
488 data_string *ds;
489 /* no Content-Body, no Content-Length */
490 if (NULL != (ds = (data_string*) array_get_element(con->response.headers, "Content-Length"))) {
491 buffer_reset(ds->value); /* Headers with empty values are ignored for output */
493 } else if (qlen > 0 || con->request.http_method != HTTP_METHOD_HEAD) {
494 /* qlen = 0 is important for Redirects (301, ...) as they MAY have
495 * a content. Browsers are waiting for a Content otherwise
497 buffer_copy_int(srv->tmp_buf, qlen);
499 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Length"), CONST_BUF_LEN(srv->tmp_buf));
502 } else {
504 * the file isn't finished yet, but we have all headers
506 * to get keep-alive we either need:
507 * - Content-Length: ... (HTTP/1.0 and HTTP/1.0) or
508 * - Transfer-Encoding: chunked (HTTP/1.1)
511 if (((con->parsed_response & HTTP_CONTENT_LENGTH) == 0) &&
512 ((con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0)) {
513 if (con->request.http_version == HTTP_VERSION_1_1) {
514 off_t qlen = chunkqueue_length(con->write_queue);
515 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
516 if (qlen) {
517 /* create initial Transfer-Encoding: chunked segment */
518 buffer *b = srv->tmp_chunk_len;
519 buffer_string_set_length(b, 0);
520 buffer_append_uint_hex(b, (uintmax_t)qlen);
521 buffer_append_string_len(b, CONST_STR_LEN("\r\n"));
522 chunkqueue_prepend_buffer(con->write_queue, b);
523 chunkqueue_append_mem(con->write_queue, CONST_STR_LEN("\r\n"));
525 } else {
526 con->keep_alive = 0;
531 * if the backend sent a Connection: close, follow the wish
533 * NOTE: if the backend sent Connection: Keep-Alive, but no Content-Length, we
534 * will close the connection. That's fine. We can always decide the close
535 * the connection
537 * FIXME: to be nice we should remove the Connection: ...
539 if (con->parsed_response & HTTP_CONNECTION) {
540 /* a subrequest disable keep-alive although the client wanted it */
541 if (con->keep_alive && !con->response.keep_alive) {
542 con->keep_alive = 0;
547 if (con->request.http_method == HTTP_METHOD_HEAD) {
549 * a HEAD request has the same as a GET
550 * without the content
552 con->file_finished = 1;
554 chunkqueue_reset(con->write_queue);
555 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
558 http_response_write_header(srv, con);
560 return 0;
563 static int connection_handle_write(server *srv, connection *con) {
564 switch(network_write_chunkqueue(srv, con, con->write_queue, MAX_WRITE_LIMIT)) {
565 case 0:
566 con->write_request_ts = srv->cur_ts;
567 if (con->file_finished) {
568 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
570 break;
571 case -1: /* error on our side */
572 log_error_write(srv, __FILE__, __LINE__, "sd",
573 "connection closed: write failed on fd", con->fd);
574 connection_set_state(srv, con, CON_STATE_ERROR);
575 break;
576 case -2: /* remote close */
577 connection_set_state(srv, con, CON_STATE_ERROR);
578 break;
579 case 1:
580 con->write_request_ts = srv->cur_ts;
581 con->is_writable = 0;
583 /* not finished yet -> WRITE */
584 break;
587 return 0;
592 connection *connection_init(server *srv) {
593 connection *con;
595 UNUSED(srv);
597 con = calloc(1, sizeof(*con));
598 force_assert(NULL != con);
600 con->fd = 0;
601 con->ndx = -1;
602 con->fde_ndx = -1;
603 con->bytes_written = 0;
604 con->bytes_read = 0;
605 con->bytes_header = 0;
606 con->loops_per_request = 0;
608 #define CLEAN(x) \
609 con->x = buffer_init();
611 CLEAN(request.uri);
612 CLEAN(request.request_line);
613 CLEAN(request.request);
614 CLEAN(request.pathinfo);
616 CLEAN(request.orig_uri);
618 CLEAN(uri.scheme);
619 CLEAN(uri.authority);
620 CLEAN(uri.path);
621 CLEAN(uri.path_raw);
622 CLEAN(uri.query);
624 CLEAN(physical.doc_root);
625 CLEAN(physical.path);
626 CLEAN(physical.basedir);
627 CLEAN(physical.rel_path);
628 CLEAN(physical.etag);
629 CLEAN(parse_request);
631 CLEAN(server_name);
632 CLEAN(dst_addr_buf);
633 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
634 CLEAN(tlsext_server_name);
635 #endif
637 #undef CLEAN
638 con->write_queue = chunkqueue_init();
639 con->read_queue = chunkqueue_init();
640 con->request_content_queue = chunkqueue_init();
642 con->request.headers = array_init();
643 con->response.headers = array_init();
644 con->environment = array_init();
646 /* init plugin specific connection structures */
648 con->plugin_ctx = calloc(1, (srv->plugins.used + 1) * sizeof(void *));
649 force_assert(NULL != con->plugin_ctx);
651 con->cond_cache = calloc(srv->config_context->used, sizeof(cond_cache_t));
652 force_assert(NULL != con->cond_cache);
653 config_setup_connection(srv, con);
655 return con;
658 void connections_free(server *srv) {
659 connections *conns = srv->conns;
660 size_t i;
662 for (i = 0; i < conns->size; i++) {
663 connection *con = conns->ptr[i];
665 connection_reset(srv, con);
667 chunkqueue_free(con->write_queue);
668 chunkqueue_free(con->read_queue);
669 chunkqueue_free(con->request_content_queue);
670 array_free(con->request.headers);
671 array_free(con->response.headers);
672 array_free(con->environment);
674 #define CLEAN(x) \
675 buffer_free(con->x);
677 CLEAN(request.uri);
678 CLEAN(request.request_line);
679 CLEAN(request.request);
680 CLEAN(request.pathinfo);
682 CLEAN(request.orig_uri);
684 CLEAN(uri.scheme);
685 CLEAN(uri.authority);
686 CLEAN(uri.path);
687 CLEAN(uri.path_raw);
688 CLEAN(uri.query);
690 CLEAN(physical.doc_root);
691 CLEAN(physical.path);
692 CLEAN(physical.basedir);
693 CLEAN(physical.etag);
694 CLEAN(physical.rel_path);
695 CLEAN(parse_request);
697 CLEAN(server_name);
698 CLEAN(dst_addr_buf);
699 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
700 CLEAN(tlsext_server_name);
701 #endif
702 #undef CLEAN
703 free(con->plugin_ctx);
704 free(con->cond_cache);
706 free(con);
709 free(conns->ptr);
713 int connection_reset(server *srv, connection *con) {
714 plugins_call_connection_reset(srv, con);
716 connection_response_reset(srv, con);
717 con->is_readable = 1;
719 con->bytes_written = 0;
720 con->bytes_written_cur_second = 0;
721 con->bytes_read = 0;
722 con->bytes_header = 0;
723 con->loops_per_request = 0;
725 con->request.http_method = HTTP_METHOD_UNSET;
726 con->request.http_version = HTTP_VERSION_UNSET;
728 con->request.http_if_modified_since = NULL;
729 con->request.http_if_none_match = NULL;
731 #define CLEAN(x) \
732 if (con->x) buffer_reset(con->x);
734 CLEAN(request.uri);
735 CLEAN(request.request_line);
736 CLEAN(request.pathinfo);
737 CLEAN(request.request);
739 /* CLEAN(request.orig_uri); */
741 CLEAN(uri.scheme);
742 /* CLEAN(uri.authority); */
743 /* CLEAN(uri.path); */
744 CLEAN(uri.path_raw);
745 /* CLEAN(uri.query); */
747 CLEAN(parse_request);
749 CLEAN(server_name);
750 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
751 CLEAN(tlsext_server_name);
752 #endif
753 #undef CLEAN
755 #define CLEAN(x) \
756 if (con->x) con->x->used = 0;
758 #undef CLEAN
760 #define CLEAN(x) \
761 con->request.x = NULL;
763 CLEAN(http_host);
764 CLEAN(http_range);
765 CLEAN(http_content_type);
766 #undef CLEAN
767 con->request.content_length = 0;
768 con->request.te_chunked = 0;
770 array_reset(con->request.headers);
771 array_reset(con->environment);
773 chunkqueue_reset(con->request_content_queue);
775 /* The cond_cache gets reset in response.c */
776 /* config_cond_cache_reset(srv, con); */
778 con->header_len = 0;
779 con->error_handler_saved_status = 0;
780 /*con->error_handler_saved_method = HTTP_METHOD_UNSET;*/
781 /*(error_handler_saved_method value is not valid unless error_handler_saved_status is set)*/
783 config_setup_connection(srv, con);
785 return 0;
789 * handle all header and content read
791 * we get called by the state-engine and by the fdevent-handler
793 static int connection_handle_read_state(server *srv, connection *con) {
794 chunk *c, *last_chunk;
795 off_t last_offset;
796 chunkqueue *cq = con->read_queue;
797 int is_closed = 0; /* the connection got closed, if we don't have a complete header, -> error */
798 /* when in CON_STATE_READ: about to receive first byte for a request: */
799 int is_request_start = chunkqueue_is_empty(cq);
801 if (con->is_readable) {
802 con->read_idle_ts = srv->cur_ts;
804 switch(connection_handle_read(srv, con)) {
805 case -1:
806 return -1;
807 case -2:
808 is_closed = 1;
809 break;
810 default:
811 break;
815 chunkqueue_remove_finished_chunks(cq);
817 /* we might have got several packets at once
820 /* update request_start timestamp when first byte of
821 * next request is received on a keep-alive connection */
822 if (con->request_count > 1 && is_request_start) {
823 con->request_start = srv->cur_ts;
824 if (con->conf.high_precision_timestamps)
825 log_clock_gettime_realtime(&con->request_start_hp);
828 /* if there is a \r\n\r\n in the chunkqueue
830 * scan the chunk-queue twice
831 * 1. to find the \r\n\r\n
832 * 2. to copy the header-packet
836 last_chunk = NULL;
837 last_offset = 0;
839 for (c = cq->first; c; c = c->next) {
840 size_t i;
841 size_t len = buffer_string_length(c->mem) - c->offset;
842 const char *b = c->mem->ptr + c->offset;
844 for (i = 0; i < len; ++i) {
845 char ch = b[i];
847 if ('\r' == ch) {
848 /* chec if \n\r\n follows */
849 size_t j = i+1;
850 chunk *cc = c;
851 const char header_end[] = "\r\n\r\n";
852 int header_end_match_pos = 1;
854 for ( ; cc; cc = cc->next, j = 0 ) {
855 size_t bblen = buffer_string_length(cc->mem) - cc->offset;
856 const char *bb = cc->mem->ptr + cc->offset;
858 for ( ; j < bblen; j++) {
859 ch = bb[j];
861 if (ch == header_end[header_end_match_pos]) {
862 header_end_match_pos++;
863 if (4 == header_end_match_pos) {
864 last_chunk = cc;
865 last_offset = j+1;
866 goto found_header_end;
868 } else {
869 goto reset_search;
874 reset_search: ;
877 found_header_end:
879 /* found */
880 if (last_chunk) {
881 buffer_reset(con->request.request);
883 for (c = cq->first; c; c = c->next) {
884 size_t len = buffer_string_length(c->mem) - c->offset;
886 if (c == last_chunk) {
887 len = last_offset;
890 buffer_append_string_len(con->request.request, c->mem->ptr + c->offset, len);
891 c->offset += len;
892 cq->bytes_out += len;
894 if (c == last_chunk) break;
897 connection_set_state(srv, con, CON_STATE_REQUEST_END);
898 } else if (is_closed) {
899 /* the connection got closed and we didn't got enough data to leave CON_STATE_READ;
900 * the only way is to leave here */
901 connection_set_state(srv, con, CON_STATE_ERROR);
904 if ((last_chunk ? buffer_string_length(con->request.request) : (size_t)chunkqueue_length(cq))
905 > srv->srvconf.max_request_field_size) {
906 log_error_write(srv, __FILE__, __LINE__, "s", "oversized request-header -> sending Status 431");
907 con->http_status = 431; /* Request Header Fields Too Large */
908 con->keep_alive = 0;
909 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
912 chunkqueue_remove_finished_chunks(cq);
914 return 0;
917 static handler_t connection_handle_fdevent(server *srv, void *context, int revents) {
918 connection *con = context;
920 joblist_append(srv, con);
922 if (con->srv_socket->is_ssl) {
923 /* ssl may read and write for both reads and writes */
924 if (revents & (FDEVENT_IN | FDEVENT_OUT)) {
925 con->is_readable = 1;
926 con->is_writable = 1;
928 } else {
929 if (revents & FDEVENT_IN) {
930 con->is_readable = 1;
932 if (revents & FDEVENT_OUT) {
933 con->is_writable = 1;
934 /* we don't need the event twice */
939 if (con->state == CON_STATE_READ) {
940 connection_handle_read_state(srv, con);
943 if (con->state == CON_STATE_WRITE &&
944 !chunkqueue_is_empty(con->write_queue) &&
945 con->is_writable) {
947 if (-1 == connection_handle_write(srv, con)) {
948 connection_set_state(srv, con, CON_STATE_ERROR);
950 log_error_write(srv, __FILE__, __LINE__, "ds",
951 con->fd,
952 "handle write failed.");
956 if (con->state == CON_STATE_CLOSE) {
957 /* flush the read buffers */
958 connection_read_for_eos(srv, con);
962 /* attempt (above) to read data in kernel socket buffers
963 * prior to handling FDEVENT_HUP and FDEVENT_ERR */
965 if ((revents & ~(FDEVENT_IN | FDEVENT_OUT)) && con->state != CON_STATE_ERROR) {
966 if (con->state == CON_STATE_CLOSE) {
967 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
968 } else if (revents & FDEVENT_HUP) {
969 if (fdevent_is_tcp_half_closed(con->fd)) {
970 con->keep_alive = 0;
971 } else {
972 connection_set_state(srv, con, CON_STATE_ERROR);
974 } else if (revents & FDEVENT_ERR) { /* error, connection reset */
975 connection_set_state(srv, con, CON_STATE_ERROR);
976 } else {
977 log_error_write(srv, __FILE__, __LINE__, "sd",
978 "connection closed: poll() -> ???", revents);
982 return HANDLER_FINISHED;
986 connection *connection_accept(server *srv, server_socket *srv_socket) {
987 /* accept everything */
989 /* search an empty place */
990 int cnt;
991 sock_addr cnt_addr;
992 socklen_t cnt_len;
993 /* accept it and register the fd */
996 * check if we can still open a new connections
998 * see #1216
1001 if (srv->conns->used >= srv->max_conns) {
1002 return NULL;
1005 cnt_len = sizeof(cnt_addr);
1007 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1008 #if defined(__NetBSD__)
1009 cnt = paccept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);
1010 #else
1011 cnt = accept4(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len, SOCK_CLOEXEC | SOCK_NONBLOCK);
1012 #endif
1013 #else
1014 cnt = accept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len);
1015 #endif
1016 if (-1 == cnt) {
1017 switch (errno) {
1018 case EAGAIN:
1019 #if EWOULDBLOCK != EAGAIN
1020 case EWOULDBLOCK:
1021 #endif
1022 case EINTR:
1023 /* we were stopped _before_ we had a connection */
1024 case ECONNABORTED: /* this is a FreeBSD thingy */
1025 /* we were stopped _after_ we had a connection */
1026 break;
1027 case EMFILE:
1028 /* out of fds */
1029 break;
1030 default:
1031 log_error_write(srv, __FILE__, __LINE__, "ssd", "accept failed:", strerror(errno), errno);
1033 return NULL;
1034 } else {
1035 if (cnt_addr.plain.sa_family != AF_UNIX) {
1036 network_accept_tcp_nagle_disable(cnt);
1038 return connection_accepted(srv, srv_socket, &cnt_addr, cnt);
1042 connection *connection_accepted(server *srv, server_socket *srv_socket, sock_addr *cnt_addr, int cnt) {
1043 connection *con;
1045 srv->cur_fds++;
1047 /* ok, we have the connection, register it */
1048 #if 0
1049 log_error_write(srv, __FILE__, __LINE__, "sd",
1050 "appected()", cnt);
1051 #endif
1052 srv->con_opened++;
1054 con = connections_get_new_connection(srv);
1056 con->fd = cnt;
1057 con->fde_ndx = -1;
1058 fdevent_register(srv->ev, con->fd, connection_handle_fdevent, con);
1060 connection_set_state(srv, con, CON_STATE_REQUEST_START);
1062 con->connection_start = srv->cur_ts;
1063 con->dst_addr = *cnt_addr;
1064 buffer_copy_string(con->dst_addr_buf, inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
1065 con->srv_socket = srv_socket;
1067 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv->ev, con->fd)) {
1068 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
1069 connection_close(srv, con);
1070 return NULL;
1072 #ifdef USE_OPENSSL
1073 /* connect FD to SSL */
1074 if (srv_socket->is_ssl) {
1075 if (NULL == (con->ssl = SSL_new(srv_socket->ssl_ctx))) {
1076 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1077 ERR_error_string(ERR_get_error(), NULL));
1079 connection_close(srv, con);
1080 return NULL;
1083 con->renegotiations = 0;
1084 SSL_set_app_data(con->ssl, con);
1085 SSL_set_accept_state(con->ssl);
1087 if (1 != (SSL_set_fd(con->ssl, cnt))) {
1088 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1089 ERR_error_string(ERR_get_error(), NULL));
1090 connection_close(srv, con);
1091 return NULL;
1094 #endif
1095 return con;
1099 int connection_state_machine(server *srv, connection *con) {
1100 int done = 0, r;
1102 if (srv->srvconf.log_state_handling) {
1103 log_error_write(srv, __FILE__, __LINE__, "sds",
1104 "state at start",
1105 con->fd,
1106 connection_get_state(con->state));
1109 while (done == 0) {
1110 size_t ostate = con->state;
1112 if (srv->srvconf.log_state_handling) {
1113 log_error_write(srv, __FILE__, __LINE__, "sds",
1114 "state for fd", con->fd, connection_get_state(con->state));
1117 switch (con->state) {
1118 case CON_STATE_REQUEST_START: /* transient */
1119 con->request_start = srv->cur_ts;
1120 con->read_idle_ts = srv->cur_ts;
1121 if (con->conf.high_precision_timestamps)
1122 log_clock_gettime_realtime(&con->request_start_hp);
1124 con->request_count++;
1125 con->loops_per_request = 0;
1127 connection_set_state(srv, con, CON_STATE_READ);
1129 break;
1130 case CON_STATE_REQUEST_END: /* transient */
1131 buffer_reset(con->uri.authority);
1132 buffer_reset(con->uri.path);
1133 buffer_reset(con->uri.query);
1134 buffer_reset(con->request.orig_uri);
1136 if (http_request_parse(srv, con)) {
1137 /* we have to read some data from the POST request */
1139 connection_set_state(srv, con, CON_STATE_READ_POST);
1141 break;
1144 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
1146 break;
1147 case CON_STATE_READ_POST:
1148 case CON_STATE_HANDLE_REQUEST:
1150 * the request is parsed
1152 * decided what to do with the request
1158 switch (r = http_response_prepare(srv, con)) {
1159 case HANDLER_WAIT_FOR_EVENT:
1160 if (!con->file_finished && (!con->file_started || 0 == con->conf.stream_response_body)) {
1161 break; /* come back here */
1163 /* response headers received from backend; fall through to start response */
1164 case HANDLER_FINISHED:
1165 if (con->error_handler_saved_status > 0) {
1166 con->request.http_method = con->error_handler_saved_method;
1168 if (con->mode == DIRECT) {
1169 if (con->error_handler_saved_status) {
1170 if (con->error_handler_saved_status > 0) {
1171 con->http_status = con->error_handler_saved_status;
1172 } else if (con->http_status == 404 || con->http_status == 403) {
1173 /* error-handler-404 is a 404 */
1174 con->http_status = -con->error_handler_saved_status;
1175 } else {
1176 /* error-handler-404 is back and has generated content */
1177 /* if Status: was set, take it otherwise use 200 */
1179 } else if (con->http_status >= 400) {
1180 buffer *error_handler = NULL;
1181 if (!buffer_string_is_empty(con->conf.error_handler)) {
1182 error_handler = con->conf.error_handler;
1183 } else if ((con->http_status == 404 || con->http_status == 403)
1184 && !buffer_string_is_empty(con->conf.error_handler_404)) {
1185 error_handler = con->conf.error_handler_404;
1188 if (error_handler) {
1189 /* call error-handler */
1191 /* set REDIRECT_STATUS to save current HTTP status code
1192 * for access by dynamic handlers
1193 * https://redmine.lighttpd.net/issues/1828 */
1194 data_string *ds;
1195 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
1196 ds = data_string_init();
1198 buffer_copy_string_len(ds->key, CONST_STR_LEN("REDIRECT_STATUS"));
1199 buffer_append_int(ds->value, con->http_status);
1200 array_insert_unique(con->environment, (data_unset *)ds);
1202 if (error_handler == con->conf.error_handler) {
1203 plugins_call_connection_reset(srv, con);
1205 if (con->request.content_length) {
1206 if (con->request.content_length != con->request_content_queue->bytes_in) {
1207 con->keep_alive = 0;
1209 con->request.content_length = 0;
1210 chunkqueue_reset(con->request_content_queue);
1213 con->is_writable = 1;
1214 con->file_finished = 0;
1215 con->file_started = 0;
1216 con->got_response = 0;
1217 con->parsed_response = 0;
1218 con->response.keep_alive = 0;
1219 con->response.content_length = -1;
1220 con->response.transfer_encoding = 0;
1222 con->error_handler_saved_status = con->http_status;
1223 con->error_handler_saved_method = con->request.http_method;
1225 con->request.http_method = HTTP_METHOD_GET;
1226 } else { /*(preserve behavior for server.error-handler-404)*/
1227 con->error_handler_saved_status = -con->http_status; /*(negative to flag old behavior)*/
1230 buffer_copy_buffer(con->request.uri, error_handler);
1231 connection_handle_errdoc_init(srv, con);
1232 con->http_status = 0; /*(after connection_handle_errdoc_init())*/
1234 done = -1;
1235 break;
1239 if (con->http_status == 0) con->http_status = 200;
1241 /* we have something to send, go on */
1242 connection_set_state(srv, con, CON_STATE_RESPONSE_START);
1243 break;
1244 case HANDLER_WAIT_FOR_FD:
1245 srv->want_fds++;
1247 fdwaitqueue_append(srv, con);
1249 break;
1250 case HANDLER_COMEBACK:
1251 done = -1;
1252 break;
1253 case HANDLER_ERROR:
1254 /* something went wrong */
1255 connection_set_state(srv, con, CON_STATE_ERROR);
1256 break;
1257 default:
1258 log_error_write(srv, __FILE__, __LINE__, "sdd", "unknown ret-value: ", con->fd, r);
1259 break;
1262 if (con->state == CON_STATE_HANDLE_REQUEST && ostate == CON_STATE_READ_POST) {
1263 ostate = CON_STATE_HANDLE_REQUEST;
1265 break;
1266 case CON_STATE_RESPONSE_START:
1268 * the decision is done
1269 * - create the HTTP-Response-Header
1273 if (-1 == connection_handle_write_prepare(srv, con)) {
1274 connection_set_state(srv, con, CON_STATE_ERROR);
1276 break;
1279 connection_set_state(srv, con, CON_STATE_WRITE);
1280 break;
1281 case CON_STATE_RESPONSE_END: /* transient */
1282 case CON_STATE_ERROR: /* transient */
1283 connection_handle_response_end_state(srv, con);
1284 break;
1285 case CON_STATE_CONNECT:
1286 chunkqueue_reset(con->read_queue);
1288 con->request_count = 0;
1290 break;
1291 case CON_STATE_CLOSE:
1292 connection_handle_close_state(srv, con);
1293 break;
1294 case CON_STATE_READ:
1295 connection_handle_read_state(srv, con);
1296 break;
1297 case CON_STATE_WRITE:
1298 do {
1299 /* only try to write if we have something in the queue */
1300 if (!chunkqueue_is_empty(con->write_queue)) {
1301 if (con->is_writable) {
1302 if (-1 == connection_handle_write(srv, con)) {
1303 log_error_write(srv, __FILE__, __LINE__, "ds",
1304 con->fd,
1305 "handle write failed.");
1306 connection_set_state(srv, con, CON_STATE_ERROR);
1307 break;
1309 if (con->state != CON_STATE_WRITE) break;
1311 } else if (con->file_finished) {
1312 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
1313 break;
1316 if (con->mode != DIRECT && !con->file_finished) {
1317 switch(r = plugins_call_handle_subrequest(srv, con)) {
1318 case HANDLER_WAIT_FOR_EVENT:
1319 case HANDLER_FINISHED:
1320 case HANDLER_GO_ON:
1321 break;
1322 case HANDLER_WAIT_FOR_FD:
1323 srv->want_fds++;
1324 fdwaitqueue_append(srv, con);
1325 break;
1326 case HANDLER_COMEBACK:
1327 default:
1328 log_error_write(srv, __FILE__, __LINE__, "sdd", "unexpected subrequest handler ret-value: ", con->fd, r);
1329 /* fall through */
1330 case HANDLER_ERROR:
1331 connection_set_state(srv, con, CON_STATE_ERROR);
1332 break;
1335 } while (con->state == CON_STATE_WRITE && (!chunkqueue_is_empty(con->write_queue) ? con->is_writable : con->file_finished));
1337 break;
1338 default:
1339 log_error_write(srv, __FILE__, __LINE__, "sdd",
1340 "unknown state:", con->fd, con->state);
1342 break;
1345 if (done == -1) {
1346 done = 0;
1347 } else if (ostate == con->state) {
1348 done = 1;
1352 if (srv->srvconf.log_state_handling) {
1353 log_error_write(srv, __FILE__, __LINE__, "sds",
1354 "state at exit:",
1355 con->fd,
1356 connection_get_state(con->state));
1359 r = 0;
1360 switch(con->state) {
1361 case CON_STATE_READ:
1362 case CON_STATE_CLOSE:
1363 r = FDEVENT_IN;
1364 break;
1365 case CON_STATE_WRITE:
1366 /* request write-fdevent only if we really need it
1367 * - if we have data to write
1368 * - if the socket is not writable yet
1370 if (!chunkqueue_is_empty(con->write_queue) &&
1371 (con->is_writable == 0) &&
1372 (con->traffic_limit_reached == 0)) {
1373 r |= FDEVENT_OUT;
1375 /* fall through */
1376 case CON_STATE_READ_POST:
1377 if (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN) {
1378 r |= FDEVENT_IN;
1380 break;
1381 default:
1382 break;
1384 if (-1 != con->fd) {
1385 const int events = fdevent_event_get_interest(srv->ev, con->fd);
1386 if (con->is_readable < 0) {
1387 con->is_readable = 0;
1388 r |= FDEVENT_IN;
1390 if (con->is_writable < 0) {
1391 con->is_writable = 0;
1392 r |= FDEVENT_OUT;
1394 if (r != events) {
1395 /* update timestamps when enabling interest in events */
1396 if ((r & FDEVENT_IN) && !(events & FDEVENT_IN)) {
1397 con->read_idle_ts = srv->cur_ts;
1399 if ((r & FDEVENT_OUT) && !(events & FDEVENT_OUT)) {
1400 con->write_request_ts = srv->cur_ts;
1402 fdevent_event_set(srv->ev, &con->fde_ndx, con->fd, r);
1406 return 0;