[mod_uploadprogress] fix mem leak (#1858)
[lighttpd.git] / src / connections.c
blobd2a6da180526f81415a1c2d7978b1e0482d10c8b
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(server *srv, connection *con) {
161 /* modules that produce headers required with error response should
162 * typically also produce an error document. Make an exception for
163 * mod_auth WWW-Authenticate response header. */
164 buffer *www_auth = NULL;
165 if (401 == con->http_status) {
166 data_string *ds = (data_string *)array_get_element(con->response.headers, "WWW-Authenticate");
167 if (NULL != ds) {
168 www_auth = buffer_init_buffer(ds->value);
172 con->response.transfer_encoding = 0;
173 buffer_reset(con->physical.path);
174 array_reset(con->response.headers);
175 chunkqueue_reset(con->write_queue);
177 if (NULL != www_auth) {
178 response_header_insert(srv, con, CONST_STR_LEN("WWW-Authenticate"), CONST_BUF_LEN(www_auth));
179 buffer_free(www_auth);
183 static int connection_handle_write_prepare(server *srv, connection *con) {
184 if (con->mode == DIRECT) {
185 /* static files */
186 switch(con->request.http_method) {
187 case HTTP_METHOD_GET:
188 case HTTP_METHOD_POST:
189 case HTTP_METHOD_HEAD:
190 break;
191 case HTTP_METHOD_OPTIONS:
193 * 400 is coming from the request-parser BEFORE uri.path is set
194 * 403 is from the response handler when noone else catched it
196 * */
197 if ((!con->http_status || con->http_status == 200) && !buffer_string_is_empty(con->uri.path) &&
198 con->uri.path->ptr[0] != '*') {
199 response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST"));
201 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
202 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
204 con->http_status = 200;
205 con->file_finished = 1;
207 chunkqueue_reset(con->write_queue);
209 break;
210 default:
211 if (0 == con->http_status) {
212 con->http_status = 501;
214 break;
218 if (con->http_status == 0) {
219 con->http_status = 403;
222 switch(con->http_status) {
223 case 204: /* class: header only */
224 case 205:
225 case 304:
226 /* disable chunked encoding again as we have no body */
227 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
228 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
229 chunkqueue_reset(con->write_queue);
231 con->file_finished = 1;
232 break;
233 default: /* class: header + body */
234 if (con->mode != DIRECT) break;
236 /* only custom body for 4xx and 5xx */
237 if (con->http_status < 400 || con->http_status >= 600) break;
239 con->file_finished = 0;
241 connection_handle_errdoc_init(srv, con);
243 /* try to send static errorfile */
244 if (!buffer_string_is_empty(con->conf.errorfile_prefix)) {
245 stat_cache_entry *sce = NULL;
247 buffer_copy_buffer(con->physical.path, con->conf.errorfile_prefix);
248 buffer_append_int(con->physical.path, con->http_status);
249 buffer_append_string_len(con->physical.path, CONST_STR_LEN(".html"));
251 if (0 == http_chunk_append_file(srv, con, con->physical.path)) {
252 con->file_finished = 1;
253 if (HANDLER_ERROR != stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
254 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce->content_type));
259 if (!con->file_finished) {
260 buffer *b;
262 buffer_reset(con->physical.path);
264 con->file_finished = 1;
265 b = buffer_init();
267 /* build default error-page */
268 buffer_copy_string_len(b, CONST_STR_LEN(
269 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
270 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
271 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
272 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
273 " <head>\n"
274 " <title>"));
275 buffer_append_int(b, con->http_status);
276 buffer_append_string_len(b, CONST_STR_LEN(" - "));
277 buffer_append_string(b, get_http_status_name(con->http_status));
279 buffer_append_string_len(b, CONST_STR_LEN(
280 "</title>\n"
281 " </head>\n"
282 " <body>\n"
283 " <h1>"));
284 buffer_append_int(b, con->http_status);
285 buffer_append_string_len(b, CONST_STR_LEN(" - "));
286 buffer_append_string(b, get_http_status_name(con->http_status));
288 buffer_append_string_len(b, CONST_STR_LEN("</h1>\n"
289 " </body>\n"
290 "</html>\n"
293 (void)http_chunk_append_buffer(srv, con, b);
294 buffer_free(b);
296 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
298 break;
301 if (con->file_finished) {
302 /* we have all the content and chunked encoding is not used, set a content-length */
304 if ((!(con->parsed_response & HTTP_CONTENT_LENGTH)) &&
305 (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0) {
306 off_t qlen = chunkqueue_length(con->write_queue);
309 * The Content-Length header only can be sent if we have content:
310 * - HEAD doesn't have a content-body (but have a content-length)
311 * - 1xx, 204 and 304 don't have a content-body (RFC 2616 Section 4.3)
313 * Otherwise generate a Content-Length header as chunked encoding is not
314 * available
316 if ((con->http_status >= 100 && con->http_status < 200) ||
317 con->http_status == 204 ||
318 con->http_status == 304) {
319 data_string *ds;
320 /* no Content-Body, no Content-Length */
321 if (NULL != (ds = (data_string*) array_get_element(con->response.headers, "Content-Length"))) {
322 buffer_reset(ds->value); /* Headers with empty values are ignored for output */
324 } else if (qlen > 0 || con->request.http_method != HTTP_METHOD_HEAD) {
325 /* qlen = 0 is important for Redirects (301, ...) as they MAY have
326 * a content. Browsers are waiting for a Content otherwise
328 buffer_copy_int(srv->tmp_buf, qlen);
330 response_header_overwrite(srv, con, CONST_STR_LEN("Content-Length"), CONST_BUF_LEN(srv->tmp_buf));
333 } else {
335 * the file isn't finished yet, but we have all headers
337 * to get keep-alive we either need:
338 * - Content-Length: ... (HTTP/1.0 and HTTP/1.0) or
339 * - Transfer-Encoding: chunked (HTTP/1.1)
342 if (((con->parsed_response & HTTP_CONTENT_LENGTH) == 0) &&
343 ((con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) == 0)) {
344 if (con->request.http_version == HTTP_VERSION_1_1) {
345 off_t qlen = chunkqueue_length(con->write_queue);
346 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
347 if (qlen) {
348 /* create initial Transfer-Encoding: chunked segment */
349 buffer *b = srv->tmp_chunk_len;
350 buffer_string_set_length(b, 0);
351 buffer_append_uint_hex(b, (uintmax_t)qlen);
352 buffer_append_string_len(b, CONST_STR_LEN("\r\n"));
353 chunkqueue_prepend_buffer(con->write_queue, b);
354 chunkqueue_append_mem(con->write_queue, CONST_STR_LEN("\r\n"));
356 } else {
357 con->keep_alive = 0;
362 * if the backend sent a Connection: close, follow the wish
364 * NOTE: if the backend sent Connection: Keep-Alive, but no Content-Length, we
365 * will close the connection. That's fine. We can always decide the close
366 * the connection
368 * FIXME: to be nice we should remove the Connection: ...
370 if (con->parsed_response & HTTP_CONNECTION) {
371 /* a subrequest disable keep-alive although the client wanted it */
372 if (con->keep_alive && !con->response.keep_alive) {
373 con->keep_alive = 0;
378 if (con->request.http_method == HTTP_METHOD_HEAD) {
380 * a HEAD request has the same as a GET
381 * without the content
383 con->file_finished = 1;
385 chunkqueue_reset(con->write_queue);
386 con->response.transfer_encoding &= ~HTTP_TRANSFER_ENCODING_CHUNKED;
389 http_response_write_header(srv, con);
391 return 0;
394 static int connection_handle_write(server *srv, connection *con) {
395 switch(network_write_chunkqueue(srv, con, con->write_queue, MAX_WRITE_LIMIT)) {
396 case 0:
397 con->write_request_ts = srv->cur_ts;
398 if (con->file_finished) {
399 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
401 break;
402 case -1: /* error on our side */
403 log_error_write(srv, __FILE__, __LINE__, "sd",
404 "connection closed: write failed on fd", con->fd);
405 connection_set_state(srv, con, CON_STATE_ERROR);
406 break;
407 case -2: /* remote close */
408 connection_set_state(srv, con, CON_STATE_ERROR);
409 break;
410 case 1:
411 con->write_request_ts = srv->cur_ts;
412 con->is_writable = 0;
414 /* not finished yet -> WRITE */
415 break;
418 return 0;
423 connection *connection_init(server *srv) {
424 connection *con;
426 UNUSED(srv);
428 con = calloc(1, sizeof(*con));
429 force_assert(NULL != con);
431 con->fd = 0;
432 con->ndx = -1;
433 con->fde_ndx = -1;
434 con->bytes_written = 0;
435 con->bytes_read = 0;
436 con->bytes_header = 0;
437 con->loops_per_request = 0;
439 #define CLEAN(x) \
440 con->x = buffer_init();
442 CLEAN(request.uri);
443 CLEAN(request.request_line);
444 CLEAN(request.request);
445 CLEAN(request.pathinfo);
447 CLEAN(request.orig_uri);
449 CLEAN(uri.scheme);
450 CLEAN(uri.authority);
451 CLEAN(uri.path);
452 CLEAN(uri.path_raw);
453 CLEAN(uri.query);
455 CLEAN(physical.doc_root);
456 CLEAN(physical.path);
457 CLEAN(physical.basedir);
458 CLEAN(physical.rel_path);
459 CLEAN(physical.etag);
460 CLEAN(parse_request);
462 CLEAN(server_name);
463 CLEAN(dst_addr_buf);
464 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
465 CLEAN(tlsext_server_name);
466 #endif
468 #undef CLEAN
469 con->write_queue = chunkqueue_init();
470 con->read_queue = chunkqueue_init();
471 con->request_content_queue = chunkqueue_init();
472 chunkqueue_set_tempdirs(
473 con->request_content_queue,
474 srv->srvconf.upload_tempdirs,
475 srv->srvconf.upload_temp_file_size);
477 con->request.headers = array_init();
478 con->response.headers = array_init();
479 con->environment = array_init();
481 /* init plugin specific connection structures */
483 con->plugin_ctx = calloc(1, (srv->plugins.used + 1) * sizeof(void *));
484 force_assert(NULL != con->plugin_ctx);
486 con->cond_cache = calloc(srv->config_context->used, sizeof(cond_cache_t));
487 force_assert(NULL != con->cond_cache);
488 config_setup_connection(srv, con);
490 return con;
493 void connections_free(server *srv) {
494 connections *conns = srv->conns;
495 size_t i;
497 for (i = 0; i < conns->size; i++) {
498 connection *con = conns->ptr[i];
500 connection_reset(srv, con);
502 chunkqueue_free(con->write_queue);
503 chunkqueue_free(con->read_queue);
504 chunkqueue_free(con->request_content_queue);
505 array_free(con->request.headers);
506 array_free(con->response.headers);
507 array_free(con->environment);
509 #define CLEAN(x) \
510 buffer_free(con->x);
512 CLEAN(request.uri);
513 CLEAN(request.request_line);
514 CLEAN(request.request);
515 CLEAN(request.pathinfo);
517 CLEAN(request.orig_uri);
519 CLEAN(uri.scheme);
520 CLEAN(uri.authority);
521 CLEAN(uri.path);
522 CLEAN(uri.path_raw);
523 CLEAN(uri.query);
525 CLEAN(physical.doc_root);
526 CLEAN(physical.path);
527 CLEAN(physical.basedir);
528 CLEAN(physical.etag);
529 CLEAN(physical.rel_path);
530 CLEAN(parse_request);
532 CLEAN(server_name);
533 CLEAN(dst_addr_buf);
534 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
535 CLEAN(tlsext_server_name);
536 #endif
537 #undef CLEAN
538 free(con->plugin_ctx);
539 free(con->cond_cache);
541 free(con);
544 free(conns->ptr);
548 int connection_reset(server *srv, connection *con) {
549 size_t i;
551 plugins_call_connection_reset(srv, con);
553 con->is_readable = 1;
554 con->is_writable = 1;
555 con->http_status = 0;
556 con->file_finished = 0;
557 con->file_started = 0;
558 con->got_response = 0;
560 con->parsed_response = 0;
562 con->bytes_written = 0;
563 con->bytes_written_cur_second = 0;
564 con->bytes_read = 0;
565 con->bytes_header = 0;
566 con->loops_per_request = 0;
568 con->request.http_method = HTTP_METHOD_UNSET;
569 con->request.http_version = HTTP_VERSION_UNSET;
571 con->request.http_if_modified_since = NULL;
572 con->request.http_if_none_match = NULL;
574 con->response.keep_alive = 0;
575 con->response.content_length = -1;
576 con->response.transfer_encoding = 0;
578 con->mode = DIRECT;
580 #define CLEAN(x) \
581 if (con->x) buffer_reset(con->x);
583 CLEAN(request.uri);
584 CLEAN(request.request_line);
585 CLEAN(request.pathinfo);
586 CLEAN(request.request);
588 /* CLEAN(request.orig_uri); */
590 CLEAN(uri.scheme);
591 /* CLEAN(uri.authority); */
592 /* CLEAN(uri.path); */
593 CLEAN(uri.path_raw);
594 /* CLEAN(uri.query); */
596 CLEAN(physical.doc_root);
597 CLEAN(physical.path);
598 CLEAN(physical.basedir);
599 CLEAN(physical.rel_path);
600 CLEAN(physical.etag);
602 CLEAN(parse_request);
604 CLEAN(server_name);
605 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
606 CLEAN(tlsext_server_name);
607 #endif
608 #undef CLEAN
610 #define CLEAN(x) \
611 if (con->x) con->x->used = 0;
613 #undef CLEAN
615 #define CLEAN(x) \
616 con->request.x = NULL;
618 CLEAN(http_host);
619 CLEAN(http_range);
620 CLEAN(http_content_type);
621 #undef CLEAN
622 con->request.content_length = 0;
624 array_reset(con->request.headers);
625 array_reset(con->response.headers);
626 array_reset(con->environment);
628 chunkqueue_reset(con->write_queue);
629 chunkqueue_reset(con->request_content_queue);
631 /* the plugins should cleanup themself */
632 for (i = 0; i < srv->plugins.used; i++) {
633 plugin *p = ((plugin **)(srv->plugins.ptr))[i];
634 plugin_data *pd = p->data;
636 if (!pd) continue;
638 if (con->plugin_ctx[pd->id] != NULL) {
639 log_error_write(srv, __FILE__, __LINE__, "sb", "missing cleanup in", p->name);
642 con->plugin_ctx[pd->id] = NULL;
645 /* The cond_cache gets reset in response.c */
646 /* config_cond_cache_reset(srv, con); */
648 con->header_len = 0;
649 con->error_handler_saved_status = 0;
650 /*con->error_handler_saved_method = HTTP_METHOD_UNSET;*/
651 /*(error_handler_saved_method value is not valid unless error_handler_saved_status is set)*/
653 config_setup_connection(srv, con);
655 return 0;
659 * handle all header and content read
661 * we get called by the state-engine and by the fdevent-handler
663 static int connection_handle_read_state(server *srv, connection *con) {
664 chunk *c, *last_chunk;
665 off_t last_offset;
666 chunkqueue *cq = con->read_queue;
667 int is_closed = 0; /* the connection got closed, if we don't have a complete header, -> error */
668 /* when in CON_STATE_READ: about to receive first byte for a request: */
669 int is_request_start = chunkqueue_is_empty(cq);
671 if (con->is_readable) {
672 con->read_idle_ts = srv->cur_ts;
674 switch(connection_handle_read(srv, con)) {
675 case -1:
676 return -1;
677 case -2:
678 is_closed = 1;
679 break;
680 default:
681 break;
685 chunkqueue_remove_finished_chunks(cq);
687 /* we might have got several packets at once
690 /* update request_start timestamp when first byte of
691 * next request is received on a keep-alive connection */
692 if (con->request_count > 1 && is_request_start) con->request_start = srv->cur_ts;
694 /* if there is a \r\n\r\n in the chunkqueue
696 * scan the chunk-queue twice
697 * 1. to find the \r\n\r\n
698 * 2. to copy the header-packet
702 last_chunk = NULL;
703 last_offset = 0;
705 for (c = cq->first; c; c = c->next) {
706 size_t i;
707 size_t len = buffer_string_length(c->mem) - c->offset;
708 const char *b = c->mem->ptr + c->offset;
710 for (i = 0; i < len; ++i) {
711 char ch = b[i];
713 if ('\r' == ch) {
714 /* chec if \n\r\n follows */
715 size_t j = i+1;
716 chunk *cc = c;
717 const char header_end[] = "\r\n\r\n";
718 int header_end_match_pos = 1;
720 for ( ; cc; cc = cc->next, j = 0 ) {
721 size_t bblen = buffer_string_length(cc->mem) - cc->offset;
722 const char *bb = cc->mem->ptr + cc->offset;
724 for ( ; j < bblen; j++) {
725 ch = bb[j];
727 if (ch == header_end[header_end_match_pos]) {
728 header_end_match_pos++;
729 if (4 == header_end_match_pos) {
730 last_chunk = cc;
731 last_offset = j+1;
732 goto found_header_end;
734 } else {
735 goto reset_search;
740 reset_search: ;
743 found_header_end:
745 /* found */
746 if (last_chunk) {
747 buffer_reset(con->request.request);
749 for (c = cq->first; c; c = c->next) {
750 size_t len = buffer_string_length(c->mem) - c->offset;
752 if (c == last_chunk) {
753 len = last_offset;
756 buffer_append_string_len(con->request.request, c->mem->ptr + c->offset, len);
757 c->offset += len;
758 cq->bytes_out += len;
760 if (c == last_chunk) break;
763 connection_set_state(srv, con, CON_STATE_REQUEST_END);
764 } else if (chunkqueue_length(cq) > 64 * 1024) {
765 log_error_write(srv, __FILE__, __LINE__, "s", "oversized request-header -> sending Status 414");
767 con->http_status = 414; /* Request-URI too large */
768 con->keep_alive = 0;
769 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
770 } else if (is_closed) {
771 /* the connection got closed and we didn't got enough data to leave CON_STATE_READ;
772 * the only way is to leave here */
773 connection_set_state(srv, con, CON_STATE_ERROR);
776 chunkqueue_remove_finished_chunks(cq);
778 return 0;
781 static handler_t connection_handle_fdevent(server *srv, void *context, int revents) {
782 connection *con = context;
784 joblist_append(srv, con);
786 if (con->srv_socket->is_ssl) {
787 /* ssl may read and write for both reads and writes */
788 if (revents & (FDEVENT_IN | FDEVENT_OUT)) {
789 con->is_readable = 1;
790 con->is_writable = 1;
792 } else {
793 if (revents & FDEVENT_IN) {
794 con->is_readable = 1;
796 if (revents & FDEVENT_OUT) {
797 con->is_writable = 1;
798 /* we don't need the event twice */
803 if (revents & ~(FDEVENT_IN | FDEVENT_OUT)) {
804 /* looks like an error */
806 /* FIXME: revents = 0x19 still means that we should read from the queue */
807 if (revents & FDEVENT_HUP) {
808 if (con->state == CON_STATE_CLOSE) {
809 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
810 } else {
811 /* sigio reports the wrong event here
813 * there was no HUP at all
815 #ifdef USE_LINUX_SIGIO
816 if (srv->ev->in_sigio == 1) {
817 log_error_write(srv, __FILE__, __LINE__, "sd",
818 "connection closed: poll() -> HUP", con->fd);
819 } else {
820 connection_set_state(srv, con, CON_STATE_ERROR);
822 #else
823 connection_set_state(srv, con, CON_STATE_ERROR);
824 #endif
827 } else if (revents & FDEVENT_ERR) {
828 /* error, connection reset, whatever... we don't want to spam the logfile */
829 #if 0
830 log_error_write(srv, __FILE__, __LINE__, "sd",
831 "connection closed: poll() -> ERR", con->fd);
832 #endif
833 connection_set_state(srv, con, CON_STATE_ERROR);
834 } else {
835 log_error_write(srv, __FILE__, __LINE__, "sd",
836 "connection closed: poll() -> ???", revents);
840 if (con->state == CON_STATE_READ) {
841 connection_handle_read_state(srv, con);
844 if (con->state == CON_STATE_WRITE &&
845 !chunkqueue_is_empty(con->write_queue) &&
846 con->is_writable) {
848 if (-1 == connection_handle_write(srv, con)) {
849 connection_set_state(srv, con, CON_STATE_ERROR);
851 log_error_write(srv, __FILE__, __LINE__, "ds",
852 con->fd,
853 "handle write failed.");
857 if (con->state == CON_STATE_CLOSE) {
858 /* flush the read buffers */
859 int len;
860 char buf[1024];
862 len = read(con->fd, buf, sizeof(buf));
863 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
864 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
868 return HANDLER_FINISHED;
872 connection *connection_accept(server *srv, server_socket *srv_socket) {
873 /* accept everything */
875 /* search an empty place */
876 int cnt;
877 sock_addr cnt_addr;
878 socklen_t cnt_len;
879 /* accept it and register the fd */
882 * check if we can still open a new connections
884 * see #1216
887 if (srv->conns->used >= srv->max_conns) {
888 return NULL;
891 cnt_len = sizeof(cnt_addr);
893 if (-1 == (cnt = accept(srv_socket->fd, (struct sockaddr *) &cnt_addr, &cnt_len))) {
894 switch (errno) {
895 case EAGAIN:
896 #if EWOULDBLOCK != EAGAIN
897 case EWOULDBLOCK:
898 #endif
899 case EINTR:
900 /* we were stopped _before_ we had a connection */
901 case ECONNABORTED: /* this is a FreeBSD thingy */
902 /* we were stopped _after_ we had a connection */
903 break;
904 case EMFILE:
905 /* out of fds */
906 break;
907 default:
908 log_error_write(srv, __FILE__, __LINE__, "ssd", "accept failed:", strerror(errno), errno);
910 return NULL;
911 } else {
912 if (cnt_addr.plain.sa_family != AF_UNIX) {
913 network_accept_tcp_nagle_disable(cnt);
915 return connection_accepted(srv, srv_socket, &cnt_addr, cnt);
919 connection *connection_accepted(server *srv, server_socket *srv_socket, sock_addr *cnt_addr, int cnt) {
920 connection *con;
922 srv->cur_fds++;
924 /* ok, we have the connection, register it */
925 #if 0
926 log_error_write(srv, __FILE__, __LINE__, "sd",
927 "appected()", cnt);
928 #endif
929 srv->con_opened++;
931 con = connections_get_new_connection(srv);
933 con->fd = cnt;
934 con->fde_ndx = -1;
935 #if 0
936 gettimeofday(&(con->start_tv), NULL);
937 #endif
938 fdevent_register(srv->ev, con->fd, connection_handle_fdevent, con);
940 connection_set_state(srv, con, CON_STATE_REQUEST_START);
942 con->connection_start = srv->cur_ts;
943 con->dst_addr = *cnt_addr;
944 buffer_copy_string(con->dst_addr_buf, inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
945 con->srv_socket = srv_socket;
947 if (-1 == (fdevent_fcntl_set(srv->ev, con->fd))) {
948 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno));
949 return NULL;
951 #ifdef USE_OPENSSL
952 /* connect FD to SSL */
953 if (srv_socket->is_ssl) {
954 if (NULL == (con->ssl = SSL_new(srv_socket->ssl_ctx))) {
955 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
956 ERR_error_string(ERR_get_error(), NULL));
958 return NULL;
961 con->renegotiations = 0;
962 SSL_set_app_data(con->ssl, con);
963 SSL_set_accept_state(con->ssl);
965 if (1 != (SSL_set_fd(con->ssl, cnt))) {
966 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
967 ERR_error_string(ERR_get_error(), NULL));
968 return NULL;
971 #endif
972 return con;
976 int connection_state_machine(server *srv, connection *con) {
977 int done = 0, r;
978 #ifdef USE_OPENSSL
979 server_socket *srv_sock = con->srv_socket;
980 #endif
982 if (srv->srvconf.log_state_handling) {
983 log_error_write(srv, __FILE__, __LINE__, "sds",
984 "state at start",
985 con->fd,
986 connection_get_state(con->state));
989 while (done == 0) {
990 size_t ostate = con->state;
992 switch (con->state) {
993 case CON_STATE_REQUEST_START: /* transient */
994 if (srv->srvconf.log_state_handling) {
995 log_error_write(srv, __FILE__, __LINE__, "sds",
996 "state for fd", con->fd, connection_get_state(con->state));
999 con->request_start = srv->cur_ts;
1000 con->read_idle_ts = srv->cur_ts;
1002 con->request_count++;
1003 con->loops_per_request = 0;
1005 connection_set_state(srv, con, CON_STATE_READ);
1007 break;
1008 case CON_STATE_REQUEST_END: /* transient */
1009 if (srv->srvconf.log_state_handling) {
1010 log_error_write(srv, __FILE__, __LINE__, "sds",
1011 "state for fd", con->fd, connection_get_state(con->state));
1014 buffer_reset(con->uri.authority);
1015 buffer_reset(con->uri.path);
1016 buffer_reset(con->uri.query);
1017 buffer_reset(con->request.orig_uri);
1019 if (http_request_parse(srv, con)) {
1020 /* we have to read some data from the POST request */
1022 connection_set_state(srv, con, CON_STATE_READ_POST);
1024 break;
1027 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
1029 break;
1030 case CON_STATE_READ_POST:
1031 case CON_STATE_HANDLE_REQUEST:
1033 * the request is parsed
1035 * decided what to do with the request
1041 if (srv->srvconf.log_state_handling) {
1042 log_error_write(srv, __FILE__, __LINE__, "sds",
1043 "state for fd", con->fd, connection_get_state(con->state));
1046 switch (r = http_response_prepare(srv, con)) {
1047 case HANDLER_WAIT_FOR_EVENT:
1048 if (!con->file_finished && (!con->file_started || 0 == con->conf.stream_response_body)) {
1049 break; /* come back here */
1051 /* response headers received from backend; fall through to start response */
1052 case HANDLER_FINISHED:
1053 if (con->error_handler_saved_status > 0) {
1054 con->request.http_method = con->error_handler_saved_method;
1056 if (con->mode == DIRECT) {
1057 if (con->error_handler_saved_status) {
1058 if (con->error_handler_saved_status > 0) {
1059 con->http_status = con->error_handler_saved_status;
1060 } else if (con->http_status == 404 || con->http_status == 403) {
1061 /* error-handler-404 is a 404 */
1062 con->http_status = -con->error_handler_saved_status;
1063 } else {
1064 /* error-handler-404 is back and has generated content */
1065 /* if Status: was set, take it otherwise use 200 */
1067 } else if (con->http_status >= 400) {
1068 buffer *error_handler = NULL;
1069 if (!buffer_string_is_empty(con->conf.error_handler)) {
1070 error_handler = con->conf.error_handler;
1071 } else if ((con->http_status == 404 || con->http_status == 403)
1072 && !buffer_string_is_empty(con->conf.error_handler_404)) {
1073 error_handler = con->conf.error_handler_404;
1076 if (error_handler) {
1077 /* call error-handler */
1079 /* set REDIRECT_STATUS to save current HTTP status code
1080 * for access by dynamic handlers
1081 * https://redmine.lighttpd.net/issues/1828 */
1082 data_string *ds;
1083 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
1084 ds = data_string_init();
1086 buffer_copy_string_len(ds->key, CONST_STR_LEN("REDIRECT_STATUS"));
1087 buffer_append_int(ds->value, con->http_status);
1088 array_insert_unique(con->environment, (data_unset *)ds);
1090 if (error_handler == con->conf.error_handler) {
1091 plugins_call_connection_reset(srv, con);
1093 if (con->request.content_length) {
1094 if ((off_t)con->request.content_length != chunkqueue_length(con->request_content_queue)) {
1095 con->keep_alive = 0;
1097 con->request.content_length = 0;
1098 chunkqueue_reset(con->request_content_queue);
1101 con->is_writable = 1;
1102 con->file_finished = 0;
1103 con->file_started = 0;
1104 con->got_response = 0;
1105 con->parsed_response = 0;
1106 con->response.keep_alive = 0;
1107 con->response.content_length = -1;
1108 con->response.transfer_encoding = 0;
1110 array_set_key_value(con->environment, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.orig_uri));
1111 con->error_handler_saved_status = con->http_status;
1112 con->error_handler_saved_method = con->request.http_method;
1114 con->request.http_method = HTTP_METHOD_GET;
1115 } else { /*(preserve behavior for server.error-handler-404)*/
1116 array_set_key_value(con->environment, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(error_handler));
1117 con->error_handler_saved_status = -con->http_status; /*(negative to flag old behavior)*/
1120 buffer_copy_buffer(con->request.uri, error_handler);
1121 connection_handle_errdoc_init(srv, con);
1122 con->http_status = 0; /*(after connection_handle_errdoc_init())*/
1124 done = -1;
1125 break;
1129 if (con->http_status == 0) con->http_status = 200;
1131 /* we have something to send, go on */
1132 connection_set_state(srv, con, CON_STATE_RESPONSE_START);
1133 break;
1134 case HANDLER_WAIT_FOR_FD:
1135 srv->want_fds++;
1137 fdwaitqueue_append(srv, con);
1139 break;
1140 case HANDLER_COMEBACK:
1141 done = -1;
1142 break;
1143 case HANDLER_ERROR:
1144 /* something went wrong */
1145 connection_set_state(srv, con, CON_STATE_ERROR);
1146 break;
1147 default:
1148 log_error_write(srv, __FILE__, __LINE__, "sdd", "unknown ret-value: ", con->fd, r);
1149 break;
1152 break;
1153 case CON_STATE_RESPONSE_START:
1155 * the decision is done
1156 * - create the HTTP-Response-Header
1160 if (srv->srvconf.log_state_handling) {
1161 log_error_write(srv, __FILE__, __LINE__, "sds",
1162 "state for fd", con->fd, connection_get_state(con->state));
1165 if (-1 == connection_handle_write_prepare(srv, con)) {
1166 connection_set_state(srv, con, CON_STATE_ERROR);
1168 break;
1171 connection_set_state(srv, con, CON_STATE_WRITE);
1172 break;
1173 case CON_STATE_RESPONSE_END: /* transient */
1174 /* log the request */
1176 if (srv->srvconf.log_state_handling) {
1177 log_error_write(srv, __FILE__, __LINE__, "sds",
1178 "state for fd", con->fd, connection_get_state(con->state));
1181 if (con->request.content_length
1182 && (off_t)con->request.content_length > con->request_content_queue->bytes_in) {
1183 /* request body is present and has not been read completely */
1184 con->keep_alive = 0;
1187 plugins_call_handle_request_done(srv, con);
1189 srv->con_written++;
1191 if (con->keep_alive) {
1192 connection_set_state(srv, con, CON_STATE_REQUEST_START);
1194 #if 0
1195 con->request_start = srv->cur_ts;
1196 con->read_idle_ts = srv->cur_ts;
1197 #endif
1198 } else {
1199 switch(r = plugins_call_handle_connection_close(srv, con)) {
1200 case HANDLER_GO_ON:
1201 case HANDLER_FINISHED:
1202 break;
1203 default:
1204 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1205 break;
1208 #ifdef USE_OPENSSL
1209 if (srv_sock->is_ssl) {
1210 switch (SSL_shutdown(con->ssl)) {
1211 case 1:
1212 /* done */
1213 break;
1214 case 0:
1215 /* wait for fd-event
1217 * FIXME: wait for fdevent and call SSL_shutdown again
1221 break;
1222 default:
1223 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1224 ERR_error_string(ERR_get_error(), NULL));
1227 #endif
1228 if ((0 == shutdown(con->fd, SHUT_WR))) {
1229 con->close_timeout_ts = srv->cur_ts;
1230 connection_set_state(srv, con, CON_STATE_CLOSE);
1231 } else {
1232 connection_close(srv, con);
1235 srv->con_closed++;
1238 connection_reset(srv, con);
1240 break;
1241 case CON_STATE_CONNECT:
1242 if (srv->srvconf.log_state_handling) {
1243 log_error_write(srv, __FILE__, __LINE__, "sds",
1244 "state for fd", con->fd, connection_get_state(con->state));
1247 chunkqueue_reset(con->read_queue);
1249 con->request_count = 0;
1251 break;
1252 case CON_STATE_CLOSE:
1253 if (srv->srvconf.log_state_handling) {
1254 log_error_write(srv, __FILE__, __LINE__, "sds",
1255 "state for fd", con->fd, connection_get_state(con->state));
1258 /* we have to do the linger_on_close stuff regardless
1259 * of con->keep_alive; even non-keepalive sockets may
1260 * still have unread data, and closing before reading
1261 * it will make the client not see all our output.
1264 int len;
1265 char buf[1024];
1267 len = read(con->fd, buf, sizeof(buf));
1268 if (len == 0 || (len < 0 && errno != EAGAIN && errno != EINTR) ) {
1269 con->close_timeout_ts = srv->cur_ts - (HTTP_LINGER_TIMEOUT+1);
1273 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1274 connection_close(srv, con);
1276 if (srv->srvconf.log_state_handling) {
1277 log_error_write(srv, __FILE__, __LINE__, "sd",
1278 "connection closed for fd", con->fd);
1282 break;
1283 case CON_STATE_READ:
1284 if (srv->srvconf.log_state_handling) {
1285 log_error_write(srv, __FILE__, __LINE__, "sds",
1286 "state for fd", con->fd, connection_get_state(con->state));
1289 connection_handle_read_state(srv, con);
1290 break;
1291 case CON_STATE_WRITE:
1292 if (srv->srvconf.log_state_handling) {
1293 log_error_write(srv, __FILE__, __LINE__, "sds",
1294 "state for fd", con->fd, connection_get_state(con->state));
1297 do {
1298 /* only try to write if we have something in the queue */
1299 if (!chunkqueue_is_empty(con->write_queue)) {
1300 if (con->is_writable) {
1301 if (-1 == connection_handle_write(srv, con)) {
1302 log_error_write(srv, __FILE__, __LINE__, "ds",
1303 con->fd,
1304 "handle write failed.");
1305 connection_set_state(srv, con, CON_STATE_ERROR);
1306 break;
1308 if (con->state != CON_STATE_WRITE) break;
1310 } else if (con->file_finished) {
1311 connection_set_state(srv, con, CON_STATE_RESPONSE_END);
1312 break;
1315 if (con->mode != DIRECT && !con->file_finished) {
1316 switch(r = plugins_call_handle_subrequest(srv, con)) {
1317 case HANDLER_WAIT_FOR_EVENT:
1318 case HANDLER_FINISHED:
1319 case HANDLER_GO_ON:
1320 break;
1321 case HANDLER_WAIT_FOR_FD:
1322 srv->want_fds++;
1323 fdwaitqueue_append(srv, con);
1324 break;
1325 case HANDLER_COMEBACK:
1326 default:
1327 log_error_write(srv, __FILE__, __LINE__, "sdd", "unexpected subrequest handler ret-value: ", con->fd, r);
1328 /* fall through */
1329 case HANDLER_ERROR:
1330 connection_set_state(srv, con, CON_STATE_ERROR);
1331 break;
1334 } while (con->state == CON_STATE_WRITE && (!chunkqueue_is_empty(con->write_queue) ? con->is_writable : con->file_finished));
1336 break;
1337 case CON_STATE_ERROR: /* transient */
1339 /* even if the connection was drop we still have to write it to the access log */
1340 if (con->http_status) {
1341 plugins_call_handle_request_done(srv, con);
1343 #ifdef USE_OPENSSL
1344 if (srv_sock->is_ssl) {
1345 int ret, ssl_r;
1346 unsigned long err;
1347 ERR_clear_error();
1348 switch ((ret = SSL_shutdown(con->ssl))) {
1349 case 1:
1350 /* ok */
1351 break;
1352 case 0:
1353 ERR_clear_error();
1354 if (-1 != (ret = SSL_shutdown(con->ssl))) break;
1356 /* fall through */
1357 default:
1359 switch ((ssl_r = SSL_get_error(con->ssl, ret))) {
1360 case SSL_ERROR_WANT_WRITE:
1361 case SSL_ERROR_WANT_READ:
1362 break;
1363 case SSL_ERROR_SYSCALL:
1364 /* perhaps we have error waiting in our error-queue */
1365 if (0 != (err = ERR_get_error())) {
1366 do {
1367 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1368 ssl_r, ret,
1369 ERR_error_string(err, NULL));
1370 } while((err = ERR_get_error()));
1371 } else if (errno != 0) { /* ssl bug (see lighttpd ticket #2213): sometimes errno == 0 */
1372 switch(errno) {
1373 case EPIPE:
1374 case ECONNRESET:
1375 break;
1376 default:
1377 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL (error):",
1378 ssl_r, ret, errno,
1379 strerror(errno));
1380 break;
1384 break;
1385 default:
1386 while((err = ERR_get_error())) {
1387 log_error_write(srv, __FILE__, __LINE__, "sdds", "SSL:",
1388 ssl_r, ret,
1389 ERR_error_string(err, NULL));
1392 break;
1395 ERR_clear_error();
1397 #endif
1399 switch(con->mode) {
1400 case DIRECT:
1401 #if 0
1402 log_error_write(srv, __FILE__, __LINE__, "sd",
1403 "emergency exit: direct",
1404 con->fd);
1405 #endif
1406 break;
1407 default:
1408 switch(r = plugins_call_handle_connection_close(srv, con)) {
1409 case HANDLER_GO_ON:
1410 case HANDLER_FINISHED:
1411 break;
1412 default:
1413 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandling return value", r);
1414 break;
1416 break;
1419 connection_reset(srv, con);
1421 /* close the connection */
1422 if ((0 == shutdown(con->fd, SHUT_WR))) {
1423 con->close_timeout_ts = srv->cur_ts;
1424 connection_set_state(srv, con, CON_STATE_CLOSE);
1426 if (srv->srvconf.log_state_handling) {
1427 log_error_write(srv, __FILE__, __LINE__, "sd",
1428 "shutdown for fd", con->fd);
1430 } else {
1431 connection_close(srv, con);
1434 con->keep_alive = 0;
1436 srv->con_closed++;
1438 break;
1439 default:
1440 log_error_write(srv, __FILE__, __LINE__, "sdd",
1441 "unknown state:", con->fd, con->state);
1443 break;
1446 if (done == -1) {
1447 done = 0;
1448 } else if (ostate == con->state) {
1449 done = 1;
1453 if (srv->srvconf.log_state_handling) {
1454 log_error_write(srv, __FILE__, __LINE__, "sds",
1455 "state at exit:",
1456 con->fd,
1457 connection_get_state(con->state));
1460 r = 0;
1461 switch(con->state) {
1462 case CON_STATE_READ:
1463 case CON_STATE_CLOSE:
1464 r = FDEVENT_IN;
1465 break;
1466 case CON_STATE_WRITE:
1467 /* request write-fdevent only if we really need it
1468 * - if we have data to write
1469 * - if the socket is not writable yet
1471 if (!chunkqueue_is_empty(con->write_queue) &&
1472 (con->is_writable == 0) &&
1473 (con->traffic_limit_reached == 0)) {
1474 r |= FDEVENT_OUT;
1476 /* fall through */
1477 case CON_STATE_READ_POST:
1478 if (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN) {
1479 r |= FDEVENT_IN;
1481 break;
1482 default:
1483 break;
1485 if (-1 != con->fd) {
1486 const int events = fdevent_event_get_interest(srv->ev, con->fd);
1487 if (r != events) {
1488 /* update timestamps when enabling interest in events */
1489 if ((r & FDEVENT_IN) && !(events & FDEVENT_IN)) {
1490 con->read_idle_ts = srv->cur_ts;
1492 if ((r & FDEVENT_OUT) && !(events & FDEVENT_OUT)) {
1493 con->write_request_ts = srv->cur_ts;
1495 fdevent_event_set(srv->ev, &con->fde_ndx, con->fd, r);
1499 return 0;