build with libressl
[lighttpd.git] / src / connections.c
blobd4a35be7a4e7d4663c37b33a0c2afd6311740fe6
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 buffer_reset(con->physical.path);
162 array_reset(con->response.headers);
163 chunkqueue_reset(con->write_queue);
166 static int connection_handle_write_prepare(server *srv, connection *con) {
167 if (con->mode == DIRECT) {
168 /* static files */
169 switch(con->request.http_method) {
170 case HTTP_METHOD_GET:
171 case HTTP_METHOD_POST:
172 case HTTP_METHOD_HEAD:
173 break;
174 case HTTP_METHOD_OPTIONS:
176 * 400 is coming from the request-parser BEFORE uri.path is set
177 * 403 is from the response handler when noone else catched it
179 * */
180 if ((!con->http_status || con->http_status == 200) && !buffer_string_is_empty(con->uri.path) &&
181 con->uri.path->ptr[0] != '*') {
182 response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST"));
184 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
185 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
187 con->http_status = 200;
188 con->file_finished = 1;
190 chunkqueue_reset(con->write_queue);
192 break;
193 default:
194 if (0 == con->http_status) {
195 con->http_status = 501;
197 break;
201 if (con->http_status == 0) {
202 con->http_status = 403;
205 switch(con->http_status) {
206 case 204: /* class: header only */
207 case 205:
208 case 304:
209 /* disable chunked encoding again as we have no body */
210 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
211 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
212 chunkqueue_reset(con->write_queue);
214 con->file_finished = 1;
215 break;
216 default: /* class: header + body */
217 if (con->mode != DIRECT) break;
219 /* only custom body for 4xx and 5xx */
220 if (con->http_status < 400 || con->http_status >= 600) break;
222 con->file_finished = 0;
224 connection_handle_errdoc_init(con);
226 /* try to send static errorfile */
227 if (!buffer_string_is_empty(con->conf.errorfile_prefix)) {
228 stat_cache_entry *sce = NULL;
230 buffer_copy_buffer(con->physical.path, con->conf.errorfile_prefix);
231 buffer_append_int(con->physical.path, con->http_status);
232 buffer_append_string_len(con->physical.path, CONST_STR_LEN(".html"));
234 if (0 == http_chunk_append_file(srv, con, con->physical.path)) {
235 con->file_finished = 1;
236 if (HANDLER_ERROR != stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
237 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce->content_type));
242 if (!con->file_finished) {
243 buffer *b;
245 buffer_reset(con->physical.path);
247 con->file_finished = 1;
248 b = buffer_init();
250 /* build default error-page */
251 buffer_copy_string_len(b, CONST_STR_LEN(
252 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
253 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
254 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
255 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
256 " <head>\n"
257 " <title>"));
258 buffer_append_int(b, con->http_status);
259 buffer_append_string_len(b, CONST_STR_LEN(" - "));
260 buffer_append_string(b, get_http_status_name(con->http_status));
262 buffer_append_string_len(b, CONST_STR_LEN(
263 "</title>\n"
264 " </head>\n"
265 " <body>\n"
266 " <h1>"));
267 buffer_append_int(b, con->http_status);
268 buffer_append_string_len(b, CONST_STR_LEN(" - "));
269 buffer_append_string(b, get_http_status_name(con->http_status));
271 buffer_append_string_len(b, CONST_STR_LEN("</h1>\n"
272 " </body>\n"
273 "</html>\n"
276 http_chunk_append_buffer(srv, con, b);
277 buffer_free(b);
278 http_chunk_close(srv, con);
280 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
282 break;
285 if (con->file_finished) {
286 /* we have all the content and chunked encoding is not used, set a content-length */
288 if ((!(con->parsed_response & HTTP_CONTENT_LENGTH)) &&
289 (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0) {
290 off_t qlen = chunkqueue_length(con->write_queue);
293 * The Content-Length header only can be sent if we have content:
294 * - HEAD doesn't have a content-body (but have a content-length)
295 * - 1xx, 204 and 304 don't have a content-body (RFC 2616 Section 4.3)
297 * Otherwise generate a Content-Length header as chunked encoding is not
298 * available
300 if ((con->http_status >= 100 && con->http_status < 200) ||
301 con->http_status == 204 ||
302 con->http_status == 304) {
303 data_string *ds;
304 /* no Content-Body, no Content-Length */
305 if (NULL != (ds = (data_string*) array_get_element(con->response.headers, "Content-Length"))) {
306 buffer_reset(ds->value); /* Headers with empty values are ignored for output */
308 } else if (qlen > 0 || con->request.http_method != HTTP_METHOD_HEAD) {
309 /* qlen = 0 is important for Redirects (301, ...) as they MAY have
310 * a content. Browsers are waiting for a Content otherwise
312 buffer_copy_int(srv->tmp_buf, qlen);
314 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Length"), CONST_BUF_LEN(srv->tmp_buf));
317 } else {
319 * the file isn't finished yet, but we have all headers
321 * to get keep-alive we either need:
322 * - Content-Length: ... (HTTP/1.0 and HTTP/1.0) or
323 * - Transfer-Encoding: chunked (HTTP/1.1)
326 if (((con->parsed_response & HTTP_CONTENT_LENGTH) == 0) &&
327 ((con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0)) {
328 con->keep_alive = 0;
332 * if the backend sent a Connection: close, follow the wish
334 * NOTE: if the backend sent Connection: Keep-Alive, but no Content-Length, we
335 * will close the connection. That's fine. We can always decide the close
336 * the connection
338 * FIXME: to be nice we should remove the Connection: ...
340 if (con->parsed_response & HTTP_CONNECTION) {
341 /* a subrequest disable keep-alive although the client wanted it */
342 if (con->keep_alive && !con->response.keep_alive) {
343 con->keep_alive = 0;
348 if (con->request.content_length
349 && (off_t)con->request.content_length > con->request_content_queue->bytes_in) {
350 /* request body is present and has not been read completely */
351 con->keep_alive = 0;
354 if (con->request.http_method == HTTP_METHOD_HEAD) {
356 * a HEAD request has the same as a GET
357 * without the content
359 con->file_finished = 1;
361 chunkqueue_reset(con->write_queue);
362 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
365 http_response_write_header(srv, con);
367 return 0;
370 static int connection_handle_write(server *srv, connection *con) {
371 switch(network_write_chunkqueue(srv, con, con->write_queue, MAX_WRITE_LIMIT)) {
372 case 0:
373 con->write_request_ts = srv->cur_ts;
374 if (con->file_finished) {
375 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
376 joblist_append(srv, con);
378 break;
379 case -1: /* error on our side */
380 log_error_write(srv, __FILE__, __LINE__, "sd",
381 "connection closed: write failed on fd", con->fd);
382 connection_set_state(srv, con, CON_STATE_ERROR);
383 joblist_append(srv, con);
384 break;
385 case -2: /* remote close */
386 connection_set_state(srv, con, CON_STATE_ERROR);
387 joblist_append(srv, con);
388 break;
389 case 1:
390 con->write_request_ts = srv->cur_ts;
391 con->is_writable = 0;
393 /* not finished yet -> WRITE */
394 break;
397 return 0;
402 connection *connection_init(server *srv) {
403 connection *con;
405 UNUSED(srv);
407 con = calloc(1, sizeof(*con));
408 force_assert(NULL != con);
410 con->fd = 0;
411 con->ndx = -1;
412 con->fde_ndx = -1;
413 con->bytes_written = 0;
414 con->bytes_read = 0;
415 con->bytes_header = 0;
416 con->loops_per_request = 0;
418 #define CLEAN(x) \
419 con->x = buffer_init();
421 CLEAN(request.uri);
422 CLEAN(request.request_line);
423 CLEAN(request.request);
424 CLEAN(request.pathinfo);
426 CLEAN(request.orig_uri);
428 CLEAN(uri.scheme);
429 CLEAN(uri.authority);
430 CLEAN(uri.path);
431 CLEAN(uri.path_raw);
432 CLEAN(uri.query);
434 CLEAN(physical.doc_root);
435 CLEAN(physical.path);
436 CLEAN(physical.basedir);
437 CLEAN(physical.rel_path);
438 CLEAN(physical.etag);
439 CLEAN(parse_request);
441 CLEAN(server_name);
442 CLEAN(dst_addr_buf);
443 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
444 CLEAN(tlsext_server_name);
445 #endif
447 #undef CLEAN
448 con->write_queue = chunkqueue_init();
449 con->read_queue = chunkqueue_init();
450 con->request_content_queue = chunkqueue_init();
451 chunkqueue_set_tempdirs(
452 con->request_content_queue,
453 srv->srvconf.upload_tempdirs,
454 srv->srvconf.upload_temp_file_size);
456 con->request.headers = array_init();
457 con->response.headers = array_init();
458 con->environment = array_init();
460 /* init plugin specific connection structures */
462 con->plugin_ctx = calloc(1, (srv->plugins.used + 1) * sizeof(void *));
463 force_assert(NULL != con->plugin_ctx);
465 con->cond_cache = calloc(srv->config_context->used, sizeof(cond_cache_t));
466 force_assert(NULL != con->cond_cache);
467 config_setup_connection(srv, con);
469 return con;
472 void connections_free(server *srv) {
473 connections *conns = srv->conns;
474 size_t i;
476 for (i = 0; i < conns->size; i++) {
477 connection *con = conns->ptr[i];
479 connection_reset(srv, con);
481 chunkqueue_free(con->write_queue);
482 chunkqueue_free(con->read_queue);
483 chunkqueue_free(con->request_content_queue);
484 array_free(con->request.headers);
485 array_free(con->response.headers);
486 array_free(con->environment);
488 #define CLEAN(x) \
489 buffer_free(con->x);
491 CLEAN(request.uri);
492 CLEAN(request.request_line);
493 CLEAN(request.request);
494 CLEAN(request.pathinfo);
496 CLEAN(request.orig_uri);
498 CLEAN(uri.scheme);
499 CLEAN(uri.authority);
500 CLEAN(uri.path);
501 CLEAN(uri.path_raw);
502 CLEAN(uri.query);
504 CLEAN(physical.doc_root);
505 CLEAN(physical.path);
506 CLEAN(physical.basedir);
507 CLEAN(physical.etag);
508 CLEAN(physical.rel_path);
509 CLEAN(parse_request);
511 CLEAN(server_name);
512 CLEAN(dst_addr_buf);
513 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
514 CLEAN(tlsext_server_name);
515 #endif
516 #undef CLEAN
517 free(con->plugin_ctx);
518 free(con->cond_cache);
520 free(con);
523 free(conns->ptr);
527 int connection_reset(server *srv, connection *con) {
528 size_t i;
530 plugins_call_connection_reset(srv, con);
532 con->is_readable = 1;
533 con->is_writable = 1;
534 con->http_status = 0;
535 con->file_finished = 0;
536 con->file_started = 0;
537 con->got_response = 0;
539 con->parsed_response = 0;
541 con->bytes_written = 0;
542 con->bytes_written_cur_second = 0;
543 con->bytes_read = 0;
544 con->bytes_header = 0;
545 con->loops_per_request = 0;
547 con->request.http_method = HTTP_METHOD_UNSET;
548 con->request.http_version = HTTP_VERSION_UNSET;
550 con->request.http_if_modified_since = NULL;
551 con->request.http_if_none_match = NULL;
553 con->response.keep_alive = 0;
554 con->response.content_length = -1;
555 con->response.transfer_encoding = 0;
557 con->mode = DIRECT;
559 #define CLEAN(x) \
560 if (con->x) buffer_reset(con->x);
562 CLEAN(request.uri);
563 CLEAN(request.request_line);
564 CLEAN(request.pathinfo);
565 CLEAN(request.request);
567 /* CLEAN(request.orig_uri); */
569 CLEAN(uri.scheme);
570 /* CLEAN(uri.authority); */
571 /* CLEAN(uri.path); */
572 CLEAN(uri.path_raw);
573 /* CLEAN(uri.query); */
575 CLEAN(physical.doc_root);
576 CLEAN(physical.path);
577 CLEAN(physical.basedir);
578 CLEAN(physical.rel_path);
579 CLEAN(physical.etag);
581 CLEAN(parse_request);
583 CLEAN(server_name);
584 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
585 CLEAN(tlsext_server_name);
586 #endif
587 #undef CLEAN
589 #define CLEAN(x) \
590 if (con->x) con->x->used = 0;
592 #undef CLEAN
594 #define CLEAN(x) \
595 con->request.x = NULL;
597 CLEAN(http_host);
598 CLEAN(http_range);
599 CLEAN(http_content_type);
600 #undef CLEAN
601 con->request.content_length = 0;
603 array_reset(con->request.headers);
604 array_reset(con->response.headers);
605 array_reset(con->environment);
607 chunkqueue_reset(con->write_queue);
608 chunkqueue_reset(con->request_content_queue);
610 /* the plugins should cleanup themself */
611 for (i = 0; i < srv->plugins.used; i++) {
612 plugin *p = ((plugin **)(srv->plugins.ptr))[i];
613 plugin_data *pd = p->data;
615 if (!pd) continue;
617 if (con->plugin_ctx[pd->id] != NULL) {
618 log_error_write(srv, __FILE__, __LINE__, "sb", "missing cleanup in", p->name);
621 con->plugin_ctx[pd->id] = NULL;
624 /* The cond_cache gets reset in response.c */
625 /* config_cond_cache_reset(srv, con); */
627 con->header_len = 0;
628 con->error_handler_saved_status = 0;
629 /*con->error_handler_saved_method = HTTP_METHOD_UNSET;*/
630 /*(error_handler_saved_method value is not valid unless error_handler_saved_status is set)*/
632 config_setup_connection(srv, con);
634 return 0;
638 * handle all header and content read
640 * we get called by the state-engine and by the fdevent-handler
642 static int connection_handle_read_state(server *srv, connection *con) {
643 chunk *c, *last_chunk;
644 off_t last_offset;
645 chunkqueue *cq = con->read_queue;
646 int is_closed = 0; /* the connection got closed, if we don't have a complete header, -> error */
647 /* when in CON_STATE_READ: about to receive first byte for a request: */
648 int is_request_start = chunkqueue_is_empty(cq);
650 if (con->is_readable) {
651 con->read_idle_ts = srv->cur_ts;
653 switch(connection_handle_read(srv, con)) {
654 case -1:
655 return -1;
656 case -2:
657 is_closed = 1;
658 break;
659 default:
660 break;
664 chunkqueue_remove_finished_chunks(cq);
666 /* we might have got several packets at once
669 /* update request_start timestamp when first byte of
670 * next request is received on a keep-alive connection */
671 if (con->request_count > 1 && is_request_start) con->request_start = srv->cur_ts;
673 /* if there is a \r\n\r\n in the chunkqueue
675 * scan the chunk-queue twice
676 * 1. to find the \r\n\r\n
677 * 2. to copy the header-packet
681 last_chunk = NULL;
682 last_offset = 0;
684 for (c = cq->first; c; c = c->next) {
685 size_t i;
686 size_t len = buffer_string_length(c->mem) - c->offset;
687 const char *b = c->mem->ptr + c->offset;
689 for (i = 0; i < len; ++i) {
690 char ch = b[i];
692 if ('\r' == ch) {
693 /* chec if \n\r\n follows */
694 size_t j = i+1;
695 chunk *cc = c;
696 const char header_end[] = "\r\n\r\n";
697 int header_end_match_pos = 1;
699 for ( ; cc; cc = cc->next, j = 0 ) {
700 size_t bblen = buffer_string_length(cc->mem) - cc->offset;
701 const char *bb = cc->mem->ptr + cc->offset;
703 for ( ; j < bblen; j++) {
704 ch = bb[j];
706 if (ch == header_end[header_end_match_pos]) {
707 header_end_match_pos++;
708 if (4 == header_end_match_pos) {
709 last_chunk = cc;
710 last_offset = j+1;
711 goto found_header_end;
713 } else {
714 goto reset_search;
719 reset_search: ;
722 found_header_end:
724 /* found */
725 if (last_chunk) {
726 buffer_reset(con->request.request);
728 for (c = cq->first; c; c = c->next) {
729 size_t len = buffer_string_length(c->mem) - c->offset;
731 if (c == last_chunk) {
732 len = last_offset;
735 buffer_append_string_len(con->request.request, c->mem->ptr + c->offset, len);
736 c->offset += len;
737 cq->bytes_out += len;
739 if (c == last_chunk) break;
742 connection_set_state(srv, con, CON_STATE_REQUEST_END);
743 } else if (chunkqueue_length(cq) > 64 * 1024) {
744 log_error_write(srv, __FILE__, __LINE__, "s", "oversized request-header -> sending Status 414");
746 con->http_status = 414; /* Request-URI too large */
747 con->keep_alive = 0;
748 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
749 } else if (is_closed) {
750 /* the connection got closed and we didn't got enough data to leave CON_STATE_READ;
751 * the only way is to leave here */
752 connection_set_state(srv, con, CON_STATE_ERROR);
755 chunkqueue_remove_finished_chunks(cq);
757 return 0;
760 static handler_t connection_handle_fdevent(server *srv, void *context, int revents) {
761 connection *con = context;
763 joblist_append(srv, con);
765 if (con->srv_socket->is_ssl) {
766 /* ssl may read and write for both reads and writes */
767 if (revents & (FDEVENT_IN | FDEVENT_OUT)) {
768 con->is_readable = 1;
769 con->is_writable = 1;
771 } else {
772 if (revents & FDEVENT_IN) {
773 con->is_readable = 1;
775 if (revents & FDEVENT_OUT) {
776 con->is_writable = 1;
777 /* we don't need the event twice */
782 if (revents & ~(FDEVENT_IN | FDEVENT_OUT)) {
783 /* looks like an error */
785 /* FIXME: revents = 0x19 still means that we should read from the queue */
786 if (revents & FDEVENT_HUP) {
787 if (con->state == CON_STATE_CLOSE) {
788 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
789 } else {
790 /* sigio reports the wrong event here
792 * there was no HUP at all
794 #ifdef USE_LINUX_SIGIO
795 if (srv->ev->in_sigio == 1) {
796 log_error_write(srv, __FILE__, __LINE__, "sd",
797 "connection closed: poll() -> HUP", con->fd);
798 } else {
799 connection_set_state(srv, con, CON_STATE_ERROR);
801 #else
802 connection_set_state(srv, con, CON_STATE_ERROR);
803 #endif
806 } else if (revents & FDEVENT_ERR) {
807 /* error, connection reset, whatever... we don't want to spam the logfile */
808 #if 0
809 log_error_write(srv, __FILE__, __LINE__, "sd",
810 "connection closed: poll() -> ERR", con->fd);
811 #endif
812 connection_set_state(srv, con, CON_STATE_ERROR);
813 } else {
814 log_error_write(srv, __FILE__, __LINE__, "sd",
815 "connection closed: poll() -> ???", revents);
819 if (con->state == CON_STATE_READ) {
820 connection_handle_read_state(srv, con);
823 if (con->state == CON_STATE_WRITE &&
824 !chunkqueue_is_empty(con->write_queue) &&
825 con->is_writable) {
827 if (-1 == connection_handle_write(srv, con)) {
828 connection_set_state(srv, con, CON_STATE_ERROR);
830 log_error_write(srv, __FILE__, __LINE__, "ds",
831 con->fd,
832 "handle write failed.");
836 if (con->state == CON_STATE_CLOSE) {
837 /* flush the read buffers */
838 int len;
839 char buf[1024];
841 len = read(con->fd, buf, sizeof(buf));
842 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
843 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
847 return HANDLER_FINISHED;
851 connection *connection_accept(server *srv, server_socket *srv_socket) {
852 /* accept everything */
854 /* search an empty place */
855 int cnt;
856 sock_addr cnt_addr;
857 socklen_t cnt_len;
858 /* accept it and register the fd */
861 * check if we can still open a new connections
863 * see #1216
866 if (srv->conns->used >= srv->max_conns) {
867 return NULL;
870 cnt_len = sizeof(cnt_addr);
872 if (-1 == (cnt = accept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len))) {
873 switch (errno) {
874 case EAGAIN:
875 #if EWOULDBLOCK != EAGAIN
876 case EWOULDBLOCK:
877 #endif
878 case EINTR:
879 /* we were stopped _before_ we had a connection */
880 case ECONNABORTED: /* this is a FreeBSD thingy */
881 /* we were stopped _after_ we had a connection */
882 break;
883 case EMFILE:
884 /* out of fds */
885 break;
886 default:
887 log_error_write(srv, __FILE__, __LINE__, "ssd", "accept failed:", strerror(errno), errno);
889 return NULL;
890 } else {
891 return connection_accepted(srv, srv_socket, &cnt_addr, cnt);
895 connection *connection_accepted(server *srv, server_socket *srv_socket, sock_addr *cnt_addr, int cnt) {
896 connection *con;
898 srv->cur_fds++;
900 /* ok, we have the connection, register it */
901 #if 0
902 log_error_write(srv, __FILE__, __LINE__, "sd",
903 "appected()", cnt);
904 #endif
905 srv->con_opened++;
907 con = connections_get_new_connection(srv);
909 con->fd = cnt;
910 con->fde_ndx = -1;
911 #if 0
912 gettimeofday(&(con->start_tv), NULL);
913 #endif
914 fdevent_register(srv->ev, con->fd, connection_handle_fdevent, con);
916 connection_set_state(srv, con, CON_STATE_REQUEST_START);
918 con->connection_start = srv->cur_ts;
919 con->dst_addr = *cnt_addr;
920 buffer_copy_string(con->dst_addr_buf, inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
921 con->srv_socket = srv_socket;
923 if (-1 == (fdevent_fcntl_set(srv->ev, con->fd))) {
924 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
925 return NULL;
927 #ifdef USE_OPENSSL
928 /* connect FD to SSL */
929 if (srv_socket->is_ssl) {
930 if (NULL == (con->ssl = SSL_new(srv_socket->ssl_ctx))) {
931 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
932 ERR_error_string(ERR_get_error(), NULL));
934 return NULL;
937 con->renegotiations = 0;
938 SSL_set_app_data(con->ssl, con);
939 SSL_set_accept_state(con->ssl);
941 if (1 != (SSL_set_fd(con->ssl, cnt))) {
942 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
943 ERR_error_string(ERR_get_error(), NULL));
944 return NULL;
947 #endif
948 return con;
952 int connection_state_machine(server *srv, connection *con) {
953 int done = 0, r;
954 #ifdef USE_OPENSSL
955 server_socket *srv_sock = con->srv_socket;
956 #endif
958 if (srv->srvconf.log_state_handling) {
959 log_error_write(srv, __FILE__, __LINE__, "sds",
960 "state at start",
961 con->fd,
962 connection_get_state(con->state));
965 while (done == 0) {
966 size_t ostate = con->state;
968 switch (con->state) {
969 case CON_STATE_REQUEST_START: /* transient */
970 if (srv->srvconf.log_state_handling) {
971 log_error_write(srv, __FILE__, __LINE__, "sds",
972 "state for fd", con->fd, connection_get_state(con->state));
975 con->request_start = srv->cur_ts;
976 con->read_idle_ts = srv->cur_ts;
978 con->request_count++;
979 con->loops_per_request = 0;
981 connection_set_state(srv, con, CON_STATE_READ);
983 break;
984 case CON_STATE_REQUEST_END: /* transient */
985 if (srv->srvconf.log_state_handling) {
986 log_error_write(srv, __FILE__, __LINE__, "sds",
987 "state for fd", con->fd, connection_get_state(con->state));
990 buffer_reset(con->uri.authority);
991 buffer_reset(con->uri.path);
992 buffer_reset(con->uri.query);
993 buffer_reset(con->request.orig_uri);
995 if (http_request_parse(srv, con)) {
996 /* we have to read some data from the POST request */
998 connection_set_state(srv, con, CON_STATE_READ_POST);
1000 break;
1003 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
1005 break;
1006 case CON_STATE_READ_POST:
1007 case CON_STATE_HANDLE_REQUEST:
1009 * the request is parsed
1011 * decided what to do with the request
1017 if (srv->srvconf.log_state_handling) {
1018 log_error_write(srv, __FILE__, __LINE__, "sds",
1019 "state for fd", con->fd, connection_get_state(con->state));
1022 switch (r = http_response_prepare(srv, con)) {
1023 case HANDLER_FINISHED:
1024 if (con->error_handler_saved_status > 0) {
1025 con->request.http_method = con->error_handler_saved_method;
1027 if (con->mode == DIRECT) {
1028 if (con->error_handler_saved_status) {
1029 if (con->error_handler_saved_status > 0) {
1030 con->http_status = con->error_handler_saved_status;
1031 } else if (con->http_status == 404 || con->http_status == 403) {
1032 /* error-handler-404 is a 404 */
1033 con->http_status = -con->error_handler_saved_status;
1034 } else {
1035 /* error-handler-404 is back and has generated content */
1036 /* if Status: was set, take it otherwise use 200 */
1038 } else if (con->http_status >= 400) {
1039 buffer *error_handler = NULL;
1040 if (!buffer_string_is_empty(con->conf.error_handler)) {
1041 error_handler = con->conf.error_handler;
1042 } else if ((con->http_status == 404 || con->http_status == 403)
1043 && !buffer_string_is_empty(con->conf.error_handler_404)) {
1044 error_handler = con->conf.error_handler_404;
1047 if (error_handler) {
1048 /* call error-handler */
1050 /* set REDIRECT_STATUS to save current HTTP status code
1051 * for access by dynamic handlers
1052 * https://redmine.lighttpd.net/issues/1828 */
1053 data_string *ds;
1054 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
1055 ds = data_string_init();
1057 buffer_copy_string_len(ds->key, CONST_STR_LEN("REDIRECT_STATUS"));
1058 buffer_append_int(ds->value, con->http_status);
1059 array_insert_unique(con->environment, (data_unset *)ds);
1061 if (error_handler == con->conf.error_handler) {
1062 plugins_call_connection_reset(srv, con);
1064 if (con->request.content_length) {
1065 if ((off_t)con->request.content_length != chunkqueue_length(con->request_content_queue)) {
1066 con->keep_alive = 0;
1068 con->request.content_length = 0;
1069 chunkqueue_reset(con->request_content_queue);
1072 con->is_writable = 1;
1073 con->file_finished = 0;
1074 con->file_started = 0;
1075 con->got_response = 0;
1076 con->parsed_response = 0;
1077 con->response.keep_alive = 0;
1078 con->response.content_length = -1;
1079 con->response.transfer_encoding = 0;
1081 array_set_key_value(con->environment, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.orig_uri));
1082 con->error_handler_saved_status = con->http_status;
1083 con->error_handler_saved_method = con->request.http_method;
1085 con->request.http_method = HTTP_METHOD_GET;
1086 } else { /*(preserve behavior for server.error-handler-404)*/
1087 array_set_key_value(con->environment, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(error_handler));
1088 con->error_handler_saved_status = -con->http_status; /*(negative to flag old behavior)*/
1090 con->http_status = 0;
1092 buffer_copy_buffer(con->request.uri, error_handler);
1093 connection_handle_errdoc_init(con);
1095 done = -1;
1096 break;
1100 if (con->http_status == 0) con->http_status = 200;
1102 /* we have something to send, go on */
1103 connection_set_state(srv, con, CON_STATE_RESPONSE_START);
1104 break;
1105 case HANDLER_WAIT_FOR_FD:
1106 srv->want_fds++;
1108 fdwaitqueue_append(srv, con);
1110 break;
1111 case HANDLER_COMEBACK:
1112 done = -1;
1113 /* fallthrough */
1114 case HANDLER_WAIT_FOR_EVENT:
1115 /* come back here */
1116 break;
1117 case HANDLER_ERROR:
1118 /* something went wrong */
1119 connection_set_state(srv, con, CON_STATE_ERROR);
1120 break;
1121 default:
1122 log_error_write(srv, __FILE__, __LINE__, "sdd", "unknown ret-value: ", con->fd, r);
1123 break;
1126 break;
1127 case CON_STATE_RESPONSE_START:
1129 * the decision is done
1130 * - create the HTTP-Response-Header
1134 if (srv->srvconf.log_state_handling) {
1135 log_error_write(srv, __FILE__, __LINE__, "sds",
1136 "state for fd", con->fd, connection_get_state(con->state));
1139 if (-1 == connection_handle_write_prepare(srv, con)) {
1140 connection_set_state(srv, con, CON_STATE_ERROR);
1142 break;
1145 connection_set_state(srv, con, CON_STATE_WRITE);
1146 break;
1147 case CON_STATE_RESPONSE_END: /* transient */
1148 /* log the request */
1150 if (srv->srvconf.log_state_handling) {
1151 log_error_write(srv, __FILE__, __LINE__, "sds",
1152 "state for fd", con->fd, connection_get_state(con->state));
1155 plugins_call_handle_request_done(srv, con);
1157 srv->con_written++;
1159 if (con->keep_alive) {
1160 connection_set_state(srv, con, CON_STATE_REQUEST_START);
1162 #if 0
1163 con->request_start = srv->cur_ts;
1164 con->read_idle_ts = srv->cur_ts;
1165 #endif
1166 } else {
1167 switch(r = plugins_call_handle_connection_close(srv, con)) {
1168 case HANDLER_GO_ON:
1169 case HANDLER_FINISHED:
1170 break;
1171 default:
1172 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1173 break;
1176 #ifdef USE_OPENSSL
1177 if (srv_sock->is_ssl) {
1178 switch (SSL_shutdown(con->ssl)) {
1179 case 1:
1180 /* done */
1181 break;
1182 case 0:
1183 /* wait for fd-event
1185 * FIXME: wait for fdevent and call SSL_shutdown again
1189 break;
1190 default:
1191 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1192 ERR_error_string(ERR_get_error(), NULL));
1195 #endif
1196 if ((0 == shutdown(con->fd, SHUT_WR))) {
1197 con->close_timeout_ts = srv->cur_ts;
1198 connection_set_state(srv, con, CON_STATE_CLOSE);
1199 } else {
1200 connection_close(srv, con);
1203 srv->con_closed++;
1206 connection_reset(srv, con);
1208 break;
1209 case CON_STATE_CONNECT:
1210 if (srv->srvconf.log_state_handling) {
1211 log_error_write(srv, __FILE__, __LINE__, "sds",
1212 "state for fd", con->fd, connection_get_state(con->state));
1215 chunkqueue_reset(con->read_queue);
1217 con->request_count = 0;
1219 break;
1220 case CON_STATE_CLOSE:
1221 if (srv->srvconf.log_state_handling) {
1222 log_error_write(srv, __FILE__, __LINE__, "sds",
1223 "state for fd", con->fd, connection_get_state(con->state));
1226 /* we have to do the linger_on_close stuff regardless
1227 * of con->keep_alive; even non-keepalive sockets may
1228 * still have unread data, and closing before reading
1229 * it will make the client not see all our output.
1232 int len;
1233 char buf[1024];
1235 len = read(con->fd, buf, sizeof(buf));
1236 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
1237 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
1241 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1242 connection_close(srv, con);
1244 if (srv->srvconf.log_state_handling) {
1245 log_error_write(srv, __FILE__, __LINE__, "sd",
1246 "connection closed for fd", con->fd);
1250 break;
1251 case CON_STATE_READ:
1252 if (srv->srvconf.log_state_handling) {
1253 log_error_write(srv, __FILE__, __LINE__, "sds",
1254 "state for fd", con->fd, connection_get_state(con->state));
1257 connection_handle_read_state(srv, con);
1258 break;
1259 case CON_STATE_WRITE:
1260 if (srv->srvconf.log_state_handling) {
1261 log_error_write(srv, __FILE__, __LINE__, "sds",
1262 "state for fd", con->fd, connection_get_state(con->state));
1265 /* only try to write if we have something in the queue */
1266 if (!chunkqueue_is_empty(con->write_queue)) {
1267 if (con->is_writable) {
1268 if (-1 == connection_handle_write(srv, con)) {
1269 log_error_write(srv, __FILE__, __LINE__, "ds",
1270 con->fd,
1271 "handle write failed.");
1272 connection_set_state(srv, con, CON_STATE_ERROR);
1275 } else if (con->file_finished) {
1276 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
1279 break;
1280 case CON_STATE_ERROR: /* transient */
1282 /* even if the connection was drop we still have to write it to the access log */
1283 if (con->http_status) {
1284 plugins_call_handle_request_done(srv, con);
1286 #ifdef USE_OPENSSL
1287 if (srv_sock->is_ssl) {
1288 int ret, ssl_r;
1289 unsigned long err;
1290 ERR_clear_error();
1291 switch ((ret = SSL_shutdown(con->ssl))) {
1292 case 1:
1293 /* ok */
1294 break;
1295 case 0:
1296 ERR_clear_error();
1297 if (-1 != (ret = SSL_shutdown(con->ssl))) break;
1299 /* fall through */
1300 default:
1302 switch ((ssl_r = SSL_get_error(con->ssl, ret))) {
1303 case SSL_ERROR_WANT_WRITE:
1304 case SSL_ERROR_WANT_READ:
1305 break;
1306 case SSL_ERROR_SYSCALL:
1307 /* perhaps we have error waiting in our error-queue */
1308 if (0 != (err = ERR_get_error())) {
1309 do {
1310 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1311 ssl_r, ret,
1312 ERR_error_string(err, NULL));
1313 } while((err = ERR_get_error()));
1314 } else if (errno != 0) { /* ssl bug (see lighttpd ticket #2213): sometimes errno == 0 */
1315 switch(errno) {
1316 case EPIPE:
1317 case ECONNRESET:
1318 break;
1319 default:
1320 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL (error):",
1321 ssl_r, ret, errno,
1322 strerror(errno));
1323 break;
1327 break;
1328 default:
1329 while((err = ERR_get_error())) {
1330 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1331 ssl_r, ret,
1332 ERR_error_string(err, NULL));
1335 break;
1338 ERR_clear_error();
1340 #endif
1342 switch(con->mode) {
1343 case DIRECT:
1344 #if 0
1345 log_error_write(srv, __FILE__, __LINE__, "sd",
1346 "emergency exit: direct",
1347 con->fd);
1348 #endif
1349 break;
1350 default:
1351 switch(r = plugins_call_handle_connection_close(srv, con)) {
1352 case HANDLER_GO_ON:
1353 case HANDLER_FINISHED:
1354 break;
1355 default:
1356 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1357 break;
1359 break;
1362 connection_reset(srv, con);
1364 /* close the connection */
1365 if ((0 == shutdown(con->fd, SHUT_WR))) {
1366 con->close_timeout_ts = srv->cur_ts;
1367 connection_set_state(srv, con, CON_STATE_CLOSE);
1369 if (srv->srvconf.log_state_handling) {
1370 log_error_write(srv, __FILE__, __LINE__, "sd",
1371 "shutdown for fd", con->fd);
1373 } else {
1374 connection_close(srv, con);
1377 con->keep_alive = 0;
1379 srv->con_closed++;
1381 break;
1382 default:
1383 log_error_write(srv, __FILE__, __LINE__, "sdd",
1384 "unknown state:", con->fd, con->state);
1386 break;
1389 if (done == -1) {
1390 done = 0;
1391 } else if (ostate == con->state) {
1392 done = 1;
1396 if (srv->srvconf.log_state_handling) {
1397 log_error_write(srv, __FILE__, __LINE__, "sds",
1398 "state at exit:",
1399 con->fd,
1400 connection_get_state(con->state));
1403 switch(con->state) {
1404 case CON_STATE_READ_POST:
1405 case CON_STATE_READ:
1406 case CON_STATE_CLOSE:
1407 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, FDEVENT_IN);
1408 break;
1409 case CON_STATE_WRITE:
1410 /* request write-fdevent only if we really need it
1411 * - if we have data to write
1412 * - if the socket is not writable yet
1414 if (!chunkqueue_is_empty(con->write_queue) &&
1415 (con->is_writable == 0) &&
1416 (con->traffic_limit_reached == 0)) {
1417 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, FDEVENT_OUT);
1418 } else {
1419 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, 0);
1421 break;
1422 default:
1423 fdevent_event_set(srv->ev, &(con->fde_ndx), con->fd, 0);
1424 break;
1427 return 0;