[core] server.error-handler new directive for error pages (fixes #2702)
[lighttpd.git] / src / connections.c
blobd9aaaebfbc926abce338753601db627a2737382d
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(dst_addr_buf);
449 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
450 CLEAN(tlsext_server_name);
451 #endif
453 #undef CLEAN
454 con->write_queue = chunkqueue_init();
455 con->read_queue = chunkqueue_init();
456 con->request_content_queue = chunkqueue_init();
457 chunkqueue_set_tempdirs(
458 con->request_content_queue,
459 srv->srvconf.upload_tempdirs,
460 srv->srvconf.upload_temp_file_size);
462 con->request.headers = array_init();
463 con->response.headers = array_init();
464 con->environment = array_init();
466 /* init plugin specific connection structures */
468 con->plugin_ctx = calloc(1, (srv->plugins.used + 1) * sizeof(void *));
469 force_assert(NULL != con->plugin_ctx);
471 con->cond_cache = calloc(srv->config_context->used, sizeof(cond_cache_t));
472 force_assert(NULL != con->cond_cache);
473 config_setup_connection(srv, con);
475 return con;
478 void connections_free(server *srv) {
479 connections *conns = srv->conns;
480 size_t i;
482 for (i = 0; i < conns->size; i++) {
483 connection *con = conns->ptr[i];
485 connection_reset(srv, con);
487 chunkqueue_free(con->write_queue);
488 chunkqueue_free(con->read_queue);
489 chunkqueue_free(con->request_content_queue);
490 array_free(con->request.headers);
491 array_free(con->response.headers);
492 array_free(con->environment);
494 #define CLEAN(x) \
495 buffer_free(con->x);
497 CLEAN(request.uri);
498 CLEAN(request.request_line);
499 CLEAN(request.request);
500 CLEAN(request.pathinfo);
502 CLEAN(request.orig_uri);
504 CLEAN(uri.scheme);
505 CLEAN(uri.authority);
506 CLEAN(uri.path);
507 CLEAN(uri.path_raw);
508 CLEAN(uri.query);
510 CLEAN(physical.doc_root);
511 CLEAN(physical.path);
512 CLEAN(physical.basedir);
513 CLEAN(physical.etag);
514 CLEAN(physical.rel_path);
515 CLEAN(parse_request);
517 CLEAN(server_name);
518 CLEAN(dst_addr_buf);
519 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
520 CLEAN(tlsext_server_name);
521 #endif
522 #undef CLEAN
523 free(con->plugin_ctx);
524 free(con->cond_cache);
526 free(con);
529 free(conns->ptr);
533 int connection_reset(server *srv, connection *con) {
534 size_t i;
536 plugins_call_connection_reset(srv, con);
538 con->is_readable = 1;
539 con->is_writable = 1;
540 con->http_status = 0;
541 con->file_finished = 0;
542 con->file_started = 0;
543 con->got_response = 0;
545 con->parsed_response = 0;
547 con->bytes_written = 0;
548 con->bytes_written_cur_second = 0;
549 con->bytes_read = 0;
550 con->bytes_header = 0;
551 con->loops_per_request = 0;
553 con->request.http_method = HTTP_METHOD_UNSET;
554 con->request.http_version = HTTP_VERSION_UNSET;
556 con->request.http_if_modified_since = NULL;
557 con->request.http_if_none_match = NULL;
559 con->response.keep_alive = 0;
560 con->response.content_length = -1;
561 con->response.transfer_encoding = 0;
563 con->mode = DIRECT;
565 #define CLEAN(x) \
566 if (con->x) buffer_reset(con->x);
568 CLEAN(request.uri);
569 CLEAN(request.request_line);
570 CLEAN(request.pathinfo);
571 CLEAN(request.request);
573 /* CLEAN(request.orig_uri); */
575 CLEAN(uri.scheme);
576 /* CLEAN(uri.authority); */
577 /* CLEAN(uri.path); */
578 CLEAN(uri.path_raw);
579 /* CLEAN(uri.query); */
581 CLEAN(physical.doc_root);
582 CLEAN(physical.path);
583 CLEAN(physical.basedir);
584 CLEAN(physical.rel_path);
585 CLEAN(physical.etag);
587 CLEAN(parse_request);
589 CLEAN(server_name);
590 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
591 CLEAN(tlsext_server_name);
592 #endif
593 #undef CLEAN
595 #define CLEAN(x) \
596 if (con->x) con->x->used = 0;
598 #undef CLEAN
600 #define CLEAN(x) \
601 con->request.x = NULL;
603 CLEAN(http_host);
604 CLEAN(http_range);
605 CLEAN(http_content_type);
606 #undef CLEAN
607 con->request.content_length = 0;
609 array_reset(con->request.headers);
610 array_reset(con->response.headers);
611 array_reset(con->environment);
613 chunkqueue_reset(con->write_queue);
614 chunkqueue_reset(con->request_content_queue);
616 /* the plugins should cleanup themself */
617 for (i = 0; i < srv->plugins.used; i++) {
618 plugin *p = ((plugin **)(srv->plugins.ptr))[i];
619 plugin_data *pd = p->data;
621 if (!pd) continue;
623 if (con->plugin_ctx[pd->id] != NULL) {
624 log_error_write(srv, __FILE__, __LINE__, "sb", "missing cleanup in", p->name);
627 con->plugin_ctx[pd->id] = NULL;
630 /* The cond_cache gets reset in response.c */
631 /* config_cond_cache_reset(srv, con); */
633 con->header_len = 0;
634 con->error_handler_saved_status = 0;
635 /*con->error_handler_saved_method = HTTP_METHOD_UNSET;*/
636 /*(error_handler_saved_method value is not valid unless error_handler_saved_status is set)*/
638 config_setup_connection(srv, con);
640 return 0;
644 * handle all header and content read
646 * we get called by the state-engine and by the fdevent-handler
648 static int connection_handle_read_state(server *srv, connection *con) {
649 chunk *c, *last_chunk;
650 off_t last_offset;
651 chunkqueue *cq = con->read_queue;
652 int is_closed = 0; /* the connection got closed, if we don't have a complete header, -> error */
653 /* when in CON_STATE_READ: about to receive first byte for a request: */
654 int is_request_start = chunkqueue_is_empty(cq);
656 if (con->is_readable) {
657 con->read_idle_ts = srv->cur_ts;
659 switch(connection_handle_read(srv, con)) {
660 case -1:
661 return -1;
662 case -2:
663 is_closed = 1;
664 break;
665 default:
666 break;
670 chunkqueue_remove_finished_chunks(cq);
672 /* we might have got several packets at once
675 /* update request_start timestamp when first byte of
676 * next request is received on a keep-alive connection */
677 if (con->request_count > 1 && is_request_start) con->request_start = srv->cur_ts;
679 /* if there is a \r\n\r\n in the chunkqueue
681 * scan the chunk-queue twice
682 * 1. to find the \r\n\r\n
683 * 2. to copy the header-packet
687 last_chunk = NULL;
688 last_offset = 0;
690 for (c = cq->first; c; c = c->next) {
691 size_t i;
692 size_t len = buffer_string_length(c->mem) - c->offset;
693 const char *b = c->mem->ptr + c->offset;
695 for (i = 0; i < len; ++i) {
696 char ch = b[i];
698 if ('\r' == ch) {
699 /* chec if \n\r\n follows */
700 size_t j = i+1;
701 chunk *cc = c;
702 const char header_end[] = "\r\n\r\n";
703 int header_end_match_pos = 1;
705 for ( ; cc; cc = cc->next, j = 0 ) {
706 size_t bblen = buffer_string_length(cc->mem) - cc->offset;
707 const char *bb = cc->mem->ptr + cc->offset;
709 for ( ; j < bblen; j++) {
710 ch = bb[j];
712 if (ch == header_end[header_end_match_pos]) {
713 header_end_match_pos++;
714 if (4 == header_end_match_pos) {
715 last_chunk = cc;
716 last_offset = j+1;
717 goto found_header_end;
719 } else {
720 goto reset_search;
725 reset_search: ;
728 found_header_end:
730 /* found */
731 if (last_chunk) {
732 buffer_reset(con->request.request);
734 for (c = cq->first; c; c = c->next) {
735 size_t len = buffer_string_length(c->mem) - c->offset;
737 if (c == last_chunk) {
738 len = last_offset;
741 buffer_append_string_len(con->request.request, c->mem->ptr + c->offset, len);
742 c->offset += len;
743 cq->bytes_out += len;
745 if (c == last_chunk) break;
748 connection_set_state(srv, con, CON_STATE_REQUEST_END);
749 } else if (chunkqueue_length(cq) > 64 * 1024) {
750 log_error_write(srv, __FILE__, __LINE__, "s", "oversized request-header -> sending Status 414");
752 con->http_status = 414; /* Request-URI too large */
753 con->keep_alive = 0;
754 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
755 } else if (is_closed) {
756 /* the connection got closed and we didn't got enough data to leave CON_STATE_READ;
757 * the only way is to leave here */
758 connection_set_state(srv, con, CON_STATE_ERROR);
761 chunkqueue_remove_finished_chunks(cq);
763 return 0;
766 static handler_t connection_handle_fdevent(server *srv, void *context, int revents) {
767 connection *con = context;
769 joblist_append(srv, con);
771 if (con->srv_socket->is_ssl) {
772 /* ssl may read and write for both reads and writes */
773 if (revents & (FDEVENT_IN | FDEVENT_OUT)) {
774 con->is_readable = 1;
775 con->is_writable = 1;
777 } else {
778 if (revents & FDEVENT_IN) {
779 con->is_readable = 1;
781 if (revents & FDEVENT_OUT) {
782 con->is_writable = 1;
783 /* we don't need the event twice */
788 if (revents & ~(FDEVENT_IN | FDEVENT_OUT)) {
789 /* looks like an error */
791 /* FIXME: revents = 0x19 still means that we should read from the queue */
792 if (revents & FDEVENT_HUP) {
793 if (con->state == CON_STATE_CLOSE) {
794 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
795 } else {
796 /* sigio reports the wrong event here
798 * there was no HUP at all
800 #ifdef USE_LINUX_SIGIO
801 if (srv->ev->in_sigio == 1) {
802 log_error_write(srv, __FILE__, __LINE__, "sd",
803 "connection closed: poll() -> HUP", con->fd);
804 } else {
805 connection_set_state(srv, con, CON_STATE_ERROR);
807 #else
808 connection_set_state(srv, con, CON_STATE_ERROR);
809 #endif
812 } else if (revents & FDEVENT_ERR) {
813 /* error, connection reset, whatever... we don't want to spam the logfile */
814 #if 0
815 log_error_write(srv, __FILE__, __LINE__, "sd",
816 "connection closed: poll() -> ERR", con->fd);
817 #endif
818 connection_set_state(srv, con, CON_STATE_ERROR);
819 } else {
820 log_error_write(srv, __FILE__, __LINE__, "sd",
821 "connection closed: poll() -> ???", revents);
825 if (con->state == CON_STATE_READ) {
826 connection_handle_read_state(srv, con);
829 if (con->state == CON_STATE_WRITE &&
830 !chunkqueue_is_empty(con->write_queue) &&
831 con->is_writable) {
833 if (-1 == connection_handle_write(srv, con)) {
834 connection_set_state(srv, con, CON_STATE_ERROR);
836 log_error_write(srv, __FILE__, __LINE__, "ds",
837 con->fd,
838 "handle write failed.");
842 if (con->state == CON_STATE_CLOSE) {
843 /* flush the read buffers */
844 int len;
845 char buf[1024];
847 len = read(con->fd, buf, sizeof(buf));
848 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
849 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
853 return HANDLER_FINISHED;
857 connection *connection_accept(server *srv, server_socket *srv_socket) {
858 /* accept everything */
860 /* search an empty place */
861 int cnt;
862 sock_addr cnt_addr;
863 socklen_t cnt_len;
864 /* accept it and register the fd */
867 * check if we can still open a new connections
869 * see #1216
872 if (srv->conns->used >= srv->max_conns) {
873 return NULL;
876 cnt_len = sizeof(cnt_addr);
878 if (-1 == (cnt = accept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len))) {
879 switch (errno) {
880 case EAGAIN:
881 #if EWOULDBLOCK != EAGAIN
882 case EWOULDBLOCK:
883 #endif
884 case EINTR:
885 /* we were stopped _before_ we had a connection */
886 case ECONNABORTED: /* this is a FreeBSD thingy */
887 /* we were stopped _after_ we had a connection */
888 break;
889 case EMFILE:
890 /* out of fds */
891 break;
892 default:
893 log_error_write(srv, __FILE__, __LINE__, "ssd", "accept failed:", strerror(errno), errno);
895 return NULL;
896 } else {
897 connection *con;
899 srv->cur_fds++;
901 /* ok, we have the connection, register it */
902 #if 0
903 log_error_write(srv, __FILE__, __LINE__, "sd",
904 "appected()", cnt);
905 #endif
906 srv->con_opened++;
908 con = connections_get_new_connection(srv);
910 con->fd = cnt;
911 con->fde_ndx = -1;
912 #if 0
913 gettimeofday(&(con->start_tv), NULL);
914 #endif
915 fdevent_register(srv->ev, con->fd, connection_handle_fdevent, con);
917 connection_set_state(srv, con, CON_STATE_REQUEST_START);
919 con->connection_start = srv->cur_ts;
920 con->dst_addr = cnt_addr;
921 buffer_copy_string(con->dst_addr_buf, inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
922 con->srv_socket = srv_socket;
924 if (-1 == (fdevent_fcntl_set(srv->ev, con->fd))) {
925 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
926 return NULL;
928 #ifdef USE_OPENSSL
929 /* connect FD to SSL */
930 if (srv_socket->is_ssl) {
931 if (NULL == (con->ssl = SSL_new(srv_socket->ssl_ctx))) {
932 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
933 ERR_error_string(ERR_get_error(), NULL));
935 return NULL;
938 con->renegotiations = 0;
939 SSL_set_app_data(con->ssl, con);
940 SSL_set_accept_state(con->ssl);
942 if (1 != (SSL_set_fd(con->ssl, cnt))) {
943 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
944 ERR_error_string(ERR_get_error(), NULL));
945 return NULL;
948 #endif
949 return con;
954 int connection_state_machine(server *srv, connection *con) {
955 int done = 0, r;
956 #ifdef USE_OPENSSL
957 server_socket *srv_sock = con->srv_socket;
958 #endif
960 if (srv->srvconf.log_state_handling) {
961 log_error_write(srv, __FILE__, __LINE__, "sds",
962 "state at start",
963 con->fd,
964 connection_get_state(con->state));
967 while (done == 0) {
968 size_t ostate = con->state;
970 switch (con->state) {
971 case CON_STATE_REQUEST_START: /* transient */
972 if (srv->srvconf.log_state_handling) {
973 log_error_write(srv, __FILE__, __LINE__, "sds",
974 "state for fd", con->fd, connection_get_state(con->state));
977 con->request_start = srv->cur_ts;
978 con->read_idle_ts = srv->cur_ts;
980 con->request_count++;
981 con->loops_per_request = 0;
983 connection_set_state(srv, con, CON_STATE_READ);
985 break;
986 case CON_STATE_REQUEST_END: /* transient */
987 if (srv->srvconf.log_state_handling) {
988 log_error_write(srv, __FILE__, __LINE__, "sds",
989 "state for fd", con->fd, connection_get_state(con->state));
992 buffer_reset(con->uri.authority);
993 buffer_reset(con->uri.path);
994 buffer_reset(con->uri.query);
995 buffer_reset(con->request.orig_uri);
997 if (http_request_parse(srv, con)) {
998 /* we have to read some data from the POST request */
1000 connection_set_state(srv, con, CON_STATE_READ_POST);
1002 break;
1005 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
1007 break;
1008 case CON_STATE_READ_POST:
1009 case CON_STATE_HANDLE_REQUEST:
1011 * the request is parsed
1013 * decided what to do with the request
1019 if (srv->srvconf.log_state_handling) {
1020 log_error_write(srv, __FILE__, __LINE__, "sds",
1021 "state for fd", con->fd, connection_get_state(con->state));
1024 switch (r = http_response_prepare(srv, con)) {
1025 case HANDLER_FINISHED:
1026 if (con->error_handler_saved_status > 0) {
1027 con->request.http_method = con->error_handler_saved_method;
1029 if (con->mode == DIRECT) {
1030 if (con->error_handler_saved_status) {
1031 if (con->error_handler_saved_status > 0) {
1032 con->http_status = con->error_handler_saved_status;
1033 } else if (con->http_status == 404 || con->http_status == 403) {
1034 /* error-handler-404 is a 404 */
1035 con->http_status = -con->error_handler_saved_status;
1036 } else {
1037 /* error-handler-404 is back and has generated content */
1038 /* if Status: was set, take it otherwise use 200 */
1040 } else if (con->http_status >= 400) {
1041 buffer *error_handler = NULL;
1042 if (!buffer_string_is_empty(con->conf.error_handler)) {
1043 error_handler = con->conf.error_handler;
1044 } else if ((con->http_status == 404 || con->http_status == 403)
1045 && !buffer_string_is_empty(con->conf.error_handler_404)) {
1046 error_handler = con->conf.error_handler_404;
1049 if (error_handler) {
1050 /* call error-handler */
1052 /* set REDIRECT_STATUS to save current HTTP status code
1053 * for access by dynamic handlers
1054 * https://redmine.lighttpd.net/issues/1828 */
1055 data_string *ds;
1056 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
1057 ds = data_string_init();
1059 buffer_copy_string_len(ds->key, CONST_STR_LEN("REDIRECT_STATUS"));
1060 buffer_append_int(ds->value, con->http_status);
1061 array_insert_unique(con->environment, (data_unset *)ds);
1063 if (error_handler == con->conf.error_handler) {
1064 plugins_call_connection_reset(srv, con);
1066 if (con->request.content_length) {
1067 if ((off_t)con->request.content_length != chunkqueue_length(con->request_content_queue)) {
1068 con->keep_alive = 0;
1070 con->request.content_length = 0;
1071 chunkqueue_reset(con->request_content_queue);
1074 con->is_writable = 1;
1075 con->file_finished = 0;
1076 con->file_started = 0;
1077 con->got_response = 0;
1078 con->parsed_response = 0;
1079 con->response.keep_alive = 0;
1080 con->response.content_length = -1;
1081 con->response.transfer_encoding = 0;
1082 array_reset(con->response.headers);
1083 chunkqueue_reset(con->write_queue);
1085 array_set_key_value(con->environment, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.orig_uri));
1086 con->error_handler_saved_status = con->http_status;
1087 con->error_handler_saved_method = con->request.http_method;
1089 con->request.http_method = HTTP_METHOD_GET;
1090 } else { /*(preserve behavior for server.error-handler-404)*/
1091 array_set_key_value(con->environment, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(error_handler));
1092 con->error_handler_saved_status = -con->http_status; /*(negative to flag old behavior)*/
1094 con->http_status = 0;
1096 buffer_copy_buffer(con->request.uri, error_handler);
1097 buffer_reset(con->physical.path);
1098 connection_handle_errdoc_init(con);
1100 done = -1;
1101 break;
1105 if (con->http_status == 0) con->http_status = 200;
1107 /* we have something to send, go on */
1108 connection_set_state(srv, con, CON_STATE_RESPONSE_START);
1109 break;
1110 case HANDLER_WAIT_FOR_FD:
1111 srv->want_fds++;
1113 fdwaitqueue_append(srv, con);
1115 break;
1116 case HANDLER_COMEBACK:
1117 done = -1;
1118 /* fallthrough */
1119 case HANDLER_WAIT_FOR_EVENT:
1120 /* come back here */
1121 break;
1122 case HANDLER_ERROR:
1123 /* something went wrong */
1124 connection_set_state(srv, con, CON_STATE_ERROR);
1125 break;
1126 default:
1127 log_error_write(srv, __FILE__, __LINE__, "sdd", "unknown ret-value: ", con->fd, r);
1128 break;
1131 break;
1132 case CON_STATE_RESPONSE_START:
1134 * the decision is done
1135 * - create the HTTP-Response-Header
1139 if (srv->srvconf.log_state_handling) {
1140 log_error_write(srv, __FILE__, __LINE__, "sds",
1141 "state for fd", con->fd, connection_get_state(con->state));
1144 if (-1 == connection_handle_write_prepare(srv, con)) {
1145 connection_set_state(srv, con, CON_STATE_ERROR);
1147 break;
1150 connection_set_state(srv, con, CON_STATE_WRITE);
1151 break;
1152 case CON_STATE_RESPONSE_END: /* transient */
1153 /* log the request */
1155 if (srv->srvconf.log_state_handling) {
1156 log_error_write(srv, __FILE__, __LINE__, "sds",
1157 "state for fd", con->fd, connection_get_state(con->state));
1160 plugins_call_handle_request_done(srv, con);
1162 srv->con_written++;
1164 if (con->keep_alive) {
1165 connection_set_state(srv, con, CON_STATE_REQUEST_START);
1167 #if 0
1168 con->request_start = srv->cur_ts;
1169 con->read_idle_ts = srv->cur_ts;
1170 #endif
1171 } else {
1172 switch(r = plugins_call_handle_connection_close(srv, con)) {
1173 case HANDLER_GO_ON:
1174 case HANDLER_FINISHED:
1175 break;
1176 default:
1177 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1178 break;
1181 #ifdef USE_OPENSSL
1182 if (srv_sock->is_ssl) {
1183 switch (SSL_shutdown(con->ssl)) {
1184 case 1:
1185 /* done */
1186 break;
1187 case 0:
1188 /* wait for fd-event
1190 * FIXME: wait for fdevent and call SSL_shutdown again
1194 break;
1195 default:
1196 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1197 ERR_error_string(ERR_get_error(), NULL));
1200 #endif
1201 if ((0 == shutdown(con->fd, SHUT_WR))) {
1202 con->close_timeout_ts = srv->cur_ts;
1203 connection_set_state(srv, con, CON_STATE_CLOSE);
1204 } else {
1205 connection_close(srv, con);
1208 srv->con_closed++;
1211 connection_reset(srv, con);
1213 break;
1214 case CON_STATE_CONNECT:
1215 if (srv->srvconf.log_state_handling) {
1216 log_error_write(srv, __FILE__, __LINE__, "sds",
1217 "state for fd", con->fd, connection_get_state(con->state));
1220 chunkqueue_reset(con->read_queue);
1222 con->request_count = 0;
1224 break;
1225 case CON_STATE_CLOSE:
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 /* we have to do the linger_on_close stuff regardless
1232 * of con->keep_alive; even non-keepalive sockets may
1233 * still have unread data, and closing before reading
1234 * it will make the client not see all our output.
1237 int len;
1238 char buf[1024];
1240 len = read(con->fd, buf, sizeof(buf));
1241 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
1242 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
1246 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1247 connection_close(srv, con);
1249 if (srv->srvconf.log_state_handling) {
1250 log_error_write(srv, __FILE__, __LINE__, "sd",
1251 "connection closed for fd", con->fd);
1255 break;
1256 case CON_STATE_READ:
1257 if (srv->srvconf.log_state_handling) {
1258 log_error_write(srv, __FILE__, __LINE__, "sds",
1259 "state for fd", con->fd, connection_get_state(con->state));
1262 connection_handle_read_state(srv, con);
1263 break;
1264 case CON_STATE_WRITE:
1265 if (srv->srvconf.log_state_handling) {
1266 log_error_write(srv, __FILE__, __LINE__, "sds",
1267 "state for fd", con->fd, connection_get_state(con->state));
1270 /* only try to write if we have something in the queue */
1271 if (!chunkqueue_is_empty(con->write_queue)) {
1272 if (con->is_writable) {
1273 if (-1 == connection_handle_write(srv, con)) {
1274 log_error_write(srv, __FILE__, __LINE__, "ds",
1275 con->fd,
1276 "handle write failed.");
1277 connection_set_state(srv, con, CON_STATE_ERROR);
1280 } else if (con->file_finished) {
1281 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
1284 break;
1285 case CON_STATE_ERROR: /* transient */
1287 /* even if the connection was drop we still have to write it to the access log */
1288 if (con->http_status) {
1289 plugins_call_handle_request_done(srv, con);
1291 #ifdef USE_OPENSSL
1292 if (srv_sock->is_ssl) {
1293 int ret, ssl_r;
1294 unsigned long err;
1295 ERR_clear_error();
1296 switch ((ret = SSL_shutdown(con->ssl))) {
1297 case 1:
1298 /* ok */
1299 break;
1300 case 0:
1301 ERR_clear_error();
1302 if (-1 != (ret = SSL_shutdown(con->ssl))) break;
1304 /* fall through */
1305 default:
1307 switch ((ssl_r = SSL_get_error(con->ssl, ret))) {
1308 case SSL_ERROR_WANT_WRITE:
1309 case SSL_ERROR_WANT_READ:
1310 break;
1311 case SSL_ERROR_SYSCALL:
1312 /* perhaps we have error waiting in our error-queue */
1313 if (0 != (err = ERR_get_error())) {
1314 do {
1315 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1316 ssl_r, ret,
1317 ERR_error_string(err, NULL));
1318 } while((err = ERR_get_error()));
1319 } else if (errno != 0) { /* ssl bug (see lighttpd ticket #2213): sometimes errno == 0 */
1320 switch(errno) {
1321 case EPIPE:
1322 case ECONNRESET:
1323 break;
1324 default:
1325 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL (error):",
1326 ssl_r, ret, errno,
1327 strerror(errno));
1328 break;
1332 break;
1333 default:
1334 while((err = ERR_get_error())) {
1335 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1336 ssl_r, ret,
1337 ERR_error_string(err, NULL));
1340 break;
1343 ERR_clear_error();
1345 #endif
1347 switch(con->mode) {
1348 case DIRECT:
1349 #if 0
1350 log_error_write(srv, __FILE__, __LINE__, "sd",
1351 "emergency exit: direct",
1352 con->fd);
1353 #endif
1354 break;
1355 default:
1356 switch(r = plugins_call_handle_connection_close(srv, con)) {
1357 case HANDLER_GO_ON:
1358 case HANDLER_FINISHED:
1359 break;
1360 default:
1361 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1362 break;
1364 break;
1367 connection_reset(srv, con);
1369 /* close the connection */
1370 if ((0 == shutdown(con->fd, SHUT_WR))) {
1371 con->close_timeout_ts = srv->cur_ts;
1372 connection_set_state(srv, con, CON_STATE_CLOSE);
1374 if (srv->srvconf.log_state_handling) {
1375 log_error_write(srv, __FILE__, __LINE__, "sd",
1376 "shutdown for fd", con->fd);
1378 } else {
1379 connection_close(srv, con);
1382 con->keep_alive = 0;
1384 srv->con_closed++;
1386 break;
1387 default:
1388 log_error_write(srv, __FILE__, __LINE__, "sdd",
1389 "unknown state:", con->fd, con->state);
1391 break;
1394 if (done == -1) {
1395 done = 0;
1396 } else if (ostate == con->state) {
1397 done = 1;
1401 if (srv->srvconf.log_state_handling) {
1402 log_error_write(srv, __FILE__, __LINE__, "sds",
1403 "state at exit:",
1404 con->fd,
1405 connection_get_state(con->state));
1408 switch(con->state) {
1409 case CON_STATE_READ_POST:
1410 case CON_STATE_READ:
1411 case CON_STATE_CLOSE:
1412 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, FDEVENT_IN);
1413 break;
1414 case CON_STATE_WRITE:
1415 /* request write-fdevent only if we really need it
1416 * - if we have data to write
1417 * - if the socket is not writable yet
1419 if (!chunkqueue_is_empty(con->write_queue) &&
1420 (con->is_writable == 0) &&
1421 (con->traffic_limit_reached == 0)) {
1422 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, FDEVENT_OUT);
1423 } else {
1424 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, 0);
1426 break;
1427 default:
1428 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, 0);
1429 break;
1432 return 0;