[core] set REDIRECT_STATUS to error_handler_saved_status (fixes #1828)
[lighttpd.git] / src / connections.c
blob2cd730f5cc6d9df1546f528cd9bbb88e3892bf56
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 #endif
126 #ifdef USE_OPENSSL
127 if (srv_sock->is_ssl) {
128 if (con->ssl) SSL_free(con->ssl);
129 con->ssl = NULL;
131 #endif
133 fdevent_event_del(srv->ev, &(con->fde_ndx), con->fd);
134 fdevent_unregister(srv->ev, con->fd);
135 #ifdef __WIN32
136 if (closesocket(con->fd)) {
137 log_error_write(srv, __FILE__, __LINE__, "sds",
138 "(warning) close:", con->fd, strerror(errno));
140 #else
141 if (close(con->fd)) {
142 log_error_write(srv, __FILE__, __LINE__, "sds",
143 "(warning) close:", con->fd, strerror(errno));
145 #endif
146 con->fd = -1;
148 srv->cur_fds--;
149 #if 0
150 log_error_write(srv, __FILE__, __LINE__, "sd",
151 "closed()", con->fd);
152 #endif
154 connection_del(srv, con);
155 connection_set_state(srv, con, CON_STATE_CONNECT);
157 return 0;
160 static void connection_handle_errdoc_init(connection *con) {
161 /* reset caching response headers potentially added by mod_expire */
162 data_string *ds;
163 if (NULL != (ds = (data_string*) array_get_element(con->response.headers, "Expires"))) {
164 buffer_reset(ds->value); /* Headers with empty values are ignored for output */
166 if (NULL != (ds = (data_string*) array_get_element(con->response.headers, "Cache-Control"))) {
167 buffer_reset(ds->value); /* Headers with empty values are ignored for output */
171 static int connection_handle_write_prepare(server *srv, connection *con) {
172 if (con->mode == DIRECT) {
173 /* static files */
174 switch(con->request.http_method) {
175 case HTTP_METHOD_GET:
176 case HTTP_METHOD_POST:
177 case HTTP_METHOD_HEAD:
178 break;
179 case HTTP_METHOD_OPTIONS:
181 * 400 is coming from the request-parser BEFORE uri.path is set
182 * 403 is from the response handler when noone else catched it
184 * */
185 if ((!con->http_status || con->http_status == 200) && !buffer_string_is_empty(con->uri.path) &&
186 con->uri.path->ptr[0] != '*') {
187 response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST"));
189 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
190 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
192 con->http_status = 200;
193 con->file_finished = 1;
195 chunkqueue_reset(con->write_queue);
197 break;
198 default:
199 if (0 == con->http_status) {
200 con->http_status = 501;
202 break;
206 if (con->http_status == 0) {
207 con->http_status = 403;
210 switch(con->http_status) {
211 case 204: /* class: header only */
212 case 205:
213 case 304:
214 /* disable chunked encoding again as we have no body */
215 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
216 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
217 chunkqueue_reset(con->write_queue);
219 con->file_finished = 1;
220 break;
221 default: /* class: header + body */
222 if (con->mode != DIRECT) break;
224 /* only custom body for 4xx and 5xx */
225 if (con->http_status < 400 || con->http_status >= 600) break;
227 con->file_finished = 0;
229 buffer_reset(con->physical.path);
230 connection_handle_errdoc_init(con);
232 /* try to send static errorfile */
233 if (!buffer_string_is_empty(con->conf.errorfile_prefix)) {
234 stat_cache_entry *sce = NULL;
236 buffer_copy_buffer(con->physical.path, con->conf.errorfile_prefix);
237 buffer_append_int(con->physical.path, con->http_status);
238 buffer_append_string_len(con->physical.path, CONST_STR_LEN(".html"));
240 if (0 == http_chunk_append_file(srv, con, con->physical.path)) {
241 con->file_finished = 1;
242 if (HANDLER_ERROR != stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
243 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce->content_type));
248 if (!con->file_finished) {
249 buffer *b;
251 buffer_reset(con->physical.path);
253 con->file_finished = 1;
254 b = buffer_init();
256 /* build default error-page */
257 buffer_copy_string_len(b, CONST_STR_LEN(
258 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
259 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
260 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
261 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
262 " <head>\n"
263 " <title>"));
264 buffer_append_int(b, con->http_status);
265 buffer_append_string_len(b, CONST_STR_LEN(" - "));
266 buffer_append_string(b, get_http_status_name(con->http_status));
268 buffer_append_string_len(b, CONST_STR_LEN(
269 "</title>\n"
270 " </head>\n"
271 " <body>\n"
272 " <h1>"));
273 buffer_append_int(b, con->http_status);
274 buffer_append_string_len(b, CONST_STR_LEN(" - "));
275 buffer_append_string(b, get_http_status_name(con->http_status));
277 buffer_append_string_len(b, CONST_STR_LEN("</h1>\n"
278 " </body>\n"
279 "</html>\n"
282 http_chunk_append_buffer(srv, con, b);
283 buffer_free(b);
284 http_chunk_close(srv, con);
286 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
288 break;
291 if (con->file_finished) {
292 /* we have all the content and chunked encoding is not used, set a content-length */
294 if ((!(con->parsed_response & HTTP_CONTENT_LENGTH)) &&
295 (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0) {
296 off_t qlen = chunkqueue_length(con->write_queue);
299 * The Content-Length header only can be sent if we have content:
300 * - HEAD doesn't have a content-body (but have a content-length)
301 * - 1xx, 204 and 304 don't have a content-body (RFC 2616 Section 4.3)
303 * Otherwise generate a Content-Length header as chunked encoding is not
304 * available
306 if ((con->http_status >= 100 && con->http_status < 200) ||
307 con->http_status == 204 ||
308 con->http_status == 304) {
309 data_string *ds;
310 /* no Content-Body, no Content-Length */
311 if (NULL != (ds = (data_string*) array_get_element(con->response.headers, "Content-Length"))) {
312 buffer_reset(ds->value); /* Headers with empty values are ignored for output */
314 } else if (qlen > 0 || con->request.http_method != HTTP_METHOD_HEAD) {
315 /* qlen = 0 is important for Redirects (301, ...) as they MAY have
316 * a content. Browsers are waiting for a Content otherwise
318 buffer_copy_int(srv->tmp_buf, qlen);
320 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Length"), CONST_BUF_LEN(srv->tmp_buf));
323 } else {
325 * the file isn't finished yet, but we have all headers
327 * to get keep-alive we either need:
328 * - Content-Length: ... (HTTP/1.0 and HTTP/1.0) or
329 * - Transfer-Encoding: chunked (HTTP/1.1)
332 if (((con->parsed_response & HTTP_CONTENT_LENGTH) == 0) &&
333 ((con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0)) {
334 con->keep_alive = 0;
338 * if the backend sent a Connection: close, follow the wish
340 * NOTE: if the backend sent Connection: Keep-Alive, but no Content-Length, we
341 * will close the connection. That's fine. We can always decide the close
342 * the connection
344 * FIXME: to be nice we should remove the Connection: ...
346 if (con->parsed_response & HTTP_CONNECTION) {
347 /* a subrequest disable keep-alive although the client wanted it */
348 if (con->keep_alive && !con->response.keep_alive) {
349 con->keep_alive = 0;
354 if (con->request.content_length
355 && (off_t)con->request.content_length > con->request_content_queue->bytes_in) {
356 /* request body is present and has not been read completely */
357 con->keep_alive = 0;
360 if (con->request.http_method == HTTP_METHOD_HEAD) {
362 * a HEAD request has the same as a GET
363 * without the content
365 con->file_finished = 1;
367 chunkqueue_reset(con->write_queue);
368 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
371 http_response_write_header(srv, con);
373 return 0;
376 static int connection_handle_write(server *srv, connection *con) {
377 switch(network_write_chunkqueue(srv, con, con->write_queue, MAX_WRITE_LIMIT)) {
378 case 0:
379 con->write_request_ts = srv->cur_ts;
380 if (con->file_finished) {
381 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
382 joblist_append(srv, con);
384 break;
385 case -1: /* error on our side */
386 log_error_write(srv, __FILE__, __LINE__, "sd",
387 "connection closed: write failed on fd", con->fd);
388 connection_set_state(srv, con, CON_STATE_ERROR);
389 joblist_append(srv, con);
390 break;
391 case -2: /* remote close */
392 connection_set_state(srv, con, CON_STATE_ERROR);
393 joblist_append(srv, con);
394 break;
395 case 1:
396 con->write_request_ts = srv->cur_ts;
397 con->is_writable = 0;
399 /* not finished yet -> WRITE */
400 break;
403 return 0;
408 connection *connection_init(server *srv) {
409 connection *con;
411 UNUSED(srv);
413 con = calloc(1, sizeof(*con));
414 force_assert(NULL != con);
416 con->fd = 0;
417 con->ndx = -1;
418 con->fde_ndx = -1;
419 con->bytes_written = 0;
420 con->bytes_read = 0;
421 con->bytes_header = 0;
422 con->loops_per_request = 0;
424 #define CLEAN(x) \
425 con->x = buffer_init();
427 CLEAN(request.uri);
428 CLEAN(request.request_line);
429 CLEAN(request.request);
430 CLEAN(request.pathinfo);
432 CLEAN(request.orig_uri);
434 CLEAN(uri.scheme);
435 CLEAN(uri.authority);
436 CLEAN(uri.path);
437 CLEAN(uri.path_raw);
438 CLEAN(uri.query);
440 CLEAN(physical.doc_root);
441 CLEAN(physical.path);
442 CLEAN(physical.basedir);
443 CLEAN(physical.rel_path);
444 CLEAN(physical.etag);
445 CLEAN(parse_request);
447 CLEAN(server_name);
448 CLEAN(error_handler);
449 CLEAN(dst_addr_buf);
450 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
451 CLEAN(tlsext_server_name);
452 #endif
454 #undef CLEAN
455 con->write_queue = chunkqueue_init();
456 con->read_queue = chunkqueue_init();
457 con->request_content_queue = chunkqueue_init();
458 chunkqueue_set_tempdirs(
459 con->request_content_queue,
460 srv->srvconf.upload_tempdirs,
461 srv->srvconf.upload_temp_file_size);
463 con->request.headers = array_init();
464 con->response.headers = array_init();
465 con->environment = array_init();
467 /* init plugin specific connection structures */
469 con->plugin_ctx = calloc(1, (srv->plugins.used + 1) * sizeof(void *));
470 force_assert(NULL != con->plugin_ctx);
472 con->cond_cache = calloc(srv->config_context->used, sizeof(cond_cache_t));
473 force_assert(NULL != con->cond_cache);
474 config_setup_connection(srv, con);
476 return con;
479 void connections_free(server *srv) {
480 connections *conns = srv->conns;
481 size_t i;
483 for (i = 0; i < conns->size; i++) {
484 connection *con = conns->ptr[i];
486 connection_reset(srv, con);
488 chunkqueue_free(con->write_queue);
489 chunkqueue_free(con->read_queue);
490 chunkqueue_free(con->request_content_queue);
491 array_free(con->request.headers);
492 array_free(con->response.headers);
493 array_free(con->environment);
495 #define CLEAN(x) \
496 buffer_free(con->x);
498 CLEAN(request.uri);
499 CLEAN(request.request_line);
500 CLEAN(request.request);
501 CLEAN(request.pathinfo);
503 CLEAN(request.orig_uri);
505 CLEAN(uri.scheme);
506 CLEAN(uri.authority);
507 CLEAN(uri.path);
508 CLEAN(uri.path_raw);
509 CLEAN(uri.query);
511 CLEAN(physical.doc_root);
512 CLEAN(physical.path);
513 CLEAN(physical.basedir);
514 CLEAN(physical.etag);
515 CLEAN(physical.rel_path);
516 CLEAN(parse_request);
518 CLEAN(server_name);
519 CLEAN(error_handler);
520 CLEAN(dst_addr_buf);
521 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
522 CLEAN(tlsext_server_name);
523 #endif
524 #undef CLEAN
525 free(con->plugin_ctx);
526 free(con->cond_cache);
528 free(con);
531 free(conns->ptr);
535 int connection_reset(server *srv, connection *con) {
536 size_t i;
538 plugins_call_connection_reset(srv, con);
540 con->is_readable = 1;
541 con->is_writable = 1;
542 con->http_status = 0;
543 con->file_finished = 0;
544 con->file_started = 0;
545 con->got_response = 0;
547 con->parsed_response = 0;
549 con->bytes_written = 0;
550 con->bytes_written_cur_second = 0;
551 con->bytes_read = 0;
552 con->bytes_header = 0;
553 con->loops_per_request = 0;
555 con->request.http_method = HTTP_METHOD_UNSET;
556 con->request.http_version = HTTP_VERSION_UNSET;
558 con->request.http_if_modified_since = NULL;
559 con->request.http_if_none_match = NULL;
561 con->response.keep_alive = 0;
562 con->response.content_length = -1;
563 con->response.transfer_encoding = 0;
565 con->mode = DIRECT;
567 #define CLEAN(x) \
568 if (con->x) buffer_reset(con->x);
570 CLEAN(request.uri);
571 CLEAN(request.request_line);
572 CLEAN(request.pathinfo);
573 CLEAN(request.request);
575 /* CLEAN(request.orig_uri); */
577 CLEAN(uri.scheme);
578 /* CLEAN(uri.authority); */
579 /* CLEAN(uri.path); */
580 CLEAN(uri.path_raw);
581 /* CLEAN(uri.query); */
583 CLEAN(physical.doc_root);
584 CLEAN(physical.path);
585 CLEAN(physical.basedir);
586 CLEAN(physical.rel_path);
587 CLEAN(physical.etag);
589 CLEAN(parse_request);
591 CLEAN(server_name);
592 CLEAN(error_handler);
593 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
594 CLEAN(tlsext_server_name);
595 #endif
596 #undef CLEAN
598 #define CLEAN(x) \
599 if (con->x) con->x->used = 0;
601 #undef CLEAN
603 #define CLEAN(x) \
604 con->request.x = NULL;
606 CLEAN(http_host);
607 CLEAN(http_range);
608 CLEAN(http_content_type);
609 #undef CLEAN
610 con->request.content_length = 0;
612 array_reset(con->request.headers);
613 array_reset(con->response.headers);
614 array_reset(con->environment);
616 chunkqueue_reset(con->write_queue);
617 chunkqueue_reset(con->request_content_queue);
619 /* the plugins should cleanup themself */
620 for (i = 0; i < srv->plugins.used; i++) {
621 plugin *p = ((plugin **)(srv->plugins.ptr))[i];
622 plugin_data *pd = p->data;
624 if (!pd) continue;
626 if (con->plugin_ctx[pd->id] != NULL) {
627 log_error_write(srv, __FILE__, __LINE__, "sb", "missing cleanup in", p->name);
630 con->plugin_ctx[pd->id] = NULL;
633 /* The cond_cache gets reset in response.c */
634 /* config_cond_cache_reset(srv, con); */
636 con->header_len = 0;
637 con->in_error_handler = 0;
638 con->error_handler_saved_status = 0;
640 config_setup_connection(srv, con);
642 return 0;
646 * handle all header and content read
648 * we get called by the state-engine and by the fdevent-handler
650 static int connection_handle_read_state(server *srv, connection *con) {
651 chunk *c, *last_chunk;
652 off_t last_offset;
653 chunkqueue *cq = con->read_queue;
654 int is_closed = 0; /* the connection got closed, if we don't have a complete header, -> error */
655 /* when in CON_STATE_READ: about to receive first byte for a request: */
656 int is_request_start = chunkqueue_is_empty(cq);
658 if (con->is_readable) {
659 con->read_idle_ts = srv->cur_ts;
661 switch(connection_handle_read(srv, con)) {
662 case -1:
663 return -1;
664 case -2:
665 is_closed = 1;
666 break;
667 default:
668 break;
672 chunkqueue_remove_finished_chunks(cq);
674 /* we might have got several packets at once
677 /* update request_start timestamp when first byte of
678 * next request is received on a keep-alive connection */
679 if (con->request_count > 1 && is_request_start) con->request_start = srv->cur_ts;
681 /* if there is a \r\n\r\n in the chunkqueue
683 * scan the chunk-queue twice
684 * 1. to find the \r\n\r\n
685 * 2. to copy the header-packet
689 last_chunk = NULL;
690 last_offset = 0;
692 for (c = cq->first; c; c = c->next) {
693 size_t i;
694 size_t len = buffer_string_length(c->mem) - c->offset;
695 const char *b = c->mem->ptr + c->offset;
697 for (i = 0; i < len; ++i) {
698 char ch = b[i];
700 if ('\r' == ch) {
701 /* chec if \n\r\n follows */
702 size_t j = i+1;
703 chunk *cc = c;
704 const char header_end[] = "\r\n\r\n";
705 int header_end_match_pos = 1;
707 for ( ; cc; cc = cc->next, j = 0 ) {
708 size_t bblen = buffer_string_length(cc->mem) - cc->offset;
709 const char *bb = cc->mem->ptr + cc->offset;
711 for ( ; j < bblen; j++) {
712 ch = bb[j];
714 if (ch == header_end[header_end_match_pos]) {
715 header_end_match_pos++;
716 if (4 == header_end_match_pos) {
717 last_chunk = cc;
718 last_offset = j+1;
719 goto found_header_end;
721 } else {
722 goto reset_search;
727 reset_search: ;
730 found_header_end:
732 /* found */
733 if (last_chunk) {
734 buffer_reset(con->request.request);
736 for (c = cq->first; c; c = c->next) {
737 size_t len = buffer_string_length(c->mem) - c->offset;
739 if (c == last_chunk) {
740 len = last_offset;
743 buffer_append_string_len(con->request.request, c->mem->ptr + c->offset, len);
744 c->offset += len;
745 cq->bytes_out += len;
747 if (c == last_chunk) break;
750 connection_set_state(srv, con, CON_STATE_REQUEST_END);
751 } else if (chunkqueue_length(cq) > 64 * 1024) {
752 log_error_write(srv, __FILE__, __LINE__, "s", "oversized request-header -> sending Status 414");
754 con->http_status = 414; /* Request-URI too large */
755 con->keep_alive = 0;
756 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
757 } else if (is_closed) {
758 /* the connection got closed and we didn't got enough data to leave CON_STATE_READ;
759 * the only way is to leave here */
760 connection_set_state(srv, con, CON_STATE_ERROR);
763 chunkqueue_remove_finished_chunks(cq);
765 return 0;
768 static handler_t connection_handle_fdevent(server *srv, void *context, int revents) {
769 connection *con = context;
771 joblist_append(srv, con);
773 if (con->srv_socket->is_ssl) {
774 /* ssl may read and write for both reads and writes */
775 if (revents & (FDEVENT_IN | FDEVENT_OUT)) {
776 con->is_readable = 1;
777 con->is_writable = 1;
779 } else {
780 if (revents & FDEVENT_IN) {
781 con->is_readable = 1;
783 if (revents & FDEVENT_OUT) {
784 con->is_writable = 1;
785 /* we don't need the event twice */
790 if (revents & ~(FDEVENT_IN | FDEVENT_OUT)) {
791 /* looks like an error */
793 /* FIXME: revents = 0x19 still means that we should read from the queue */
794 if (revents & FDEVENT_HUP) {
795 if (con->state == CON_STATE_CLOSE) {
796 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
797 } else {
798 /* sigio reports the wrong event here
800 * there was no HUP at all
802 #ifdef USE_LINUX_SIGIO
803 if (srv->ev->in_sigio == 1) {
804 log_error_write(srv, __FILE__, __LINE__, "sd",
805 "connection closed: poll() -> HUP", con->fd);
806 } else {
807 connection_set_state(srv, con, CON_STATE_ERROR);
809 #else
810 connection_set_state(srv, con, CON_STATE_ERROR);
811 #endif
814 } else if (revents & FDEVENT_ERR) {
815 /* error, connection reset, whatever... we don't want to spam the logfile */
816 #if 0
817 log_error_write(srv, __FILE__, __LINE__, "sd",
818 "connection closed: poll() -> ERR", con->fd);
819 #endif
820 connection_set_state(srv, con, CON_STATE_ERROR);
821 } else {
822 log_error_write(srv, __FILE__, __LINE__, "sd",
823 "connection closed: poll() -> ???", revents);
827 if (con->state == CON_STATE_READ) {
828 connection_handle_read_state(srv, con);
831 if (con->state == CON_STATE_WRITE &&
832 !chunkqueue_is_empty(con->write_queue) &&
833 con->is_writable) {
835 if (-1 == connection_handle_write(srv, con)) {
836 connection_set_state(srv, con, CON_STATE_ERROR);
838 log_error_write(srv, __FILE__, __LINE__, "ds",
839 con->fd,
840 "handle write failed.");
844 if (con->state == CON_STATE_CLOSE) {
845 /* flush the read buffers */
846 int len;
847 char buf[1024];
849 len = read(con->fd, buf, sizeof(buf));
850 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
851 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
855 return HANDLER_FINISHED;
859 connection *connection_accept(server *srv, server_socket *srv_socket) {
860 /* accept everything */
862 /* search an empty place */
863 int cnt;
864 sock_addr cnt_addr;
865 socklen_t cnt_len;
866 /* accept it and register the fd */
869 * check if we can still open a new connections
871 * see #1216
874 if (srv->conns->used >= srv->max_conns) {
875 return NULL;
878 cnt_len = sizeof(cnt_addr);
880 if (-1 == (cnt = accept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len))) {
881 switch (errno) {
882 case EAGAIN:
883 #if EWOULDBLOCK != EAGAIN
884 case EWOULDBLOCK:
885 #endif
886 case EINTR:
887 /* we were stopped _before_ we had a connection */
888 case ECONNABORTED: /* this is a FreeBSD thingy */
889 /* we were stopped _after_ we had a connection */
890 break;
891 case EMFILE:
892 /* out of fds */
893 break;
894 default:
895 log_error_write(srv, __FILE__, __LINE__, "ssd", "accept failed:", strerror(errno), errno);
897 return NULL;
898 } else {
899 connection *con;
901 srv->cur_fds++;
903 /* ok, we have the connection, register it */
904 #if 0
905 log_error_write(srv, __FILE__, __LINE__, "sd",
906 "appected()", cnt);
907 #endif
908 srv->con_opened++;
910 con = connections_get_new_connection(srv);
912 con->fd = cnt;
913 con->fde_ndx = -1;
914 #if 0
915 gettimeofday(&(con->start_tv), NULL);
916 #endif
917 fdevent_register(srv->ev, con->fd, connection_handle_fdevent, con);
919 connection_set_state(srv, con, CON_STATE_REQUEST_START);
921 con->connection_start = srv->cur_ts;
922 con->dst_addr = cnt_addr;
923 buffer_copy_string(con->dst_addr_buf, inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
924 con->srv_socket = srv_socket;
926 if (-1 == (fdevent_fcntl_set(srv->ev, con->fd))) {
927 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
928 return NULL;
930 #ifdef USE_OPENSSL
931 /* connect FD to SSL */
932 if (srv_socket->is_ssl) {
933 if (NULL == (con->ssl = SSL_new(srv_socket->ssl_ctx))) {
934 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
935 ERR_error_string(ERR_get_error(), NULL));
937 return NULL;
940 con->renegotiations = 0;
941 SSL_set_app_data(con->ssl, con);
942 SSL_set_accept_state(con->ssl);
944 if (1 != (SSL_set_fd(con->ssl, cnt))) {
945 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
946 ERR_error_string(ERR_get_error(), NULL));
947 return NULL;
950 #endif
951 return con;
956 int connection_state_machine(server *srv, connection *con) {
957 int done = 0, r;
958 #ifdef USE_OPENSSL
959 server_socket *srv_sock = con->srv_socket;
960 #endif
962 if (srv->srvconf.log_state_handling) {
963 log_error_write(srv, __FILE__, __LINE__, "sds",
964 "state at start",
965 con->fd,
966 connection_get_state(con->state));
969 while (done == 0) {
970 size_t ostate = con->state;
972 switch (con->state) {
973 case CON_STATE_REQUEST_START: /* transient */
974 if (srv->srvconf.log_state_handling) {
975 log_error_write(srv, __FILE__, __LINE__, "sds",
976 "state for fd", con->fd, connection_get_state(con->state));
979 con->request_start = srv->cur_ts;
980 con->read_idle_ts = srv->cur_ts;
982 con->request_count++;
983 con->loops_per_request = 0;
985 connection_set_state(srv, con, CON_STATE_READ);
987 break;
988 case CON_STATE_REQUEST_END: /* transient */
989 if (srv->srvconf.log_state_handling) {
990 log_error_write(srv, __FILE__, __LINE__, "sds",
991 "state for fd", con->fd, connection_get_state(con->state));
994 buffer_reset(con->uri.authority);
995 buffer_reset(con->uri.path);
996 buffer_reset(con->uri.query);
997 buffer_reset(con->request.orig_uri);
999 if (http_request_parse(srv, con)) {
1000 /* we have to read some data from the POST request */
1002 connection_set_state(srv, con, CON_STATE_READ_POST);
1004 break;
1007 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
1009 break;
1010 case CON_STATE_READ_POST:
1011 case CON_STATE_HANDLE_REQUEST:
1013 * the request is parsed
1015 * decided what to do with the request
1021 if (srv->srvconf.log_state_handling) {
1022 log_error_write(srv, __FILE__, __LINE__, "sds",
1023 "state for fd", con->fd, connection_get_state(con->state));
1026 switch (r = http_response_prepare(srv, con)) {
1027 case HANDLER_FINISHED:
1028 if (con->mode == DIRECT) {
1029 if (con->http_status == 404 ||
1030 con->http_status == 403) {
1031 /* 404 error-handler */
1033 if (con->in_error_handler == 0 &&
1034 (!buffer_string_is_empty(con->conf.error_handler) ||
1035 !buffer_string_is_empty(con->error_handler))) {
1036 /* call error-handler */
1038 /* set REDIRECT_STATUS to save current HTTP status code
1039 * for access by dynamic handlers
1040 * https://redmine.lighttpd.net/issues/1828 */
1041 data_string *ds;
1042 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
1043 ds = data_string_init();
1045 buffer_copy_string_len(ds->key, CONST_STR_LEN("REDIRECT_STATUS"));
1046 buffer_append_int(ds->value, con->http_status);
1047 array_insert_unique(con->environment, (data_unset *)ds);
1049 con->error_handler_saved_status = con->http_status;
1050 con->http_status = 0;
1052 if (buffer_string_is_empty(con->error_handler)) {
1053 buffer_copy_buffer(con->request.uri, con->conf.error_handler);
1054 } else {
1055 buffer_copy_buffer(con->request.uri, con->error_handler);
1057 buffer_reset(con->physical.path);
1058 connection_handle_errdoc_init(con);
1060 con->in_error_handler = 1;
1062 done = -1;
1063 break;
1064 } else if (con->in_error_handler) {
1065 /* error-handler is a 404 */
1067 con->http_status = con->error_handler_saved_status;
1069 } else if (con->in_error_handler) {
1070 /* error-handler is back and has generated content */
1071 /* if Status: was set, take it otherwise use 200 */
1074 if (con->http_status == 0) con->http_status = 200;
1076 /* we have something to send, go on */
1077 connection_set_state(srv, con, CON_STATE_RESPONSE_START);
1078 break;
1079 case HANDLER_WAIT_FOR_FD:
1080 srv->want_fds++;
1082 fdwaitqueue_append(srv, con);
1084 break;
1085 case HANDLER_COMEBACK:
1086 done = -1;
1087 /* fallthrough */
1088 case HANDLER_WAIT_FOR_EVENT:
1089 /* come back here */
1090 break;
1091 case HANDLER_ERROR:
1092 /* something went wrong */
1093 connection_set_state(srv, con, CON_STATE_ERROR);
1094 break;
1095 default:
1096 log_error_write(srv, __FILE__, __LINE__, "sdd", "unknown ret-value: ", con->fd, r);
1097 break;
1100 break;
1101 case CON_STATE_RESPONSE_START:
1103 * the decision is done
1104 * - create the HTTP-Response-Header
1108 if (srv->srvconf.log_state_handling) {
1109 log_error_write(srv, __FILE__, __LINE__, "sds",
1110 "state for fd", con->fd, connection_get_state(con->state));
1113 if (-1 == connection_handle_write_prepare(srv, con)) {
1114 connection_set_state(srv, con, CON_STATE_ERROR);
1116 break;
1119 connection_set_state(srv, con, CON_STATE_WRITE);
1120 break;
1121 case CON_STATE_RESPONSE_END: /* transient */
1122 /* log the request */
1124 if (srv->srvconf.log_state_handling) {
1125 log_error_write(srv, __FILE__, __LINE__, "sds",
1126 "state for fd", con->fd, connection_get_state(con->state));
1129 plugins_call_handle_request_done(srv, con);
1131 srv->con_written++;
1133 if (con->keep_alive) {
1134 connection_set_state(srv, con, CON_STATE_REQUEST_START);
1136 #if 0
1137 con->request_start = srv->cur_ts;
1138 con->read_idle_ts = srv->cur_ts;
1139 #endif
1140 } else {
1141 switch(r = plugins_call_handle_connection_close(srv, con)) {
1142 case HANDLER_GO_ON:
1143 case HANDLER_FINISHED:
1144 break;
1145 default:
1146 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1147 break;
1150 #ifdef USE_OPENSSL
1151 if (srv_sock->is_ssl) {
1152 switch (SSL_shutdown(con->ssl)) {
1153 case 1:
1154 /* done */
1155 break;
1156 case 0:
1157 /* wait for fd-event
1159 * FIXME: wait for fdevent and call SSL_shutdown again
1163 break;
1164 default:
1165 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1166 ERR_error_string(ERR_get_error(), NULL));
1169 #endif
1170 if ((0 == shutdown(con->fd, SHUT_WR))) {
1171 con->close_timeout_ts = srv->cur_ts;
1172 connection_set_state(srv, con, CON_STATE_CLOSE);
1173 } else {
1174 connection_close(srv, con);
1177 srv->con_closed++;
1180 connection_reset(srv, con);
1182 break;
1183 case CON_STATE_CONNECT:
1184 if (srv->srvconf.log_state_handling) {
1185 log_error_write(srv, __FILE__, __LINE__, "sds",
1186 "state for fd", con->fd, connection_get_state(con->state));
1189 chunkqueue_reset(con->read_queue);
1191 con->request_count = 0;
1193 break;
1194 case CON_STATE_CLOSE:
1195 if (srv->srvconf.log_state_handling) {
1196 log_error_write(srv, __FILE__, __LINE__, "sds",
1197 "state for fd", con->fd, connection_get_state(con->state));
1200 /* we have to do the linger_on_close stuff regardless
1201 * of con->keep_alive; even non-keepalive sockets may
1202 * still have unread data, and closing before reading
1203 * it will make the client not see all our output.
1206 int len;
1207 char buf[1024];
1209 len = read(con->fd, buf, sizeof(buf));
1210 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
1211 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
1215 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1216 connection_close(srv, con);
1218 if (srv->srvconf.log_state_handling) {
1219 log_error_write(srv, __FILE__, __LINE__, "sd",
1220 "connection closed for fd", con->fd);
1224 break;
1225 case CON_STATE_READ:
1226 if (srv->srvconf.log_state_handling) {
1227 log_error_write(srv, __FILE__, __LINE__, "sds",
1228 "state for fd", con->fd, connection_get_state(con->state));
1231 connection_handle_read_state(srv, con);
1232 break;
1233 case CON_STATE_WRITE:
1234 if (srv->srvconf.log_state_handling) {
1235 log_error_write(srv, __FILE__, __LINE__, "sds",
1236 "state for fd", con->fd, connection_get_state(con->state));
1239 /* only try to write if we have something in the queue */
1240 if (!chunkqueue_is_empty(con->write_queue)) {
1241 if (con->is_writable) {
1242 if (-1 == connection_handle_write(srv, con)) {
1243 log_error_write(srv, __FILE__, __LINE__, "ds",
1244 con->fd,
1245 "handle write failed.");
1246 connection_set_state(srv, con, CON_STATE_ERROR);
1249 } else if (con->file_finished) {
1250 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
1253 break;
1254 case CON_STATE_ERROR: /* transient */
1256 /* even if the connection was drop we still have to write it to the access log */
1257 if (con->http_status) {
1258 plugins_call_handle_request_done(srv, con);
1260 #ifdef USE_OPENSSL
1261 if (srv_sock->is_ssl) {
1262 int ret, ssl_r;
1263 unsigned long err;
1264 ERR_clear_error();
1265 switch ((ret = SSL_shutdown(con->ssl))) {
1266 case 1:
1267 /* ok */
1268 break;
1269 case 0:
1270 ERR_clear_error();
1271 if (-1 != (ret = SSL_shutdown(con->ssl))) break;
1273 /* fall through */
1274 default:
1276 switch ((ssl_r = SSL_get_error(con->ssl, ret))) {
1277 case SSL_ERROR_WANT_WRITE:
1278 case SSL_ERROR_WANT_READ:
1279 break;
1280 case SSL_ERROR_SYSCALL:
1281 /* perhaps we have error waiting in our error-queue */
1282 if (0 != (err = ERR_get_error())) {
1283 do {
1284 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1285 ssl_r, ret,
1286 ERR_error_string(err, NULL));
1287 } while((err = ERR_get_error()));
1288 } else if (errno != 0) { /* ssl bug (see lighttpd ticket #2213): sometimes errno == 0 */
1289 switch(errno) {
1290 case EPIPE:
1291 case ECONNRESET:
1292 break;
1293 default:
1294 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL (error):",
1295 ssl_r, ret, errno,
1296 strerror(errno));
1297 break;
1301 break;
1302 default:
1303 while((err = ERR_get_error())) {
1304 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1305 ssl_r, ret,
1306 ERR_error_string(err, NULL));
1309 break;
1312 ERR_clear_error();
1314 #endif
1316 switch(con->mode) {
1317 case DIRECT:
1318 #if 0
1319 log_error_write(srv, __FILE__, __LINE__, "sd",
1320 "emergency exit: direct",
1321 con->fd);
1322 #endif
1323 break;
1324 default:
1325 switch(r = plugins_call_handle_connection_close(srv, con)) {
1326 case HANDLER_GO_ON:
1327 case HANDLER_FINISHED:
1328 break;
1329 default:
1330 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1331 break;
1333 break;
1336 connection_reset(srv, con);
1338 /* close the connection */
1339 if ((0 == shutdown(con->fd, SHUT_WR))) {
1340 con->close_timeout_ts = srv->cur_ts;
1341 connection_set_state(srv, con, CON_STATE_CLOSE);
1343 if (srv->srvconf.log_state_handling) {
1344 log_error_write(srv, __FILE__, __LINE__, "sd",
1345 "shutdown for fd", con->fd);
1347 } else {
1348 connection_close(srv, con);
1351 con->keep_alive = 0;
1353 srv->con_closed++;
1355 break;
1356 default:
1357 log_error_write(srv, __FILE__, __LINE__, "sdd",
1358 "unknown state:", con->fd, con->state);
1360 break;
1363 if (done == -1) {
1364 done = 0;
1365 } else if (ostate == con->state) {
1366 done = 1;
1370 if (srv->srvconf.log_state_handling) {
1371 log_error_write(srv, __FILE__, __LINE__, "sds",
1372 "state at exit:",
1373 con->fd,
1374 connection_get_state(con->state));
1377 switch(con->state) {
1378 case CON_STATE_READ_POST:
1379 case CON_STATE_READ:
1380 case CON_STATE_CLOSE:
1381 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, FDEVENT_IN);
1382 break;
1383 case CON_STATE_WRITE:
1384 /* request write-fdevent only if we really need it
1385 * - if we have data to write
1386 * - if the socket is not writable yet
1388 if (!chunkqueue_is_empty(con->write_queue) &&
1389 (con->is_writable == 0) &&
1390 (con->traffic_limit_reached == 0)) {
1391 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, FDEVENT_OUT);
1392 } else {
1393 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, 0);
1395 break;
1396 default:
1397 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, 0);
1398 break;
1401 return 0;