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
302 && (off_t
)con
->request
.content_length
> con
->request_content_queue
->bytes_in
)
303 || con
->state
== CON_STATE_ERROR
) {
304 /* request body is present and has not been read completely */
308 if (con
->keep_alive
) {
309 connection_reset(srv
, con
);
311 con
->request_start
= srv
->cur_ts
;
312 con
->read_idle_ts
= srv
->cur_ts
;
314 connection_set_state(srv
, con
, CON_STATE_REQUEST_START
);
316 connection_handle_shutdown(srv
, con
);
320 static void connection_handle_errdoc_init(server
*srv
, connection
*con
) {
321 /* modules that produce headers required with error response should
322 * typically also produce an error document. Make an exception for
323 * mod_auth WWW-Authenticate response header. */
324 buffer
*www_auth
= NULL
;
325 if (401 == con
->http_status
) {
326 data_string
*ds
= (data_string
*)array_get_element(con
->response
.headers
, "WWW-Authenticate");
328 www_auth
= buffer_init_buffer(ds
->value
);
332 con
->response
.transfer_encoding
= 0;
333 buffer_reset(con
->physical
.path
);
334 array_reset(con
->response
.headers
);
335 chunkqueue_reset(con
->write_queue
);
337 if (NULL
!= www_auth
) {
338 response_header_insert(srv
, con
, CONST_STR_LEN("WWW-Authenticate"), CONST_BUF_LEN(www_auth
));
339 buffer_free(www_auth
);
343 static int connection_handle_write_prepare(server
*srv
, connection
*con
) {
344 if (con
->mode
== DIRECT
) {
346 switch(con
->request
.http_method
) {
347 case HTTP_METHOD_GET
:
348 case HTTP_METHOD_POST
:
349 case HTTP_METHOD_HEAD
:
351 case HTTP_METHOD_OPTIONS
:
353 * 400 is coming from the request-parser BEFORE uri.path is set
354 * 403 is from the response handler when noone else catched it
357 if ((!con
->http_status
|| con
->http_status
== 200) && !buffer_string_is_empty(con
->uri
.path
) &&
358 con
->uri
.path
->ptr
[0] != '*') {
359 response_header_insert(srv
, con
, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST"));
361 con
->response
.transfer_encoding
&= ~HTTP_TRANSFER_ENCODING_CHUNKED
;
362 con
->parsed_response
&= ~HTTP_CONTENT_LENGTH
;
364 con
->http_status
= 200;
365 con
->file_finished
= 1;
367 chunkqueue_reset(con
->write_queue
);
371 if (0 == con
->http_status
) {
372 con
->http_status
= 501;
378 if (con
->http_status
== 0) {
379 con
->http_status
= 403;
382 switch(con
->http_status
) {
383 case 204: /* class: header only */
386 /* disable chunked encoding again as we have no body */
387 con
->response
.transfer_encoding
&= ~HTTP_TRANSFER_ENCODING_CHUNKED
;
388 con
->parsed_response
&= ~HTTP_CONTENT_LENGTH
;
389 chunkqueue_reset(con
->write_queue
);
391 con
->file_finished
= 1;
393 default: /* class: header + body */
394 if (con
->mode
!= DIRECT
) break;
396 /* only custom body for 4xx and 5xx */
397 if (con
->http_status
< 400 || con
->http_status
>= 600) break;
399 con
->file_finished
= 0;
401 connection_handle_errdoc_init(srv
, con
);
403 /* try to send static errorfile */
404 if (!buffer_string_is_empty(con
->conf
.errorfile_prefix
)) {
405 stat_cache_entry
*sce
= NULL
;
407 buffer_copy_buffer(con
->physical
.path
, con
->conf
.errorfile_prefix
);
408 buffer_append_int(con
->physical
.path
, con
->http_status
);
409 buffer_append_string_len(con
->physical
.path
, CONST_STR_LEN(".html"));
411 if (0 == http_chunk_append_file(srv
, con
, con
->physical
.path
)) {
412 con
->file_finished
= 1;
413 if (HANDLER_ERROR
!= stat_cache_get_entry(srv
, con
, con
->physical
.path
, &sce
)) {
414 response_header_overwrite(srv
, con
, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce
->content_type
));
419 if (!con
->file_finished
) {
422 buffer_reset(con
->physical
.path
);
424 con
->file_finished
= 1;
427 /* build default error-page */
428 buffer_copy_string_len(b
, CONST_STR_LEN(
429 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
430 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
431 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
432 "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
435 buffer_append_int(b
, con
->http_status
);
436 buffer_append_string_len(b
, CONST_STR_LEN(" - "));
437 buffer_append_string(b
, get_http_status_name(con
->http_status
));
439 buffer_append_string_len(b
, CONST_STR_LEN(
444 buffer_append_int(b
, con
->http_status
);
445 buffer_append_string_len(b
, CONST_STR_LEN(" - "));
446 buffer_append_string(b
, get_http_status_name(con
->http_status
));
448 buffer_append_string_len(b
, CONST_STR_LEN("</h1>\n"
453 (void)http_chunk_append_buffer(srv
, con
, b
);
456 response_header_overwrite(srv
, con
, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("text/html"));
461 /* Allow filter plugins to change response headers before they are written. */
462 switch(plugins_call_handle_response_start(srv
, con
)) {
464 case HANDLER_FINISHED
:
467 log_error_write(srv
, __FILE__
, __LINE__
, "s", "response_start plugin failed");
471 if (con
->file_finished
) {
472 /* we have all the content and chunked encoding is not used, set a content-length */
474 if ((!(con
->parsed_response
& HTTP_CONTENT_LENGTH
)) &&
475 (con
->response
.transfer_encoding
& HTTP_TRANSFER_ENCODING_CHUNKED
) == 0) {
476 off_t qlen
= chunkqueue_length(con
->write_queue
);
479 * The Content-Length header only can be sent if we have content:
480 * - HEAD doesn't have a content-body (but have a content-length)
481 * - 1xx, 204 and 304 don't have a content-body (RFC 2616 Section 4.3)
483 * Otherwise generate a Content-Length header as chunked encoding is not
486 if ((con
->http_status
>= 100 && con
->http_status
< 200) ||
487 con
->http_status
== 204 ||
488 con
->http_status
== 304) {
490 /* no Content-Body, no Content-Length */
491 if (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "Content-Length"))) {
492 buffer_reset(ds
->value
); /* Headers with empty values are ignored for output */
494 } else if (qlen
> 0 || con
->request
.http_method
!= HTTP_METHOD_HEAD
) {
495 /* qlen = 0 is important for Redirects (301, ...) as they MAY have
496 * a content. Browsers are waiting for a Content otherwise
498 buffer_copy_int(srv
->tmp_buf
, qlen
);
500 response_header_overwrite(srv
, con
, CONST_STR_LEN("Content-Length"), CONST_BUF_LEN(srv
->tmp_buf
));
505 * the file isn't finished yet, but we have all headers
507 * to get keep-alive we either need:
508 * - Content-Length: ... (HTTP/1.0 and HTTP/1.0) or
509 * - Transfer-Encoding: chunked (HTTP/1.1)
512 if (((con
->parsed_response
& HTTP_CONTENT_LENGTH
) == 0) &&
513 ((con
->response
.transfer_encoding
& HTTP_TRANSFER_ENCODING_CHUNKED
) == 0)) {
514 if (con
->request
.http_version
== HTTP_VERSION_1_1
) {
515 off_t qlen
= chunkqueue_length(con
->write_queue
);
516 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
518 /* create initial Transfer-Encoding: chunked segment */
519 buffer
*b
= srv
->tmp_chunk_len
;
520 buffer_string_set_length(b
, 0);
521 buffer_append_uint_hex(b
, (uintmax_t)qlen
);
522 buffer_append_string_len(b
, CONST_STR_LEN("\r\n"));
523 chunkqueue_prepend_buffer(con
->write_queue
, b
);
524 chunkqueue_append_mem(con
->write_queue
, CONST_STR_LEN("\r\n"));
532 * if the backend sent a Connection: close, follow the wish
534 * NOTE: if the backend sent Connection: Keep-Alive, but no Content-Length, we
535 * will close the connection. That's fine. We can always decide the close
538 * FIXME: to be nice we should remove the Connection: ...
540 if (con
->parsed_response
& HTTP_CONNECTION
) {
541 /* a subrequest disable keep-alive although the client wanted it */
542 if (con
->keep_alive
&& !con
->response
.keep_alive
) {
548 if (con
->request
.http_method
== HTTP_METHOD_HEAD
) {
550 * a HEAD request has the same as a GET
551 * without the content
553 con
->file_finished
= 1;
555 chunkqueue_reset(con
->write_queue
);
556 con
->response
.transfer_encoding
&= ~HTTP_TRANSFER_ENCODING_CHUNKED
;
559 http_response_write_header(srv
, con
);
564 static int connection_handle_write(server
*srv
, connection
*con
) {
565 switch(network_write_chunkqueue(srv
, con
, con
->write_queue
, MAX_WRITE_LIMIT
)) {
567 con
->write_request_ts
= srv
->cur_ts
;
568 if (con
->file_finished
) {
569 connection_set_state(srv
, con
, CON_STATE_RESPONSE_END
);
572 case -1: /* error on our side */
573 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
574 "connection closed: write failed on fd", con
->fd
);
575 connection_set_state(srv
, con
, CON_STATE_ERROR
);
577 case -2: /* remote close */
578 connection_set_state(srv
, con
, CON_STATE_ERROR
);
581 con
->write_request_ts
= srv
->cur_ts
;
582 con
->is_writable
= 0;
584 /* not finished yet -> WRITE */
593 connection
*connection_init(server
*srv
) {
598 con
= calloc(1, sizeof(*con
));
599 force_assert(NULL
!= con
);
604 con
->bytes_written
= 0;
606 con
->bytes_header
= 0;
607 con
->loops_per_request
= 0;
610 con->x = buffer_init();
613 CLEAN(request
.request_line
);
614 CLEAN(request
.request
);
615 CLEAN(request
.pathinfo
);
617 CLEAN(request
.orig_uri
);
620 CLEAN(uri
.authority
);
625 CLEAN(physical
.doc_root
);
626 CLEAN(physical
.path
);
627 CLEAN(physical
.basedir
);
628 CLEAN(physical
.rel_path
);
629 CLEAN(physical
.etag
);
630 CLEAN(parse_request
);
634 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
635 CLEAN(tlsext_server_name
);
639 con
->write_queue
= chunkqueue_init();
640 con
->read_queue
= chunkqueue_init();
641 con
->request_content_queue
= chunkqueue_init();
643 con
->request
.headers
= array_init();
644 con
->response
.headers
= array_init();
645 con
->environment
= array_init();
647 /* init plugin specific connection structures */
649 con
->plugin_ctx
= calloc(1, (srv
->plugins
.used
+ 1) * sizeof(void *));
650 force_assert(NULL
!= con
->plugin_ctx
);
652 con
->cond_cache
= calloc(srv
->config_context
->used
, sizeof(cond_cache_t
));
653 force_assert(NULL
!= con
->cond_cache
);
654 config_setup_connection(srv
, con
);
659 void connections_free(server
*srv
) {
660 connections
*conns
= srv
->conns
;
663 for (i
= 0; i
< conns
->size
; i
++) {
664 connection
*con
= conns
->ptr
[i
];
666 connection_reset(srv
, con
);
668 chunkqueue_free(con
->write_queue
);
669 chunkqueue_free(con
->read_queue
);
670 chunkqueue_free(con
->request_content_queue
);
671 array_free(con
->request
.headers
);
672 array_free(con
->response
.headers
);
673 array_free(con
->environment
);
679 CLEAN(request
.request_line
);
680 CLEAN(request
.request
);
681 CLEAN(request
.pathinfo
);
683 CLEAN(request
.orig_uri
);
686 CLEAN(uri
.authority
);
691 CLEAN(physical
.doc_root
);
692 CLEAN(physical
.path
);
693 CLEAN(physical
.basedir
);
694 CLEAN(physical
.etag
);
695 CLEAN(physical
.rel_path
);
696 CLEAN(parse_request
);
700 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
701 CLEAN(tlsext_server_name
);
704 free(con
->plugin_ctx
);
705 free(con
->cond_cache
);
714 int connection_reset(server
*srv
, connection
*con
) {
715 plugins_call_connection_reset(srv
, con
);
717 connection_response_reset(srv
, con
);
718 con
->is_readable
= 1;
720 con
->bytes_written
= 0;
721 con
->bytes_written_cur_second
= 0;
723 con
->bytes_header
= 0;
724 con
->loops_per_request
= 0;
726 con
->request
.http_method
= HTTP_METHOD_UNSET
;
727 con
->request
.http_version
= HTTP_VERSION_UNSET
;
729 con
->request
.http_if_modified_since
= NULL
;
730 con
->request
.http_if_none_match
= NULL
;
733 if (con->x) buffer_reset(con->x);
736 CLEAN(request
.request_line
);
737 CLEAN(request
.pathinfo
);
738 CLEAN(request
.request
);
740 /* CLEAN(request.orig_uri); */
743 /* CLEAN(uri.authority); */
744 /* CLEAN(uri.path); */
746 /* CLEAN(uri.query); */
748 CLEAN(parse_request
);
751 #if defined USE_OPENSSL && ! defined OPENSSL_NO_TLSEXT
752 CLEAN(tlsext_server_name
);
757 if (con->x) con->x->used = 0;
762 con->request.x = NULL;
766 CLEAN(http_content_type
);
768 con
->request
.content_length
= 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 ((off_t
)con
->request
.content_length
!= chunkqueue_length(con
->request_content_queue
)) {
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
);