8 #include "http_chunk.h"
10 #include "connections.h"
16 #include "inet_ntop_cache.h"
19 #include <sys/types.h>
31 #include "sys-socket.h"
33 #define data_proxy data_fastcgi
34 #define data_proxy_init data_fastcgi_init
36 #define PROXY_RETRY_TIMEOUT 60
40 * the proxy module is based on the fastcgi module
42 * 28.06.2004 Jan Kneschke The first release
43 * 01.07.2004 Evgeny Rodichev Several bugfixes and cleanups
44 * - co-ordinate up- and downstream flows correctly (proxy_demux_response
45 * and proxy_handle_fdevent)
46 * - correctly transfer upstream http_response_status;
47 * - some unused structures removed.
49 * TODO: - delay upstream read if write_queue is too large
50 * (to prevent memory eating, like in apache). Shoud be
52 * - persistent connection with upstream servers
66 proxy_balance_t balance
;
72 buffer
*parse_response
;
75 plugin_config
**config_storage
;
83 PROXY_STATE_PREPARE_WRITE
,
86 } proxy_connection_state_t
;
88 enum { PROXY_STDOUT
, PROXY_END_REQUEST
};
91 proxy_connection_state_t state
;
92 time_t state_timestamp
;
97 buffer
*response_header
;
102 int fd
; /* fd to the proxy process */
103 int fde_ndx
; /* index into the fd-event buffer */
105 size_t path_info_offset
; /* start of path_info in uri.path */
107 connection
*remote_conn
; /* dump pointer */
108 plugin_data
*plugin_data
; /* dump pointer */
112 /* ok, we need a prototype */
113 static handler_t
proxy_handle_fdevent(server
*srv
, void *ctx
, int revents
);
115 static handler_ctx
* handler_ctx_init(void) {
119 hctx
= calloc(1, sizeof(*hctx
));
121 hctx
->state
= PROXY_STATE_INIT
;
124 hctx
->response
= buffer_init();
125 hctx
->response_header
= buffer_init();
127 hctx
->wb
= chunkqueue_init();
136 static void handler_ctx_free(handler_ctx
*hctx
) {
137 buffer_free(hctx
->response
);
138 buffer_free(hctx
->response_header
);
139 chunkqueue_free(hctx
->wb
);
144 INIT_FUNC(mod_proxy_init
) {
147 p
= calloc(1, sizeof(*p
));
149 p
->parse_response
= buffer_init();
150 p
->balance_buf
= buffer_init();
156 FREE_FUNC(mod_proxy_free
) {
157 plugin_data
*p
= p_d
;
161 buffer_free(p
->parse_response
);
162 buffer_free(p
->balance_buf
);
164 if (p
->config_storage
) {
166 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
167 plugin_config
*s
= p
->config_storage
[i
];
169 if (NULL
== s
) continue;
171 array_free(s
->extensions
);
175 free(p
->config_storage
);
180 return HANDLER_GO_ON
;
183 SETDEFAULTS_FUNC(mod_proxy_set_defaults
) {
184 plugin_data
*p
= p_d
;
188 config_values_t cv
[] = {
189 { "proxy.server", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
190 { "proxy.debug", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
191 { "proxy.balance", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
192 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
195 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
197 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
198 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
201 s
= malloc(sizeof(plugin_config
));
202 s
->extensions
= array_init();
205 cv
[0].destination
= s
->extensions
;
206 cv
[1].destination
= &(s
->debug
);
207 cv
[2].destination
= p
->balance_buf
;
209 buffer_reset(p
->balance_buf
);
211 p
->config_storage
[i
] = s
;
213 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
214 return HANDLER_ERROR
;
217 if (buffer_string_is_empty(p
->balance_buf
)) {
218 s
->balance
= PROXY_BALANCE_FAIR
;
219 } else if (buffer_is_equal_string(p
->balance_buf
, CONST_STR_LEN("fair"))) {
220 s
->balance
= PROXY_BALANCE_FAIR
;
221 } else if (buffer_is_equal_string(p
->balance_buf
, CONST_STR_LEN("round-robin"))) {
222 s
->balance
= PROXY_BALANCE_RR
;
223 } else if (buffer_is_equal_string(p
->balance_buf
, CONST_STR_LEN("hash"))) {
224 s
->balance
= PROXY_BALANCE_HASH
;
226 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
227 "proxy.balance has to be one of: fair, round-robin, hash, but not:", p
->balance_buf
);
228 return HANDLER_ERROR
;
231 if (NULL
!= (du
= array_get_element(config
->value
, "proxy.server"))) {
233 data_array
*da
= (data_array
*)du
;
235 if (du
->type
!= TYPE_ARRAY
) {
236 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
237 "unexpected type for key: ", "proxy.server", "expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
239 return HANDLER_ERROR
;
243 * proxy.server = ( "<ext>" => ...,
247 for (j
= 0; j
< da
->value
->used
; j
++) {
248 data_array
*da_ext
= (data_array
*)da
->value
->data
[j
];
251 if (da_ext
->type
!= TYPE_ARRAY
) {
252 log_error_write(srv
, __FILE__
, __LINE__
, "sssbs",
253 "unexpected type for key: ", "proxy.server",
254 "[", da
->value
->data
[j
]->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
256 return HANDLER_ERROR
;
260 * proxy.server = ( "<ext>" =>
261 * ( "<host>" => ( ... ),
262 * "<host>" => ( ... )
267 for (n
= 0; n
< da_ext
->value
->used
; n
++) {
268 data_array
*da_host
= (data_array
*)da_ext
->value
->data
[n
];
273 config_values_t pcv
[] = {
274 { "host", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
275 { "port", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
276 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
279 if (da_host
->type
!= TYPE_ARRAY
) {
280 log_error_write(srv
, __FILE__
, __LINE__
, "ssSBS",
281 "unexpected type for key:",
283 "[", da_ext
->value
->data
[n
]->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
285 return HANDLER_ERROR
;
288 df
= data_proxy_init();
292 buffer_copy_buffer(df
->key
, da_host
->key
);
294 pcv
[0].destination
= df
->host
;
295 pcv
[1].destination
= &(df
->port
);
297 if (0 != config_insert_values_internal(srv
, da_host
->value
, pcv
, T_CONFIG_SCOPE_CONNECTION
)) {
298 df
->free((data_unset
*) df
);
299 return HANDLER_ERROR
;
302 if (buffer_string_is_empty(df
->host
)) {
303 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
304 "missing key (string):",
310 df
->free((data_unset
*) df
);
311 return HANDLER_ERROR
;
314 /* if extension already exists, take it */
316 if (NULL
== (dfa
= (data_array
*)array_get_element(s
->extensions
, da_ext
->key
->ptr
))) {
317 dfa
= data_array_init();
319 buffer_copy_buffer(dfa
->key
, da_ext
->key
);
321 array_insert_unique(dfa
->value
, (data_unset
*)df
);
322 array_insert_unique(s
->extensions
, (data_unset
*)dfa
);
324 array_insert_unique(dfa
->value
, (data_unset
*)df
);
331 return HANDLER_GO_ON
;
334 static void proxy_connection_close(server
*srv
, handler_ctx
*hctx
) {
338 p
= hctx
->plugin_data
;
339 con
= hctx
->remote_conn
;
341 if (hctx
->fd
!= -1) {
342 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
343 fdevent_unregister(srv
->ev
, hctx
->fd
);
353 handler_ctx_free(hctx
);
354 con
->plugin_ctx
[p
->id
] = NULL
;
356 /* finish response (if not already con->file_started, con->file_finished) */
357 if (con
->mode
== p
->id
) {
358 http_response_backend_done(srv
, con
);
362 static int proxy_establish_connection(server
*srv
, handler_ctx
*hctx
) {
363 struct sockaddr
*proxy_addr
;
364 struct sockaddr_in proxy_addr_in
;
365 #if defined(HAVE_SYS_UN_H)
366 struct sockaddr_un proxy_addr_un
;
368 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
369 struct sockaddr_in6 proxy_addr_in6
;
373 plugin_data
*p
= hctx
->plugin_data
;
374 data_proxy
*host
= hctx
->host
;
375 int proxy_fd
= hctx
->fd
;
378 #if defined(HAVE_SYS_UN_H)
379 if (strstr(host
->host
->ptr
, "/")) {
380 if (buffer_string_length(host
->host
) + 1 > sizeof(proxy_addr_un
.sun_path
)) {
381 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
382 "ERROR: Unix Domain socket filename too long:",
387 memset(&proxy_addr_un
, 0, sizeof(proxy_addr_un
));
388 proxy_addr_un
.sun_family
= AF_UNIX
;
389 memcpy(proxy_addr_un
.sun_path
, host
->host
->ptr
, buffer_string_length(host
->host
) + 1);
390 servlen
= sizeof(proxy_addr_un
);
391 proxy_addr
= (struct sockaddr
*) &proxy_addr_un
;
394 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
395 if (strstr(host
->host
->ptr
, ":")) {
396 memset(&proxy_addr_in6
, 0, sizeof(proxy_addr_in6
));
397 proxy_addr_in6
.sin6_family
= AF_INET6
;
398 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &proxy_addr_in6
.sin6_addr
);
399 proxy_addr_in6
.sin6_port
= htons(host
->port
);
400 servlen
= sizeof(proxy_addr_in6
);
401 proxy_addr
= (struct sockaddr
*) &proxy_addr_in6
;
405 memset(&proxy_addr_in
, 0, sizeof(proxy_addr_in
));
406 proxy_addr_in
.sin_family
= AF_INET
;
407 proxy_addr_in
.sin_addr
.s_addr
= inet_addr(host
->host
->ptr
);
408 proxy_addr_in
.sin_port
= htons(host
->port
);
409 servlen
= sizeof(proxy_addr_in
);
410 proxy_addr
= (struct sockaddr
*) &proxy_addr_in
;
414 if (-1 == connect(proxy_fd
, proxy_addr
, servlen
)) {
415 if (errno
== EINPROGRESS
|| errno
== EALREADY
) {
417 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
418 "connect delayed:", proxy_fd
);
424 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
425 "connect failed:", proxy_fd
, strerror(errno
), errno
);
431 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
432 "connect succeeded: ", proxy_fd
);
438 static void proxy_set_header(connection
*con
, const char *key
, const char *value
) {
441 if (NULL
== (ds_dst
= (data_string
*)array_get_unused_element(con
->request
.headers
, TYPE_STRING
))) {
442 ds_dst
= data_string_init();
445 buffer_copy_string(ds_dst
->key
, key
);
446 buffer_copy_string(ds_dst
->value
, value
);
447 array_insert_unique(con
->request
.headers
, (data_unset
*)ds_dst
);
450 static void proxy_append_header(connection
*con
, const char *key
, const char *value
) {
453 if (NULL
== (ds_dst
= (data_string
*)array_get_unused_element(con
->request
.headers
, TYPE_STRING
))) {
454 ds_dst
= data_string_init();
457 buffer_copy_string(ds_dst
->key
, key
);
458 buffer_append_string(ds_dst
->value
, value
);
459 array_insert_unique(con
->request
.headers
, (data_unset
*)ds_dst
);
463 static int proxy_create_env(server
*srv
, handler_ctx
*hctx
) {
466 connection
*con
= hctx
->remote_conn
;
474 buffer_copy_string(b
, get_http_method_name(con
->request
.http_method
));
475 buffer_append_string_len(b
, CONST_STR_LEN(" "));
477 buffer_append_string_buffer(b
, con
->request
.uri
);
478 buffer_append_string_len(b
, CONST_STR_LEN(" HTTP/1.0\r\n"));
480 proxy_append_header(con
, "X-Forwarded-For", (char *)inet_ntop_cache_get_ip(srv
, &(con
->dst_addr
)));
481 /* http_host is NOT is just a pointer to a buffer
482 * which is NULL if it is not set */
483 if (!buffer_string_is_empty(con
->request
.http_host
)) {
484 proxy_set_header(con
, "X-Host", con
->request
.http_host
->ptr
);
486 proxy_set_header(con
, "X-Forwarded-Proto", con
->uri
.scheme
->ptr
);
489 for (i
= 0; i
< con
->request
.headers
->used
; i
++) {
492 ds
= (data_string
*)con
->request
.headers
->data
[i
];
494 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
495 if (buffer_is_equal_caseless_string(ds
->key
, CONST_STR_LEN("Connection"))) continue;
496 if (buffer_is_equal_caseless_string(ds
->key
, CONST_STR_LEN("Proxy-Connection"))) continue;
498 buffer_append_string_buffer(b
, ds
->key
);
499 buffer_append_string_len(b
, CONST_STR_LEN(": "));
500 buffer_append_string_buffer(b
, ds
->value
);
501 buffer_append_string_len(b
, CONST_STR_LEN("\r\n"));
505 buffer_append_string_len(b
, CONST_STR_LEN("Connection: close\r\n\r\n"));
507 hctx
->wb_reqlen
= buffer_string_length(b
);
508 chunkqueue_append_buffer(hctx
->wb
, b
);
513 if (con
->request
.content_length
) {
514 chunkqueue_append_chunkqueue(hctx
->wb
, con
->request_content_queue
);
515 hctx
->wb_reqlen
+= con
->request
.content_length
;/* (eventual) total request size */
521 static int proxy_set_state(server
*srv
, handler_ctx
*hctx
, proxy_connection_state_t state
) {
523 hctx
->state_timestamp
= srv
->cur_ts
;
529 static int proxy_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
) {
531 int http_response_status
= -1;
535 /* [\r]\n -> [\0]\0 */
537 buffer_copy_buffer(p
->parse_response
, in
);
539 for (s
= p
->parse_response
->ptr
; NULL
!= (ns
= strchr(s
, '\n')); s
= ns
+ 1) {
546 if (s
!= ns
&& ns
[-1] == '\r') ns
[-1] = '\0';
548 if (-1 == http_response_status
) {
549 /* The first line of a Response message is the Status-Line */
551 for (key
=s
; *key
&& *key
!= ' '; key
++);
554 http_response_status
= (int) strtol(key
, NULL
, 10);
555 if (http_response_status
< 100 || http_response_status
>= 1000) http_response_status
= 502;
557 http_response_status
= 502;
560 con
->http_status
= http_response_status
;
561 con
->parsed_response
|= HTTP_STATUS
;
565 if (NULL
== (value
= strchr(s
, ':'))) {
566 /* now we expect: "<key>: <value>\n" */
572 key_len
= value
- key
;
576 while (*value
== ' ' || *value
== '\t') value
++;
582 if (0 == strncasecmp(key
, "Date", key_len
)) {
583 con
->parsed_response
|= HTTP_DATE
;
587 if (0 == strncasecmp(key
, "Location", key_len
)) {
588 con
->parsed_response
|= HTTP_LOCATION
;
592 if (0 == strncasecmp(key
, "Connection", key_len
)) {
597 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
598 con
->response
.content_length
= strtoul(value
, NULL
, 10);
599 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
607 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
608 ds
= data_response_init();
610 buffer_copy_string_len(ds
->key
, key
, key_len
);
611 buffer_copy_string(ds
->value
, value
);
613 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
621 static int proxy_demux_response(server
*srv
, handler_ctx
*hctx
) {
626 plugin_data
*p
= hctx
->plugin_data
;
627 connection
*con
= hctx
->remote_conn
;
628 int proxy_fd
= hctx
->fd
;
630 /* check how much we have to read */
631 if (ioctl(hctx
->fd
, FIONREAD
, &b
)) {
632 if (errno
== EAGAIN
) {
633 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
636 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
644 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
645 "proxy - have to read:", b
);
649 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)) {
650 off_t cqlen
= chunkqueue_length(con
->write_queue
);
651 if (cqlen
+ b
> 65536 - 4096) {
652 if (!con
->is_writable
) {
653 /*(defer removal of FDEVENT_IN interest since
654 * connection_state_machine() might be able to send data
655 * immediately, unless !con->is_writable, where
656 * connection_state_machine() might not loop back to call
657 * mod_proxy_handle_subrequest())*/
658 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
660 if (cqlen
>= 65536-1) return 0;
661 b
= 65536 - 1 - (int)cqlen
;
665 buffer_string_prepare_append(hctx
->response
, b
);
667 if (-1 == (r
= read(hctx
->fd
, hctx
->response
->ptr
+ buffer_string_length(hctx
->response
), buffer_string_space(hctx
->response
)))) {
668 if (errno
== EAGAIN
) {
669 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
672 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
673 "unexpected end-of-file (perhaps the proxy process died):",
674 proxy_fd
, strerror(errno
));
678 /* this should be catched by the b > 0 above */
681 buffer_commit(hctx
->response
, r
);
684 log_error_write(srv
, __FILE__
, __LINE__
, "sdsbs",
685 "demux: Response buffer len", hctx
->response
->used
, ":", hctx
->response
, ":");
688 if (0 == con
->got_response
) {
689 con
->got_response
= 1;
690 buffer_string_prepare_copy(hctx
->response_header
, 1023);
693 if (0 == con
->file_started
) {
696 /* search for the \r\n\r\n in the string */
697 if (NULL
!= (c
= buffer_search_string_len(hctx
->response
, CONST_STR_LEN("\r\n\r\n")))) {
698 size_t hlen
= c
- hctx
->response
->ptr
+ 4;
699 size_t blen
= buffer_string_length(hctx
->response
) - hlen
;
702 buffer_append_string_len(hctx
->response_header
, hctx
->response
->ptr
, hlen
);
704 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "Header:", hctx
->response_header
);
706 /* parse the response header */
707 proxy_response_parse(srv
, con
, p
, hctx
->response_header
);
709 con
->file_started
= 1;
711 if (0 != http_chunk_append_mem(srv
, con
, c
+ 4, blen
)) {
712 /* error writing to tempfile;
713 * truncate response or send 500 if nothing sent yet */
715 con
->file_started
= 0;
718 buffer_reset(hctx
->response
);
720 /* no luck, no header found */
721 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
722 if (buffer_string_length(hctx
->response
) > MAX_HTTP_REQUEST_HEADER
) {
723 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "response headers too large for", con
->uri
.path
);
724 con
->http_status
= 502; /* Bad Gateway */
730 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response
)) {
731 /* error writing to tempfile;
732 * truncate response or send 500 if nothing sent yet */
735 buffer_reset(hctx
->response
);
738 /* reading from upstream done */
746 static handler_t
proxy_write_request(server
*srv
, handler_ctx
*hctx
) {
747 data_proxy
*host
= hctx
->host
;
748 connection
*con
= hctx
->remote_conn
;
752 if (!host
|| buffer_string_is_empty(host
->host
) || !host
->port
) return HANDLER_ERROR
;
754 switch(hctx
->state
) {
755 case PROXY_STATE_CONNECT
:
756 /* wait for the connect() to finish */
758 /* connect failed ? */
759 if (-1 == hctx
->fde_ndx
) return HANDLER_ERROR
;
762 return HANDLER_WAIT_FOR_EVENT
;
764 case PROXY_STATE_INIT
:
765 #if defined(HAVE_SYS_UN_H)
766 if (strstr(host
->host
->ptr
,"/")) {
767 if (-1 == (hctx
->fd
= socket(AF_UNIX
, SOCK_STREAM
, 0))) {
768 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "socket failed: ", strerror(errno
));
769 return HANDLER_ERROR
;
773 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
774 if (strstr(host
->host
->ptr
,":")) {
775 if (-1 == (hctx
->fd
= socket(AF_INET6
, SOCK_STREAM
, 0))) {
776 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "socket failed: ", strerror(errno
));
777 return HANDLER_ERROR
;
782 if (-1 == (hctx
->fd
= socket(AF_INET
, SOCK_STREAM
, 0))) {
783 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "socket failed: ", strerror(errno
));
784 return HANDLER_ERROR
;
791 fdevent_register(srv
->ev
, hctx
->fd
, proxy_handle_fdevent
, hctx
);
793 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
794 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl failed: ", strerror(errno
));
796 return HANDLER_ERROR
;
799 switch (proxy_establish_connection(srv
, hctx
)) {
801 proxy_set_state(srv
, hctx
, PROXY_STATE_CONNECT
);
803 /* connection is in progress, wait for an event and call getsockopt() below */
805 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
807 return HANDLER_WAIT_FOR_EVENT
;
809 /* if ECONNREFUSED choose another connection -> FIXME */
812 return HANDLER_ERROR
;
814 /* everything is ok, go on */
815 proxy_set_state(srv
, hctx
, PROXY_STATE_PREPARE_WRITE
);
821 case PROXY_STATE_PREPARE_WRITE
:
822 proxy_create_env(srv
, hctx
);
824 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
825 proxy_set_state(srv
, hctx
, PROXY_STATE_WRITE
);
828 case PROXY_STATE_WRITE
:;
829 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
831 chunkqueue_remove_finished_chunks(hctx
->wb
);
833 if (-1 == ret
) { /* error on our side */
834 log_error_write(srv
, __FILE__
, __LINE__
, "ssd", "write failed:", strerror(errno
), errno
);
836 return HANDLER_ERROR
;
837 } else if (-2 == ret
) { /* remote close */
838 log_error_write(srv
, __FILE__
, __LINE__
, "ssd", "write failed, remote connection close:", strerror(errno
), errno
);
840 return HANDLER_ERROR
;
843 if (hctx
->wb
->bytes_out
== hctx
->wb_reqlen
) {
844 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
845 shutdown(hctx
->fd
, SHUT_WR
);/* future: remove if HTTP/1.1 request */
846 proxy_set_state(srv
, hctx
, PROXY_STATE_READ
);
848 off_t wblen
= hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
;
849 if (hctx
->wb
->bytes_in
< hctx
->wb_reqlen
&& wblen
< 65536 - 16384) {
850 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
851 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
852 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
853 con
->is_readable
= 1; /* trigger optimistic read from client */
857 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
859 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
863 return HANDLER_WAIT_FOR_EVENT
;
864 case PROXY_STATE_READ
:
865 /* waiting for a response */
866 return HANDLER_WAIT_FOR_EVENT
;
868 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
869 return HANDLER_ERROR
;
875 static int mod_proxy_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
877 plugin_config
*s
= p
->config_storage
[0];
883 /* skip the first, the global context */
884 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
885 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
886 s
= p
->config_storage
[i
];
888 /* condition didn't match */
889 if (!config_check_cond(srv
, con
, dc
)) continue;
892 for (j
= 0; j
< dc
->value
->used
; j
++) {
893 data_unset
*du
= dc
->value
->data
[j
];
895 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("proxy.server"))) {
897 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("proxy.debug"))) {
899 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("proxy.balance"))) {
909 static handler_t
proxy_send_request(server
*srv
, handler_ctx
*hctx
) {
910 /* ok, create the request */
911 handler_t rc
= proxy_write_request(srv
, hctx
);
912 if (HANDLER_ERROR
!= rc
) {
915 data_proxy
*host
= hctx
->host
;
916 connection
*con
= hctx
->remote_conn
;
917 plugin_data
*p
= hctx
->plugin_data
;
918 log_error_write(srv
, __FILE__
, __LINE__
, "sbdd", "proxy-server disabled:",
923 /* disable this server */
924 host
->is_disabled
= 1;
925 host
->disable_ts
= srv
->cur_ts
;
927 /* reset the enviroment and restart the sub-request */
928 con
->mode
= DIRECT
;/*(avoid changing con->state, con->http_status)*/
929 proxy_connection_close(srv
, hctx
);
932 return HANDLER_COMEBACK
;
937 static handler_t
proxy_recv_response(server
*srv
, handler_ctx
*hctx
);
940 SUBREQUEST_FUNC(mod_proxy_handle_subrequest
) {
941 plugin_data
*p
= p_d
;
943 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
945 if (NULL
== hctx
) return HANDLER_GO_ON
;
948 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
950 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
951 && con
->file_started
) {
952 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
953 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
954 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
955 /* optimistic read from backend, which might re-enable FDEVENT_IN */
956 handler_t rc
= proxy_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
957 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
961 if (0 == hctx
->wb
->bytes_in
962 ? con
->state
== CON_STATE_READ_POST
963 : hctx
->wb
->bytes_in
< hctx
->wb_reqlen
) {
964 /*(64k - 4k to attempt to avoid temporary files
965 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
966 if (hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
> 65536 - 4096
967 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
968 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
969 if (0 != hctx
->wb
->bytes_in
) return HANDLER_WAIT_FOR_EVENT
;
971 handler_t r
= connection_handle_read_post_state(srv
, con
);
972 chunkqueue
*req_cq
= con
->request_content_queue
;
973 if (0 != hctx
->wb
->bytes_in
&& !chunkqueue_is_empty(req_cq
)) {
974 chunkqueue_append_chunkqueue(hctx
->wb
, req_cq
);
975 if (fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_OUT
) {
976 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
979 if (r
!= HANDLER_GO_ON
) return r
;
983 return (0 == hctx
->wb
->bytes_in
|| !chunkqueue_is_empty(hctx
->wb
))
984 ? proxy_send_request(srv
, hctx
)
985 : HANDLER_WAIT_FOR_EVENT
;
989 static handler_t
proxy_recv_response(server
*srv
, handler_ctx
*hctx
) {
991 switch (proxy_demux_response(srv
, hctx
)) {
995 http_response_backend_error(srv
, hctx
->remote_conn
);
999 proxy_connection_close(srv
, hctx
);
1001 return HANDLER_FINISHED
;
1004 return HANDLER_GO_ON
;
1008 static handler_t
proxy_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
1009 handler_ctx
*hctx
= ctx
;
1010 connection
*con
= hctx
->remote_conn
;
1011 plugin_data
*p
= hctx
->plugin_data
;
1013 joblist_append(srv
, con
);
1015 if (revents
& FDEVENT_IN
) {
1017 if (p
->conf
.debug
) {
1018 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1019 "proxy: fdevent-in", hctx
->state
);
1023 handler_t rc
= proxy_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
1024 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
1028 if (revents
& FDEVENT_OUT
) {
1029 if (p
->conf
.debug
) {
1030 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1031 "proxy: fdevent-out", hctx
->state
);
1034 if (hctx
->state
== PROXY_STATE_CONNECT
) {
1036 socklen_t socket_error_len
= sizeof(socket_error
);
1038 /* try to finish the connect() */
1039 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
1040 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1041 "getsockopt failed:", strerror(errno
));
1043 return HANDLER_FINISHED
;
1045 if (socket_error
!= 0) {
1046 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1047 "establishing connection failed:", strerror(socket_error
),
1048 "port:", hctx
->host
->port
);
1050 return HANDLER_FINISHED
;
1052 if (p
->conf
.debug
) {
1053 log_error_write(srv
, __FILE__
, __LINE__
, "s", "proxy - connect - delayed success");
1056 proxy_set_state(srv
, hctx
, PROXY_STATE_PREPARE_WRITE
);
1059 return proxy_send_request(srv
, hctx
); /*(might invalidate hctx)*/
1062 /* perhaps this issue is already handled */
1063 if (revents
& FDEVENT_HUP
) {
1064 if (p
->conf
.debug
) {
1065 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1066 "proxy: fdevent-hup", hctx
->state
);
1069 if (hctx
->state
== PROXY_STATE_CONNECT
) {
1070 /* connect() -> EINPROGRESS -> HUP */
1073 * what is proxy is doing if it can't reach the next hop ?
1078 hctx
->host
->is_disabled
= 1;
1079 hctx
->host
->disable_ts
= srv
->cur_ts
;
1080 log_error_write(srv
, __FILE__
, __LINE__
, "sbdd", "proxy-server disabled:",
1085 /* disable this server */
1086 hctx
->host
->is_disabled
= 1;
1087 hctx
->host
->disable_ts
= srv
->cur_ts
;
1089 /* reset the environment and restart the sub-request */
1090 con
->mode
= DIRECT
;/*(avoid changing con->state, con->http_status)*/
1091 proxy_connection_close(srv
, hctx
);
1094 proxy_connection_close(srv
, hctx
);
1095 con
->http_status
= 503;
1097 } else if (con
->file_started
) {
1098 /* drain any remaining data from kernel pipe buffers
1099 * even if (con->conf.stream_response_body
1100 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
1101 * since event loop will spin on fd FDEVENT_HUP event
1102 * until unregistered. */
1105 rc
= proxy_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
1106 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
1107 return rc
; /* HANDLER_FINISHED or HANDLER_ERROR */
1109 proxy_connection_close(srv
, hctx
);
1111 } else if (revents
& FDEVENT_ERR
) {
1112 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "proxy-FDEVENT_ERR, but no HUP", revents
);
1114 http_response_backend_error(srv
, con
);
1115 proxy_connection_close(srv
, hctx
);
1118 return HANDLER_FINISHED
;
1121 static handler_t
mod_proxy_check_extension(server
*srv
, connection
*con
, void *p_d
) {
1122 plugin_data
*p
= p_d
;
1124 unsigned long last_max
= ULONG_MAX
;
1125 int max_usage
= INT_MAX
;
1129 data_array
*extension
= NULL
;
1130 size_t path_info_offset
;
1132 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
1134 /* Possibly, we processed already this request */
1135 if (con
->file_started
== 1) return HANDLER_GO_ON
;
1137 mod_proxy_patch_connection(srv
, con
, p
);
1140 if (buffer_string_is_empty(fn
)) return HANDLER_ERROR
;
1141 s_len
= buffer_string_length(fn
);
1143 path_info_offset
= 0;
1145 if (p
->conf
.debug
) {
1146 log_error_write(srv
, __FILE__
, __LINE__
, "s", "proxy - start");
1149 /* check if extension matches */
1150 for (k
= 0; k
< p
->conf
.extensions
->used
; k
++) {
1151 data_array
*ext
= NULL
;
1154 ext
= (data_array
*)p
->conf
.extensions
->data
[k
];
1156 if (buffer_is_empty(ext
->key
)) continue;
1158 ct_len
= buffer_string_length(ext
->key
);
1160 if (s_len
< ct_len
) continue;
1162 /* check extension in the form "/proxy_pattern" */
1163 if (*(ext
->key
->ptr
) == '/') {
1164 if (strncmp(fn
->ptr
, ext
->key
->ptr
, ct_len
) == 0) {
1165 if (s_len
> ct_len
+ 1) {
1168 if (NULL
!= (pi_offset
= strchr(fn
->ptr
+ ct_len
+ 1, '/'))) {
1169 path_info_offset
= pi_offset
- fn
->ptr
;
1175 } else if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
)) {
1176 /* check extension in the form ".fcg" */
1182 if (NULL
== extension
) {
1183 return HANDLER_GO_ON
;
1186 if (p
->conf
.debug
) {
1187 log_error_write(srv
, __FILE__
, __LINE__
, "s", "proxy - ext found");
1190 if (extension
->value
->used
== 1) {
1191 if ( ((data_proxy
*)extension
->value
->data
[0])->is_disabled
) {
1196 } else if (extension
->value
->used
!= 0) switch(p
->conf
.balance
) {
1197 case PROXY_BALANCE_HASH
:
1198 /* hash balancing */
1200 if (p
->conf
.debug
) {
1201 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1202 "proxy - used hash balancing, hosts:", extension
->value
->used
);
1205 for (k
= 0, ndx
= -1, last_max
= ULONG_MAX
; k
< extension
->value
->used
; k
++) {
1206 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[k
];
1207 unsigned long cur_max
;
1209 if (host
->is_disabled
) continue;
1211 cur_max
= generate_crc32c(CONST_BUF_LEN(con
->uri
.path
)) +
1212 generate_crc32c(CONST_BUF_LEN(host
->host
)) + /* we can cache this */
1213 generate_crc32c(CONST_BUF_LEN(con
->uri
.authority
));
1215 if (p
->conf
.debug
) {
1216 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbd",
1217 "proxy - election:",
1224 if ((last_max
== ULONG_MAX
) || /* first round */
1225 (cur_max
> last_max
)) {
1233 case PROXY_BALANCE_FAIR
:
1234 /* fair balancing */
1235 if (p
->conf
.debug
) {
1236 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1237 "proxy - used fair balancing");
1240 for (k
= 0, ndx
= -1, max_usage
= INT_MAX
; k
< extension
->value
->used
; k
++) {
1241 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[k
];
1243 if (host
->is_disabled
) continue;
1245 if (host
->usage
< max_usage
) {
1246 max_usage
= host
->usage
;
1253 case PROXY_BALANCE_RR
: {
1257 if (p
->conf
.debug
) {
1258 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1259 "proxy - used round-robin balancing");
1262 /* just to be sure */
1263 force_assert(extension
->value
->used
< INT_MAX
);
1265 host
= (data_proxy
*)extension
->value
->data
[0];
1267 /* Use last_used_ndx from first host in list */
1268 k
= host
->last_used_ndx
;
1269 ndx
= k
+ 1; /* use next host after the last one */
1270 if (ndx
< 0) ndx
= 0;
1272 /* Search first active host after last_used_ndx */
1273 while ( ndx
< (int) extension
->value
->used
1274 && (host
= (data_proxy
*)extension
->value
->data
[ndx
])->is_disabled
) ndx
++;
1276 if (ndx
>= (int) extension
->value
->used
) {
1277 /* didn't found a higher id, wrap to the start */
1278 for (ndx
= 0; ndx
<= (int) k
; ndx
++) {
1279 host
= (data_proxy
*)extension
->value
->data
[ndx
];
1280 if (!host
->is_disabled
) break;
1283 /* No active host found */
1284 if (host
->is_disabled
) ndx
= -1;
1287 /* Save new index for next round */
1288 ((data_proxy
*)extension
->value
->data
[0])->last_used_ndx
= ndx
;
1296 /* found a server */
1298 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[ndx
];
1301 * if check-local is disabled, use the uri.path handler
1305 /* init handler-context */
1307 hctx
= handler_ctx_init();
1309 hctx
->path_info_offset
= path_info_offset
;
1310 hctx
->remote_conn
= con
;
1311 hctx
->plugin_data
= p
;
1314 con
->plugin_ctx
[p
->id
] = hctx
;
1320 if (p
->conf
.debug
) {
1321 log_error_write(srv
, __FILE__
, __LINE__
, "sbd",
1322 "proxy - found a host",
1323 host
->host
, host
->port
);
1326 return HANDLER_GO_ON
;
1328 /* no handler found */
1329 con
->http_status
= 500;
1331 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1332 "no proxy-handler found for:",
1335 return HANDLER_FINISHED
;
1337 return HANDLER_GO_ON
;
1340 static handler_t
mod_proxy_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1341 plugin_data
*p
= p_d
;
1342 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1343 if (hctx
) proxy_connection_close(srv
, hctx
);
1345 return HANDLER_GO_ON
;
1350 * the trigger re-enables the disabled connections after the timeout is over
1354 TRIGGER_FUNC(mod_proxy_trigger
) {
1355 plugin_data
*p
= p_d
;
1357 if (p
->config_storage
) {
1359 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1360 plugin_config
*s
= p
->config_storage
[i
];
1364 /* get the extensions for all configs */
1366 for (k
= 0; k
< s
->extensions
->used
; k
++) {
1367 data_array
*extension
= (data_array
*)s
->extensions
->data
[k
];
1370 for (n
= 0; n
< extension
->value
->used
; n
++) {
1371 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[n
];
1373 if (!host
->is_disabled
||
1374 srv
->cur_ts
- host
->disable_ts
< 5) continue;
1376 log_error_write(srv
, __FILE__
, __LINE__
, "sbd",
1377 "proxy - re-enabled:",
1378 host
->host
, host
->port
);
1380 host
->is_disabled
= 0;
1386 return HANDLER_GO_ON
;
1390 int mod_proxy_plugin_init(plugin
*p
);
1391 int mod_proxy_plugin_init(plugin
*p
) {
1392 p
->version
= LIGHTTPD_VERSION_ID
;
1393 p
->name
= buffer_init_string("proxy");
1395 p
->init
= mod_proxy_init
;
1396 p
->cleanup
= mod_proxy_free
;
1397 p
->set_defaults
= mod_proxy_set_defaults
;
1398 p
->connection_reset
= mod_proxy_connection_reset
; /* end of req-resp cycle */
1399 p
->handle_connection_close
= mod_proxy_connection_reset
; /* end of client connection */
1400 p
->handle_uri_clean
= mod_proxy_check_extension
;
1401 p
->handle_subrequest
= mod_proxy_handle_subrequest
;
1402 p
->handle_trigger
= mod_proxy_trigger
;