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;
497 /* Do not emit HTTP_PROXY in environment.
498 * Some executables use HTTP_PROXY to configure
499 * outgoing proxy. See also https://httpoxy.org/ */
500 if (buffer_is_equal_caseless_string(ds
->key
, CONST_STR_LEN("Proxy"))) continue;
502 buffer_append_string_buffer(b
, ds
->key
);
503 buffer_append_string_len(b
, CONST_STR_LEN(": "));
504 buffer_append_string_buffer(b
, ds
->value
);
505 buffer_append_string_len(b
, CONST_STR_LEN("\r\n"));
509 buffer_append_string_len(b
, CONST_STR_LEN("Connection: close\r\n\r\n"));
511 hctx
->wb_reqlen
= buffer_string_length(b
);
512 chunkqueue_append_buffer(hctx
->wb
, b
);
517 if (con
->request
.content_length
) {
518 chunkqueue_append_chunkqueue(hctx
->wb
, con
->request_content_queue
);
519 hctx
->wb_reqlen
+= con
->request
.content_length
;/* (eventual) total request size */
525 static int proxy_set_state(server
*srv
, handler_ctx
*hctx
, proxy_connection_state_t state
) {
527 hctx
->state_timestamp
= srv
->cur_ts
;
533 static int proxy_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
) {
535 int http_response_status
= -1;
539 /* [\r]\n -> [\0]\0 */
541 buffer_copy_buffer(p
->parse_response
, in
);
543 for (s
= p
->parse_response
->ptr
; NULL
!= (ns
= strchr(s
, '\n')); s
= ns
+ 1) {
550 if (s
!= ns
&& ns
[-1] == '\r') ns
[-1] = '\0';
552 if (-1 == http_response_status
) {
553 /* The first line of a Response message is the Status-Line */
555 for (key
=s
; *key
&& *key
!= ' '; key
++);
558 http_response_status
= (int) strtol(key
, NULL
, 10);
559 if (http_response_status
< 100 || http_response_status
>= 1000) http_response_status
= 502;
561 http_response_status
= 502;
564 con
->http_status
= http_response_status
;
565 con
->parsed_response
|= HTTP_STATUS
;
569 if (NULL
== (value
= strchr(s
, ':'))) {
570 /* now we expect: "<key>: <value>\n" */
576 key_len
= value
- key
;
580 while (*value
== ' ' || *value
== '\t') value
++;
586 if (0 == strncasecmp(key
, "Date", key_len
)) {
587 con
->parsed_response
|= HTTP_DATE
;
591 if (0 == strncasecmp(key
, "Location", key_len
)) {
592 con
->parsed_response
|= HTTP_LOCATION
;
596 if (0 == strncasecmp(key
, "Connection", key_len
)) {
601 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
602 con
->response
.content_length
= strtoul(value
, NULL
, 10);
603 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
611 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
612 ds
= data_response_init();
614 buffer_copy_string_len(ds
->key
, key
, key_len
);
615 buffer_copy_string(ds
->value
, value
);
617 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
625 static int proxy_demux_response(server
*srv
, handler_ctx
*hctx
) {
630 plugin_data
*p
= hctx
->plugin_data
;
631 connection
*con
= hctx
->remote_conn
;
632 int proxy_fd
= hctx
->fd
;
634 /* check how much we have to read */
635 #if !defined(_WIN32) && !defined(__CYGWIN__)
636 if (ioctl(hctx
->fd
, FIONREAD
, &b
)) {
637 if (errno
== EAGAIN
) {
638 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
641 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
652 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
653 "proxy - have to read:", b
);
657 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)) {
658 off_t cqlen
= chunkqueue_length(con
->write_queue
);
659 if (cqlen
+ b
> 65536 - 4096) {
660 if (!con
->is_writable
) {
661 /*(defer removal of FDEVENT_IN interest since
662 * connection_state_machine() might be able to send data
663 * immediately, unless !con->is_writable, where
664 * connection_state_machine() might not loop back to call
665 * mod_proxy_handle_subrequest())*/
666 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
668 if (cqlen
>= 65536-1) return 0;
669 b
= 65536 - 1 - (int)cqlen
;
673 buffer_string_prepare_append(hctx
->response
, b
);
675 if (-1 == (r
= read(hctx
->fd
, hctx
->response
->ptr
+ buffer_string_length(hctx
->response
), buffer_string_space(hctx
->response
)))) {
676 if (errno
== EAGAIN
) {
677 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
680 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
681 "unexpected end-of-file (perhaps the proxy process died):",
682 proxy_fd
, strerror(errno
));
686 #if defined(_WIN32) || defined(__CYGWIN__)
687 if (0 == r
) return 1; /* fin */
690 /* this should be catched by the b > 0 above */
693 buffer_commit(hctx
->response
, r
);
696 log_error_write(srv
, __FILE__
, __LINE__
, "sdsbs",
697 "demux: Response buffer len", hctx
->response
->used
, ":", hctx
->response
, ":");
700 if (0 == con
->got_response
) {
701 con
->got_response
= 1;
702 buffer_string_prepare_copy(hctx
->response_header
, 1023);
705 if (0 == con
->file_started
) {
708 /* search for the \r\n\r\n in the string */
709 if (NULL
!= (c
= buffer_search_string_len(hctx
->response
, CONST_STR_LEN("\r\n\r\n")))) {
710 size_t hlen
= c
- hctx
->response
->ptr
+ 4;
711 size_t blen
= buffer_string_length(hctx
->response
) - hlen
;
714 buffer_append_string_len(hctx
->response_header
, hctx
->response
->ptr
, hlen
);
716 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "Header:", hctx
->response_header
);
718 /* parse the response header */
719 proxy_response_parse(srv
, con
, p
, hctx
->response_header
);
721 con
->file_started
= 1;
723 if (0 != http_chunk_append_mem(srv
, con
, c
+ 4, blen
)) {
724 /* error writing to tempfile;
725 * truncate response or send 500 if nothing sent yet */
727 con
->file_started
= 0;
730 buffer_reset(hctx
->response
);
732 /* no luck, no header found */
733 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
734 if (buffer_string_length(hctx
->response
) > MAX_HTTP_REQUEST_HEADER
) {
735 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "response headers too large for", con
->uri
.path
);
736 con
->http_status
= 502; /* Bad Gateway */
742 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response
)) {
743 /* error writing to tempfile;
744 * truncate response or send 500 if nothing sent yet */
747 buffer_reset(hctx
->response
);
750 /* reading from upstream done */
758 static handler_t
proxy_write_request(server
*srv
, handler_ctx
*hctx
) {
759 data_proxy
*host
= hctx
->host
;
760 connection
*con
= hctx
->remote_conn
;
764 if (!host
|| buffer_string_is_empty(host
->host
) || !host
->port
) return HANDLER_ERROR
;
766 switch(hctx
->state
) {
767 case PROXY_STATE_CONNECT
:
768 /* wait for the connect() to finish */
770 /* connect failed ? */
771 if (-1 == hctx
->fde_ndx
) return HANDLER_ERROR
;
774 return HANDLER_WAIT_FOR_EVENT
;
776 case PROXY_STATE_INIT
:
777 #if defined(HAVE_SYS_UN_H)
778 if (strstr(host
->host
->ptr
,"/")) {
779 if (-1 == (hctx
->fd
= socket(AF_UNIX
, SOCK_STREAM
, 0))) {
780 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "socket failed: ", strerror(errno
));
781 return HANDLER_ERROR
;
785 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
786 if (strstr(host
->host
->ptr
,":")) {
787 if (-1 == (hctx
->fd
= socket(AF_INET6
, SOCK_STREAM
, 0))) {
788 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "socket failed: ", strerror(errno
));
789 return HANDLER_ERROR
;
794 if (-1 == (hctx
->fd
= socket(AF_INET
, SOCK_STREAM
, 0))) {
795 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "socket failed: ", strerror(errno
));
796 return HANDLER_ERROR
;
803 fdevent_register(srv
->ev
, hctx
->fd
, proxy_handle_fdevent
, hctx
);
805 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
806 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl failed: ", strerror(errno
));
808 return HANDLER_ERROR
;
811 switch (proxy_establish_connection(srv
, hctx
)) {
813 proxy_set_state(srv
, hctx
, PROXY_STATE_CONNECT
);
815 /* connection is in progress, wait for an event and call getsockopt() below */
817 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
819 return HANDLER_WAIT_FOR_EVENT
;
821 /* if ECONNREFUSED choose another connection -> FIXME */
824 return HANDLER_ERROR
;
826 /* everything is ok, go on */
827 proxy_set_state(srv
, hctx
, PROXY_STATE_PREPARE_WRITE
);
833 case PROXY_STATE_PREPARE_WRITE
:
834 proxy_create_env(srv
, hctx
);
836 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
837 proxy_set_state(srv
, hctx
, PROXY_STATE_WRITE
);
840 case PROXY_STATE_WRITE
:;
841 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
843 chunkqueue_remove_finished_chunks(hctx
->wb
);
845 if (-1 == ret
) { /* error on our side */
846 log_error_write(srv
, __FILE__
, __LINE__
, "ssd", "write failed:", strerror(errno
), errno
);
848 return HANDLER_ERROR
;
849 } else if (-2 == ret
) { /* remote close */
850 log_error_write(srv
, __FILE__
, __LINE__
, "ssd", "write failed, remote connection close:", strerror(errno
), errno
);
852 return HANDLER_ERROR
;
855 if (hctx
->wb
->bytes_out
== hctx
->wb_reqlen
) {
856 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
857 shutdown(hctx
->fd
, SHUT_WR
);/* future: remove if HTTP/1.1 request */
858 proxy_set_state(srv
, hctx
, PROXY_STATE_READ
);
860 off_t wblen
= hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
;
861 if (hctx
->wb
->bytes_in
< hctx
->wb_reqlen
&& wblen
< 65536 - 16384) {
862 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
863 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
864 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
865 con
->is_readable
= 1; /* trigger optimistic read from client */
869 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
871 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
875 return HANDLER_WAIT_FOR_EVENT
;
876 case PROXY_STATE_READ
:
877 /* waiting for a response */
878 return HANDLER_WAIT_FOR_EVENT
;
880 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
881 return HANDLER_ERROR
;
887 static int mod_proxy_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
889 plugin_config
*s
= p
->config_storage
[0];
895 /* skip the first, the global context */
896 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
897 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
898 s
= p
->config_storage
[i
];
900 /* condition didn't match */
901 if (!config_check_cond(srv
, con
, dc
)) continue;
904 for (j
= 0; j
< dc
->value
->used
; j
++) {
905 data_unset
*du
= dc
->value
->data
[j
];
907 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("proxy.server"))) {
909 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("proxy.debug"))) {
911 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("proxy.balance"))) {
921 static handler_t
proxy_send_request(server
*srv
, handler_ctx
*hctx
) {
922 /* ok, create the request */
923 handler_t rc
= proxy_write_request(srv
, hctx
);
924 if (HANDLER_ERROR
!= rc
) {
927 data_proxy
*host
= hctx
->host
;
928 connection
*con
= hctx
->remote_conn
;
929 plugin_data
*p
= hctx
->plugin_data
;
930 log_error_write(srv
, __FILE__
, __LINE__
, "sbdd", "proxy-server disabled:",
935 /* disable this server */
936 host
->is_disabled
= 1;
937 host
->disable_ts
= srv
->cur_ts
;
939 /* reset the enviroment and restart the sub-request */
940 con
->mode
= DIRECT
;/*(avoid changing con->state, con->http_status)*/
941 proxy_connection_close(srv
, hctx
);
944 return HANDLER_COMEBACK
;
949 static handler_t
proxy_recv_response(server
*srv
, handler_ctx
*hctx
);
952 SUBREQUEST_FUNC(mod_proxy_handle_subrequest
) {
953 plugin_data
*p
= p_d
;
955 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
957 if (NULL
== hctx
) return HANDLER_GO_ON
;
960 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
962 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
963 && con
->file_started
) {
964 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
965 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
966 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
967 /* optimistic read from backend, which might re-enable FDEVENT_IN */
968 handler_t rc
= proxy_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
969 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
973 if (0 == hctx
->wb
->bytes_in
974 ? con
->state
== CON_STATE_READ_POST
975 : hctx
->wb
->bytes_in
< hctx
->wb_reqlen
) {
976 /*(64k - 4k to attempt to avoid temporary files
977 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
978 if (hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
> 65536 - 4096
979 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
980 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
981 if (0 != hctx
->wb
->bytes_in
) return HANDLER_WAIT_FOR_EVENT
;
983 handler_t r
= connection_handle_read_post_state(srv
, con
);
984 chunkqueue
*req_cq
= con
->request_content_queue
;
985 if (0 != hctx
->wb
->bytes_in
&& !chunkqueue_is_empty(req_cq
)) {
986 chunkqueue_append_chunkqueue(hctx
->wb
, req_cq
);
987 if (fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_OUT
) {
988 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
991 if (r
!= HANDLER_GO_ON
) return r
;
995 return (0 == hctx
->wb
->bytes_in
|| !chunkqueue_is_empty(hctx
->wb
))
996 ? proxy_send_request(srv
, hctx
)
997 : HANDLER_WAIT_FOR_EVENT
;
1001 static handler_t
proxy_recv_response(server
*srv
, handler_ctx
*hctx
) {
1003 switch (proxy_demux_response(srv
, hctx
)) {
1007 http_response_backend_error(srv
, hctx
->remote_conn
);
1011 proxy_connection_close(srv
, hctx
);
1013 return HANDLER_FINISHED
;
1016 return HANDLER_GO_ON
;
1020 static handler_t
proxy_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
1021 handler_ctx
*hctx
= ctx
;
1022 connection
*con
= hctx
->remote_conn
;
1023 plugin_data
*p
= hctx
->plugin_data
;
1025 joblist_append(srv
, con
);
1027 if (revents
& FDEVENT_IN
) {
1029 if (p
->conf
.debug
) {
1030 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1031 "proxy: fdevent-in", hctx
->state
);
1035 handler_t rc
= proxy_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
1036 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
1040 if (revents
& FDEVENT_OUT
) {
1041 if (p
->conf
.debug
) {
1042 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1043 "proxy: fdevent-out", hctx
->state
);
1046 if (hctx
->state
== PROXY_STATE_CONNECT
) {
1048 socklen_t socket_error_len
= sizeof(socket_error
);
1050 /* try to finish the connect() */
1051 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
1052 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1053 "getsockopt failed:", strerror(errno
));
1055 return HANDLER_FINISHED
;
1057 if (socket_error
!= 0) {
1058 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1059 "establishing connection failed:", strerror(socket_error
),
1060 "port:", hctx
->host
->port
);
1062 return HANDLER_FINISHED
;
1064 if (p
->conf
.debug
) {
1065 log_error_write(srv
, __FILE__
, __LINE__
, "s", "proxy - connect - delayed success");
1068 proxy_set_state(srv
, hctx
, PROXY_STATE_PREPARE_WRITE
);
1071 return proxy_send_request(srv
, hctx
); /*(might invalidate hctx)*/
1074 /* perhaps this issue is already handled */
1075 if (revents
& FDEVENT_HUP
) {
1076 if (p
->conf
.debug
) {
1077 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1078 "proxy: fdevent-hup", hctx
->state
);
1081 if (hctx
->state
== PROXY_STATE_CONNECT
) {
1082 /* connect() -> EINPROGRESS -> HUP */
1085 * what is proxy is doing if it can't reach the next hop ?
1090 hctx
->host
->is_disabled
= 1;
1091 hctx
->host
->disable_ts
= srv
->cur_ts
;
1092 log_error_write(srv
, __FILE__
, __LINE__
, "sbdd", "proxy-server disabled:",
1097 /* disable this server */
1098 hctx
->host
->is_disabled
= 1;
1099 hctx
->host
->disable_ts
= srv
->cur_ts
;
1101 /* reset the environment and restart the sub-request */
1102 con
->mode
= DIRECT
;/*(avoid changing con->state, con->http_status)*/
1103 proxy_connection_close(srv
, hctx
);
1106 proxy_connection_close(srv
, hctx
);
1107 con
->http_status
= 503;
1109 } else if (con
->file_started
) {
1110 /* drain any remaining data from kernel pipe buffers
1111 * even if (con->conf.stream_response_body
1112 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
1113 * since event loop will spin on fd FDEVENT_HUP event
1114 * until unregistered. */
1117 rc
= proxy_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
1118 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
1119 return rc
; /* HANDLER_FINISHED or HANDLER_ERROR */
1121 proxy_connection_close(srv
, hctx
);
1123 } else if (revents
& FDEVENT_ERR
) {
1124 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "proxy-FDEVENT_ERR, but no HUP", revents
);
1126 http_response_backend_error(srv
, con
);
1127 proxy_connection_close(srv
, hctx
);
1130 return HANDLER_FINISHED
;
1133 static handler_t
mod_proxy_check_extension(server
*srv
, connection
*con
, void *p_d
) {
1134 plugin_data
*p
= p_d
;
1136 unsigned long last_max
= ULONG_MAX
;
1137 int max_usage
= INT_MAX
;
1141 data_array
*extension
= NULL
;
1142 size_t path_info_offset
;
1144 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
1146 /* Possibly, we processed already this request */
1147 if (con
->file_started
== 1) return HANDLER_GO_ON
;
1149 mod_proxy_patch_connection(srv
, con
, p
);
1152 if (buffer_string_is_empty(fn
)) return HANDLER_ERROR
;
1153 s_len
= buffer_string_length(fn
);
1155 path_info_offset
= 0;
1157 if (p
->conf
.debug
) {
1158 log_error_write(srv
, __FILE__
, __LINE__
, "s", "proxy - start");
1161 /* check if extension matches */
1162 for (k
= 0; k
< p
->conf
.extensions
->used
; k
++) {
1163 data_array
*ext
= NULL
;
1166 ext
= (data_array
*)p
->conf
.extensions
->data
[k
];
1168 if (buffer_is_empty(ext
->key
)) continue;
1170 ct_len
= buffer_string_length(ext
->key
);
1172 if (s_len
< ct_len
) continue;
1174 /* check extension in the form "/proxy_pattern" */
1175 if (*(ext
->key
->ptr
) == '/') {
1176 if (strncmp(fn
->ptr
, ext
->key
->ptr
, ct_len
) == 0) {
1177 if (s_len
> ct_len
+ 1) {
1180 if (NULL
!= (pi_offset
= strchr(fn
->ptr
+ ct_len
+ 1, '/'))) {
1181 path_info_offset
= pi_offset
- fn
->ptr
;
1187 } else if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
)) {
1188 /* check extension in the form ".fcg" */
1194 if (NULL
== extension
) {
1195 return HANDLER_GO_ON
;
1198 if (p
->conf
.debug
) {
1199 log_error_write(srv
, __FILE__
, __LINE__
, "s", "proxy - ext found");
1202 if (extension
->value
->used
== 1) {
1203 if ( ((data_proxy
*)extension
->value
->data
[0])->is_disabled
) {
1208 } else if (extension
->value
->used
!= 0) switch(p
->conf
.balance
) {
1209 case PROXY_BALANCE_HASH
:
1210 /* hash balancing */
1212 if (p
->conf
.debug
) {
1213 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1214 "proxy - used hash balancing, hosts:", extension
->value
->used
);
1217 for (k
= 0, ndx
= -1, last_max
= ULONG_MAX
; k
< extension
->value
->used
; k
++) {
1218 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[k
];
1219 unsigned long cur_max
;
1221 if (host
->is_disabled
) continue;
1223 cur_max
= generate_crc32c(CONST_BUF_LEN(con
->uri
.path
)) +
1224 generate_crc32c(CONST_BUF_LEN(host
->host
)) + /* we can cache this */
1225 generate_crc32c(CONST_BUF_LEN(con
->uri
.authority
));
1227 if (p
->conf
.debug
) {
1228 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbd",
1229 "proxy - election:",
1236 if ((last_max
== ULONG_MAX
) || /* first round */
1237 (cur_max
> last_max
)) {
1245 case PROXY_BALANCE_FAIR
:
1246 /* fair balancing */
1247 if (p
->conf
.debug
) {
1248 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1249 "proxy - used fair balancing");
1252 for (k
= 0, ndx
= -1, max_usage
= INT_MAX
; k
< extension
->value
->used
; k
++) {
1253 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[k
];
1255 if (host
->is_disabled
) continue;
1257 if (host
->usage
< max_usage
) {
1258 max_usage
= host
->usage
;
1265 case PROXY_BALANCE_RR
: {
1269 if (p
->conf
.debug
) {
1270 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1271 "proxy - used round-robin balancing");
1274 /* just to be sure */
1275 force_assert(extension
->value
->used
< INT_MAX
);
1277 host
= (data_proxy
*)extension
->value
->data
[0];
1279 /* Use last_used_ndx from first host in list */
1280 k
= host
->last_used_ndx
;
1281 ndx
= k
+ 1; /* use next host after the last one */
1282 if (ndx
< 0) ndx
= 0;
1284 /* Search first active host after last_used_ndx */
1285 while ( ndx
< (int) extension
->value
->used
1286 && (host
= (data_proxy
*)extension
->value
->data
[ndx
])->is_disabled
) ndx
++;
1288 if (ndx
>= (int) extension
->value
->used
) {
1289 /* didn't found a higher id, wrap to the start */
1290 for (ndx
= 0; ndx
<= (int) k
; ndx
++) {
1291 host
= (data_proxy
*)extension
->value
->data
[ndx
];
1292 if (!host
->is_disabled
) break;
1295 /* No active host found */
1296 if (host
->is_disabled
) ndx
= -1;
1299 /* Save new index for next round */
1300 ((data_proxy
*)extension
->value
->data
[0])->last_used_ndx
= ndx
;
1308 /* found a server */
1310 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[ndx
];
1313 * if check-local is disabled, use the uri.path handler
1317 /* init handler-context */
1319 hctx
= handler_ctx_init();
1321 hctx
->path_info_offset
= path_info_offset
;
1322 hctx
->remote_conn
= con
;
1323 hctx
->plugin_data
= p
;
1326 con
->plugin_ctx
[p
->id
] = hctx
;
1332 if (p
->conf
.debug
) {
1333 log_error_write(srv
, __FILE__
, __LINE__
, "sbd",
1334 "proxy - found a host",
1335 host
->host
, host
->port
);
1338 return HANDLER_GO_ON
;
1340 /* no handler found */
1341 con
->http_status
= 500;
1343 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1344 "no proxy-handler found for:",
1347 return HANDLER_FINISHED
;
1349 return HANDLER_GO_ON
;
1352 static handler_t
mod_proxy_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1353 plugin_data
*p
= p_d
;
1354 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1355 if (hctx
) proxy_connection_close(srv
, hctx
);
1357 return HANDLER_GO_ON
;
1362 * the trigger re-enables the disabled connections after the timeout is over
1366 TRIGGER_FUNC(mod_proxy_trigger
) {
1367 plugin_data
*p
= p_d
;
1369 if (p
->config_storage
) {
1371 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1372 plugin_config
*s
= p
->config_storage
[i
];
1376 /* get the extensions for all configs */
1378 for (k
= 0; k
< s
->extensions
->used
; k
++) {
1379 data_array
*extension
= (data_array
*)s
->extensions
->data
[k
];
1382 for (n
= 0; n
< extension
->value
->used
; n
++) {
1383 data_proxy
*host
= (data_proxy
*)extension
->value
->data
[n
];
1385 if (!host
->is_disabled
||
1386 srv
->cur_ts
- host
->disable_ts
< 5) continue;
1388 log_error_write(srv
, __FILE__
, __LINE__
, "sbd",
1389 "proxy - re-enabled:",
1390 host
->host
, host
->port
);
1392 host
->is_disabled
= 0;
1398 return HANDLER_GO_ON
;
1402 int mod_proxy_plugin_init(plugin
*p
);
1403 int mod_proxy_plugin_init(plugin
*p
) {
1404 p
->version
= LIGHTTPD_VERSION_ID
;
1405 p
->name
= buffer_init_string("proxy");
1407 p
->init
= mod_proxy_init
;
1408 p
->cleanup
= mod_proxy_free
;
1409 p
->set_defaults
= mod_proxy_set_defaults
;
1410 p
->connection_reset
= mod_proxy_connection_reset
; /* end of req-resp cycle */
1411 p
->handle_connection_close
= mod_proxy_connection_reset
; /* end of client connection */
1412 p
->handle_uri_clean
= mod_proxy_check_extension
;
1413 p
->handle_subrequest
= mod_proxy_handle_subrequest
;
1414 p
->handle_trigger
= mod_proxy_trigger
;