6 #include "connections.h"
9 #include "configfile.h"
13 #include "http_chunk.h"
14 #include "stat_cache.h"
19 #include "inet_ntop_cache.h"
32 # include <openssl/ssl.h>
33 # include <openssl/err.h>
36 #ifdef HAVE_SYS_FILIO_H
37 # include <sys/filio.h>
40 #include "sys-socket.h"
46 static connection
*connections_get_new_connection(server
*srv
) {
47 connections
*conns
= srv
->conns
;
50 if (conns
->size
== 0) {
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
) {
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
]);
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");
77 conns
->ptr
[conns
->used
]->ndx
= conns
->used
;
78 return conns
->ptr
[conns
->used
++];
81 static int connection_del(server
*srv
, connection
*con
) {
83 connections
*conns
= srv
->conns
;
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
);
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;
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");
121 static int connection_close(server
*srv
, connection
*con
) {
123 server_socket
*srv_sock
= con
->srv_socket
;
124 if (srv_sock
->is_ssl
) {
125 if (con
->ssl
) SSL_free(con
->ssl
);
130 fdevent_event_del(srv
->ev
, &(con
->fde_ndx
), con
->fd
);
131 fdevent_unregister(srv
->ev
, con
->fd
);
133 if (closesocket(con
->fd
)) {
134 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
135 "(warning) close:", con
->fd
, strerror(errno
));
138 if (close(con
->fd
)) {
139 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
140 "(warning) close:", con
->fd
, strerror(errno
));
147 if (srv
->srvconf
.log_state_handling
) {
148 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
149 "connection closed for fd", con
->fd
);
152 connection_del(srv
, con
);
153 connection_set_state(srv
, con
, CON_STATE_CONNECT
);
158 static void connection_read_for_eos(server
*srv
, connection
*con
) {
159 /* we have to do the linger_on_close stuff regardless
160 * of con->keep_alive; even non-keepalive sockets may
161 * still have unread data, and closing before reading
162 * it will make the client not see all our output.
168 len
= read(con
->fd
, buf
, sizeof(buf
));
169 } while (len
> 0 || (len
< 0 && errno
== EINTR
));
171 if (len
< 0 && errno
== EAGAIN
) return;
172 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
173 if (len
< 0 && errno
== EWOULDBLOCK
) return;
176 /* 0 == len || (len < 0 && (errno is a non-recoverable error)) */
177 con
->close_timeout_ts
= srv
->cur_ts
- (HTTP_LINGER_TIMEOUT
+1);
180 static void connection_handle_close_state(server
*srv
, connection
*con
) {
181 connection_read_for_eos(srv
, con
);
183 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
) {
184 connection_close(srv
, con
);
188 static void connection_handle_shutdown(server
*srv
, connection
*con
) {
192 server_socket
*srv_sock
= con
->srv_socket
;
193 if (srv_sock
->is_ssl
&& SSL_is_init_finished(con
->ssl
)) {
197 switch ((ret
= SSL_shutdown(con
->ssl
))) {
204 * FIXME: wait for fdevent and call SSL_shutdown again
208 if (-1 != (ret
= SSL_shutdown(con
->ssl
))) break;
213 switch ((ssl_r
= SSL_get_error(con
->ssl
, ret
))) {
214 case SSL_ERROR_ZERO_RETURN
:
216 case SSL_ERROR_WANT_WRITE
:
217 /*con->is_writable = -1;*//*(no effect; shutdown() called below)*/
218 case SSL_ERROR_WANT_READ
:
220 case SSL_ERROR_SYSCALL
:
221 /* perhaps we have error waiting in our error-queue */
222 if (0 != (err
= ERR_get_error())) {
224 log_error_write(srv
, __FILE__
, __LINE__
, "sdds", "SSL:",
226 ERR_error_string(err
, NULL
));
227 } while((err
= ERR_get_error()));
228 } else if (errno
!= 0) { /* ssl bug (see lighttpd ticket #2213): sometimes errno == 0 */
234 log_error_write(srv
, __FILE__
, __LINE__
, "sddds", "SSL (error):",
243 while((err
= ERR_get_error())) {
244 log_error_write(srv
, __FILE__
, __LINE__
, "sdds", "SSL:",
246 ERR_error_string(err
, NULL
));
256 switch(r
= plugins_call_handle_connection_close(srv
, con
)) {
258 case HANDLER_FINISHED
:
261 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "unhandling return value", r
);
266 connection_reset(srv
, con
);
268 /* plugins should have cleaned themselves up */
269 for (size_t i
= 0; i
< srv
->plugins
.used
; ++i
) {
270 plugin
*p
= ((plugin
**)(srv
->plugins
.ptr
))[i
];
271 plugin_data
*pd
= p
->data
;
272 if (!pd
|| NULL
== con
->plugin_ctx
[pd
->id
]) continue;
273 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
274 "missing cleanup in", p
->name
);
275 con
->plugin_ctx
[pd
->id
] = NULL
;
278 /* close the connection */
279 if ((0 == shutdown(con
->fd
, SHUT_WR
))) {
280 con
->close_timeout_ts
= srv
->cur_ts
;
281 connection_set_state(srv
, con
, CON_STATE_CLOSE
);
283 if (srv
->srvconf
.log_state_handling
) {
284 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
285 "shutdown for fd", con
->fd
);
288 connection_close(srv
, con
);
292 static void connection_handle_response_end_state(server
*srv
, connection
*con
) {
293 /* log the request */
294 /* (even if error, connection dropped, still write to access log if http_status) */
295 if (con
->http_status
) {
296 plugins_call_handle_request_done(srv
, con
);
299 if (con
->state
!= CON_STATE_ERROR
) srv
->con_written
++;
301 if (con
->request
.content_length
!= con
->request_content_queue
->bytes_in
302 || con
->state
== CON_STATE_ERROR
) {
303 /* request body is present and has not been read completely */
307 if (con
->keep_alive
) {
308 connection_reset(srv
, con
);
310 con
->request_start
= srv
->cur_ts
;
311 con
->read_idle_ts
= srv
->cur_ts
;
313 connection_set_state(srv
, con
, CON_STATE_REQUEST_START
);
315 connection_handle_shutdown(srv
, con
);
319 static void connection_handle_errdoc_init(server
*srv
, connection
*con
) {
320 /* modules that produce headers required with error response should
321 * typically also produce an error document. Make an exception for
322 * mod_auth WWW-Authenticate response header. */
323 buffer
*www_auth
= NULL
;
324 if (401 == con
->http_status
) {
325 data_string
*ds
= (data_string
*)array_get_element(con
->response
.headers
, "WWW-Authenticate");
327 www_auth
= buffer_init_buffer(ds
->value
);
331 con
->response
.transfer_encoding
= 0;
332 buffer_reset(con
->physical
.path
);
333 array_reset(con
->response
.headers
);
334 chunkqueue_reset(con
->write_queue
);
336 if (NULL
!= www_auth
) {
337 response_header_insert(srv
, con
, CONST_STR_LEN("WWW-Authenticate"), CONST_BUF_LEN(www_auth
));
338 buffer_free(www_auth
);
342 static int connection_handle_write_prepare(server
*srv
, connection
*con
) {
343 if (con
->mode
== DIRECT
) {
345 switch(con
->request
.http_method
) {
346 case HTTP_METHOD_GET
:
347 case HTTP_METHOD_POST
:
348 case HTTP_METHOD_HEAD
:
350 case HTTP_METHOD_OPTIONS
:
352 * 400 is coming from the request-parser BEFORE uri.path is set
353 * 403 is from the response handler when noone else catched it
356 if ((!con
->http_status
|| con
->http_status
== 200) && !buffer_string_is_empty(con
->uri
.path
) &&
357 con
->uri
.path
->ptr
[0] != '*') {
358 response_header_insert(srv
, con
, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST"));
360 con
->response
.transfer_encoding
&= ~HTTP_TRANSFER_ENCODING_CHUNKED
;
361 con
->parsed_response
&= ~HTTP_CONTENT_LENGTH
;
363 con
->http_status
= 200;
364 con
->file_finished
= 1;
366 chunkqueue_reset(con
->write_queue
);
370 if (0 == con
->http_status
) {
371 con
->http_status
= 501;
377 if (con
->http_status
== 0) {
378 con
->http_status
= 403;
381 switch(con
->http_status
) {
382 case 204: /* class: header only */
385 /* disable chunked encoding again as we have no body */
386 con
->response
.transfer_encoding
&= ~HTTP_TRANSFER_ENCODING_CHUNKED
;
387 con
->parsed_response
&= ~HTTP_CONTENT_LENGTH
;
388 chunkqueue_reset(con
->write_queue
);
390 con
->file_finished
= 1;
392 default: /* class: header + body */
393 if (con
->mode
!= DIRECT
) break;
395 /* only custom body for 4xx and 5xx */
396 if (con
->http_status
< 400 || con
->http_status
>= 600) break;
398 con
->file_finished
= 0;
400 connection_handle_errdoc_init(srv
, con
);
402 /* try to send static errorfile */
403 if (!buffer_string_is_empty(con
->conf
.errorfile_prefix
)) {
404 stat_cache_entry
*sce
= NULL
;
406 buffer_copy_buffer(con
->physical
.path
, con
->conf
.errorfile_prefix
);
407 buffer_append_int(con
->physical
.path
, con
->http_status
);
408 buffer_append_string_len(con
->physical
.path
, CONST_STR_LEN(".html"));
410 if (0 == http_chunk_append_file(srv
, con
, con
->physical
.path
)) {
411 con
->file_finished
= 1;
412 if (HANDLER_ERROR
!= stat_cache_get_entry(srv
, con
, con
->physical
.path
, &sce
)) {
413 response_header_overwrite(srv
, con
, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce
->content_type
));
418 if (!con
->file_finished
) {
421 buffer_reset(con
->physical
.path
);
423 con
->file_finished
= 1;
426 /* build default error-page */
427 buffer_copy_string_len(b
, CONST_STR_LEN(
428 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
429 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
430 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
431 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
434 buffer_append_int(b
, con
->http_status
);
435 buffer_append_string_len(b
, CONST_STR_LEN(" - "));
436 buffer_append_string(b
, get_http_status_name(con
->http_status
));
438 buffer_append_string_len(b
, CONST_STR_LEN(
443 buffer_append_int(b
, con
->http_status
);
444 buffer_append_string_len(b
, CONST_STR_LEN(" - "));
445 buffer_append_string(b
, get_http_status_name(con
->http_status
));
447 buffer_append_string_len(b
, CONST_STR_LEN("</h1>\n"
452 (void)http_chunk_append_buffer(srv
, con
, b
);
455 response_header_overwrite(srv
, con
, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
460 /* Allow filter plugins to change response headers before they are written. */
461 switch(plugins_call_handle_response_start(srv
, con
)) {
463 case HANDLER_FINISHED
:
466 log_error_write(srv
, __FILE__
, __LINE__
, "s", "response_start plugin failed");
470 if (con
->file_finished
) {
471 /* we have all the content and chunked encoding is not used, set a content-length */
473 if ((!(con
->parsed_response
& HTTP_CONTENT_LENGTH
)) &&
474 (con
->response
.transfer_encoding
& HTTP_TRANSFER_ENCODING_CHUNKED
) == 0) {
475 off_t qlen
= chunkqueue_length(con
->write_queue
);
478 * The Content-Length header only can be sent if we have content:
479 * - HEAD doesn't have a content-body (but have a content-length)
480 * - 1xx, 204 and 304 don't have a content-body (RFC 2616 Section 4.3)
482 * Otherwise generate a Content-Length header as chunked encoding is not
485 if ((con
->http_status
>= 100 && con
->http_status
< 200) ||
486 con
->http_status
== 204 ||
487 con
->http_status
== 304) {
489 /* no Content-Body, no Content-Length */
490 if (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "Content-Length"))) {
491 buffer_reset(ds
->value
); /* Headers with empty values are ignored for output */
493 } else if (qlen
> 0 || con
->request
.http_method
!= HTTP_METHOD_HEAD
) {
494 /* qlen = 0 is important for Redirects (301, ...) as they MAY have
495 * a content. Browsers are waiting for a Content otherwise
497 buffer_copy_int(srv
->tmp_buf
, qlen
);
499 response_header_overwrite(srv
, con
, CONST_STR_LEN("Content-Length"), CONST_BUF_LEN(srv
->tmp_buf
));
504 * the file isn't finished yet, but we have all headers
506 * to get keep-alive we either need:
507 * - Content-Length: ... (HTTP/1.0 and HTTP/1.0) or
508 * - Transfer-Encoding: chunked (HTTP/1.1)
511 if (((con
->parsed_response
& HTTP_CONTENT_LENGTH
) == 0) &&
512 ((con
->response
.transfer_encoding
& HTTP_TRANSFER_ENCODING_CHUNKED
) == 0)) {
513 if (con
->request
.http_version
== HTTP_VERSION_1_1
) {
514 off_t qlen
= chunkqueue_length(con
->write_queue
);
515 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
517 /* create initial Transfer-Encoding: chunked segment */
518 buffer
*b
= srv
->tmp_chunk_len
;
519 buffer_string_set_length(b
, 0);
520 buffer_append_uint_hex(b
, (uintmax_t)qlen
);
521 buffer_append_string_len(b
, CONST_STR_LEN("\r\n"));
522 chunkqueue_prepend_buffer(con
->write_queue
, b
);
523 chunkqueue_append_mem(con
->write_queue
, CONST_STR_LEN("\r\n"));
531 * if the backend sent a Connection: close, follow the wish
533 * NOTE: if the backend sent Connection: Keep-Alive, but no Content-Length, we
534 * will close the connection. That's fine. We can always decide the close
537 * FIXME: to be nice we should remove the Connection: ...
539 if (con
->parsed_response
& HTTP_CONNECTION
) {
540 /* a subrequest disable keep-alive although the client wanted it */
541 if (con
->keep_alive
&& !con
->response
.keep_alive
) {
547 if (con
->request
.http_method
== HTTP_METHOD_HEAD
) {
549 * a HEAD request has the same as a GET
550 * without the content
552 con
->file_finished
= 1;
554 chunkqueue_reset(con
->write_queue
);
555 con
->response
.transfer_encoding
&= ~HTTP_TRANSFER_ENCODING_CHUNKED
;
558 http_response_write_header(srv
, con
);
563 static int connection_handle_write(server
*srv
, connection
*con
) {
564 switch(network_write_chunkqueue(srv
, con
, con
->write_queue
, MAX_WRITE_LIMIT
)) {
566 con
->write_request_ts
= srv
->cur_ts
;
567 if (con
->file_finished
) {
568 connection_set_state(srv
, con
, CON_STATE_RESPONSE_END
);
571 case -1: /* error on our side */
572 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
573 "connection closed: write failed on fd", con
->fd
);
574 connection_set_state(srv
, con
, CON_STATE_ERROR
);
576 case -2: /* remote close */
577 connection_set_state(srv
, con
, CON_STATE_ERROR
);
580 con
->write_request_ts
= srv
->cur_ts
;
581 con
->is_writable
= 0;
583 /* not finished yet -> WRITE */
592 connection
*connection_init(server
*srv
) {
597 con
= calloc(1, sizeof(*con
));
598 force_assert(NULL
!= con
);
603 con
->bytes_written
= 0;
605 con
->bytes_header
= 0;
606 con
->loops_per_request
= 0;
609 con->x = buffer_init();
612 CLEAN(request
.request_line
);
613 CLEAN(request
.request
);
614 CLEAN(request
.pathinfo
);
616 CLEAN(request
.orig_uri
);
619 CLEAN(uri
.authority
);
624 CLEAN(physical
.doc_root
);
625 CLEAN(physical
.path
);
626 CLEAN(physical
.basedir
);
627 CLEAN(physical
.rel_path
);
628 CLEAN(physical
.etag
);
629 CLEAN(parse_request
);
633 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
634 CLEAN(tlsext_server_name
);
638 con
->write_queue
= chunkqueue_init();
639 con
->read_queue
= chunkqueue_init();
640 con
->request_content_queue
= chunkqueue_init();
642 con
->request
.headers
= array_init();
643 con
->response
.headers
= array_init();
644 con
->environment
= array_init();
646 /* init plugin specific connection structures */
648 con
->plugin_ctx
= calloc(1, (srv
->plugins
.used
+ 1) * sizeof(void *));
649 force_assert(NULL
!= con
->plugin_ctx
);
651 con
->cond_cache
= calloc(srv
->config_context
->used
, sizeof(cond_cache_t
));
652 force_assert(NULL
!= con
->cond_cache
);
653 config_setup_connection(srv
, con
);
658 void connections_free(server
*srv
) {
659 connections
*conns
= srv
->conns
;
662 for (i
= 0; i
< conns
->size
; i
++) {
663 connection
*con
= conns
->ptr
[i
];
665 connection_reset(srv
, con
);
667 chunkqueue_free(con
->write_queue
);
668 chunkqueue_free(con
->read_queue
);
669 chunkqueue_free(con
->request_content_queue
);
670 array_free(con
->request
.headers
);
671 array_free(con
->response
.headers
);
672 array_free(con
->environment
);
678 CLEAN(request
.request_line
);
679 CLEAN(request
.request
);
680 CLEAN(request
.pathinfo
);
682 CLEAN(request
.orig_uri
);
685 CLEAN(uri
.authority
);
690 CLEAN(physical
.doc_root
);
691 CLEAN(physical
.path
);
692 CLEAN(physical
.basedir
);
693 CLEAN(physical
.etag
);
694 CLEAN(physical
.rel_path
);
695 CLEAN(parse_request
);
699 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
700 CLEAN(tlsext_server_name
);
703 free(con
->plugin_ctx
);
704 free(con
->cond_cache
);
713 int connection_reset(server
*srv
, connection
*con
) {
714 plugins_call_connection_reset(srv
, con
);
716 connection_response_reset(srv
, con
);
717 con
->is_readable
= 1;
719 con
->bytes_written
= 0;
720 con
->bytes_written_cur_second
= 0;
722 con
->bytes_header
= 0;
723 con
->loops_per_request
= 0;
725 con
->request
.http_method
= HTTP_METHOD_UNSET
;
726 con
->request
.http_version
= HTTP_VERSION_UNSET
;
728 con
->request
.http_if_modified_since
= NULL
;
729 con
->request
.http_if_none_match
= NULL
;
732 if (con->x) buffer_reset(con->x);
735 CLEAN(request
.request_line
);
736 CLEAN(request
.pathinfo
);
737 CLEAN(request
.request
);
739 /* CLEAN(request.orig_uri); */
742 /* CLEAN(uri.authority); */
743 /* CLEAN(uri.path); */
745 /* CLEAN(uri.query); */
747 CLEAN(parse_request
);
750 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
751 CLEAN(tlsext_server_name
);
756 if (con->x) con->x->used = 0;
761 con->request.x = NULL;
765 CLEAN(http_content_type
);
767 con
->request
.content_length
= 0;
768 con
->request
.te_chunked
= 0;
770 array_reset(con
->request
.headers
);
771 array_reset(con
->environment
);
773 chunkqueue_reset(con
->request_content_queue
);
775 /* The cond_cache gets reset in response.c */
776 /* config_cond_cache_reset(srv, con); */
779 con
->error_handler_saved_status
= 0;
780 /*con->error_handler_saved_method = HTTP_METHOD_UNSET;*/
781 /*(error_handler_saved_method value is not valid unless error_handler_saved_status is set)*/
783 config_setup_connection(srv
, con
);
789 * handle all header and content read
791 * we get called by the state-engine and by the fdevent-handler
793 static int connection_handle_read_state(server
*srv
, connection
*con
) {
794 chunk
*c
, *last_chunk
;
796 chunkqueue
*cq
= con
->read_queue
;
797 int is_closed
= 0; /* the connection got closed, if we don't have a complete header, -> error */
798 /* when in CON_STATE_READ: about to receive first byte for a request: */
799 int is_request_start
= chunkqueue_is_empty(cq
);
801 if (con
->is_readable
) {
802 con
->read_idle_ts
= srv
->cur_ts
;
804 switch(connection_handle_read(srv
, con
)) {
815 chunkqueue_remove_finished_chunks(cq
);
817 /* we might have got several packets at once
820 /* update request_start timestamp when first byte of
821 * next request is received on a keep-alive connection */
822 if (con
->request_count
> 1 && is_request_start
) {
823 con
->request_start
= srv
->cur_ts
;
824 if (con
->conf
.high_precision_timestamps
)
825 log_clock_gettime_realtime(&con
->request_start_hp
);
828 /* if there is a \r\n\r\n in the chunkqueue
830 * scan the chunk-queue twice
831 * 1. to find the \r\n\r\n
832 * 2. to copy the header-packet
839 for (c
= cq
->first
; c
; c
= c
->next
) {
841 size_t len
= buffer_string_length(c
->mem
) - c
->offset
;
842 const char *b
= c
->mem
->ptr
+ c
->offset
;
844 for (i
= 0; i
< len
; ++i
) {
848 /* chec if \n\r\n follows */
851 const char header_end
[] = "\r\n\r\n";
852 int header_end_match_pos
= 1;
854 for ( ; cc
; cc
= cc
->next
, j
= 0 ) {
855 size_t bblen
= buffer_string_length(cc
->mem
) - cc
->offset
;
856 const char *bb
= cc
->mem
->ptr
+ cc
->offset
;
858 for ( ; j
< bblen
; j
++) {
861 if (ch
== header_end
[header_end_match_pos
]) {
862 header_end_match_pos
++;
863 if (4 == header_end_match_pos
) {
866 goto found_header_end
;
881 buffer_reset(con
->request
.request
);
883 for (c
= cq
->first
; c
; c
= c
->next
) {
884 size_t len
= buffer_string_length(c
->mem
) - c
->offset
;
886 if (c
== last_chunk
) {
890 buffer_append_string_len(con
->request
.request
, c
->mem
->ptr
+ c
->offset
, len
);
892 cq
->bytes_out
+= len
;
894 if (c
== last_chunk
) break;
897 connection_set_state(srv
, con
, CON_STATE_REQUEST_END
);
898 } else if (is_closed
) {
899 /* the connection got closed and we didn't got enough data to leave CON_STATE_READ;
900 * the only way is to leave here */
901 connection_set_state(srv
, con
, CON_STATE_ERROR
);
904 if ((last_chunk
? buffer_string_length(con
->request
.request
) : (size_t)chunkqueue_length(cq
))
905 > srv
->srvconf
.max_request_field_size
) {
906 log_error_write(srv
, __FILE__
, __LINE__
, "s", "oversized request-header -> sending Status 431");
907 con
->http_status
= 431; /* Request Header Fields Too Large */
909 connection_set_state(srv
, con
, CON_STATE_HANDLE_REQUEST
);
912 chunkqueue_remove_finished_chunks(cq
);
917 static handler_t
connection_handle_fdevent(server
*srv
, void *context
, int revents
) {
918 connection
*con
= context
;
920 joblist_append(srv
, con
);
922 if (con
->srv_socket
->is_ssl
) {
923 /* ssl may read and write for both reads and writes */
924 if (revents
& (FDEVENT_IN
| FDEVENT_OUT
)) {
925 con
->is_readable
= 1;
926 con
->is_writable
= 1;
929 if (revents
& FDEVENT_IN
) {
930 con
->is_readable
= 1;
932 if (revents
& FDEVENT_OUT
) {
933 con
->is_writable
= 1;
934 /* we don't need the event twice */
939 if (con
->state
== CON_STATE_READ
) {
940 connection_handle_read_state(srv
, con
);
943 if (con
->state
== CON_STATE_WRITE
&&
944 !chunkqueue_is_empty(con
->write_queue
) &&
947 if (-1 == connection_handle_write(srv
, con
)) {
948 connection_set_state(srv
, con
, CON_STATE_ERROR
);
950 log_error_write(srv
, __FILE__
, __LINE__
, "ds",
952 "handle write failed.");
956 if (con
->state
== CON_STATE_CLOSE
) {
957 /* flush the read buffers */
958 connection_read_for_eos(srv
, con
);
962 /* attempt (above) to read data in kernel socket buffers
963 * prior to handling FDEVENT_HUP and FDEVENT_ERR */
965 if ((revents
& ~(FDEVENT_IN
| FDEVENT_OUT
)) && con
->state
!= CON_STATE_ERROR
) {
966 if (con
->state
== CON_STATE_CLOSE
) {
967 con
->close_timeout_ts
= srv
->cur_ts
- (HTTP_LINGER_TIMEOUT
+1);
968 } else if (revents
& FDEVENT_HUP
) {
969 if (fdevent_is_tcp_half_closed(con
->fd
)) {
972 connection_set_state(srv
, con
, CON_STATE_ERROR
);
974 } else if (revents
& FDEVENT_ERR
) { /* error, connection reset */
975 connection_set_state(srv
, con
, CON_STATE_ERROR
);
977 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
978 "connection closed: poll() -> ???", revents
);
982 return HANDLER_FINISHED
;
986 connection
*connection_accept(server
*srv
, server_socket
*srv_socket
) {
987 /* accept everything */
989 /* search an empty place */
993 /* accept it and register the fd */
996 * check if we can still open a new connections
1001 if (srv
->conns
->used
>= srv
->max_conns
) {
1005 cnt_len
= sizeof(cnt_addr
);
1007 #if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
1008 #if defined(__NetBSD__)
1009 cnt
= paccept(srv_socket
->fd
, (struct sockaddr
*) &cnt_addr
, &cnt_len
, NULL
, SOCK_CLOEXEC
| SOCK_NONBLOCK
);
1011 cnt
= accept4(srv_socket
->fd
, (struct sockaddr
*) &cnt_addr
, &cnt_len
, SOCK_CLOEXEC
| SOCK_NONBLOCK
);
1014 cnt
= accept(srv_socket
->fd
, (struct sockaddr
*) &cnt_addr
, &cnt_len
);
1019 #if EWOULDBLOCK != EAGAIN
1023 /* we were stopped _before_ we had a connection */
1024 case ECONNABORTED
: /* this is a FreeBSD thingy */
1025 /* we were stopped _after_ we had a connection */
1031 log_error_write(srv
, __FILE__
, __LINE__
, "ssd", "accept failed:", strerror(errno
), errno
);
1035 if (cnt_addr
.plain
.sa_family
!= AF_UNIX
) {
1036 network_accept_tcp_nagle_disable(cnt
);
1038 return connection_accepted(srv
, srv_socket
, &cnt_addr
, cnt
);
1042 connection
*connection_accepted(server
*srv
, server_socket
*srv_socket
, sock_addr
*cnt_addr
, int cnt
) {
1047 /* ok, we have the connection, register it */
1049 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1054 con
= connections_get_new_connection(srv
);
1058 fdevent_register(srv
->ev
, con
->fd
, connection_handle_fdevent
, con
);
1060 connection_set_state(srv
, con
, CON_STATE_REQUEST_START
);
1062 con
->connection_start
= srv
->cur_ts
;
1063 con
->dst_addr
= *cnt_addr
;
1064 buffer_copy_string(con
->dst_addr_buf
, inet_ntop_cache_get_ip(srv
, &(con
->dst_addr
)));
1065 con
->srv_socket
= srv_socket
;
1067 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv
->ev
, con
->fd
)) {
1068 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl failed: ", strerror(errno
));
1069 connection_close(srv
, con
);
1073 /* connect FD to SSL */
1074 if (srv_socket
->is_ssl
) {
1075 if (NULL
== (con
->ssl
= SSL_new(srv_socket
->ssl_ctx
))) {
1076 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "SSL:",
1077 ERR_error_string(ERR_get_error(), NULL
));
1079 connection_close(srv
, con
);
1083 con
->renegotiations
= 0;
1084 SSL_set_app_data(con
->ssl
, con
);
1085 SSL_set_accept_state(con
->ssl
);
1087 if (1 != (SSL_set_fd(con
->ssl
, cnt
))) {
1088 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "SSL:",
1089 ERR_error_string(ERR_get_error(), NULL
));
1090 connection_close(srv
, con
);
1099 int connection_state_machine(server
*srv
, connection
*con
) {
1102 if (srv
->srvconf
.log_state_handling
) {
1103 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
1106 connection_get_state(con
->state
));
1110 size_t ostate
= con
->state
;
1112 if (srv
->srvconf
.log_state_handling
) {
1113 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
1114 "state for fd", con
->fd
, connection_get_state(con
->state
));
1117 switch (con
->state
) {
1118 case CON_STATE_REQUEST_START
: /* transient */
1119 con
->request_start
= srv
->cur_ts
;
1120 con
->read_idle_ts
= srv
->cur_ts
;
1121 if (con
->conf
.high_precision_timestamps
)
1122 log_clock_gettime_realtime(&con
->request_start_hp
);
1124 con
->request_count
++;
1125 con
->loops_per_request
= 0;
1127 connection_set_state(srv
, con
, CON_STATE_READ
);
1130 case CON_STATE_REQUEST_END
: /* transient */
1131 buffer_reset(con
->uri
.authority
);
1132 buffer_reset(con
->uri
.path
);
1133 buffer_reset(con
->uri
.query
);
1134 buffer_reset(con
->request
.orig_uri
);
1136 if (http_request_parse(srv
, con
)) {
1137 /* we have to read some data from the POST request */
1139 connection_set_state(srv
, con
, CON_STATE_READ_POST
);
1144 connection_set_state(srv
, con
, CON_STATE_HANDLE_REQUEST
);
1147 case CON_STATE_READ_POST
:
1148 case CON_STATE_HANDLE_REQUEST
:
1150 * the request is parsed
1152 * decided what to do with the request
1158 switch (r
= http_response_prepare(srv
, con
)) {
1159 case HANDLER_WAIT_FOR_EVENT
:
1160 if (!con
->file_finished
&& (!con
->file_started
|| 0 == con
->conf
.stream_response_body
)) {
1161 break; /* come back here */
1163 /* response headers received from backend; fall through to start response */
1164 case HANDLER_FINISHED
:
1165 if (con
->error_handler_saved_status
> 0) {
1166 con
->request
.http_method
= con
->error_handler_saved_method
;
1168 if (con
->mode
== DIRECT
) {
1169 if (con
->error_handler_saved_status
) {
1170 if (con
->error_handler_saved_status
> 0) {
1171 con
->http_status
= con
->error_handler_saved_status
;
1172 } else if (con
->http_status
== 404 || con
->http_status
== 403) {
1173 /* error-handler-404 is a 404 */
1174 con
->http_status
= -con
->error_handler_saved_status
;
1176 /* error-handler-404 is back and has generated content */
1177 /* if Status: was set, take it otherwise use 200 */
1179 } else if (con
->http_status
>= 400) {
1180 buffer
*error_handler
= NULL
;
1181 if (!buffer_string_is_empty(con
->conf
.error_handler
)) {
1182 error_handler
= con
->conf
.error_handler
;
1183 } else if ((con
->http_status
== 404 || con
->http_status
== 403)
1184 && !buffer_string_is_empty(con
->conf
.error_handler_404
)) {
1185 error_handler
= con
->conf
.error_handler_404
;
1188 if (error_handler
) {
1189 /* call error-handler */
1191 /* set REDIRECT_STATUS to save current HTTP status code
1192 * for access by dynamic handlers
1193 * https://redmine.lighttpd.net/issues/1828 */
1195 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->environment
, TYPE_STRING
))) {
1196 ds
= data_string_init();
1198 buffer_copy_string_len(ds
->key
, CONST_STR_LEN("REDIRECT_STATUS"));
1199 buffer_append_int(ds
->value
, con
->http_status
);
1200 array_insert_unique(con
->environment
, (data_unset
*)ds
);
1202 if (error_handler
== con
->conf
.error_handler
) {
1203 plugins_call_connection_reset(srv
, con
);
1205 if (con
->request
.content_length
) {
1206 if (con
->request
.content_length
!= con
->request_content_queue
->bytes_in
) {
1207 con
->keep_alive
= 0;
1209 con
->request
.content_length
= 0;
1210 chunkqueue_reset(con
->request_content_queue
);
1213 con
->is_writable
= 1;
1214 con
->file_finished
= 0;
1215 con
->file_started
= 0;
1216 con
->got_response
= 0;
1217 con
->parsed_response
= 0;
1218 con
->response
.keep_alive
= 0;
1219 con
->response
.content_length
= -1;
1220 con
->response
.transfer_encoding
= 0;
1222 con
->error_handler_saved_status
= con
->http_status
;
1223 con
->error_handler_saved_method
= con
->request
.http_method
;
1225 con
->request
.http_method
= HTTP_METHOD_GET
;
1226 } else { /*(preserve behavior for server.error-handler-404)*/
1227 con
->error_handler_saved_status
= -con
->http_status
; /*(negative to flag old behavior)*/
1230 buffer_copy_buffer(con
->request
.uri
, error_handler
);
1231 connection_handle_errdoc_init(srv
, con
);
1232 con
->http_status
= 0; /*(after connection_handle_errdoc_init())*/
1239 if (con
->http_status
== 0) con
->http_status
= 200;
1241 /* we have something to send, go on */
1242 connection_set_state(srv
, con
, CON_STATE_RESPONSE_START
);
1244 case HANDLER_WAIT_FOR_FD
:
1247 fdwaitqueue_append(srv
, con
);
1250 case HANDLER_COMEBACK
:
1254 /* something went wrong */
1255 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1258 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "unknown ret-value: ", con
->fd
, r
);
1262 if (con
->state
== CON_STATE_HANDLE_REQUEST
&& ostate
== CON_STATE_READ_POST
) {
1263 ostate
= CON_STATE_HANDLE_REQUEST
;
1266 case CON_STATE_RESPONSE_START
:
1268 * the decision is done
1269 * - create the HTTP-Response-Header
1273 if (-1 == connection_handle_write_prepare(srv
, con
)) {
1274 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1279 connection_set_state(srv
, con
, CON_STATE_WRITE
);
1281 case CON_STATE_RESPONSE_END
: /* transient */
1282 case CON_STATE_ERROR
: /* transient */
1283 connection_handle_response_end_state(srv
, con
);
1285 case CON_STATE_CONNECT
:
1286 chunkqueue_reset(con
->read_queue
);
1288 con
->request_count
= 0;
1291 case CON_STATE_CLOSE
:
1292 connection_handle_close_state(srv
, con
);
1294 case CON_STATE_READ
:
1295 connection_handle_read_state(srv
, con
);
1297 case CON_STATE_WRITE
:
1299 /* only try to write if we have something in the queue */
1300 if (!chunkqueue_is_empty(con
->write_queue
)) {
1301 if (con
->is_writable
) {
1302 if (-1 == connection_handle_write(srv
, con
)) {
1303 log_error_write(srv
, __FILE__
, __LINE__
, "ds",
1305 "handle write failed.");
1306 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1309 if (con
->state
!= CON_STATE_WRITE
) break;
1311 } else if (con
->file_finished
) {
1312 connection_set_state(srv
, con
, CON_STATE_RESPONSE_END
);
1316 if (con
->mode
!= DIRECT
&& !con
->file_finished
) {
1317 switch(r
= plugins_call_handle_subrequest(srv
, con
)) {
1318 case HANDLER_WAIT_FOR_EVENT
:
1319 case HANDLER_FINISHED
:
1322 case HANDLER_WAIT_FOR_FD
:
1324 fdwaitqueue_append(srv
, con
);
1326 case HANDLER_COMEBACK
:
1328 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "unexpected subrequest handler ret-value: ", con
->fd
, r
);
1331 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1335 } while (con
->state
== CON_STATE_WRITE
&& (!chunkqueue_is_empty(con
->write_queue
) ? con
->is_writable
: con
->file_finished
));
1339 log_error_write(srv
, __FILE__
, __LINE__
, "sdd",
1340 "unknown state:", con
->fd
, con
->state
);
1347 } else if (ostate
== con
->state
) {
1352 if (srv
->srvconf
.log_state_handling
) {
1353 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
1356 connection_get_state(con
->state
));
1360 switch(con
->state
) {
1361 case CON_STATE_READ
:
1362 case CON_STATE_CLOSE
:
1365 case CON_STATE_WRITE
:
1366 /* request write-fdevent only if we really need it
1367 * - if we have data to write
1368 * - if the socket is not writable yet
1370 if (!chunkqueue_is_empty(con
->write_queue
) &&
1371 (con
->is_writable
== 0) &&
1372 (con
->traffic_limit_reached
== 0)) {
1376 case CON_STATE_READ_POST
:
1377 if (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
) {
1384 if (-1 != con
->fd
) {
1385 const int events
= fdevent_event_get_interest(srv
->ev
, con
->fd
);
1386 if (con
->is_readable
< 0) {
1387 con
->is_readable
= 0;
1390 if (con
->is_writable
< 0) {
1391 con
->is_writable
= 0;
1395 /* update timestamps when enabling interest in events */
1396 if ((r
& FDEVENT_IN
) && !(events
& FDEVENT_IN
)) {
1397 con
->read_idle_ts
= srv
->cur_ts
;
1399 if ((r
& FDEVENT_OUT
) && !(events
& FDEVENT_OUT
)) {
1400 con
->write_request_ts
= srv
->cur_ts
;
1402 fdevent_event_set(srv
->ev
, &con
->fde_ndx
, con
->fd
, r
);