1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2020, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief General high-level functions to handle reading and writing
12 * Each connection (ideally) represents a TLS connection, a TCP socket, a unix
13 * socket, or a UDP socket on which reads and writes can occur. (But see
14 * connection_edge.c for cases where connections can also represent streams
15 * that do not have a corresponding socket.)
17 * The module implements the abstract type, connection_t. The subtypes are:
19 * <li>listener_connection_t, implemented here in connection.c
20 * <li>dir_connection_t, implemented in directory.c
21 * <li>or_connection_t, implemented in connection_or.c
22 * <li>edge_connection_t, implemented in connection_edge.c, along with
24 * <ul><li>entry_connection_t, also implemented in connection_edge.c
26 * <li>control_connection_t, implemented in control.c
29 * The base type implemented in this module is responsible for basic
30 * rate limiting, flow control, and marshalling bytes onto and off of the
31 * network (either directly or via TLS).
33 * Connections are registered with the main loop with connection_add(). As
34 * they become able to read or write register the fact with the event main
35 * loop by calling connection_watch_events(), connection_start_reading(), or
36 * connection_start_writing(). When they no longer want to read or write,
37 * they call connection_stop_reading() or connection_stop_writing().
39 * To queue data to be written on a connection, call
40 * connection_buf_add(). When data arrives, the
41 * connection_process_inbuf() callback is invoked, which dispatches to a
42 * type-specific function (such as connection_edge_process_inbuf() for
43 * example). Connection types that need notice of when data has been written
44 * receive notification via connection_flushed_some() and
45 * connection_finished_flushing(). These functions all delegate to
46 * type-specific implementations.
48 * Additionally, beyond the core of connection_t, this module also implements:
50 * <li>Listeners, which wait for incoming sockets and launch connections
51 * <li>Outgoing SOCKS proxy support
52 * <li>Outgoing HTTP proxy support
53 * <li>An out-of-sockets handler for dealing with socket exhaustion
57 #define CONNECTION_PRIVATE
58 #include "core/or/or.h"
59 #include "feature/client/bridges.h"
60 #include "lib/buf/buffers.h"
61 #include "lib/tls/buffers_tls.h"
62 #include "lib/err/backtrace.h"
65 * Define this so we get channel internal functions, since we're implementing
66 * part of a subclass (channel_tls_t).
68 #define CHANNEL_OBJECT_PRIVATE
69 #include "app/config/config.h"
70 #include "app/config/resolve_addr.h"
71 #include "core/mainloop/connection.h"
72 #include "core/mainloop/mainloop.h"
73 #include "core/mainloop/netstatus.h"
74 #include "core/or/channel.h"
75 #include "core/or/channeltls.h"
76 #include "core/or/circuitbuild.h"
77 #include "core/or/circuitlist.h"
78 #include "core/or/circuituse.h"
79 #include "core/or/connection_edge.h"
80 #include "core/or/connection_or.h"
81 #include "core/or/dos.h"
82 #include "core/or/policies.h"
83 #include "core/or/reasons.h"
84 #include "core/or/relay.h"
85 #include "core/or/status.h"
86 #include "core/or/crypt_path.h"
87 #include "core/proto/proto_haproxy.h"
88 #include "core/proto/proto_http.h"
89 #include "core/proto/proto_socks.h"
90 #include "feature/client/dnsserv.h"
91 #include "feature/client/entrynodes.h"
92 #include "feature/client/transports.h"
93 #include "feature/control/control.h"
94 #include "feature/control/control_events.h"
95 #include "feature/dirauth/authmode.h"
96 #include "feature/dirauth/dirauth_config.h"
97 #include "feature/dircache/dirserv.h"
98 #include "feature/dircommon/directory.h"
99 #include "feature/hibernate/hibernate.h"
100 #include "feature/hs/hs_common.h"
101 #include "feature/hs/hs_ident.h"
102 #include "feature/hs/hs_metrics.h"
103 #include "feature/metrics/metrics.h"
104 #include "feature/nodelist/nodelist.h"
105 #include "feature/nodelist/routerlist.h"
106 #include "feature/relay/dns.h"
107 #include "feature/relay/ext_orport.h"
108 #include "feature/relay/routermode.h"
109 #include "feature/rend/rendclient.h"
110 #include "feature/rend/rendcommon.h"
111 #include "feature/stats/connstats.h"
112 #include "feature/stats/rephist.h"
113 #include "feature/stats/bwhist.h"
114 #include "lib/crypt_ops/crypto_util.h"
115 #include "lib/crypt_ops/crypto_format.h"
116 #include "lib/geoip/geoip.h"
118 #include "lib/cc/ctassert.h"
119 #include "lib/sandbox/sandbox.h"
120 #include "lib/net/buffers_net.h"
121 #include "lib/tls/tortls.h"
122 #include "lib/evloop/compat_libevent.h"
123 #include "lib/compress/compress.h"
132 #ifdef HAVE_SYS_STAT_H
133 #include <sys/stat.h>
137 #include <sys/socket.h>
141 #include "feature/dircommon/dir_connection_st.h"
142 #include "feature/control/control_connection_st.h"
143 #include "core/or/entry_connection_st.h"
144 #include "core/or/listener_connection_st.h"
145 #include "core/or/or_connection_st.h"
146 #include "core/or/port_cfg_st.h"
147 #include "feature/nodelist/routerinfo_st.h"
148 #include "core/or/socks_request_st.h"
151 * On Windows and Linux we cannot reliably bind() a socket to an
152 * address and port if: 1) There's already a socket bound to wildcard
153 * address (0.0.0.0 or ::) with the same port; 2) We try to bind()
154 * to wildcard address and there's another socket bound to a
155 * specific address and the same port.
157 * To address this problem on these two platforms we implement a
159 * 1) Checks if first attempt to bind() a new socket failed with
161 * 2) If so, it will close the appropriate old listener connection and
162 * 3) Attempts bind()'ing the new listener socket again.
164 * Just to be safe, we are enabling listener rebind code on all platforms,
165 * to account for unexpected cases where it may be needed.
167 #define ENABLE_LISTENER_REBIND
169 static connection_t
*connection_listener_new(
170 const struct sockaddr
*listensockaddr
,
171 socklen_t listensocklen
, int type
,
173 const port_cfg_t
*portcfg
,
175 static connection_t
*connection_listener_new_for_port(
176 const port_cfg_t
*port
,
177 int *defer
, int *addr_in_use
);
178 static void connection_init(time_t now
, connection_t
*conn
, int type
,
180 static int connection_handle_listener_read(connection_t
*conn
, int new_type
);
181 static int connection_finished_flushing(connection_t
*conn
);
182 static int connection_flushed_some(connection_t
*conn
);
183 static int connection_finished_connecting(connection_t
*conn
);
184 static int connection_reached_eof(connection_t
*conn
);
185 static int connection_buf_read_from_socket(connection_t
*conn
,
186 ssize_t
*max_to_read
,
188 static int connection_process_inbuf(connection_t
*conn
, int package_partial
);
189 static void client_check_address_changed(tor_socket_t sock
);
190 static void set_constrained_socket_buffers(tor_socket_t sock
, int size
);
192 static const char *connection_proxy_state_to_string(int state
);
193 static int connection_read_https_proxy_response(connection_t
*conn
);
194 static void connection_send_socks5_connect(connection_t
*conn
);
195 static const char *proxy_type_to_string(int proxy_type
);
196 static int conn_get_proxy_type(const connection_t
*conn
);
197 const tor_addr_t
*conn_get_outbound_address(sa_family_t family
,
198 const or_options_t
*options
, unsigned int conn_type
);
199 static void reenable_blocked_connection_init(const or_options_t
*options
);
200 static void reenable_blocked_connection_schedule(void);
202 /** The last addresses that our network interface seemed to have been
203 * binding to. We use this as one way to detect when our IP changes.
205 * XXXX+ We should really use the entire list of interfaces here.
207 static tor_addr_t
*last_interface_ipv4
= NULL
;
208 /* DOCDOC last_interface_ipv6 */
209 static tor_addr_t
*last_interface_ipv6
= NULL
;
210 /** A list of tor_addr_t for addresses we've used in outgoing connections.
211 * Used to detect IP address changes. */
212 static smartlist_t
*outgoing_addrs
= NULL
;
214 #define CASE_ANY_LISTENER_TYPE \
215 case CONN_TYPE_OR_LISTENER: \
216 case CONN_TYPE_EXT_OR_LISTENER: \
217 case CONN_TYPE_AP_LISTENER: \
218 case CONN_TYPE_DIR_LISTENER: \
219 case CONN_TYPE_CONTROL_LISTENER: \
220 case CONN_TYPE_AP_TRANS_LISTENER: \
221 case CONN_TYPE_AP_NATD_LISTENER: \
222 case CONN_TYPE_AP_DNS_LISTENER: \
223 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER: \
224 case CONN_TYPE_METRICS_LISTENER
226 /**************************************************************/
229 * Cast a `connection_t *` to a `listener_connection_t *`.
231 * Exit with an assertion failure if the input is not a
232 * `listener_connection_t`.
234 listener_connection_t
*
235 TO_LISTENER_CONN(connection_t
*c
)
237 tor_assert(c
->magic
== LISTENER_CONNECTION_MAGIC
);
238 return DOWNCAST(listener_connection_t
, c
);
242 * Cast a `const connection_t *` to a `const listener_connection_t *`.
244 * Exit with an assertion failure if the input is not a
245 * `listener_connection_t`.
247 const listener_connection_t
*
248 CONST_TO_LISTENER_CONN(const connection_t
*c
)
250 return TO_LISTENER_CONN((connection_t
*)c
);
254 connection_get_inbuf_len(connection_t
*conn
)
256 return conn
->inbuf
? buf_datalen(conn
->inbuf
) : 0;
260 connection_get_outbuf_len(connection_t
*conn
)
262 return conn
->outbuf
? buf_datalen(conn
->outbuf
) : 0;
266 * Return the human-readable name for the connection type <b>type</b>
269 conn_type_to_string(int type
)
273 case CONN_TYPE_OR_LISTENER
: return "OR listener";
274 case CONN_TYPE_OR
: return "OR";
275 case CONN_TYPE_EXIT
: return "Exit";
276 case CONN_TYPE_AP_LISTENER
: return "Socks listener";
277 case CONN_TYPE_AP_TRANS_LISTENER
:
278 return "Transparent pf/netfilter listener";
279 case CONN_TYPE_AP_NATD_LISTENER
: return "Transparent natd listener";
280 case CONN_TYPE_AP_DNS_LISTENER
: return "DNS listener";
281 case CONN_TYPE_AP
: return "Socks";
282 case CONN_TYPE_DIR_LISTENER
: return "Directory listener";
283 case CONN_TYPE_DIR
: return "Directory";
284 case CONN_TYPE_CONTROL_LISTENER
: return "Control listener";
285 case CONN_TYPE_CONTROL
: return "Control";
286 case CONN_TYPE_EXT_OR
: return "Extended OR";
287 case CONN_TYPE_EXT_OR_LISTENER
: return "Extended OR listener";
288 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER
: return "HTTP tunnel listener";
289 case CONN_TYPE_METRICS_LISTENER
: return "Metrics listener";
290 case CONN_TYPE_METRICS
: return "Metrics";
292 log_warn(LD_BUG
, "unknown connection type %d", type
);
293 tor_snprintf(buf
, sizeof(buf
), "unknown [%d]", type
);
299 * Return the human-readable name for the connection state <b>state</b>
300 * for the connection type <b>type</b>
303 conn_state_to_string(int type
, int state
)
307 CASE_ANY_LISTENER_TYPE
:
308 if (state
== LISTENER_STATE_READY
)
313 case OR_CONN_STATE_CONNECTING
: return "connect()ing";
314 case OR_CONN_STATE_PROXY_HANDSHAKING
: return "handshaking (proxy)";
315 case OR_CONN_STATE_TLS_HANDSHAKING
: return "handshaking (TLS)";
316 case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
:
317 return "renegotiating (TLS, v2 handshake)";
318 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
:
319 return "waiting for renegotiation or V3 handshake";
320 case OR_CONN_STATE_OR_HANDSHAKING_V2
:
321 return "handshaking (Tor, v2 handshake)";
322 case OR_CONN_STATE_OR_HANDSHAKING_V3
:
323 return "handshaking (Tor, v3 handshake)";
324 case OR_CONN_STATE_OPEN
: return "open";
327 case CONN_TYPE_EXT_OR
:
329 case EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE
:
330 return "waiting for authentication type";
331 case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE
:
332 return "waiting for client nonce";
333 case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH
:
334 return "waiting for client hash";
335 case EXT_OR_CONN_STATE_OPEN
: return "open";
336 case EXT_OR_CONN_STATE_FLUSHING
: return "flushing final OKAY";
341 case EXIT_CONN_STATE_RESOLVING
: return "waiting for dest info";
342 case EXIT_CONN_STATE_CONNECTING
: return "connecting";
343 case EXIT_CONN_STATE_OPEN
: return "open";
344 case EXIT_CONN_STATE_RESOLVEFAILED
: return "resolve failed";
349 case AP_CONN_STATE_SOCKS_WAIT
: return "waiting for socks info";
350 case AP_CONN_STATE_NATD_WAIT
: return "waiting for natd dest info";
351 case AP_CONN_STATE_RENDDESC_WAIT
: return "waiting for rendezvous desc";
352 case AP_CONN_STATE_CONTROLLER_WAIT
: return "waiting for controller";
353 case AP_CONN_STATE_CIRCUIT_WAIT
: return "waiting for circuit";
354 case AP_CONN_STATE_CONNECT_WAIT
: return "waiting for connect response";
355 case AP_CONN_STATE_RESOLVE_WAIT
: return "waiting for resolve response";
356 case AP_CONN_STATE_OPEN
: return "open";
361 case DIR_CONN_STATE_CONNECTING
: return "connecting";
362 case DIR_CONN_STATE_CLIENT_SENDING
: return "client sending";
363 case DIR_CONN_STATE_CLIENT_READING
: return "client reading";
364 case DIR_CONN_STATE_CLIENT_FINISHED
: return "client finished";
365 case DIR_CONN_STATE_SERVER_COMMAND_WAIT
: return "waiting for command";
366 case DIR_CONN_STATE_SERVER_WRITING
: return "writing";
369 case CONN_TYPE_CONTROL
:
371 case CONTROL_CONN_STATE_OPEN
: return "open (protocol v1)";
372 case CONTROL_CONN_STATE_NEEDAUTH
:
373 return "waiting for authentication (protocol v1)";
379 return "uninitialized";
382 log_warn(LD_BUG
, "unknown connection state %d (type %d)", state
, type
);
383 tor_snprintf(buf
, sizeof(buf
),
384 "unknown state [%d] on unknown [%s] connection",
385 state
, conn_type_to_string(type
));
386 tor_assert_nonfatal_unreached_once();
391 * Helper: describe the peer or address of connection @a conn in a
392 * human-readable manner.
394 * Returns a pointer to a static buffer; future calls to
395 * connection_describe_peer_internal() will invalidate this buffer.
397 * If <b>include_preposition</b> is true, include a preposition before the
400 * Nobody should parse the output of this function; it can and will change in
401 * future versions of tor.
404 connection_describe_peer_internal(const connection_t
*conn
,
405 bool include_preposition
)
411 static char peer_buf
[256];
412 const tor_addr_t
*addr
= &conn
->addr
;
413 const char *address
= NULL
;
419 /* First, figure out the preposition to use */
420 switch (conn
->type
) {
421 CASE_ANY_LISTENER_TYPE
:
427 case CONN_TYPE_CONTROL
:
429 case CONN_TYPE_EXT_OR
:
437 /* Now figure out the address. */
438 if (conn
->socket_family
== AF_UNIX
) {
439 /* For unix sockets, we always use the `address` string. */
440 address
= conn
->address
? conn
->address
: "unix socket";
441 } else if (conn
->type
== CONN_TYPE_OR
) {
442 /* For OR connections, we have a lot to do. */
443 const or_connection_t
*or_conn
= CONST_TO_OR_CONN(conn
);
444 /* We report the IDs we're talking to... */
445 if (fast_digest_is_zero(or_conn
->identity_digest
)) {
446 // This could be a client, so scrub it. No identity to report.
449 const ed25519_public_key_t
*ed_id
=
450 connection_or_get_alleged_ed25519_id(or_conn
);
451 char ed_id_buf
[ED25519_BASE64_LEN
+1];
452 char rsa_id_buf
[HEX_DIGEST_LEN
+1];
454 ed25519_public_to_base64(ed_id_buf
, ed_id
);
456 strlcpy(ed_id_buf
, "<none>", sizeof(ed_id_buf
));
458 base16_encode(rsa_id_buf
, sizeof(rsa_id_buf
),
459 or_conn
->identity_digest
, DIGEST_LEN
);
460 tor_snprintf(extra_buf
, sizeof(extra_buf
),
461 " ID=%s RSA_ID=%s", ed_id_buf
, rsa_id_buf
);
463 if (! scrub
&& (! tor_addr_eq(addr
, &or_conn
->canonical_orport
.addr
) ||
464 conn
->port
!= or_conn
->canonical_orport
.port
)) {
465 /* We report canonical address, if it's different */
466 char canonical_addr_buf
[TOR_ADDR_BUF_LEN
];
467 if (tor_addr_to_str(canonical_addr_buf
, &or_conn
->canonical_orport
.addr
,
468 sizeof(canonical_addr_buf
), 1)) {
469 tor_snprintf(extra_buf
+strlen(extra_buf
),
470 sizeof(extra_buf
)-strlen(extra_buf
),
471 " canonical_addr=%s:%"PRIu16
,
473 or_conn
->canonical_orport
.port
);
476 } else if (conn
->type
== CONN_TYPE_EXIT
) {
477 scrub
= true; /* This is a client's request; scrub it with SafeLogging. */
478 if (tor_addr_is_null(addr
)) {
479 address
= conn
->address
;
480 strlcpy(extra_buf
, " (DNS lookup pending)", sizeof(extra_buf
));
484 char addr_buf
[TOR_ADDR_BUF_LEN
];
485 if (address
== NULL
) {
486 if (tor_addr_family(addr
) == 0) {
489 address
= tor_addr_to_str(addr_buf
, addr
, sizeof(addr_buf
), 1);
491 address
= "<can't format!>";
492 tor_assert_nonfatal_unreached_once();
499 if (scrub
&& get_options()->SafeLogging_
!= SAFELOG_SCRUB_NONE
) {
500 address
= "[scrubbed]";
502 /* Only set the port if we're not scrubbing the address. */
503 if (conn
->port
!= 0) {
504 tor_snprintf(portbuf
, sizeof(portbuf
), ":%d", conn
->port
);
508 const char *sp
= include_preposition
? " " : "";
509 if (! include_preposition
)
512 tor_snprintf(peer_buf
, sizeof(peer_buf
),
513 "%s%s%s%s%s", prep
, sp
, address
, portbuf
, extra_buf
);
518 * Describe the peer or address of connection @a conn in a
519 * human-readable manner.
521 * Returns a pointer to a static buffer; future calls to
522 * connection_describe_peer() or connection_describe() will invalidate this
525 * Nobody should parse the output of this function; it can and will change in
526 * future versions of tor.
529 connection_describe_peer(const connection_t
*conn
)
531 return connection_describe_peer_internal(conn
, false);
535 * Describe a connection for logging purposes.
537 * Returns a pointer to a static buffer; future calls to connection_describe()
538 * will invalidate this buffer.
540 * Nobody should parse the output of this function; it can and will change in
541 * future versions of tor.
544 connection_describe(const connection_t
*conn
)
547 return "null connection";
549 static char desc_buf
[256];
550 const char *peer
= connection_describe_peer_internal(conn
, true);
551 tor_snprintf(desc_buf
, sizeof(desc_buf
),
552 "%s connection (%s) %s",
553 conn_type_to_string(conn
->type
),
554 conn_state_to_string(conn
->type
, conn
->state
),
559 /** Allocate and return a new dir_connection_t, initialized as by
560 * connection_init(). */
562 dir_connection_new(int socket_family
)
564 dir_connection_t
*dir_conn
= tor_malloc_zero(sizeof(dir_connection_t
));
565 connection_init(time(NULL
), TO_CONN(dir_conn
), CONN_TYPE_DIR
, socket_family
);
569 /** Allocate and return a new or_connection_t, initialized as by
572 * Initialize active_circuit_pqueue.
574 * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
577 or_connection_new(int type
, int socket_family
)
579 or_connection_t
*or_conn
= tor_malloc_zero(sizeof(or_connection_t
));
580 time_t now
= time(NULL
);
581 tor_assert(type
== CONN_TYPE_OR
|| type
== CONN_TYPE_EXT_OR
);
582 connection_init(now
, TO_CONN(or_conn
), type
, socket_family
);
584 tor_addr_make_unspec(&or_conn
->canonical_orport
.addr
);
585 connection_or_set_canonical(or_conn
, 0);
587 if (type
== CONN_TYPE_EXT_OR
) {
588 /* If we aren't told an address for this connection, we should
589 * presume it isn't local, and should be rate-limited. */
590 TO_CONN(or_conn
)->always_rate_limit_as_remote
= 1;
591 connection_or_set_ext_or_identifier(or_conn
);
597 /** Allocate and return a new entry_connection_t, initialized as by
600 * Allocate space to store the socks_request.
603 entry_connection_new(int type
, int socket_family
)
605 entry_connection_t
*entry_conn
= tor_malloc_zero(sizeof(entry_connection_t
));
606 tor_assert(type
== CONN_TYPE_AP
);
607 connection_init(time(NULL
), ENTRY_TO_CONN(entry_conn
), type
, socket_family
);
608 entry_conn
->socks_request
= socks_request_new();
609 /* If this is coming from a listener, we'll set it up based on the listener
610 * in a little while. Otherwise, we're doing this as a linked connection
611 * of some kind, and we should set it up here based on the socket family */
612 if (socket_family
== AF_INET
)
613 entry_conn
->entry_cfg
.ipv4_traffic
= 1;
614 else if (socket_family
== AF_INET6
)
615 entry_conn
->entry_cfg
.ipv6_traffic
= 1;
619 /** Allocate and return a new edge_connection_t, initialized as by
620 * connection_init(). */
622 edge_connection_new(int type
, int socket_family
)
624 edge_connection_t
*edge_conn
= tor_malloc_zero(sizeof(edge_connection_t
));
625 tor_assert(type
== CONN_TYPE_EXIT
);
626 connection_init(time(NULL
), TO_CONN(edge_conn
), type
, socket_family
);
630 /** Allocate and return a new control_connection_t, initialized as by
631 * connection_init(). */
632 control_connection_t
*
633 control_connection_new(int socket_family
)
635 control_connection_t
*control_conn
=
636 tor_malloc_zero(sizeof(control_connection_t
));
637 connection_init(time(NULL
),
638 TO_CONN(control_conn
), CONN_TYPE_CONTROL
, socket_family
);
642 /** Allocate and return a new listener_connection_t, initialized as by
643 * connection_init(). */
644 listener_connection_t
*
645 listener_connection_new(int type
, int socket_family
)
647 listener_connection_t
*listener_conn
=
648 tor_malloc_zero(sizeof(listener_connection_t
));
649 connection_init(time(NULL
), TO_CONN(listener_conn
), type
, socket_family
);
650 return listener_conn
;
653 /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
654 * to make or receive connections of address family <b>socket_family</b>. The
655 * type should be one of the CONN_TYPE_* constants. */
657 connection_new(int type
, int socket_family
)
661 case CONN_TYPE_EXT_OR
:
662 return TO_CONN(or_connection_new(type
, socket_family
));
665 return TO_CONN(edge_connection_new(type
, socket_family
));
668 return ENTRY_TO_CONN(entry_connection_new(type
, socket_family
));
671 return TO_CONN(dir_connection_new(socket_family
));
673 case CONN_TYPE_CONTROL
:
674 return TO_CONN(control_connection_new(socket_family
));
676 CASE_ANY_LISTENER_TYPE
:
677 return TO_CONN(listener_connection_new(type
, socket_family
));
680 connection_t
*conn
= tor_malloc_zero(sizeof(connection_t
));
681 connection_init(time(NULL
), conn
, type
, socket_family
);
687 /** Initializes conn. (you must call connection_add() to link it into the main
690 * Set conn-\>magic to the correct value.
692 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
693 * -1 to signify they are not yet assigned.
695 * Initialize conn's timestamps to now.
698 connection_init(time_t now
, connection_t
*conn
, int type
, int socket_family
)
700 static uint64_t n_connections_allocated
= 1;
704 case CONN_TYPE_EXT_OR
:
705 conn
->magic
= OR_CONNECTION_MAGIC
;
708 conn
->magic
= EDGE_CONNECTION_MAGIC
;
711 conn
->magic
= ENTRY_CONNECTION_MAGIC
;
714 conn
->magic
= DIR_CONNECTION_MAGIC
;
716 case CONN_TYPE_CONTROL
:
717 conn
->magic
= CONTROL_CONNECTION_MAGIC
;
719 CASE_ANY_LISTENER_TYPE
:
720 conn
->magic
= LISTENER_CONNECTION_MAGIC
;
723 conn
->magic
= BASE_CONNECTION_MAGIC
;
727 conn
->s
= TOR_INVALID_SOCKET
; /* give it a default of 'not used' */
728 conn
->conn_array_index
= -1; /* also default to 'not used' */
729 conn
->global_identifier
= n_connections_allocated
++;
732 conn
->socket_family
= socket_family
;
733 if (!connection_is_listener(conn
)) {
734 /* listeners never use their buf */
735 conn
->inbuf
= buf_new();
736 conn
->outbuf
= buf_new();
739 conn
->timestamp_created
= now
;
740 conn
->timestamp_last_read_allowed
= now
;
741 conn
->timestamp_last_write_allowed
= now
;
744 /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
746 connection_link_connections(connection_t
*conn_a
, connection_t
*conn_b
)
748 tor_assert(! SOCKET_OK(conn_a
->s
));
749 tor_assert(! SOCKET_OK(conn_b
->s
));
753 conn_a
->linked_conn
= conn_b
;
754 conn_b
->linked_conn
= conn_a
;
757 /** Return true iff the provided connection listener type supports AF_UNIX
760 conn_listener_type_supports_af_unix(int type
)
762 /* For now only control ports or SOCKS ports can be Unix domain sockets
763 * and listeners at the same time */
765 case CONN_TYPE_CONTROL_LISTENER
:
766 case CONN_TYPE_AP_LISTENER
:
773 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
774 * necessary, close its socket if necessary, and mark the directory as dirty
775 * if <b>conn</b> is an OR or OP connection.
778 connection_free_minimal(connection_t
*conn
)
785 switch (conn
->type
) {
787 case CONN_TYPE_EXT_OR
:
788 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
789 mem
= TO_OR_CONN(conn
);
790 memlen
= sizeof(or_connection_t
);
793 tor_assert(conn
->magic
== ENTRY_CONNECTION_MAGIC
);
794 mem
= TO_ENTRY_CONN(conn
);
795 memlen
= sizeof(entry_connection_t
);
798 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
799 mem
= TO_EDGE_CONN(conn
);
800 memlen
= sizeof(edge_connection_t
);
803 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
804 mem
= TO_DIR_CONN(conn
);
805 memlen
= sizeof(dir_connection_t
);
807 case CONN_TYPE_CONTROL
:
808 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
809 mem
= TO_CONTROL_CONN(conn
);
810 memlen
= sizeof(control_connection_t
);
812 CASE_ANY_LISTENER_TYPE
:
813 tor_assert(conn
->magic
== LISTENER_CONNECTION_MAGIC
);
814 mem
= TO_LISTENER_CONN(conn
);
815 memlen
= sizeof(listener_connection_t
);
818 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
820 memlen
= sizeof(connection_t
);
825 log_info(LD_GENERAL
, "Freeing linked %s connection [%s] with %d "
826 "bytes on inbuf, %d on outbuf.",
827 conn_type_to_string(conn
->type
),
828 conn_state_to_string(conn
->type
, conn
->state
),
829 (int)connection_get_inbuf_len(conn
),
830 (int)connection_get_outbuf_len(conn
));
833 if (!connection_is_listener(conn
)) {
834 buf_free(conn
->inbuf
);
835 buf_free(conn
->outbuf
);
837 if (conn
->socket_family
== AF_UNIX
) {
838 /* For now only control and SOCKS ports can be Unix domain sockets
839 * and listeners at the same time */
840 tor_assert(conn_listener_type_supports_af_unix(conn
->type
));
842 if (unlink(conn
->address
) < 0 && errno
!= ENOENT
) {
843 log_warn(LD_NET
, "Could not unlink %s: %s", conn
->address
,
849 tor_str_wipe_and_free(conn
->address
);
851 if (connection_speaks_cells(conn
)) {
852 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
854 if (! SOCKET_OK(conn
->s
)) {
855 /* The socket has been closed by somebody else; we must tell the
856 * TLS object not to close it. */
857 tor_tls_release_socket(or_conn
->tls
);
859 /* The tor_tls_free() call below will close the socket; we must tell
860 * the code below not to close it a second time. */
861 tor_release_socket_ownership(conn
->s
);
862 conn
->s
= TOR_INVALID_SOCKET
;
864 tor_tls_free(or_conn
->tls
);
867 or_handshake_state_free(or_conn
->handshake_state
);
868 or_conn
->handshake_state
= NULL
;
869 tor_str_wipe_and_free(or_conn
->nickname
);
871 /* Owww, this shouldn't happen, but... */
872 channel_t
*base_chan
= TLS_CHAN_TO_BASE(or_conn
->chan
);
873 tor_assert(base_chan
);
875 "Freeing orconn at %p, saw channel %p with ID "
876 "%"PRIu64
" left un-NULLed",
878 base_chan
->global_identifier
);
879 if (!CHANNEL_FINISHED(base_chan
)) {
880 channel_close_for_error(base_chan
);
883 or_conn
->chan
->conn
= NULL
;
884 or_conn
->chan
= NULL
;
887 if (conn
->type
== CONN_TYPE_AP
) {
888 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(conn
);
889 tor_str_wipe_and_free(entry_conn
->chosen_exit_name
);
890 tor_str_wipe_and_free(entry_conn
->original_dest_address
);
891 if (entry_conn
->socks_request
)
892 socks_request_free(entry_conn
->socks_request
);
893 if (entry_conn
->pending_optimistic_data
) {
894 buf_free(entry_conn
->pending_optimistic_data
);
896 if (entry_conn
->sending_optimistic_data
) {
897 buf_free(entry_conn
->sending_optimistic_data
);
900 if (CONN_IS_EDGE(conn
)) {
901 rend_data_free(TO_EDGE_CONN(conn
)->rend_data
);
902 hs_ident_edge_conn_free(TO_EDGE_CONN(conn
)->hs_ident
);
904 if (conn
->type
== CONN_TYPE_CONTROL
) {
905 control_connection_t
*control_conn
= TO_CONTROL_CONN(conn
);
906 tor_free(control_conn
->safecookie_client_hash
);
907 tor_free(control_conn
->incoming_cmd
);
908 tor_free(control_conn
->current_cmd
);
909 if (control_conn
->ephemeral_onion_services
) {
910 SMARTLIST_FOREACH(control_conn
->ephemeral_onion_services
, char *, cp
, {
911 memwipe(cp
, 0, strlen(cp
));
914 smartlist_free(control_conn
->ephemeral_onion_services
);
918 /* Probably already freed by connection_free. */
919 tor_event_free(conn
->read_event
);
920 tor_event_free(conn
->write_event
);
921 conn
->read_event
= conn
->write_event
= NULL
;
923 if (conn
->type
== CONN_TYPE_DIR
) {
924 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
925 tor_free(dir_conn
->requested_resource
);
927 tor_compress_free(dir_conn
->compress_state
);
928 dir_conn_clear_spool(dir_conn
);
930 rend_data_free(dir_conn
->rend_data
);
931 hs_ident_dir_conn_free(dir_conn
->hs_ident
);
932 if (dir_conn
->guard_state
) {
933 /* Cancel before freeing, if it's still there. */
934 entry_guard_cancel(&dir_conn
->guard_state
);
936 circuit_guard_state_free(dir_conn
->guard_state
);
939 if (SOCKET_OK(conn
->s
)) {
940 log_debug(LD_NET
,"closing fd %d.",(int)conn
->s
);
941 tor_close_socket(conn
->s
);
942 conn
->s
= TOR_INVALID_SOCKET
;
945 if (conn
->type
== CONN_TYPE_OR
&&
946 !tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
947 log_warn(LD_BUG
, "called on OR conn with non-zeroed identity_digest");
948 connection_or_clear_identity(TO_OR_CONN(conn
));
950 if (conn
->type
== CONN_TYPE_OR
|| conn
->type
== CONN_TYPE_EXT_OR
) {
951 tor_free(TO_OR_CONN(conn
)->ext_or_conn_id
);
952 tor_free(TO_OR_CONN(conn
)->ext_or_auth_correct_client_hash
);
953 tor_free(TO_OR_CONN(conn
)->ext_or_transport
);
956 memwipe(mem
, 0xCC, memlen
); /* poison memory */
960 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
963 connection_free_
,(connection_t
*conn
))
967 tor_assert(!connection_is_on_closeable_list(conn
));
968 tor_assert(!connection_in_array(conn
));
969 if (BUG(conn
->linked_conn
)) {
970 conn
->linked_conn
->linked_conn
= NULL
;
971 if (! conn
->linked_conn
->marked_for_close
&&
972 conn
->linked_conn
->reading_from_linked_conn
)
973 connection_start_reading(conn
->linked_conn
);
974 conn
->linked_conn
= NULL
;
976 if (connection_speaks_cells(conn
)) {
977 if (!tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
)) {
978 connection_or_clear_identity(TO_OR_CONN(conn
));
981 if (conn
->type
== CONN_TYPE_CONTROL
) {
982 connection_control_closed(TO_CONTROL_CONN(conn
));
986 if (conn
->type
== CONN_TYPE_AP
) {
987 connection_ap_warn_and_unmark_if_pending_circ(TO_ENTRY_CONN(conn
),
992 /* Notify the circuit creation DoS mitigation subsystem that an OR client
993 * connection has been closed. And only do that if we track it. */
994 if (conn
->type
== CONN_TYPE_OR
) {
995 dos_close_client_conn(TO_OR_CONN(conn
));
998 connection_unregister_events(conn
);
999 connection_free_minimal(conn
);
1003 * Called when we're about to finally unlink and free a connection:
1004 * perform necessary accounting and cleanup
1005 * - Directory conns that failed to fetch a rendezvous descriptor
1006 * need to inform pending rendezvous streams.
1007 * - OR conns need to call rep_hist_note_*() to record status.
1008 * - AP conns need to send a socks reject if necessary.
1009 * - Exit conns need to call connection_dns_remove() if necessary.
1010 * - AP and Exit conns need to send an end cell if they can.
1011 * - DNS conns need to fail any resolves that are pending on them.
1012 * - OR and edge connections need to be unlinked from circuits.
1015 connection_about_to_close_connection(connection_t
*conn
)
1017 tor_assert(conn
->marked_for_close
);
1019 switch (conn
->type
) {
1021 connection_dir_about_to_close(TO_DIR_CONN(conn
));
1024 case CONN_TYPE_EXT_OR
:
1025 connection_or_about_to_close(TO_OR_CONN(conn
));
1028 connection_ap_about_to_close(TO_ENTRY_CONN(conn
));
1030 case CONN_TYPE_EXIT
:
1031 connection_exit_about_to_close(TO_EDGE_CONN(conn
));
1036 /** Return true iff connection_close_immediate() has been called on this
1038 #define CONN_IS_CLOSED(c) \
1039 ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
1041 /** Close the underlying socket for <b>conn</b>, so we don't try to
1042 * flush it. Must be used in conjunction with (right before)
1043 * connection_mark_for_close().
1046 connection_close_immediate(connection_t
*conn
)
1048 assert_connection_ok(conn
,0);
1049 if (CONN_IS_CLOSED(conn
)) {
1050 log_err(LD_BUG
,"Attempt to close already-closed connection.");
1051 tor_fragile_assert();
1054 if (connection_get_outbuf_len(conn
)) {
1055 log_info(LD_NET
,"fd %d, type %s, state %s, %"TOR_PRIuSZ
" bytes on outbuf.",
1056 (int)conn
->s
, conn_type_to_string(conn
->type
),
1057 conn_state_to_string(conn
->type
, conn
->state
),
1058 buf_datalen(conn
->outbuf
));
1061 connection_unregister_events(conn
);
1063 /* Prevent the event from getting unblocked. */
1064 conn
->read_blocked_on_bw
= 0;
1065 conn
->write_blocked_on_bw
= 0;
1067 if (SOCKET_OK(conn
->s
))
1068 tor_close_socket(conn
->s
);
1069 conn
->s
= TOR_INVALID_SOCKET
;
1071 conn
->linked_conn_is_closed
= 1;
1073 buf_clear(conn
->outbuf
);
1076 /** Mark <b>conn</b> to be closed next time we loop through
1077 * conn_close_if_marked() in main.c. */
1079 connection_mark_for_close_(connection_t
*conn
, int line
, const char *file
)
1081 assert_connection_ok(conn
,0);
1083 tor_assert(line
< 1<<16); /* marked_for_close can only fit a uint16_t. */
1086 if (conn
->type
== CONN_TYPE_OR
) {
1088 * An or_connection should have been closed through one of the channel-
1089 * aware functions in connection_or.c. We'll assume this is an error
1090 * close and do that, and log a bug warning.
1092 log_warn(LD_CHANNEL
| LD_BUG
,
1093 "Something tried to close an or_connection_t without going "
1094 "through channels at %s:%d",
1096 connection_or_close_for_error(TO_OR_CONN(conn
), 0);
1098 /* Pass it down to the real function */
1099 connection_mark_for_close_internal_(conn
, line
, file
);
1103 /** Mark <b>conn</b> to be closed next time we loop through
1104 * conn_close_if_marked() in main.c.
1106 * This _internal version bypasses the CONN_TYPE_OR checks; this should be
1107 * called when you either are sure that if this is an or_connection_t the
1108 * controlling channel has been notified (e.g. with
1109 * connection_or_notify_error()), or you actually are the
1110 * connection_or_close_for_error() or connection_or_close_normally() function.
1111 * For all other cases, use connection_mark_and_flush() which checks for
1112 * or_connection_t properly, instead. See below.
1114 * We want to keep this function simple and quick, since it can be called from
1115 * quite deep in the call chain, and hence it should avoid having side-effects
1116 * that interfere with its callers view of the connection.
1119 connection_mark_for_close_internal_
, (connection_t
*conn
,
1120 int line
, const char *file
))
1122 assert_connection_ok(conn
,0);
1124 tor_assert(line
< 1<<16); /* marked_for_close can only fit a uint16_t. */
1127 if (conn
->marked_for_close
) {
1128 log_warn(LD_BUG
,"Duplicate call to connection_mark_for_close at %s:%d"
1129 " (first at %s:%d)", file
, line
, conn
->marked_for_close_file
,
1130 conn
->marked_for_close
);
1131 tor_fragile_assert();
1135 if (conn
->type
== CONN_TYPE_OR
) {
1137 * Bad news if this happens without telling the controlling channel; do
1138 * this so we can find things that call this wrongly when the asserts hit.
1140 log_debug(LD_CHANNEL
,
1141 "Calling connection_mark_for_close_internal_() on an OR conn "
1146 conn
->marked_for_close
= line
;
1147 conn
->marked_for_close_file
= file
;
1148 add_connection_to_closeable_list(conn
);
1150 /* in case we're going to be held-open-til-flushed, reset
1151 * the number of seconds since last successful write, so
1152 * we get our whole 15 seconds */
1153 conn
->timestamp_last_write_allowed
= time(NULL
);
1156 /** Find each connection that has hold_open_until_flushed set to
1157 * 1 but hasn't written in the past 15 seconds, and set
1158 * hold_open_until_flushed to 0. This means it will get cleaned
1159 * up in the next loop through close_if_marked() in main.c.
1162 connection_expire_held_open(void)
1165 smartlist_t
*conns
= get_connection_array();
1169 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1170 /* If we've been holding the connection open, but we haven't written
1173 if (conn
->hold_open_until_flushed
) {
1174 tor_assert(conn
->marked_for_close
);
1175 if (now
- conn
->timestamp_last_write_allowed
>= 15) {
1177 if (conn
->type
== CONN_TYPE_EXIT
||
1178 (conn
->type
== CONN_TYPE_DIR
&&
1179 conn
->purpose
== DIR_PURPOSE_SERVER
))
1180 severity
= LOG_INFO
;
1182 severity
= LOG_NOTICE
;
1183 log_fn(severity
, LD_NET
,
1184 "Giving up on marked_for_close conn that's been flushing "
1185 "for 15s (fd %d, type %s, state %s).",
1186 (int)conn
->s
, conn_type_to_string(conn
->type
),
1187 conn_state_to_string(conn
->type
, conn
->state
));
1188 conn
->hold_open_until_flushed
= 0;
1191 } SMARTLIST_FOREACH_END(conn
);
1194 #if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
1195 /** Create an AF_UNIX listenaddr struct.
1196 * <b>listenaddress</b> provides the path to the Unix socket.
1198 * Eventually <b>listenaddress</b> will also optionally contain user, group,
1199 * and file permissions for the new socket. But not yet. XXX
1200 * Also, since we do not create the socket here the information doesn't help
1203 * If not NULL <b>readable_address</b> will contain a copy of the path part of
1204 * <b>listenaddress</b>.
1206 * The listenaddr struct has to be freed by the caller.
1208 static struct sockaddr_un
*
1209 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
1212 struct sockaddr_un
*sockaddr
= NULL
;
1214 sockaddr
= tor_malloc_zero(sizeof(struct sockaddr_un
));
1215 sockaddr
->sun_family
= AF_UNIX
;
1216 if (strlcpy(sockaddr
->sun_path
, listenaddress
, sizeof(sockaddr
->sun_path
))
1217 >= sizeof(sockaddr
->sun_path
)) {
1218 log_warn(LD_CONFIG
, "Unix socket path '%s' is too long to fit.",
1219 escaped(listenaddress
));
1224 if (readable_address
)
1225 *readable_address
= tor_strdup(listenaddress
);
1227 *len_out
= sizeof(struct sockaddr_un
);
1230 #else /* !(defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)) */
1231 static struct sockaddr
*
1232 create_unix_sockaddr(const char *listenaddress
, char **readable_address
,
1235 (void)listenaddress
;
1236 (void)readable_address
;
1237 log_fn(LOG_ERR
, LD_BUG
,
1238 "Unix domain sockets not supported, yet we tried to create one.");
1240 tor_fragile_assert();
1243 #endif /* defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN) */
1245 /** Warn that an accept or a connect has failed because we're running out of
1246 * TCP sockets we can use on current system. Rate-limit these warnings so
1247 * that we don't spam the log. */
1249 warn_too_many_conns(void)
1251 #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
1252 static ratelim_t last_warned
= RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL
);
1254 if ((m
= rate_limit_log(&last_warned
, approx_time()))) {
1255 int n_conns
= get_n_open_sockets();
1256 log_warn(LD_NET
,"Failing because we have %d connections already. Please "
1257 "read doc/TUNING for guidance.%s", n_conns
, m
);
1259 control_event_general_status(LOG_WARN
, "TOO_MANY_CONNECTIONS CURRENT=%d",
1264 #ifdef HAVE_SYS_UN_H
1266 #define UNIX_SOCKET_PURPOSE_CONTROL_SOCKET 0
1267 #define UNIX_SOCKET_PURPOSE_SOCKS_SOCKET 1
1269 /** Check if the purpose isn't one of the ones we know what to do with */
1272 is_valid_unix_socket_purpose(int purpose
)
1277 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET
:
1278 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET
:
1286 /** Return a string description of a unix socket purpose */
1288 unix_socket_purpose_to_string(int purpose
)
1290 const char *s
= "unknown-purpose socket";
1293 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET
:
1294 s
= "control socket";
1296 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET
:
1304 /** Check whether we should be willing to open an AF_UNIX socket in
1305 * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
1307 check_location_for_unix_socket(const or_options_t
*options
, const char *path
,
1308 int purpose
, const port_cfg_t
*port
)
1313 tor_assert(is_valid_unix_socket_purpose(purpose
));
1315 p
= tor_strdup(path
);
1316 cpd_check_t flags
= CPD_CHECK_MODE_ONLY
;
1317 if (get_parent_directory(p
)<0 || p
[0] != '/') {
1318 log_warn(LD_GENERAL
, "Bad unix socket address '%s'. Tor does not support "
1319 "relative paths for unix sockets.", path
);
1323 if (port
->is_world_writable
) {
1324 /* World-writable sockets can go anywhere. */
1329 if (port
->is_group_writable
) {
1330 flags
|= CPD_GROUP_OK
;
1333 if (port
->relax_dirmode_check
) {
1334 flags
|= CPD_RELAX_DIRMODE_CHECK
;
1337 if (check_private_dir(p
, flags
, options
->User
) < 0) {
1338 char *escpath
, *escdir
;
1339 escpath
= esc_for_log(path
);
1340 escdir
= esc_for_log(p
);
1341 log_warn(LD_GENERAL
, "Before Tor can create a %s in %s, the directory "
1342 "%s needs to exist, and to be accessible only by the user%s "
1343 "account that is running Tor. (On some Unix systems, anybody "
1344 "who can list a socket can connect to it, so Tor is being "
1346 unix_socket_purpose_to_string(purpose
), escpath
, escdir
,
1347 port
->is_group_writable
? " and group" : "");
1358 #endif /* defined(HAVE_SYS_UN_H) */
1360 /** Tell the TCP stack that it shouldn't wait for a long time after
1361 * <b>sock</b> has closed before reusing its port. Return 0 on success,
1364 make_socket_reuseable(tor_socket_t sock
)
1372 /* REUSEADDR on normal places means you can rebind to the port
1373 * right after somebody else has let it go. But REUSEADDR on win32
1374 * means you can bind to the port _even when somebody else
1375 * already has it bound_. So, don't do that on Win32. */
1376 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
,
1377 (socklen_t
)sizeof(one
)) == -1) {
1381 #endif /* defined(_WIN32) */
1385 /** Tell the Windows TCP stack to prevent other applications from receiving
1386 * traffic from tor's open ports. Return 0 on success, -1 on failure. */
1388 make_win32_socket_exclusive(tor_socket_t sock
)
1390 #ifdef SO_EXCLUSIVEADDRUSE
1393 /* Any socket that sets REUSEADDR on win32 can bind to a port _even when
1394 * somebody else already has it bound_, and _even if the original socket
1395 * didn't set REUSEADDR_. Use EXCLUSIVEADDRUSE to prevent this port-stealing
1397 if (setsockopt(sock
, SOL_SOCKET
, SO_EXCLUSIVEADDRUSE
, (void*) &one
,
1398 (socklen_t
)sizeof(one
))) {
1402 #else /* !defined(SO_EXCLUSIVEADDRUSE) */
1405 #endif /* defined(SO_EXCLUSIVEADDRUSE) */
1407 #endif /* defined(_WIN32) */
1409 /** Max backlog to pass to listen. We start at */
1410 static int listen_limit
= INT_MAX
;
1412 /* Listen on <b>fd</b> with appropriate backlog. Return as for listen. */
1414 tor_listen(tor_socket_t fd
)
1418 if ((r
= listen(fd
, listen_limit
)) < 0) {
1419 if (listen_limit
== SOMAXCONN
)
1421 if ((r
= listen(fd
, SOMAXCONN
)) == 0) {
1422 listen_limit
= SOMAXCONN
;
1423 log_warn(LD_NET
, "Setting listen backlog to INT_MAX connections "
1424 "didn't work, but SOMAXCONN did. Lowering backlog limit.");
1430 /** Bind a new non-blocking socket listening to the socket described
1431 * by <b>listensockaddr</b>.
1433 * <b>address</b> is only used for logging purposes and to add the information
1436 * Set <b>addr_in_use</b> to true in case socket binding fails with
1439 static connection_t
*
1440 connection_listener_new(const struct sockaddr
*listensockaddr
,
1442 int type
, const char *address
,
1443 const port_cfg_t
*port_cfg
,
1446 listener_connection_t
*lis_conn
;
1447 connection_t
*conn
= NULL
;
1448 tor_socket_t s
= TOR_INVALID_SOCKET
; /* the socket we're going to make */
1449 or_options_t
const *options
= get_options();
1450 (void) options
; /* Windows doesn't use this. */
1451 #if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
1452 const struct passwd
*pw
= NULL
;
1454 uint16_t usePort
= 0, gotPort
= 0;
1455 int start_reading
= 0;
1456 static int global_next_session_group
= SESSION_GROUP_FIRST_AUTO
;
1463 if (listensockaddr
->sa_family
== AF_INET
||
1464 listensockaddr
->sa_family
== AF_INET6
) {
1465 int is_stream
= (type
!= CONN_TYPE_AP_DNS_LISTENER
);
1469 tor_addr_from_sockaddr(&addr
, listensockaddr
, &usePort
);
1470 log_notice(LD_NET
, "Opening %s on %s",
1471 conn_type_to_string(type
), fmt_addrport(&addr
, usePort
));
1473 s
= tor_open_socket_nonblocking(tor_addr_family(&addr
),
1474 is_stream
? SOCK_STREAM
: SOCK_DGRAM
,
1475 is_stream
? IPPROTO_TCP
: IPPROTO_UDP
);
1476 if (!SOCKET_OK(s
)) {
1477 int e
= tor_socket_errno(s
);
1478 if (ERRNO_IS_RESOURCE_LIMIT(e
)) {
1479 warn_too_many_conns();
1481 * We'll call the OOS handler at the error exit, so set the
1482 * exhaustion flag for it.
1486 log_warn(LD_NET
, "Socket creation failed: %s",
1487 tor_socket_strerror(e
));
1492 if (make_socket_reuseable(s
) < 0) {
1493 log_warn(LD_NET
, "Error setting SO_REUSEADDR flag on %s: %s",
1494 conn_type_to_string(type
),
1495 tor_socket_strerror(errno
));
1499 if (make_win32_socket_exclusive(s
) < 0) {
1500 log_warn(LD_NET
, "Error setting SO_EXCLUSIVEADDRUSE flag on %s: %s",
1501 conn_type_to_string(type
),
1502 tor_socket_strerror(errno
));
1504 #endif /* defined(_WIN32) */
1506 #if defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT)
1507 if (options
->TransProxyType_parsed
== TPT_TPROXY
&&
1508 type
== CONN_TYPE_AP_TRANS_LISTENER
) {
1510 if (setsockopt(s
, SOL_IP
, IP_TRANSPARENT
, (void*)&one
,
1511 (socklen_t
)sizeof(one
)) < 0) {
1512 const char *extra
= "";
1513 int e
= tor_socket_errno(s
);
1515 extra
= "TransTPROXY requires root privileges or similar"
1517 log_warn(LD_NET
, "Error setting IP_TRANSPARENT flag: %s.%s",
1518 tor_socket_strerror(e
), extra
);
1521 #endif /* defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT) */
1524 if (listensockaddr
->sa_family
== AF_INET6
) {
1526 /* We need to set IPV6_V6ONLY so that this socket can't get used for
1527 * IPv4 connections. */
1528 if (setsockopt(s
,IPPROTO_IPV6
, IPV6_V6ONLY
,
1529 (void*)&one
, (socklen_t
)sizeof(one
)) < 0) {
1530 int e
= tor_socket_errno(s
);
1531 log_warn(LD_NET
, "Error setting IPV6_V6ONLY flag: %s",
1532 tor_socket_strerror(e
));
1533 /* Keep going; probably not harmful. */
1536 #endif /* defined(IPV6_V6ONLY) */
1538 if (bind(s
,listensockaddr
,socklen
) < 0) {
1539 const char *helpfulhint
= "";
1540 int e
= tor_socket_errno(s
);
1541 if (ERRNO_IS_EADDRINUSE(e
)) {
1542 helpfulhint
= ". Is Tor already running?";
1546 log_warn(LD_NET
, "Could not bind to %s:%u: %s%s", address
, usePort
,
1547 tor_socket_strerror(e
), helpfulhint
);
1552 if (tor_listen(s
) < 0) {
1553 log_warn(LD_NET
, "Could not listen on %s:%u: %s", address
, usePort
,
1554 tor_socket_strerror(tor_socket_errno(s
)));
1563 struct sockaddr_storage ss
;
1564 socklen_t ss_len
=sizeof(ss
);
1565 if (getsockname(s
, (struct sockaddr
*)&ss
, &ss_len
)<0) {
1566 log_warn(LD_NET
, "getsockname() couldn't learn address for %s: %s",
1567 conn_type_to_string(type
),
1568 tor_socket_strerror(tor_socket_errno(s
)));
1571 tor_addr_from_sockaddr(&addr2
, (struct sockaddr
*)&ss
, &gotPort
);
1573 #ifdef HAVE_SYS_UN_H
1575 * AF_UNIX generic setup stuff
1577 } else if (listensockaddr
->sa_family
== AF_UNIX
) {
1578 /* We want to start reading for both AF_UNIX cases */
1581 tor_assert(conn_listener_type_supports_af_unix(type
));
1583 if (check_location_for_unix_socket(options
, address
,
1584 (type
== CONN_TYPE_CONTROL_LISTENER
) ?
1585 UNIX_SOCKET_PURPOSE_CONTROL_SOCKET
:
1586 UNIX_SOCKET_PURPOSE_SOCKS_SOCKET
, port_cfg
) < 0) {
1590 log_notice(LD_NET
, "Opening %s on %s",
1591 conn_type_to_string(type
), address
);
1593 tor_addr_make_unspec(&addr
);
1595 if (unlink(address
) < 0 && errno
!= ENOENT
) {
1596 log_warn(LD_NET
, "Could not unlink %s: %s", address
,
1601 s
= tor_open_socket_nonblocking(AF_UNIX
, SOCK_STREAM
, 0);
1602 if (! SOCKET_OK(s
)) {
1603 int e
= tor_socket_errno(s
);
1604 if (ERRNO_IS_RESOURCE_LIMIT(e
)) {
1605 warn_too_many_conns();
1607 * We'll call the OOS handler at the error exit, so set the
1608 * exhaustion flag for it.
1612 log_warn(LD_NET
,"Socket creation failed: %s.", strerror(e
));
1617 if (bind(s
, listensockaddr
,
1618 (socklen_t
)sizeof(struct sockaddr_un
)) == -1) {
1619 log_warn(LD_NET
,"Bind to %s failed: %s.", address
,
1620 tor_socket_strerror(tor_socket_errno(s
)));
1625 if (options
->User
) {
1626 pw
= tor_getpwnam(options
->User
);
1629 log_warn(LD_NET
,"Unable to chown() %s socket: user %s not found.",
1630 address
, options
->User
);
1632 } else if (fstat(s
, &st
) == 0 &&
1633 st
.st_uid
== pw
->pw_uid
&& st
.st_gid
== pw
->pw_gid
) {
1634 /* No change needed */
1635 } else if (chown(sandbox_intern_string(address
),
1636 pw
->pw_uid
, pw
->pw_gid
) < 0) {
1637 log_warn(LD_NET
,"Unable to chown() %s socket: %s.",
1638 address
, strerror(errno
));
1642 #endif /* defined(HAVE_PWD_H) */
1648 if (port_cfg
->is_world_writable
) {
1650 status
= "world-writable";
1651 } else if (port_cfg
->is_group_writable
) {
1653 status
= "group-writable";
1658 /* We need to use chmod; fchmod doesn't work on sockets on all
1660 if (fstat(s
, &st
) == 0 && (st
.st_mode
& 0777) == mode
) {
1661 /* no change needed */
1662 } else if (chmod(sandbox_intern_string(address
), mode
) < 0) {
1663 log_warn(LD_FS
,"Unable to make %s %s.", address
, status
);
1668 if (listen(s
, SOMAXCONN
) < 0) {
1669 log_warn(LD_NET
, "Could not listen on %s: %s", address
,
1670 tor_socket_strerror(tor_socket_errno(s
)));
1675 /* This code was introduced to help debug #28229. */
1677 socklen_t len
= sizeof(value
);
1679 if (!getsockopt(s
, SOL_SOCKET
, SO_ACCEPTCONN
, &value
, &len
)) {
1681 log_err(LD_NET
, "Could not listen on %s - "
1682 "getsockopt(.,SO_ACCEPTCONN,.) yields 0.", address
);
1686 #endif /* !defined(__APPLE__) */
1687 #endif /* defined(HAVE_SYS_UN_H) */
1689 log_err(LD_BUG
, "Got unexpected address family %d.",
1690 listensockaddr
->sa_family
);
1694 lis_conn
= listener_connection_new(type
, listensockaddr
->sa_family
);
1695 conn
= TO_CONN(lis_conn
);
1696 conn
->socket_family
= listensockaddr
->sa_family
;
1698 s
= TOR_INVALID_SOCKET
; /* Prevent double-close */
1699 conn
->address
= tor_strdup(address
);
1700 conn
->port
= gotPort
;
1701 tor_addr_copy(&conn
->addr
, &addr
);
1703 memcpy(&lis_conn
->entry_cfg
, &port_cfg
->entry_cfg
, sizeof(entry_port_cfg_t
));
1705 if (port_cfg
->entry_cfg
.isolation_flags
) {
1706 lis_conn
->entry_cfg
.isolation_flags
= port_cfg
->entry_cfg
.isolation_flags
;
1707 if (port_cfg
->entry_cfg
.session_group
>= 0) {
1708 lis_conn
->entry_cfg
.session_group
= port_cfg
->entry_cfg
.session_group
;
1710 /* This can wrap after around INT_MAX listeners are opened. But I don't
1711 * believe that matters, since you would need to open a ridiculous
1712 * number of listeners while keeping the early ones open before you ever
1713 * hit this. An OR with a dozen ports open, for example, would have to
1714 * close and re-open its listeners every second for 4 years nonstop.
1716 lis_conn
->entry_cfg
.session_group
= global_next_session_group
--;
1720 if (connection_add(conn
) < 0) { /* no space, forget it */
1721 log_warn(LD_NET
,"connection_add for listener failed. Giving up.");
1725 log_fn(usePort
==gotPort
? LOG_DEBUG
: LOG_NOTICE
, LD_NET
,
1726 "%s listening on port %u.",
1727 conn_type_to_string(type
), gotPort
);
1729 conn
->state
= LISTENER_STATE_READY
;
1730 if (start_reading
) {
1731 connection_start_reading(conn
);
1733 tor_assert(type
== CONN_TYPE_AP_DNS_LISTENER
);
1734 dnsserv_configure_listener(conn
);
1738 * Normal exit; call the OOS handler since connection count just changed;
1739 * the exhaustion flag will always be zero here though.
1741 connection_check_oos(get_n_open_sockets(), 0);
1743 log_notice(LD_NET
, "Opened %s", connection_describe(conn
));
1749 tor_close_socket(s
);
1751 connection_free(conn
);
1753 /* Call the OOS handler, indicate if we saw an exhaustion-related error */
1754 connection_check_oos(get_n_open_sockets(), exhaustion
);
1760 * Create a new listener connection for a given <b>port</b>. In case we
1761 * for a reason that is not an error condition, set <b>defer</b>
1762 * to true. If we cannot bind listening socket because address is already
1763 * in use, set <b>addr_in_use</b> to true.
1765 static connection_t
*
1766 connection_listener_new_for_port(const port_cfg_t
*port
,
1767 int *defer
, int *addr_in_use
)
1770 struct sockaddr
*listensockaddr
;
1771 socklen_t listensocklen
= 0;
1773 int real_port
= port
->port
== CFG_AUTO_PORT
? 0 : port
->port
;
1774 tor_assert(real_port
<= UINT16_MAX
);
1779 if (port
->server_cfg
.no_listen
) {
1786 /* We don't need to be root to create a UNIX socket, so defer until after
1788 const or_options_t
*options
= get_options();
1789 if (port
->is_unix_addr
&& !geteuid() && (options
->User
) &&
1790 strcmp(options
->User
, "root")) {
1795 #endif /* !defined(_WIN32) */
1797 if (port
->is_unix_addr
) {
1798 listensockaddr
= (struct sockaddr
*)
1799 create_unix_sockaddr(port
->unix_addr
,
1800 &address
, &listensocklen
);
1802 listensockaddr
= tor_malloc(sizeof(struct sockaddr_storage
));
1803 listensocklen
= tor_addr_to_sockaddr(&port
->addr
,
1806 sizeof(struct sockaddr_storage
));
1807 address
= tor_addr_to_str_dup(&port
->addr
);
1810 if (listensockaddr
) {
1811 conn
= connection_listener_new(listensockaddr
, listensocklen
,
1812 port
->type
, address
, port
,
1814 tor_free(listensockaddr
);
1823 /** Do basic sanity checking on a newly received socket. Return 0
1824 * if it looks ok, else return -1.
1826 * Notably, some TCP stacks can erroneously have accept() return successfully
1827 * with socklen 0, when the client sends an RST before the accept call (as
1828 * nmap does). We want to detect that, and not go on with the connection.
1831 check_sockaddr(const struct sockaddr
*sa
, int len
, int level
)
1835 if (sa
->sa_family
== AF_INET
) {
1836 struct sockaddr_in
*sin
=(struct sockaddr_in
*)sa
;
1837 if (len
!= sizeof(struct sockaddr_in
)) {
1838 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1839 len
,(int)sizeof(struct sockaddr_in
));
1842 if (sin
->sin_addr
.s_addr
== 0 || sin
->sin_port
== 0) {
1843 log_fn(level
, LD_NET
,
1844 "Address for new connection has address/port equal to zero.");
1847 } else if (sa
->sa_family
== AF_INET6
) {
1848 struct sockaddr_in6
*sin6
=(struct sockaddr_in6
*)sa
;
1849 if (len
!= sizeof(struct sockaddr_in6
)) {
1850 log_fn(level
, LD_NET
, "Length of address not as expected: %d vs %d",
1851 len
,(int)sizeof(struct sockaddr_in6
));
1854 if (fast_mem_is_zero((void*)sin6
->sin6_addr
.s6_addr
, 16) ||
1855 sin6
->sin6_port
== 0) {
1856 log_fn(level
, LD_NET
,
1857 "Address for new connection has address/port equal to zero.");
1860 } else if (sa
->sa_family
== AF_UNIX
) {
1868 /** Check whether the socket family from an accepted socket <b>got</b> is the
1869 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1870 * a useful message and return -1. Else return 0.
1872 * This is annoying, but can apparently happen on some Darwins. */
1874 check_sockaddr_family_match(sa_family_t got
, connection_t
*listener
)
1876 if (got
!= listener
->socket_family
) {
1877 log_info(LD_BUG
, "A listener connection returned a socket with a "
1878 "mismatched family. %s for addr_family %d gave us a socket "
1879 "with address family %d. Dropping.",
1880 conn_type_to_string(listener
->type
),
1881 (int)listener
->socket_family
,
1888 /** The listener connection <b>conn</b> told poll() it wanted to read.
1889 * Call accept() on conn-\>s, and add the new connection if necessary.
1892 connection_handle_listener_read(connection_t
*conn
, int new_type
)
1894 tor_socket_t news
; /* the new socket */
1895 connection_t
*newconn
= 0;
1896 /* information about the remote peer when connecting to other routers */
1897 struct sockaddr_storage addrbuf
;
1898 struct sockaddr
*remote
= (struct sockaddr
*)&addrbuf
;
1899 /* length of the remote address. Must be whatever accept() needs. */
1900 socklen_t remotelen
= (socklen_t
)sizeof(addrbuf
);
1901 const or_options_t
*options
= get_options();
1903 tor_assert((size_t)remotelen
>= sizeof(struct sockaddr_in
));
1904 memset(&addrbuf
, 0, sizeof(addrbuf
));
1906 news
= tor_accept_socket_nonblocking(conn
->s
,remote
,&remotelen
);
1907 if (!SOCKET_OK(news
)) { /* accept() error */
1908 int e
= tor_socket_errno(conn
->s
);
1909 if (ERRNO_IS_ACCEPT_EAGAIN(e
)) {
1911 * they hung up before we could accept(). that's fine.
1913 * give the OOS handler a chance to run though
1915 connection_check_oos(get_n_open_sockets(), 0);
1917 } else if (ERRNO_IS_RESOURCE_LIMIT(e
)) {
1918 warn_too_many_conns();
1919 /* Exhaustion; tell the OOS handler */
1920 connection_check_oos(get_n_open_sockets(), 1);
1923 /* else there was a real error. */
1924 log_warn(LD_NET
,"accept() failed: %s. Closing listener.",
1925 tor_socket_strerror(e
));
1926 connection_mark_for_close(conn
);
1927 /* Tell the OOS handler about this too */
1928 connection_check_oos(get_n_open_sockets(), 0);
1932 "Connection accepted on socket %d (child of fd %d).",
1933 (int)news
,(int)conn
->s
);
1935 /* We accepted a new conn; run OOS handler */
1936 connection_check_oos(get_n_open_sockets(), 0);
1938 if (make_socket_reuseable(news
) < 0) {
1939 if (tor_socket_errno(news
) == EINVAL
) {
1940 /* This can happen on OSX if we get a badly timed shutdown. */
1941 log_debug(LD_NET
, "make_socket_reuseable returned EINVAL");
1943 log_warn(LD_NET
, "Error setting SO_REUSEADDR flag on %s: %s",
1944 conn_type_to_string(new_type
),
1945 tor_socket_strerror(errno
));
1947 tor_close_socket(news
);
1951 if (options
->ConstrainedSockets
)
1952 set_constrained_socket_buffers(news
, (int)options
->ConstrainedSockSize
);
1954 if (check_sockaddr_family_match(remote
->sa_family
, conn
) < 0) {
1955 tor_close_socket(news
);
1959 if (conn
->socket_family
== AF_INET
|| conn
->socket_family
== AF_INET6
||
1960 (conn
->socket_family
== AF_UNIX
&& new_type
== CONN_TYPE_AP
)) {
1963 if (check_sockaddr(remote
, remotelen
, LOG_INFO
)<0) {
1965 "accept() returned a strange address; closing connection.");
1966 tor_close_socket(news
);
1970 tor_addr_from_sockaddr(&addr
, remote
, &port
);
1972 /* process entrance policies here, before we even create the connection */
1973 if (new_type
== CONN_TYPE_AP
) {
1974 /* check sockspolicy to see if we should accept it */
1975 if (socks_policy_permits_address(&addr
) == 0) {
1977 "Denying socks connection from untrusted address %s.",
1978 fmt_and_decorate_addr(&addr
));
1979 tor_close_socket(news
);
1983 if (new_type
== CONN_TYPE_DIR
) {
1984 /* check dirpolicy to see if we should accept it */
1985 if (dir_policy_permits_address(&addr
) == 0) {
1986 log_notice(LD_DIRSERV
,"Denying dir connection from address %s.",
1987 fmt_and_decorate_addr(&addr
));
1988 tor_close_socket(news
);
1992 if (new_type
== CONN_TYPE_OR
) {
1993 /* Assess with the connection DoS mitigation subsystem if this address
1994 * can open a new connection. */
1995 if (dos_conn_addr_get_defense_type(&addr
) == DOS_CONN_DEFENSE_CLOSE
) {
1996 tor_close_socket(news
);
2001 newconn
= connection_new(new_type
, conn
->socket_family
);
2004 /* remember the remote address */
2005 tor_addr_copy(&newconn
->addr
, &addr
);
2006 if (new_type
== CONN_TYPE_AP
&& conn
->socket_family
== AF_UNIX
) {
2008 newconn
->address
= tor_strdup(conn
->address
);
2010 newconn
->port
= port
;
2011 newconn
->address
= tor_addr_to_str_dup(&addr
);
2014 if (new_type
== CONN_TYPE_AP
&& conn
->socket_family
!= AF_UNIX
) {
2015 log_info(LD_NET
, "New SOCKS connection opened from %s.",
2016 fmt_and_decorate_addr(&addr
));
2018 if (new_type
== CONN_TYPE_AP
&& conn
->socket_family
== AF_UNIX
) {
2019 log_info(LD_NET
, "New SOCKS AF_UNIX connection opened");
2021 if (new_type
== CONN_TYPE_CONTROL
) {
2022 log_notice(LD_CONTROL
, "New control connection opened from %s.",
2023 fmt_and_decorate_addr(&addr
));
2025 if (new_type
== CONN_TYPE_METRICS
) {
2026 log_info(LD_CONTROL
, "New metrics connection opened from %s.",
2027 fmt_and_decorate_addr(&addr
));
2030 } else if (conn
->socket_family
== AF_UNIX
&& conn
->type
!= CONN_TYPE_AP
) {
2031 tor_assert(conn
->type
== CONN_TYPE_CONTROL_LISTENER
);
2032 tor_assert(new_type
== CONN_TYPE_CONTROL
);
2033 log_notice(LD_CONTROL
, "New control connection opened.");
2035 newconn
= connection_new(new_type
, conn
->socket_family
);
2038 /* remember the remote address -- do we have anything sane to put here? */
2039 tor_addr_make_unspec(&newconn
->addr
);
2041 newconn
->address
= tor_strdup(conn
->address
);
2046 if (connection_add(newconn
) < 0) { /* no space, forget it */
2047 connection_free(newconn
);
2048 return 0; /* no need to tear down the parent */
2051 if (connection_init_accepted_conn(newconn
, TO_LISTENER_CONN(conn
)) < 0) {
2052 if (! newconn
->marked_for_close
)
2053 connection_mark_for_close(newconn
);
2057 note_connection(true /* inbound */, conn
->socket_family
);
2062 /** Initialize states for newly accepted connection <b>conn</b>.
2064 * If conn is an OR, start the TLS handshake.
2066 * If conn is a transparent AP, get its original destination
2067 * and place it in circuit_wait.
2069 * The <b>listener</b> parameter is only used for AP connections.
2072 connection_init_accepted_conn(connection_t
*conn
,
2073 const listener_connection_t
*listener
)
2077 connection_start_reading(conn
);
2079 switch (conn
->type
) {
2080 case CONN_TYPE_EXT_OR
:
2081 /* Initiate Extended ORPort authentication. */
2082 return connection_ext_or_start_auth(TO_OR_CONN(conn
));
2084 connection_or_event_status(TO_OR_CONN(conn
), OR_CONN_EVENT_NEW
, 0);
2085 rv
= connection_tls_start_handshake(TO_OR_CONN(conn
), 1);
2087 connection_or_close_for_error(TO_OR_CONN(conn
), 0);
2092 memcpy(&TO_ENTRY_CONN(conn
)->entry_cfg
, &listener
->entry_cfg
,
2093 sizeof(entry_port_cfg_t
));
2094 TO_ENTRY_CONN(conn
)->nym_epoch
= get_signewnym_epoch();
2095 TO_ENTRY_CONN(conn
)->socks_request
->listener_type
= listener
->base_
.type
;
2097 /* Any incoming connection on an entry port counts as user activity. */
2098 note_user_activity(approx_time());
2100 switch (TO_CONN(listener
)->type
) {
2101 case CONN_TYPE_AP_LISTENER
:
2102 conn
->state
= AP_CONN_STATE_SOCKS_WAIT
;
2103 TO_ENTRY_CONN(conn
)->socks_request
->socks_prefer_no_auth
=
2104 listener
->entry_cfg
.socks_prefer_no_auth
;
2105 TO_ENTRY_CONN(conn
)->socks_request
->socks_use_extended_errors
=
2106 listener
->entry_cfg
.extended_socks5_codes
;
2108 case CONN_TYPE_AP_TRANS_LISTENER
:
2109 TO_ENTRY_CONN(conn
)->is_transparent_ap
= 1;
2110 /* XXXX028 -- is this correct still, with the addition of
2111 * pending_entry_connections ? */
2112 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2113 return connection_ap_process_transparent(TO_ENTRY_CONN(conn
));
2114 case CONN_TYPE_AP_NATD_LISTENER
:
2115 TO_ENTRY_CONN(conn
)->is_transparent_ap
= 1;
2116 conn
->state
= AP_CONN_STATE_NATD_WAIT
;
2118 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER
:
2119 conn
->state
= AP_CONN_STATE_HTTP_CONNECT_WAIT
;
2123 conn
->purpose
= DIR_PURPOSE_SERVER
;
2124 conn
->state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
2126 case CONN_TYPE_CONTROL
:
2127 conn
->state
= CONTROL_CONN_STATE_NEEDAUTH
;
2133 /** Take conn, make a nonblocking socket; try to connect to
2134 * sa, binding to bindaddr if sa is not localhost. If fail, return -1 and if
2135 * applicable put your best guess about errno into *<b>socket_error</b>.
2136 * If connected return 1, if EAGAIN return 0.
2138 MOCK_IMPL(STATIC
int,
2139 connection_connect_sockaddr
,(connection_t
*conn
,
2140 const struct sockaddr
*sa
,
2142 const struct sockaddr
*bindaddr
,
2143 socklen_t bindaddr_len
,
2148 const or_options_t
*options
= get_options();
2152 tor_assert(socket_error
);
2154 if (net_is_completely_disabled()) {
2155 /* We should never even try to connect anyplace if the network is
2156 * completely shut off.
2158 * (We don't check net_is_disabled() here, since we still sometimes
2159 * want to open connections when we're in soft hibernation.)
2161 static ratelim_t disablenet_violated
= RATELIM_INIT(30*60);
2162 *socket_error
= SOCK_ERRNO(ENETUNREACH
);
2163 log_fn_ratelim(&disablenet_violated
, LOG_WARN
, LD_BUG
,
2164 "Tried to open a socket with DisableNetwork set.");
2165 tor_fragile_assert();
2169 const int protocol_family
= sa
->sa_family
;
2170 const int proto
= (sa
->sa_family
== AF_INET6
||
2171 sa
->sa_family
== AF_INET
) ? IPPROTO_TCP
: 0;
2173 s
= tor_open_socket_nonblocking(protocol_family
, SOCK_STREAM
, proto
);
2174 if (! SOCKET_OK(s
)) {
2176 * Early OOS handler calls; it matters if it's an exhaustion-related
2179 *socket_error
= tor_socket_errno(s
);
2180 if (ERRNO_IS_RESOURCE_LIMIT(*socket_error
)) {
2181 warn_too_many_conns();
2182 connection_check_oos(get_n_open_sockets(), 1);
2184 log_warn(LD_NET
,"Error creating network socket: %s",
2185 tor_socket_strerror(*socket_error
));
2186 connection_check_oos(get_n_open_sockets(), 0);
2191 if (make_socket_reuseable(s
) < 0) {
2192 log_warn(LD_NET
, "Error setting SO_REUSEADDR flag on new connection: %s",
2193 tor_socket_strerror(errno
));
2197 * We've got the socket open; give the OOS handler a chance to check
2198 * against configured maximum socket number, but tell it no exhaustion
2201 connection_check_oos(get_n_open_sockets(), 0);
2203 if (bindaddr
&& bind(s
, bindaddr
, bindaddr_len
) < 0) {
2204 *socket_error
= tor_socket_errno(s
);
2205 log_warn(LD_NET
,"Error binding network socket: %s",
2206 tor_socket_strerror(*socket_error
));
2207 tor_close_socket(s
);
2211 tor_assert(options
);
2212 if (options
->ConstrainedSockets
)
2213 set_constrained_socket_buffers(s
, (int)options
->ConstrainedSockSize
);
2215 if (connect(s
, sa
, sa_len
) < 0) {
2216 int e
= tor_socket_errno(s
);
2217 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
2218 /* yuck. kill it. */
2221 "connect() to socket failed: %s",
2222 tor_socket_strerror(e
));
2223 tor_close_socket(s
);
2230 note_connection(false /* outbound */, conn
->socket_family
);
2232 /* it succeeded. we're connected. */
2233 log_fn(inprogress
? LOG_DEBUG
: LOG_INFO
, LD_NET
,
2234 "Connection to socket %s (sock "TOR_SOCKET_T_FORMAT
").",
2235 inprogress
? "in progress" : "established", s
);
2237 if (connection_add_connecting(conn
) < 0) {
2238 /* no space, forget it */
2239 *socket_error
= SOCK_ERRNO(ENOBUFS
);
2243 return inprogress
? 0 : 1;
2246 /* Log a message if connection attempt is made when IPv4 or IPv6 is disabled.
2247 * Log a less severe message if we couldn't conform to ClientPreferIPv6ORPort
2248 * or ClientPreferIPv6ORPort. */
2250 connection_connect_log_client_use_ip_version(const connection_t
*conn
)
2252 const or_options_t
*options
= get_options();
2254 /* Only clients care about ClientUseIPv4/6, bail out early on servers, and
2255 * on connections we don't care about */
2256 if (server_mode(options
) || !conn
|| conn
->type
== CONN_TYPE_EXIT
) {
2260 /* We're only prepared to log OR and DIR connections here */
2261 if (conn
->type
!= CONN_TYPE_OR
&& conn
->type
!= CONN_TYPE_DIR
) {
2265 const int must_ipv4
= !reachable_addr_use_ipv6(options
);
2266 const int must_ipv6
= (options
->ClientUseIPv4
== 0);
2267 const int pref_ipv6
= (conn
->type
== CONN_TYPE_OR
2268 ? reachable_addr_prefer_ipv6_orport(options
)
2269 : reachable_addr_prefer_ipv6_dirport(options
));
2270 tor_addr_t real_addr
;
2271 tor_addr_copy(&real_addr
, &conn
->addr
);
2273 /* Check if we broke a mandatory address family restriction */
2274 if ((must_ipv4
&& tor_addr_family(&real_addr
) == AF_INET6
)
2275 || (must_ipv6
&& tor_addr_family(&real_addr
) == AF_INET
)) {
2276 static int logged_backtrace
= 0;
2277 log_info(LD_BUG
, "Outgoing %s connection to %s violated ClientUseIPv%s 0.",
2278 conn
->type
== CONN_TYPE_OR
? "OR" : "Dir",
2279 fmt_addr(&real_addr
),
2280 options
->ClientUseIPv4
== 0 ? "4" : "6");
2281 if (!logged_backtrace
) {
2282 log_backtrace(LOG_INFO
, LD_BUG
, "Address came from");
2283 logged_backtrace
= 1;
2287 /* Bridges are allowed to break IPv4/IPv6 ORPort preferences to connect to
2288 * the node's configured address when ClientPreferIPv6ORPort is auto */
2289 if (options
->UseBridges
&& conn
->type
== CONN_TYPE_OR
2290 && options
->ClientPreferIPv6ORPort
== -1) {
2294 if (reachable_addr_use_ipv6(options
)) {
2295 log_info(LD_NET
, "Our outgoing connection is using IPv%d.",
2296 tor_addr_family(&real_addr
) == AF_INET6
? 6 : 4);
2299 /* Check if we couldn't satisfy an address family preference */
2300 if ((!pref_ipv6
&& tor_addr_family(&real_addr
) == AF_INET6
)
2301 || (pref_ipv6
&& tor_addr_family(&real_addr
) == AF_INET
)) {
2302 log_info(LD_NET
, "Outgoing connection to %s doesn't satisfy "
2303 "ClientPreferIPv6%sPort %d, with ClientUseIPv4 %d, and "
2304 "reachable_addr_use_ipv6 %d (ClientUseIPv6 %d and UseBridges "
2306 fmt_addr(&real_addr
),
2307 conn
->type
== CONN_TYPE_OR
? "OR" : "Dir",
2308 conn
->type
== CONN_TYPE_OR
? options
->ClientPreferIPv6ORPort
2309 : options
->ClientPreferIPv6DirPort
,
2310 options
->ClientUseIPv4
, reachable_addr_use_ipv6(options
),
2311 options
->ClientUseIPv6
, options
->UseBridges
);
2315 /** Retrieve the outbound address depending on the protocol (IPv4 or IPv6)
2316 * and the connection type (relay, exit, ...)
2317 * Return a socket address or NULL in case nothing is configured.
2320 conn_get_outbound_address(sa_family_t family
,
2321 const or_options_t
*options
, unsigned int conn_type
)
2323 const tor_addr_t
*ext_addr
= NULL
;
2337 // If an exit connection, use the exit address (if present)
2338 if (conn_type
== CONN_TYPE_EXIT
) {
2339 if (!tor_addr_is_null(
2340 &options
->OutboundBindAddresses
[OUTBOUND_ADDR_EXIT
][fam_index
])) {
2341 ext_addr
= &options
->OutboundBindAddresses
[OUTBOUND_ADDR_EXIT
]
2343 } else if (!tor_addr_is_null(
2344 &options
->OutboundBindAddresses
[OUTBOUND_ADDR_ANY
]
2346 ext_addr
= &options
->OutboundBindAddresses
[OUTBOUND_ADDR_ANY
]
2349 } else { // All non-exit connections
2350 if (!tor_addr_is_null(
2351 &options
->OutboundBindAddresses
[OUTBOUND_ADDR_OR
][fam_index
])) {
2352 ext_addr
= &options
->OutboundBindAddresses
[OUTBOUND_ADDR_OR
]
2354 } else if (!tor_addr_is_null(
2355 &options
->OutboundBindAddresses
[OUTBOUND_ADDR_ANY
]
2357 ext_addr
= &options
->OutboundBindAddresses
[OUTBOUND_ADDR_ANY
]
2364 /** Take conn, make a nonblocking socket; try to connect to
2365 * addr:port (port arrives in *host order*). If fail, return -1 and if
2366 * applicable put your best guess about errno into *<b>socket_error</b>.
2367 * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
2369 * addr:port can be different to conn->addr:conn->port if connecting through
2372 * address is used to make the logs useful.
2374 * On success, add conn to the list of polled connections.
2377 connection_connect(connection_t
*conn
, const char *address
,
2378 const tor_addr_t
*addr
, uint16_t port
, int *socket_error
)
2380 struct sockaddr_storage addrbuf
;
2381 struct sockaddr_storage bind_addr_ss
;
2382 struct sockaddr
*bind_addr
= NULL
;
2383 struct sockaddr
*dest_addr
;
2384 int dest_addr_len
, bind_addr_len
= 0;
2386 /* Log if we didn't stick to ClientUseIPv4/6 or ClientPreferIPv6OR/DirPort
2388 connection_connect_log_client_use_ip_version(conn
);
2390 if (!tor_addr_is_loopback(addr
)) {
2391 const tor_addr_t
*ext_addr
= NULL
;
2392 ext_addr
= conn_get_outbound_address(tor_addr_family(addr
), get_options(),
2395 memset(&bind_addr_ss
, 0, sizeof(bind_addr_ss
));
2396 bind_addr_len
= tor_addr_to_sockaddr(ext_addr
, 0,
2397 (struct sockaddr
*) &bind_addr_ss
,
2398 sizeof(bind_addr_ss
));
2399 if (bind_addr_len
== 0) {
2401 "Error converting OutboundBindAddress %s into sockaddr. "
2402 "Ignoring.", fmt_and_decorate_addr(ext_addr
));
2404 bind_addr
= (struct sockaddr
*)&bind_addr_ss
;
2409 memset(&addrbuf
,0,sizeof(addrbuf
));
2410 dest_addr
= (struct sockaddr
*) &addrbuf
;
2411 dest_addr_len
= tor_addr_to_sockaddr(addr
, port
, dest_addr
, sizeof(addrbuf
));
2412 tor_assert(dest_addr_len
> 0);
2414 log_debug(LD_NET
, "Connecting to %s:%u.",
2415 escaped_safe_str_client(address
), port
);
2417 return connection_connect_sockaddr(conn
, dest_addr
, dest_addr_len
,
2418 bind_addr
, bind_addr_len
, socket_error
);
2421 #ifdef HAVE_SYS_UN_H
2423 /** Take conn, make a nonblocking socket; try to connect to
2424 * an AF_UNIX socket at socket_path. If fail, return -1 and if applicable
2425 * put your best guess about errno into *<b>socket_error</b>. Else assign s
2426 * to conn-\>s: if connected return 1, if EAGAIN return 0.
2428 * On success, add conn to the list of polled connections.
2431 connection_connect_unix(connection_t
*conn
, const char *socket_path
,
2434 struct sockaddr_un dest_addr
;
2436 tor_assert(socket_path
);
2438 /* Check that we'll be able to fit it into dest_addr later */
2439 if (strlen(socket_path
) + 1 > sizeof(dest_addr
.sun_path
)) {
2441 "Path %s is too long for an AF_UNIX socket\n",
2442 escaped_safe_str_client(socket_path
));
2443 *socket_error
= SOCK_ERRNO(ENAMETOOLONG
);
2447 memset(&dest_addr
, 0, sizeof(dest_addr
));
2448 dest_addr
.sun_family
= AF_UNIX
;
2449 strlcpy(dest_addr
.sun_path
, socket_path
, sizeof(dest_addr
.sun_path
));
2452 "Connecting to AF_UNIX socket at %s.",
2453 escaped_safe_str_client(socket_path
));
2455 return connection_connect_sockaddr(conn
,
2456 (struct sockaddr
*)&dest_addr
, sizeof(dest_addr
),
2457 NULL
, 0, socket_error
);
2460 #endif /* defined(HAVE_SYS_UN_H) */
2462 /** Convert state number to string representation for logging purposes.
2465 connection_proxy_state_to_string(int state
)
2467 static const char *unknown
= "???";
2468 static const char *states
[] = {
2471 "PROXY_HTTPS_WANT_CONNECT_OK",
2472 "PROXY_SOCKS4_WANT_CONNECT_OK",
2473 "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
2474 "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
2475 "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
2476 "PROXY_SOCKS5_WANT_CONNECT_OK",
2477 "PROXY_HAPROXY_WAIT_FOR_FLUSH",
2481 CTASSERT(ARRAY_LENGTH(states
) == PROXY_CONNECTED
+1);
2483 if (state
< PROXY_NONE
|| state
> PROXY_CONNECTED
)
2486 return states
[state
];
2489 /** Returns the proxy type used by tor for a single connection, for
2490 * logging or high-level purposes. Don't use it to fill the
2491 * <b>proxy_type</b> field of or_connection_t; use the actual proxy
2492 * protocol instead.*/
2494 conn_get_proxy_type(const connection_t
*conn
)
2496 const or_options_t
*options
= get_options();
2498 if (options
->ClientTransportPlugin
) {
2499 /* If we have plugins configured *and* this addr/port is a known bridge
2500 * with a transport, then we should be PROXY_PLUGGABLE. */
2501 const transport_t
*transport
= NULL
;
2503 r
= get_transport_by_bridge_addrport(&conn
->addr
, conn
->port
, &transport
);
2504 if (r
== 0 && transport
)
2505 return PROXY_PLUGGABLE
;
2508 /* In all other cases, we're using a global proxy. */
2509 if (options
->HTTPSProxy
)
2510 return PROXY_CONNECT
;
2511 else if (options
->Socks4Proxy
)
2512 return PROXY_SOCKS4
;
2513 else if (options
->Socks5Proxy
)
2514 return PROXY_SOCKS5
;
2515 else if (options
->TCPProxy
) {
2516 /* The only supported protocol in TCPProxy is haproxy. */
2517 tor_assert(options
->TCPProxyProtocol
== TCP_PROXY_PROTOCOL_HAPROXY
);
2518 return PROXY_HAPROXY
;
2523 /* One byte for the version, one for the command, two for the
2524 port, and four for the addr... and, one more for the
2526 #define SOCKS4_STANDARD_BUFFER_SIZE (1 + 1 + 2 + 4 + 1)
2528 /** Write a proxy request of https to conn for conn->addr:conn->port,
2529 * authenticating with the auth details given in the configuration
2532 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2536 connection_https_proxy_connect(connection_t
*conn
)
2540 const or_options_t
*options
= get_options();
2542 char *base64_authenticator
= NULL
;
2543 const char *authenticator
= options
->HTTPSProxyAuthenticator
;
2545 /* Send HTTP CONNECT and authentication (if available) in
2548 if (authenticator
) {
2549 base64_authenticator
= alloc_http_authenticator(authenticator
);
2550 if (!base64_authenticator
)
2551 log_warn(LD_OR
, "Encoding https authenticator failed");
2554 if (base64_authenticator
) {
2555 const char *addrport
= fmt_addrport(&conn
->addr
, conn
->port
);
2556 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s HTTP/1.1\r\n"
2558 "Proxy-Authorization: Basic %s\r\n\r\n",
2561 base64_authenticator
);
2562 tor_free(base64_authenticator
);
2564 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s HTTP/1.0\r\n\r\n",
2565 fmt_addrport(&conn
->addr
, conn
->port
));
2568 connection_buf_add(buf
, strlen(buf
), conn
);
2569 conn
->proxy_state
= PROXY_HTTPS_WANT_CONNECT_OK
;
2574 /** Write a proxy request of socks4 to conn for conn->addr:conn->port.
2576 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2580 connection_socks4_proxy_connect(connection_t
*conn
)
2587 size_t buf_size
= 0;
2588 char *socks_args_string
= NULL
;
2590 /* Send a SOCKS4 connect request */
2592 if (tor_addr_family(&conn
->addr
) != AF_INET
) {
2593 log_warn(LD_NET
, "SOCKS4 client is incompatible with IPv6");
2597 { /* If we are here because we are trying to connect to a
2598 pluggable transport proxy, check if we have any SOCKS
2599 arguments to transmit. If we do, compress all arguments to
2600 a single string in 'socks_args_string': */
2602 if (conn_get_proxy_type(conn
) == PROXY_PLUGGABLE
) {
2604 pt_get_socks_args_for_proxy_addrport(&conn
->addr
, conn
->port
);
2605 if (socks_args_string
)
2606 log_debug(LD_NET
, "Sending out '%s' as our SOCKS argument string.",
2611 { /* Figure out the buffer size we need for the SOCKS message: */
2613 buf_size
= SOCKS4_STANDARD_BUFFER_SIZE
;
2615 /* If we have a SOCKS argument string, consider its size when
2616 calculating the buffer size: */
2617 if (socks_args_string
)
2618 buf_size
+= strlen(socks_args_string
);
2621 buf
= tor_malloc_zero(buf_size
);
2623 ip4addr
= tor_addr_to_ipv4n(&conn
->addr
);
2624 portn
= htons(conn
->port
);
2626 buf
[0] = 4; /* version */
2627 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
2628 memcpy(buf
+ 2, &portn
, 2); /* port */
2629 memcpy(buf
+ 4, &ip4addr
, 4); /* addr */
2631 /* Next packet field is the userid. If we have pluggable
2632 transport SOCKS arguments, we have to embed them
2633 there. Otherwise, we use an empty userid. */
2634 if (socks_args_string
) { /* place the SOCKS args string: */
2635 tor_assert(strlen(socks_args_string
) > 0);
2636 tor_assert(buf_size
>=
2637 SOCKS4_STANDARD_BUFFER_SIZE
+ strlen(socks_args_string
));
2638 strlcpy((char *)buf
+ 8, socks_args_string
, buf_size
- 8);
2639 tor_free(socks_args_string
);
2641 buf
[8] = 0; /* no userid */
2644 connection_buf_add((char *)buf
, buf_size
, conn
);
2647 conn
->proxy_state
= PROXY_SOCKS4_WANT_CONNECT_OK
;
2651 /** Write a proxy request of socks5 to conn for conn->addr:conn->port,
2652 * authenticating with the auth details given in the configuration
2655 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2659 connection_socks5_proxy_connect(connection_t
*conn
)
2663 const or_options_t
*options
= get_options();
2664 unsigned char buf
[4]; /* fields: vers, num methods, method list */
2666 /* Send a SOCKS5 greeting (connect request must wait) */
2668 buf
[0] = 5; /* version */
2670 /* We have to use SOCKS5 authentication, if we have a
2671 Socks5ProxyUsername or if we want to pass arguments to our
2672 pluggable transport proxy: */
2673 if ((options
->Socks5ProxyUsername
) ||
2674 (conn_get_proxy_type(conn
) == PROXY_PLUGGABLE
&&
2675 (get_socks_args_by_bridge_addrport(&conn
->addr
, conn
->port
)))) {
2676 /* number of auth methods */
2678 buf
[2] = 0x00; /* no authentication */
2679 buf
[3] = 0x02; /* rfc1929 Username/Passwd auth */
2680 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
;
2683 buf
[2] = 0x00; /* no authentication */
2684 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
;
2687 connection_buf_add((char *)buf
, 2 + buf
[1], conn
);
2691 /** Write a proxy request of haproxy to conn for conn->addr:conn->port.
2693 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2697 connection_haproxy_proxy_connect(connection_t
*conn
)
2700 tor_addr_port_t
*addr_port
= tor_addr_port_new(&conn
->addr
, conn
->port
);
2701 char *buf
= haproxy_format_proxy_header_line(addr_port
);
2708 connection_buf_add(buf
, strlen(buf
), conn
);
2709 /* In haproxy, we don't have to wait for the response, but we wait for ack.
2710 * So we can set the state to be PROXY_HAPROXY_WAIT_FOR_FLUSH. */
2711 conn
->proxy_state
= PROXY_HAPROXY_WAIT_FOR_FLUSH
;
2716 tor_free(addr_port
);
2720 /** Write a proxy request of <b>type</b> (socks4, socks5, https, haproxy)
2721 * to conn for conn->addr:conn->port, authenticating with the auth details
2722 * given in the configuration (if available). SOCKS 5 and HTTP CONNECT
2723 * proxies support authentication.
2725 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2728 * Use connection_read_proxy_handshake() to complete the handshake.
2731 connection_proxy_connect(connection_t
*conn
, int type
)
2739 ret
= connection_https_proxy_connect(conn
);
2743 ret
= connection_socks4_proxy_connect(conn
);
2747 ret
= connection_socks5_proxy_connect(conn
);
2751 ret
= connection_haproxy_proxy_connect(conn
);
2755 log_err(LD_BUG
, "Invalid proxy protocol, %d", type
);
2756 tor_fragile_assert();
2762 log_debug(LD_NET
, "set state %s",
2763 connection_proxy_state_to_string(conn
->proxy_state
));
2769 /** Read conn's inbuf. If the http response from the proxy is all
2770 * here, make sure it's good news, then return 1. If it's bad news,
2771 * return -1. Else return 0 and hope for better luck next time.
2774 connection_read_https_proxy_response(connection_t
*conn
)
2781 switch (fetch_from_buf_http(conn
->inbuf
,
2782 &headers
, MAX_HEADERS_SIZE
,
2783 NULL
, NULL
, 10000, 0)) {
2784 case -1: /* overflow */
2785 log_warn(LD_PROTOCOL
,
2786 "Your https proxy sent back an oversized response. Closing.");
2789 log_info(LD_NET
,"https proxy response not all here yet. Waiting.");
2791 /* case 1, fall through */
2794 if (parse_http_response(headers
, &status_code
, &date_header
,
2795 NULL
, &reason
) < 0) {
2797 "Unparseable headers from proxy (%s). Closing.",
2798 connection_describe(conn
));
2803 if (!reason
) reason
= tor_strdup("[no reason given]");
2805 if (status_code
== 200) {
2807 "HTTPS connect for %s successful! (200 %s) Starting TLS.",
2808 connection_describe(conn
), escaped(reason
));
2812 /* else, bad news on the status code */
2813 switch (status_code
) {
2816 "The https proxy refused to allow connection to %s "
2817 "(status code %d, %s). Closing.",
2818 conn
->address
, status_code
, escaped(reason
));
2822 "The https proxy sent back an unexpected status code %d (%s). "
2824 status_code
, escaped(reason
));
2831 /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
2832 * and <b>conn->port</b> into the request.
2835 connection_send_socks5_connect(connection_t
*conn
)
2837 unsigned char buf
[1024];
2839 uint16_t port
= htons(conn
->port
);
2841 buf
[0] = 5; /* version */
2842 buf
[1] = SOCKS_COMMAND_CONNECT
; /* command */
2843 buf
[2] = 0; /* reserved */
2845 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
2846 uint32_t addr
= tor_addr_to_ipv4n(&conn
->addr
);
2850 memcpy(buf
+ 4, &addr
, 4);
2851 memcpy(buf
+ 8, &port
, 2);
2852 } else { /* AF_INET6 */
2855 memcpy(buf
+ 4, tor_addr_to_in6_addr8(&conn
->addr
), 16);
2856 memcpy(buf
+ 20, &port
, 2);
2859 connection_buf_add((char *)buf
, reqsize
, conn
);
2861 conn
->proxy_state
= PROXY_SOCKS5_WANT_CONNECT_OK
;
2864 /** Wrapper around fetch_from_buf_socks_client: see that functions
2865 * for documentation of its behavior. */
2867 connection_fetch_from_buf_socks_client(connection_t
*conn
,
2868 int state
, char **reason
)
2870 return fetch_from_buf_socks_client(conn
->inbuf
, state
, reason
);
2873 /** Call this from connection_*_process_inbuf() to advance the proxy
2876 * No matter what proxy protocol is used, if this function returns 1, the
2877 * handshake is complete, and the data remaining on inbuf may contain the
2878 * start of the communication with the requested server.
2880 * Returns 0 if the current buffer contains an incomplete response, and -1
2884 connection_read_proxy_handshake(connection_t
*conn
)
2887 char *reason
= NULL
;
2889 log_debug(LD_NET
, "enter state %s",
2890 connection_proxy_state_to_string(conn
->proxy_state
));
2892 switch (conn
->proxy_state
) {
2893 case PROXY_HTTPS_WANT_CONNECT_OK
:
2894 ret
= connection_read_https_proxy_response(conn
);
2896 conn
->proxy_state
= PROXY_CONNECTED
;
2899 case PROXY_SOCKS4_WANT_CONNECT_OK
:
2900 ret
= connection_fetch_from_buf_socks_client(conn
,
2904 conn
->proxy_state
= PROXY_CONNECTED
;
2907 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE
:
2908 ret
= connection_fetch_from_buf_socks_client(conn
,
2911 /* no auth needed, do connect */
2913 connection_send_socks5_connect(conn
);
2918 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929
:
2919 ret
= connection_fetch_from_buf_socks_client(conn
,
2923 /* send auth if needed, otherwise do connect */
2925 connection_send_socks5_connect(conn
);
2927 } else if (ret
== 2) {
2928 unsigned char buf
[1024];
2929 size_t reqsize
, usize
, psize
;
2930 const char *user
, *pass
;
2931 char *socks_args_string
= NULL
;
2933 if (conn_get_proxy_type(conn
) == PROXY_PLUGGABLE
) {
2935 pt_get_socks_args_for_proxy_addrport(&conn
->addr
, conn
->port
);
2936 if (!socks_args_string
) {
2937 log_warn(LD_NET
, "Could not create SOCKS args string for PT.");
2942 log_debug(LD_NET
, "PT SOCKS5 arguments: %s", socks_args_string
);
2943 tor_assert(strlen(socks_args_string
) > 0);
2944 tor_assert(strlen(socks_args_string
) <= MAX_SOCKS5_AUTH_SIZE_TOTAL
);
2946 if (strlen(socks_args_string
) > MAX_SOCKS5_AUTH_FIELD_SIZE
) {
2947 user
= socks_args_string
;
2948 usize
= MAX_SOCKS5_AUTH_FIELD_SIZE
;
2949 pass
= socks_args_string
+ MAX_SOCKS5_AUTH_FIELD_SIZE
;
2950 psize
= strlen(socks_args_string
) - MAX_SOCKS5_AUTH_FIELD_SIZE
;
2952 user
= socks_args_string
;
2953 usize
= strlen(socks_args_string
);
2957 } else if (get_options()->Socks5ProxyUsername
) {
2958 user
= get_options()->Socks5ProxyUsername
;
2959 pass
= get_options()->Socks5ProxyPassword
;
2960 tor_assert(user
&& pass
);
2961 usize
= strlen(user
);
2962 psize
= strlen(pass
);
2964 log_err(LD_BUG
, "We entered %s for no reason!", __func__
);
2965 tor_fragile_assert();
2970 /* Username and password lengths should have been checked
2971 above and during torrc parsing. */
2972 tor_assert(usize
<= MAX_SOCKS5_AUTH_FIELD_SIZE
&&
2973 psize
<= MAX_SOCKS5_AUTH_FIELD_SIZE
);
2974 reqsize
= 3 + usize
+ psize
;
2976 buf
[0] = 1; /* negotiation version */
2978 memcpy(buf
+ 2, user
, usize
);
2979 buf
[2 + usize
] = psize
;
2980 memcpy(buf
+ 3 + usize
, pass
, psize
);
2982 if (socks_args_string
)
2983 tor_free(socks_args_string
);
2985 connection_buf_add((char *)buf
, reqsize
, conn
);
2987 conn
->proxy_state
= PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
;
2992 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK
:
2993 ret
= connection_fetch_from_buf_socks_client(conn
,
2996 /* send the connect request */
2998 connection_send_socks5_connect(conn
);
3003 case PROXY_SOCKS5_WANT_CONNECT_OK
:
3004 ret
= connection_fetch_from_buf_socks_client(conn
,
3008 conn
->proxy_state
= PROXY_CONNECTED
;
3012 log_err(LD_BUG
, "Invalid proxy_state for reading, %d",
3014 tor_fragile_assert();
3019 log_debug(LD_NET
, "leaving state %s",
3020 connection_proxy_state_to_string(conn
->proxy_state
));
3024 log_warn(LD_NET
, "Proxy Client: unable to connect %s (%s)",
3025 connection_describe(conn
), escaped(reason
));
3028 log_warn(LD_NET
, "Proxy Client: unable to connect %s",
3029 connection_describe(conn
));
3031 } else if (ret
== 1) {
3032 log_info(LD_NET
, "Proxy Client: %s successful",
3033 connection_describe(conn
));
3039 /** Given a list of listener connections in <b>old_conns</b>, and list of
3040 * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
3041 * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
3043 * Remove from <b>old_conns</b> every connection that has a corresponding
3044 * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
3045 * launch. If we may need to perform socket rebind when creating new
3046 * listener that replaces old one, create a <b>listener_replacement_t</b>
3047 * struct for affected pair and add it to <b>replacements</b>.
3049 * If <b>control_listeners_only</b> is true, then we only open control
3050 * listeners, and we do not remove any noncontrol listeners from
3053 * Return 0 on success, -1 on failure.
3056 retry_listener_ports(smartlist_t
*old_conns
,
3057 const smartlist_t
*ports
,
3058 smartlist_t
*new_conns
,
3059 smartlist_t
*replacements
,
3060 int control_listeners_only
)
3062 #ifndef ENABLE_LISTENER_REBIND
3066 smartlist_t
*launch
= smartlist_new();
3069 if (control_listeners_only
) {
3070 SMARTLIST_FOREACH(ports
, port_cfg_t
*, p
, {
3071 if (p
->type
== CONN_TYPE_CONTROL_LISTENER
)
3072 smartlist_add(launch
, p
);
3075 smartlist_add_all(launch
, ports
);
3078 /* Iterate through old_conns, comparing it to launch: remove from both lists
3079 * each pair of elements that corresponds to the same port. */
3080 SMARTLIST_FOREACH_BEGIN(old_conns
, connection_t
*, conn
) {
3081 const port_cfg_t
*found_port
= NULL
;
3083 /* Okay, so this is a listener. Is it configured? */
3084 /* That is, is it either: 1) exact match - address and port
3085 * pair match exactly between old listener and new port; or 2)
3086 * wildcard match - port matches exactly, but *one* of the
3087 * addresses is wildcard (0.0.0.0 or ::)?
3089 SMARTLIST_FOREACH_BEGIN(launch
, const port_cfg_t
*, wanted
) {
3090 if (conn
->type
!= wanted
->type
)
3092 if ((conn
->socket_family
!= AF_UNIX
&& wanted
->is_unix_addr
) ||
3093 (conn
->socket_family
== AF_UNIX
&& ! wanted
->is_unix_addr
))
3096 if (wanted
->server_cfg
.no_listen
)
3097 continue; /* We don't want to open a listener for this one */
3099 if (wanted
->is_unix_addr
) {
3100 if (conn
->socket_family
== AF_UNIX
&&
3101 !strcmp(wanted
->unix_addr
, conn
->address
)) {
3102 found_port
= wanted
;
3106 /* Numeric values of old and new port match exactly. */
3107 const int port_matches_exact
= (wanted
->port
== conn
->port
);
3108 /* Ports match semantically - either their specific values
3109 match exactly, or new port is 'auto'.
3111 const int port_matches
= (wanted
->port
== CFG_AUTO_PORT
||
3112 port_matches_exact
);
3114 if (port_matches
&& tor_addr_eq(&wanted
->addr
, &conn
->addr
)) {
3115 found_port
= wanted
;
3118 #ifdef ENABLE_LISTENER_REBIND
3119 /* Rebinding may be needed if all of the following are true:
3120 * 1) Address family is the same in old and new listeners.
3121 * 2) Port number matches exactly (numeric value is the same).
3122 * 3) *One* of listeners (either old one or new one) has a
3123 * wildcard IP address (0.0.0.0 or [::]).
3125 * These are the exact conditions for a first bind() syscall
3126 * to fail with EADDRINUSE.
3128 const int may_need_rebind
=
3129 tor_addr_family(&wanted
->addr
) == tor_addr_family(&conn
->addr
) &&
3130 port_matches_exact
&& bool_neq(tor_addr_is_null(&wanted
->addr
),
3131 tor_addr_is_null(&conn
->addr
));
3132 if (replacements
&& may_need_rebind
) {
3133 listener_replacement_t
*replacement
=
3134 tor_malloc(sizeof(listener_replacement_t
));
3136 replacement
->old_conn
= conn
;
3137 replacement
->new_port
= wanted
;
3138 smartlist_add(replacements
, replacement
);
3140 SMARTLIST_DEL_CURRENT(launch
, wanted
);
3141 SMARTLIST_DEL_CURRENT(old_conns
, conn
);
3144 #endif /* defined(ENABLE_LISTENER_REBIND) */
3146 } SMARTLIST_FOREACH_END(wanted
);
3149 /* This listener is already running; we don't need to launch it. */
3150 //log_debug(LD_NET, "Already have %s on %s:%d",
3151 // conn_type_to_string(found_port->type), conn->address, conn->port);
3152 smartlist_remove(launch
, found_port
);
3153 /* And we can remove the connection from old_conns too. */
3154 SMARTLIST_DEL_CURRENT(old_conns
, conn
);
3156 } SMARTLIST_FOREACH_END(conn
);
3158 /* Now open all the listeners that are configured but not opened. */
3159 SMARTLIST_FOREACH_BEGIN(launch
, const port_cfg_t
*, port
) {
3161 connection_t
*conn
= connection_listener_new_for_port(port
, &skip
, NULL
);
3163 if (conn
&& new_conns
)
3164 smartlist_add(new_conns
, conn
);
3167 } SMARTLIST_FOREACH_END(port
);
3169 smartlist_free(launch
);
3174 /** Launch listeners for each port you should have open. Only launch
3175 * listeners who are not already open, and only close listeners we no longer
3178 * Add all new connections to <b>new_conns</b>.
3180 * If <b>close_all_noncontrol</b> is true, then we only open control
3181 * listeners, and we close all other listeners.
3184 retry_all_listeners(smartlist_t
*new_conns
, int close_all_noncontrol
)
3186 smartlist_t
*listeners
= smartlist_new();
3187 smartlist_t
*replacements
= smartlist_new();
3188 const or_options_t
*options
= get_options();
3190 const uint16_t old_or_port
= routerconf_find_or_port(options
, AF_INET
);
3191 const uint16_t old_or_port_ipv6
=
3192 routerconf_find_or_port(options
,AF_INET6
);
3193 const uint16_t old_dir_port
= routerconf_find_dir_port(options
, 0);
3195 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
3196 if (connection_is_listener(conn
) && !conn
->marked_for_close
)
3197 smartlist_add(listeners
, conn
);
3198 } SMARTLIST_FOREACH_END(conn
);
3200 if (retry_listener_ports(listeners
,
3201 get_configured_ports(),
3204 close_all_noncontrol
) < 0)
3207 #ifdef ENABLE_LISTENER_REBIND
3208 if (smartlist_len(replacements
))
3209 log_debug(LD_NET
, "%d replacements - starting rebinding loop.",
3210 smartlist_len(replacements
));
3212 SMARTLIST_FOREACH_BEGIN(replacements
, listener_replacement_t
*, r
) {
3213 int addr_in_use
= 0;
3216 tor_assert(r
->new_port
);
3217 tor_assert(r
->old_conn
);
3219 connection_t
*new_conn
=
3220 connection_listener_new_for_port(r
->new_port
, &skip
, &addr_in_use
);
3221 connection_t
*old_conn
= r
->old_conn
;
3224 log_debug(LD_NET
, "Skipping creating new listener for %s",
3225 connection_describe(old_conn
));
3229 connection_close_immediate(old_conn
);
3230 connection_mark_for_close(old_conn
);
3233 new_conn
= connection_listener_new_for_port(r
->new_port
,
3234 &skip
, &addr_in_use
);
3237 /* There are many reasons why we can't open a new listener port so in case
3238 * we hit those, bail early so tor can stop. */
3240 log_warn(LD_NET
, "Unable to create listener port: %s:%d",
3241 fmt_and_decorate_addr(&r
->new_port
->addr
), r
->new_port
->port
);
3246 smartlist_add(new_conns
, new_conn
);
3248 char *old_desc
= tor_strdup(connection_describe(old_conn
));
3249 log_notice(LD_NET
, "Closed no-longer-configured %s "
3251 old_desc
, connection_describe(new_conn
));
3253 } SMARTLIST_FOREACH_END(r
);
3254 #endif /* defined(ENABLE_LISTENER_REBIND) */
3256 /* Any members that were still in 'listeners' don't correspond to
3257 * any configured port. Kill 'em. */
3258 SMARTLIST_FOREACH_BEGIN(listeners
, connection_t
*, conn
) {
3259 log_notice(LD_NET
, "Closing no-longer-configured %s on %s:%d",
3260 conn_type_to_string(conn
->type
),
3261 fmt_and_decorate_addr(&conn
->addr
), conn
->port
);
3262 connection_close_immediate(conn
);
3263 connection_mark_for_close(conn
);
3264 } SMARTLIST_FOREACH_END(conn
);
3266 smartlist_free(listeners
);
3267 /* Cleanup any remaining listener replacement. */
3268 SMARTLIST_FOREACH(replacements
, listener_replacement_t
*, r
, tor_free(r
));
3269 smartlist_free(replacements
);
3271 if (old_or_port
!= routerconf_find_or_port(options
, AF_INET
) ||
3272 old_or_port_ipv6
!= routerconf_find_or_port(options
, AF_INET6
) ||
3273 old_dir_port
!= routerconf_find_dir_port(options
, 0)) {
3274 /* Our chosen ORPort or DirPort is not what it used to be: the
3275 * descriptor we had (if any) should be regenerated. (We won't
3276 * automatically notice this because of changes in the option,
3277 * since the value could be "auto".) */
3278 mark_my_descriptor_dirty("Chosen Or/DirPort changed");
3284 /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
3286 connection_mark_all_noncontrol_listeners(void)
3288 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
3289 if (conn
->marked_for_close
)
3291 if (conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
3293 if (connection_is_listener(conn
))
3294 connection_mark_for_close(conn
);
3295 } SMARTLIST_FOREACH_END(conn
);
3298 /** Mark every external connection not used for controllers for close. */
3300 connection_mark_all_noncontrol_connections(void)
3302 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
3303 if (conn
->marked_for_close
)
3305 switch (conn
->type
) {
3306 case CONN_TYPE_CONTROL_LISTENER
:
3307 case CONN_TYPE_CONTROL
:
3310 connection_mark_unattached_ap(TO_ENTRY_CONN(conn
),
3311 END_STREAM_REASON_HIBERNATING
);
3315 or_connection_t
*orconn
= TO_OR_CONN(conn
);
3317 connection_or_close_normally(orconn
, 0);
3320 * There should have been one, but mark for close and hope
3323 connection_mark_for_close(conn
);
3328 connection_mark_for_close(conn
);
3331 } SMARTLIST_FOREACH_END(conn
);
3334 /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
3336 * Right now this just checks if it's an internal IP address or an
3337 * internal connection. We also should, but don't, check if the connection
3338 * uses pluggable transports, since we should then limit it even if it
3339 * comes from an internal IP address. */
3341 connection_is_rate_limited(const connection_t
*conn
)
3343 const or_options_t
*options
= get_options();
3345 return 0; /* Internal connection */
3346 else if (! options
->CountPrivateBandwidth
&&
3347 ! conn
->always_rate_limit_as_remote
&&
3348 (tor_addr_family(&conn
->addr
) == AF_UNSPEC
|| /* no address */
3349 tor_addr_family(&conn
->addr
) == AF_UNIX
|| /* no address */
3350 tor_addr_is_internal(&conn
->addr
, 0)))
3351 return 0; /* Internal address */
3356 /** When was either global write bucket last empty? If this was recent, then
3357 * we're probably low on bandwidth, and we should be stingy with our bandwidth
3359 static time_t write_buckets_last_empty_at
= -100;
3361 /** How many seconds of no active local circuits will make the
3362 * connection revert to the "relayed" bandwidth class? */
3363 #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
3365 /** Return 1 if <b>conn</b> should use tokens from the "relayed"
3366 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
3367 * class 1, and directory conns that are serving data out, count.
3370 connection_counts_as_relayed_traffic(connection_t
*conn
, time_t now
)
3372 if (conn
->type
== CONN_TYPE_OR
&&
3373 connection_or_client_used(TO_OR_CONN(conn
)) +
3374 CLIENT_IDLE_TIME_FOR_PRIORITY
< now
)
3376 if (conn
->type
== CONN_TYPE_DIR
&& DIR_CONN_IS_SERVER(conn
))
3381 /** Helper function to decide how many bytes out of <b>global_bucket</b>
3382 * we're willing to use for this transaction. <b>base</b> is the size
3383 * of a cell on the network; <b>priority</b> says whether we should
3384 * write many of them or just a few; and <b>conn_bucket</b> (if
3385 * non-negative) provides an upper limit for our answer. */
3387 connection_bucket_get_share(int base
, int priority
,
3388 ssize_t global_bucket_val
, ssize_t conn_bucket
)
3391 ssize_t num_bytes_high
= (priority
? 32 : 16) * base
;
3392 ssize_t num_bytes_low
= (priority
? 4 : 2) * base
;
3394 /* Do a rudimentary limiting so one circuit can't hog a connection.
3395 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
3396 * the middle pick 1/8 of the available bandwidth. */
3397 at_most
= global_bucket_val
/ 8;
3398 at_most
-= (at_most
% base
); /* round down */
3399 if (at_most
> num_bytes_high
) /* 16 KB, or 8 KB for low-priority */
3400 at_most
= num_bytes_high
;
3401 else if (at_most
< num_bytes_low
) /* 2 KB, or 1 KB for low-priority */
3402 at_most
= num_bytes_low
;
3404 if (at_most
> global_bucket_val
)
3405 at_most
= global_bucket_val
;
3407 if (conn_bucket
>= 0 && at_most
> conn_bucket
)
3408 at_most
= conn_bucket
;
3415 /** How many bytes at most can we read onto this connection? */
3417 connection_bucket_read_limit(connection_t
*conn
, time_t now
)
3419 int base
= RELAY_PAYLOAD_SIZE
;
3420 int priority
= conn
->type
!= CONN_TYPE_DIR
;
3421 ssize_t conn_bucket
= -1;
3422 size_t global_bucket_val
= token_bucket_rw_get_read(&global_bucket
);
3424 if (connection_speaks_cells(conn
)) {
3425 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
3426 if (conn
->state
== OR_CONN_STATE_OPEN
)
3427 conn_bucket
= token_bucket_rw_get_read(&or_conn
->bucket
);
3428 base
= get_cell_network_size(or_conn
->wide_circ_ids
);
3431 if (!connection_is_rate_limited(conn
)) {
3432 /* be willing to read on local conns even if our buckets are empty */
3433 return conn_bucket
>=0 ? conn_bucket
: 1<<14;
3436 if (connection_counts_as_relayed_traffic(conn
, now
)) {
3437 size_t relayed
= token_bucket_rw_get_read(&global_relayed_bucket
);
3438 global_bucket_val
= MIN(global_bucket_val
, relayed
);
3441 return connection_bucket_get_share(base
, priority
,
3442 global_bucket_val
, conn_bucket
);
3445 /** How many bytes at most can we write onto this connection? */
3447 connection_bucket_write_limit(connection_t
*conn
, time_t now
)
3449 int base
= RELAY_PAYLOAD_SIZE
;
3450 int priority
= conn
->type
!= CONN_TYPE_DIR
;
3451 size_t conn_bucket
= buf_datalen(conn
->outbuf
);
3452 size_t global_bucket_val
= token_bucket_rw_get_write(&global_bucket
);
3454 if (!connection_is_rate_limited(conn
)) {
3455 /* be willing to write to local conns even if our buckets are empty */
3459 if (connection_speaks_cells(conn
)) {
3460 /* use the per-conn write limit if it's lower */
3461 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
3462 if (conn
->state
== OR_CONN_STATE_OPEN
)
3463 conn_bucket
= MIN(conn_bucket
,
3464 token_bucket_rw_get_write(&or_conn
->bucket
));
3465 base
= get_cell_network_size(or_conn
->wide_circ_ids
);
3468 if (connection_counts_as_relayed_traffic(conn
, now
)) {
3469 size_t relayed
= token_bucket_rw_get_write(&global_relayed_bucket
);
3470 global_bucket_val
= MIN(global_bucket_val
, relayed
);
3473 return connection_bucket_get_share(base
, priority
,
3474 global_bucket_val
, conn_bucket
);
3477 /** Return true iff the global write buckets are low enough that we
3478 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
3479 * out to <b>conn</b>.
3481 * If we are a directory authority, always answer dir requests thus true is
3484 * Note: There are a lot of parameters we could use here:
3485 * - global_relayed_write_bucket. Low is bad.
3486 * - global_write_bucket. Low is bad.
3487 * - bandwidthrate. Low is bad.
3488 * - bandwidthburst. Not a big factor?
3489 * - attempt. High is bad.
3490 * - total bytes queued on outbufs. High is bad. But I'm wary of
3491 * using this, since a few slow-flushing queues will pump up the
3492 * number without meaning what we meant to mean. What we really
3493 * mean is "total directory bytes added to outbufs recently", but
3494 * that's harder to quantify and harder to keep track of.
3497 connection_dir_is_global_write_low(const connection_t
*conn
, size_t attempt
)
3499 size_t smaller_bucket
=
3500 MIN(token_bucket_rw_get_write(&global_bucket
),
3501 token_bucket_rw_get_write(&global_relayed_bucket
));
3503 /* Special case for authorities (directory only). */
3504 if (authdir_mode_v3(get_options())) {
3505 /* Are we configured to possibly reject requests under load? */
3506 if (!dirauth_should_reject_requests_under_load()) {
3507 /* Answer request no matter what. */
3510 /* Always answer requests from a known relay which includes the other
3511 * authorities. The following looks up the addresses for relays that we
3512 * have their descriptor _and_ any configured trusted directories. */
3513 if (nodelist_probably_contains_address(&conn
->addr
)) {
3518 if (!connection_is_rate_limited(conn
))
3519 return false; /* local conns don't get limited */
3521 if (smaller_bucket
< attempt
)
3522 return true; /* not enough space. */
3525 const time_t diff
= approx_time() - write_buckets_last_empty_at
;
3527 return true; /* we're already hitting our limits, no more please */
3532 /** When did we last tell the accounting subsystem about transmitted
3534 static time_t last_recorded_accounting_at
= 0;
3536 /** Helper: adjusts our bandwidth history and informs the controller as
3537 * appropriate, given that we have just read <b>num_read</b> bytes and written
3538 * <b>num_written</b> bytes on <b>conn</b>. */
3540 record_num_bytes_transferred_impl(connection_t
*conn
,
3541 time_t now
, size_t num_read
, size_t num_written
)
3543 /* Count bytes of answering direct and tunneled directory requests */
3544 if (conn
->type
== CONN_TYPE_DIR
&& conn
->purpose
== DIR_PURPOSE_SERVER
) {
3546 bwhist_note_dir_bytes_read(num_read
, now
);
3547 if (num_written
> 0)
3548 bwhist_note_dir_bytes_written(num_written
, now
);
3551 /* Linked connections and internal IPs aren't counted for statistics or
3553 * - counting linked connections would double-count BEGINDIR bytes, because
3554 * they are sent as Dir bytes on the linked connection, and OR bytes on
3555 * the OR connection;
3556 * - relays and clients don't connect to internal IPs, unless specifically
3557 * configured to do so. If they are configured that way, we don't count
3560 if (!connection_is_rate_limited(conn
))
3563 const bool is_ipv6
= (conn
->socket_family
== AF_INET6
);
3564 if (conn
->type
== CONN_TYPE_OR
)
3565 conn_stats_note_or_conn_bytes(conn
->global_identifier
, num_read
,
3566 num_written
, now
, is_ipv6
);
3569 bwhist_note_bytes_read(num_read
, now
, is_ipv6
);
3571 if (num_written
> 0) {
3572 bwhist_note_bytes_written(num_written
, now
, is_ipv6
);
3574 if (conn
->type
== CONN_TYPE_EXIT
)
3575 rep_hist_note_exit_bytes(conn
->port
, num_written
, num_read
);
3577 /* Remember these bytes towards statistics. */
3578 stats_increment_bytes_read_and_written(num_read
, num_written
);
3580 /* Remember these bytes towards accounting. */
3581 if (accounting_is_enabled(get_options())) {
3582 if (now
> last_recorded_accounting_at
&& last_recorded_accounting_at
) {
3583 accounting_add_bytes(num_read
, num_written
,
3584 (int)(now
- last_recorded_accounting_at
));
3586 accounting_add_bytes(num_read
, num_written
, 0);
3588 last_recorded_accounting_at
= now
;
3592 /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
3593 * onto <b>conn</b>. Decrement buckets appropriately. */
3595 connection_buckets_decrement(connection_t
*conn
, time_t now
,
3596 size_t num_read
, size_t num_written
)
3598 if (num_written
>= INT_MAX
|| num_read
>= INT_MAX
) {
3599 log_err(LD_BUG
, "Value out of range. num_read=%lu, num_written=%lu, "
3600 "connection type=%s, state=%s",
3601 (unsigned long)num_read
, (unsigned long)num_written
,
3602 conn_type_to_string(conn
->type
),
3603 conn_state_to_string(conn
->type
, conn
->state
));
3604 tor_assert_nonfatal_unreached();
3605 if (num_written
>= INT_MAX
)
3607 if (num_read
>= INT_MAX
)
3611 record_num_bytes_transferred_impl(conn
, now
, num_read
, num_written
);
3613 if (!connection_is_rate_limited(conn
))
3614 return; /* local IPs are free */
3617 if (connection_counts_as_relayed_traffic(conn
, now
)) {
3618 flags
= token_bucket_rw_dec(&global_relayed_bucket
, num_read
, num_written
);
3620 flags
|= token_bucket_rw_dec(&global_bucket
, num_read
, num_written
);
3622 if (flags
& TB_WRITE
) {
3623 write_buckets_last_empty_at
= now
;
3625 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
) {
3626 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
3627 token_bucket_rw_dec(&or_conn
->bucket
, num_read
, num_written
);
3632 * Mark <b>conn</b> as needing to stop reading because bandwidth has been
3633 * exhausted. If <b>is_global_bw</b>, it is closing because global bandwidth
3634 * limit has been exhausted. Otherwise, it is closing because its own
3635 * bandwidth limit has been exhausted.
3638 connection_read_bw_exhausted(connection_t
*conn
, bool is_global_bw
)
3641 conn
->read_blocked_on_bw
= 1;
3642 connection_stop_reading(conn
);
3643 reenable_blocked_connection_schedule();
3647 * Mark <b>conn</b> as needing to stop reading because write bandwidth has
3648 * been exhausted. If <b>is_global_bw</b>, it is closing because global
3649 * bandwidth limit has been exhausted. Otherwise, it is closing because its
3650 * own bandwidth limit has been exhausted.
3653 connection_write_bw_exhausted(connection_t
*conn
, bool is_global_bw
)
3656 conn
->write_blocked_on_bw
= 1;
3657 connection_stop_writing(conn
);
3658 reenable_blocked_connection_schedule();
3661 /** If we have exhausted our global buckets, or the buckets for conn,
3664 connection_consider_empty_read_buckets(connection_t
*conn
)
3668 if (!connection_is_rate_limited(conn
))
3669 return; /* Always okay. */
3673 if (token_bucket_rw_get_read(&global_bucket
) <= 0) {
3674 reason
= "global read bucket exhausted. Pausing.";
3675 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
3676 token_bucket_rw_get_read(&global_relayed_bucket
) <= 0) {
3677 reason
= "global relayed read bucket exhausted. Pausing.";
3678 } else if (connection_speaks_cells(conn
) &&
3679 conn
->state
== OR_CONN_STATE_OPEN
&&
3680 token_bucket_rw_get_read(&TO_OR_CONN(conn
)->bucket
) <= 0) {
3681 reason
= "connection read bucket exhausted. Pausing.";
3684 return; /* all good, no need to stop it */
3686 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
3687 connection_read_bw_exhausted(conn
, is_global
);
3690 /** If we have exhausted our global buckets, or the buckets for conn,
3693 connection_consider_empty_write_buckets(connection_t
*conn
)
3697 if (!connection_is_rate_limited(conn
))
3698 return; /* Always okay. */
3700 bool is_global
= true;
3701 if (token_bucket_rw_get_write(&global_bucket
) <= 0) {
3702 reason
= "global write bucket exhausted. Pausing.";
3703 } else if (connection_counts_as_relayed_traffic(conn
, approx_time()) &&
3704 token_bucket_rw_get_write(&global_relayed_bucket
) <= 0) {
3705 reason
= "global relayed write bucket exhausted. Pausing.";
3706 } else if (connection_speaks_cells(conn
) &&
3707 conn
->state
== OR_CONN_STATE_OPEN
&&
3708 token_bucket_rw_get_write(&TO_OR_CONN(conn
)->bucket
) <= 0) {
3709 reason
= "connection write bucket exhausted. Pausing.";
3712 return; /* all good, no need to stop it */
3714 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "%s", reason
));
3715 connection_write_bw_exhausted(conn
, is_global
);
3718 /** Initialize the global buckets to the values configured in the
3721 connection_bucket_init(void)
3723 const or_options_t
*options
= get_options();
3724 const uint32_t now_ts
= monotime_coarse_get_stamp();
3725 token_bucket_rw_init(&global_bucket
,
3726 (int32_t)options
->BandwidthRate
,
3727 (int32_t)options
->BandwidthBurst
,
3729 if (options
->RelayBandwidthRate
) {
3730 token_bucket_rw_init(&global_relayed_bucket
,
3731 (int32_t)options
->RelayBandwidthRate
,
3732 (int32_t)options
->RelayBandwidthBurst
,
3735 token_bucket_rw_init(&global_relayed_bucket
,
3736 (int32_t)options
->BandwidthRate
,
3737 (int32_t)options
->BandwidthBurst
,
3741 reenable_blocked_connection_init(options
);
3744 /** Update the global connection bucket settings to a new value. */
3746 connection_bucket_adjust(const or_options_t
*options
)
3748 token_bucket_rw_adjust(&global_bucket
,
3749 (int32_t)options
->BandwidthRate
,
3750 (int32_t)options
->BandwidthBurst
);
3751 if (options
->RelayBandwidthRate
) {
3752 token_bucket_rw_adjust(&global_relayed_bucket
,
3753 (int32_t)options
->RelayBandwidthRate
,
3754 (int32_t)options
->RelayBandwidthBurst
);
3756 token_bucket_rw_adjust(&global_relayed_bucket
,
3757 (int32_t)options
->BandwidthRate
,
3758 (int32_t)options
->BandwidthBurst
);
3763 * Cached value of the last coarse-timestamp when we refilled the
3766 static uint32_t last_refilled_global_buckets_ts
=0;
3768 * Refill the token buckets for a single connection <b>conn</b>, and the
3769 * global token buckets as appropriate. Requires that <b>now_ts</b> is
3770 * the time in coarse timestamp units.
3773 connection_bucket_refill_single(connection_t
*conn
, uint32_t now_ts
)
3775 /* Note that we only check for equality here: the underlying
3776 * token bucket functions can handle moving backwards in time if they
3778 if (now_ts
!= last_refilled_global_buckets_ts
) {
3779 token_bucket_rw_refill(&global_bucket
, now_ts
);
3780 token_bucket_rw_refill(&global_relayed_bucket
, now_ts
);
3781 last_refilled_global_buckets_ts
= now_ts
;
3784 if (connection_speaks_cells(conn
) && conn
->state
== OR_CONN_STATE_OPEN
) {
3785 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
3786 token_bucket_rw_refill(&or_conn
->bucket
, now_ts
);
3791 * Event to re-enable all connections that were previously blocked on read or
3794 static mainloop_event_t
*reenable_blocked_connections_ev
= NULL
;
3796 /** True iff reenable_blocked_connections_ev is currently scheduled. */
3797 static int reenable_blocked_connections_is_scheduled
= 0;
3799 /** Delay after which to run reenable_blocked_connections_ev. */
3800 static struct timeval reenable_blocked_connections_delay
;
3803 * Re-enable all connections that were previously blocked on read or write.
3804 * This event is scheduled after enough time has elapsed to be sure
3805 * that the buckets will refill when the connections have something to do.
3808 reenable_blocked_connections_cb(mainloop_event_t
*ev
, void *arg
)
3812 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t
*, conn
) {
3813 if (conn
->read_blocked_on_bw
== 1) {
3814 connection_start_reading(conn
);
3815 conn
->read_blocked_on_bw
= 0;
3817 if (conn
->write_blocked_on_bw
== 1) {
3818 connection_start_writing(conn
);
3819 conn
->write_blocked_on_bw
= 0;
3821 } SMARTLIST_FOREACH_END(conn
);
3823 reenable_blocked_connections_is_scheduled
= 0;
3827 * Initialize the mainloop event that we use to wake up connections that
3828 * find themselves blocked on bandwidth.
3831 reenable_blocked_connection_init(const or_options_t
*options
)
3833 if (! reenable_blocked_connections_ev
) {
3834 reenable_blocked_connections_ev
=
3835 mainloop_event_new(reenable_blocked_connections_cb
, NULL
);
3836 reenable_blocked_connections_is_scheduled
= 0;
3838 time_t sec
= options
->TokenBucketRefillInterval
/ 1000;
3839 int msec
= (options
->TokenBucketRefillInterval
% 1000);
3840 reenable_blocked_connections_delay
.tv_sec
= sec
;
3841 reenable_blocked_connections_delay
.tv_usec
= msec
* 1000;
3845 * Called when we have blocked a connection for being low on bandwidth:
3846 * schedule an event to reenable such connections, if it is not already
3850 reenable_blocked_connection_schedule(void)
3852 if (reenable_blocked_connections_is_scheduled
)
3854 if (BUG(reenable_blocked_connections_ev
== NULL
)) {
3855 reenable_blocked_connection_init(get_options());
3857 mainloop_event_schedule(reenable_blocked_connections_ev
,
3858 &reenable_blocked_connections_delay
);
3859 reenable_blocked_connections_is_scheduled
= 1;
3862 /** Read bytes from conn-\>s and process them.
3864 * It calls connection_buf_read_from_socket() to bring in any new bytes,
3865 * and then calls connection_process_inbuf() to process them.
3867 * Mark the connection and return -1 if you want to close it, else
3871 connection_handle_read_impl(connection_t
*conn
)
3873 ssize_t max_to_read
=-1, try_to_read
;
3874 size_t before
, n_read
= 0;
3875 int socket_error
= 0;
3877 if (conn
->marked_for_close
)
3878 return 0; /* do nothing */
3880 conn
->timestamp_last_read_allowed
= approx_time();
3882 connection_bucket_refill_single(conn
, monotime_coarse_get_stamp());
3884 switch (conn
->type
) {
3885 case CONN_TYPE_OR_LISTENER
:
3886 return connection_handle_listener_read(conn
, CONN_TYPE_OR
);
3887 case CONN_TYPE_EXT_OR_LISTENER
:
3888 return connection_handle_listener_read(conn
, CONN_TYPE_EXT_OR
);
3889 case CONN_TYPE_AP_LISTENER
:
3890 case CONN_TYPE_AP_TRANS_LISTENER
:
3891 case CONN_TYPE_AP_NATD_LISTENER
:
3892 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER
:
3893 return connection_handle_listener_read(conn
, CONN_TYPE_AP
);
3894 case CONN_TYPE_DIR_LISTENER
:
3895 return connection_handle_listener_read(conn
, CONN_TYPE_DIR
);
3896 case CONN_TYPE_CONTROL_LISTENER
:
3897 return connection_handle_listener_read(conn
, CONN_TYPE_CONTROL
);
3898 case CONN_TYPE_METRICS_LISTENER
:
3899 return connection_handle_listener_read(conn
, CONN_TYPE_METRICS
);
3900 case CONN_TYPE_AP_DNS_LISTENER
:
3901 /* This should never happen; eventdns.c handles the reads here. */
3902 tor_fragile_assert();
3907 try_to_read
= max_to_read
;
3908 tor_assert(!conn
->marked_for_close
);
3910 before
= buf_datalen(conn
->inbuf
);
3911 if (connection_buf_read_from_socket(conn
, &max_to_read
, &socket_error
) < 0) {
3912 /* There's a read error; kill the connection.*/
3913 if (conn
->type
== CONN_TYPE_OR
) {
3914 connection_or_notify_error(TO_OR_CONN(conn
),
3916 errno_to_orconn_end_reason(socket_error
) :
3917 END_OR_CONN_REASON_CONNRESET
,
3919 tor_socket_strerror(socket_error
) :
3920 "(unknown, errno was 0)");
3922 if (CONN_IS_EDGE(conn
)) {
3923 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
3924 connection_edge_end_errno(edge_conn
);
3925 if (conn
->type
== CONN_TYPE_AP
&& TO_ENTRY_CONN(conn
)->socks_request
) {
3926 /* broken, don't send a socks reply back */
3927 TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
3930 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
3932 * This can bypass normal channel checking since we did
3933 * connection_or_notify_error() above.
3935 connection_mark_for_close_internal(conn
);
3938 n_read
+= buf_datalen(conn
->inbuf
) - before
;
3939 if (CONN_IS_EDGE(conn
) && try_to_read
!= max_to_read
) {
3940 /* instruct it not to try to package partial cells. */
3941 if (connection_process_inbuf(conn
, 0) < 0) {
3944 if (!conn
->marked_for_close
&&
3945 connection_is_reading(conn
) &&
3946 !conn
->inbuf_reached_eof
&&
3948 goto loop_again
; /* try reading again, in case more is here now */
3950 /* one last try, packaging partial cells and all. */
3951 if (!conn
->marked_for_close
&&
3952 connection_process_inbuf(conn
, 1) < 0) {
3955 if (conn
->linked_conn
) {
3956 /* The other side's handle_write() will never actually get called, so
3957 * we need to invoke the appropriate callbacks ourself. */
3958 connection_t
*linked
= conn
->linked_conn
;
3961 /* Probably a no-op, since linked conns typically don't count for
3962 * bandwidth rate limiting. But do it anyway so we can keep stats
3963 * accurately. Note that since we read the bytes from conn, and
3964 * we're writing the bytes onto the linked connection, we count
3965 * these as <i>written</i> bytes. */
3966 connection_buckets_decrement(linked
, approx_time(), 0, n_read
);
3968 if (connection_flushed_some(linked
) < 0)
3969 connection_mark_for_close(linked
);
3970 if (!connection_wants_to_flush(linked
))
3971 connection_finished_flushing(linked
);
3974 if (!buf_datalen(linked
->outbuf
) && conn
->active_on_link
)
3975 connection_stop_reading_from_linked_conn(conn
);
3977 /* If we hit the EOF, call connection_reached_eof(). */
3978 if (!conn
->marked_for_close
&&
3979 conn
->inbuf_reached_eof
&&
3980 connection_reached_eof(conn
) < 0) {
3986 /* DOCDOC connection_handle_read */
3988 connection_handle_read(connection_t
*conn
)
3991 update_current_time(time(NULL
));
3992 res
= connection_handle_read_impl(conn
);
3996 /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
3997 * either directly or via TLS. Reduce the token buckets by the number of bytes
4000 * If *max_to_read is -1, then decide it ourselves, else go with the
4001 * value passed to us. When returning, if it's changed, subtract the
4002 * number of bytes we read from *max_to_read.
4004 * Return -1 if we want to break conn, else return 0.
4007 connection_buf_read_from_socket(connection_t
*conn
, ssize_t
*max_to_read
,
4011 ssize_t at_most
= *max_to_read
;
4012 size_t slack_in_buf
, more_to_read
;
4013 size_t n_read
= 0, n_written
= 0;
4015 if (at_most
== -1) { /* we need to initialize it */
4016 /* how many bytes are we allowed to read? */
4017 at_most
= connection_bucket_read_limit(conn
, approx_time());
4020 /* Do not allow inbuf to grow past BUF_MAX_LEN. */
4021 const ssize_t maximum
= BUF_MAX_LEN
- buf_datalen(conn
->inbuf
);
4022 if (at_most
> maximum
) {
4026 slack_in_buf
= buf_slack(conn
->inbuf
);
4028 if ((size_t)at_most
> slack_in_buf
&& slack_in_buf
>= 1024) {
4029 more_to_read
= at_most
- slack_in_buf
;
4030 at_most
= slack_in_buf
;
4035 if (connection_speaks_cells(conn
) &&
4036 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
4038 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
4039 size_t initial_size
;
4040 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
4041 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
4042 /* continue handshaking even if global token bucket is empty */
4043 return connection_tls_continue_handshake(or_conn
);
4047 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
4049 (int)conn
->s
,(long)buf_datalen(conn
->inbuf
),
4050 tor_tls_get_pending_bytes(or_conn
->tls
), (long)at_most
);
4052 initial_size
= buf_datalen(conn
->inbuf
);
4053 /* else open, or closing */
4054 result
= buf_read_from_tls(conn
->inbuf
, or_conn
->tls
, at_most
);
4055 if (TOR_TLS_IS_ERROR(result
) || result
== TOR_TLS_CLOSE
)
4056 or_conn
->tls_error
= result
;
4058 or_conn
->tls_error
= 0;
4062 case TOR_TLS_ERROR_IO
:
4063 log_debug(LD_NET
,"TLS %s closed %son read. Closing.",
4064 connection_describe(conn
),
4065 result
== TOR_TLS_CLOSE
? "cleanly " : "");
4067 CASE_TOR_TLS_ERROR_ANY_NONIO
:
4068 log_debug(LD_NET
,"tls error [%s] from %s. Breaking.",
4069 tor_tls_err_to_string(result
),
4070 connection_describe(conn
));
4072 case TOR_TLS_WANTWRITE
:
4073 connection_start_writing(conn
);
4075 case TOR_TLS_WANTREAD
:
4076 if (conn
->in_connection_handle_write
) {
4077 /* We've been invoked from connection_handle_write, because we're
4078 * waiting for a TLS renegotiation, the renegotiation started, and
4079 * SSL_read returned WANTWRITE. But now SSL_read is saying WANTREAD
4080 * again. Stop waiting for write events now, or else we'll
4081 * busy-loop until data arrives for us to read.
4082 * XXX: remove this when v2 handshakes support is dropped. */
4083 connection_stop_writing(conn
);
4084 if (!connection_is_reading(conn
))
4085 connection_start_reading(conn
);
4087 /* we're already reading, one hopes */
4089 case TOR_TLS_DONE
: /* no data read, so nothing to process */
4090 break; /* so we call bucket_decrement below */
4094 pending
= tor_tls_get_pending_bytes(or_conn
->tls
);
4096 /* If we have any pending bytes, we read them now. This *can*
4097 * take us over our read allotment, but really we shouldn't be
4098 * believing that SSL bytes are the same as TCP bytes anyway. */
4099 int r2
= buf_read_from_tls(conn
->inbuf
, or_conn
->tls
, pending
);
4101 log_warn(LD_BUG
, "apparently, reading pending bytes can fail.");
4105 result
= (int)(buf_datalen(conn
->inbuf
)-initial_size
);
4106 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
4107 log_debug(LD_GENERAL
, "After TLS read of %d: %ld read, %ld written",
4108 result
, (long)n_read
, (long)n_written
);
4109 } else if (conn
->linked
) {
4110 if (conn
->linked_conn
) {
4111 result
= (int) buf_move_all(conn
->inbuf
, conn
->linked_conn
->outbuf
);
4115 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
4116 /* If the other side has disappeared, or if it's been marked for close and
4117 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
4118 if (!conn
->linked_conn
||
4119 (conn
->linked_conn
->marked_for_close
&&
4120 buf_datalen(conn
->linked_conn
->outbuf
) == 0))
4121 conn
->inbuf_reached_eof
= 1;
4123 n_read
= (size_t) result
;
4125 /* !connection_speaks_cells, !conn->linked_conn. */
4126 int reached_eof
= 0;
4127 CONN_LOG_PROTECT(conn
,
4128 result
= buf_read_from_socket(conn
->inbuf
, conn
->s
,
4133 conn
->inbuf_reached_eof
= 1;
4135 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
4139 n_read
= (size_t) result
;
4143 /* change *max_to_read */
4144 *max_to_read
= at_most
- n_read
;
4146 /* Onion service application connection. Note read bytes for metrics. */
4147 if (CONN_IS_EDGE(conn
) && TO_EDGE_CONN(conn
)->hs_ident
) {
4148 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
4149 hs_metrics_app_read_bytes(&edge_conn
->hs_ident
->identity_pk
,
4150 edge_conn
->hs_ident
->orig_virtual_port
,
4154 /* Update edge_conn->n_read */
4155 if (conn
->type
== CONN_TYPE_AP
) {
4156 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
4158 /* Check for overflow: */
4159 if (PREDICT_LIKELY(UINT32_MAX
- edge_conn
->n_read
> n_read
))
4160 edge_conn
->n_read
+= (int)n_read
;
4162 edge_conn
->n_read
= UINT32_MAX
;
4165 /* If CONN_BW events are enabled, update conn->n_read_conn_bw for
4166 * OR/DIR/EXIT connections, checking for overflow. */
4167 if (get_options()->TestingEnableConnBwEvent
&&
4168 (conn
->type
== CONN_TYPE_OR
||
4169 conn
->type
== CONN_TYPE_DIR
||
4170 conn
->type
== CONN_TYPE_EXIT
)) {
4171 if (PREDICT_LIKELY(UINT32_MAX
- conn
->n_read_conn_bw
> n_read
))
4172 conn
->n_read_conn_bw
+= (int)n_read
;
4174 conn
->n_read_conn_bw
= UINT32_MAX
;
4178 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
4180 if (more_to_read
&& result
== at_most
) {
4181 slack_in_buf
= buf_slack(conn
->inbuf
);
4182 at_most
= more_to_read
;
4186 /* Call even if result is 0, since the global read bucket may
4187 * have reached 0 on a different conn, and this connection needs to
4188 * know to stop reading. */
4189 connection_consider_empty_read_buckets(conn
);
4190 if (n_written
> 0 && connection_is_writing(conn
))
4191 connection_consider_empty_write_buckets(conn
);
4196 /** A pass-through to fetch_from_buf. */
4198 connection_buf_get_bytes(char *string
, size_t len
, connection_t
*conn
)
4200 return buf_get_bytes(conn
->inbuf
, string
, len
);
4203 /** As buf_get_line(), but read from a connection's input buffer. */
4205 connection_buf_get_line(connection_t
*conn
, char *data
,
4208 return buf_get_line(conn
->inbuf
, data
, data_len
);
4211 /** As fetch_from_buf_http, but fetches from a connection's input buffer_t as
4214 connection_fetch_from_buf_http(connection_t
*conn
,
4215 char **headers_out
, size_t max_headerlen
,
4216 char **body_out
, size_t *body_used
,
4217 size_t max_bodylen
, int force_complete
)
4219 return fetch_from_buf_http(conn
->inbuf
, headers_out
, max_headerlen
,
4220 body_out
, body_used
, max_bodylen
, force_complete
);
4223 /** Return true if this connection has data to flush. */
4225 connection_wants_to_flush(connection_t
*conn
)
4227 return connection_get_outbuf_len(conn
) > 0;
4230 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
4231 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
4232 * connection_edge_consider_sending_sendme().
4235 connection_outbuf_too_full(connection_t
*conn
)
4237 return connection_get_outbuf_len(conn
) > 10*CELL_PAYLOAD_SIZE
;
4241 * On Windows Vista and Windows 7, tune the send buffer size according to a
4244 * This should help fix slow upload rates.
4247 update_send_buffer_size(tor_socket_t sock
)
4250 /* We only do this on Vista and 7, because earlier versions of Windows
4251 * don't have the SIO_IDEAL_SEND_BACKLOG_QUERY functionality, and on
4252 * later versions it isn't necessary. */
4253 static int isVistaOr7
= -1;
4254 if (isVistaOr7
== -1) {
4256 OSVERSIONINFO osvi
= { 0 };
4257 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
4258 GetVersionEx(&osvi
);
4259 if (osvi
.dwMajorVersion
== 6 && osvi
.dwMinorVersion
< 2)
4264 if (get_options()->ConstrainedSockets
)
4267 DWORD bytesReturned
= 0;
4268 if (!WSAIoctl(sock
, SIO_IDEAL_SEND_BACKLOG_QUERY
, NULL
, 0,
4269 &isb
, sizeof(isb
), &bytesReturned
, NULL
, NULL
)) {
4270 setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
, (const char*)&isb
, sizeof(isb
));
4272 #else /* !defined(_WIN32) */
4274 #endif /* defined(_WIN32) */
4277 /** Try to flush more bytes onto <b>conn</b>-\>s.
4279 * This function is called in connection_handle_write(), which gets
4280 * called from conn_write_callback() in main.c when libevent tells us
4281 * that <b>conn</b> wants to write.
4283 * Update <b>conn</b>-\>timestamp_last_write_allowed to now, and call flush_buf
4284 * or flush_buf_tls appropriately. If it succeeds and there are no more
4285 * more bytes on <b>conn</b>-\>outbuf, then call connection_finished_flushing
4288 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
4289 * limits. (Used for flushing messages to controller connections on fatal
4292 * Mark the connection and return -1 if you want to close it, else
4296 connection_handle_write_impl(connection_t
*conn
, int force
)
4299 socklen_t len
=(socklen_t
)sizeof(e
);
4301 ssize_t max_to_write
;
4302 time_t now
= approx_time();
4303 size_t n_read
= 0, n_written
= 0;
4304 int dont_stop_writing
= 0;
4306 tor_assert(!connection_is_listener(conn
));
4308 if (conn
->marked_for_close
|| !SOCKET_OK(conn
->s
))
4309 return 0; /* do nothing */
4311 if (conn
->in_flushed_some
) {
4312 log_warn(LD_BUG
, "called recursively from inside conn->in_flushed_some");
4316 conn
->timestamp_last_write_allowed
= now
;
4318 connection_bucket_refill_single(conn
, monotime_coarse_get_stamp());
4320 /* Sometimes, "writable" means "connected". */
4321 if (connection_state_is_connecting(conn
)) {
4322 if (getsockopt(conn
->s
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &len
) < 0) {
4323 log_warn(LD_BUG
, "getsockopt() syscall failed");
4324 if (conn
->type
== CONN_TYPE_OR
) {
4325 or_connection_t
*orconn
= TO_OR_CONN(conn
);
4326 connection_or_close_for_error(orconn
, 0);
4328 if (CONN_IS_EDGE(conn
)) {
4329 connection_edge_end_errno(TO_EDGE_CONN(conn
));
4331 connection_mark_for_close(conn
);
4336 /* some sort of error, but maybe just inprogress still */
4337 if (!ERRNO_IS_CONN_EINPROGRESS(e
)) {
4338 log_info(LD_NET
,"in-progress connect failed. Removing. (%s)",
4339 tor_socket_strerror(e
));
4340 if (CONN_IS_EDGE(conn
))
4341 connection_edge_end_errno(TO_EDGE_CONN(conn
));
4342 if (conn
->type
== CONN_TYPE_OR
)
4343 connection_or_notify_error(TO_OR_CONN(conn
),
4344 errno_to_orconn_end_reason(e
),
4345 tor_socket_strerror(e
));
4347 connection_close_immediate(conn
);
4349 * This can bypass normal channel checking since we did
4350 * connection_or_notify_error() above.
4352 connection_mark_for_close_internal(conn
);
4355 return 0; /* no change, see if next time is better */
4358 /* The connection is successful. */
4359 if (connection_finished_connecting(conn
)<0)
4363 max_to_write
= force
? (ssize_t
)buf_datalen(conn
->outbuf
)
4364 : connection_bucket_write_limit(conn
, now
);
4366 if (connection_speaks_cells(conn
) &&
4367 conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
) {
4368 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
4369 size_t initial_size
;
4370 if (conn
->state
== OR_CONN_STATE_TLS_HANDSHAKING
||
4371 conn
->state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
4372 connection_stop_writing(conn
);
4373 if (connection_tls_continue_handshake(or_conn
) < 0) {
4374 /* Don't flush; connection is dead. */
4375 connection_or_notify_error(or_conn
,
4376 END_OR_CONN_REASON_MISC
,
4377 "TLS error in connection_tls_"
4378 "continue_handshake()");
4379 connection_close_immediate(conn
);
4381 * This can bypass normal channel checking since we did
4382 * connection_or_notify_error() above.
4384 connection_mark_for_close_internal(conn
);
4388 } else if (conn
->state
== OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
) {
4389 return connection_handle_read(conn
);
4392 /* else open, or closing */
4393 initial_size
= buf_datalen(conn
->outbuf
);
4394 result
= buf_flush_to_tls(conn
->outbuf
, or_conn
->tls
,
4398 update_send_buffer_size(conn
->s
);
4400 /* If we just flushed the last bytes, tell the channel on the
4401 * or_conn to check if it needs to geoip_change_dirreq_state() */
4402 /* XXXX move this to flushed_some or finished_flushing -NM */
4403 if (buf_datalen(conn
->outbuf
) == 0 && or_conn
->chan
)
4404 channel_notify_flushed(TLS_CHAN_TO_BASE(or_conn
->chan
));
4407 CASE_TOR_TLS_ERROR_ANY
:
4409 or_conn
->tls_error
= result
;
4410 log_info(LD_NET
, result
!= TOR_TLS_CLOSE
?
4411 "tls error. breaking.":"TLS connection closed on flush");
4412 /* Don't flush; connection is dead. */
4413 connection_or_notify_error(or_conn
,
4414 END_OR_CONN_REASON_MISC
,
4415 result
!= TOR_TLS_CLOSE
?
4416 "TLS error in during flush" :
4417 "TLS closed during flush");
4418 connection_close_immediate(conn
);
4420 * This can bypass normal channel checking since we did
4421 * connection_or_notify_error() above.
4423 connection_mark_for_close_internal(conn
);
4425 case TOR_TLS_WANTWRITE
:
4426 log_debug(LD_NET
,"wanted write.");
4427 /* we're already writing */
4428 dont_stop_writing
= 1;
4430 case TOR_TLS_WANTREAD
:
4431 /* Make sure to avoid a loop if the receive buckets are empty. */
4432 log_debug(LD_NET
,"wanted read.");
4433 if (!connection_is_reading(conn
)) {
4434 connection_write_bw_exhausted(conn
, true);
4435 /* we'll start reading again when we get more tokens in our
4436 * read bucket; then we'll start writing again too.
4439 /* else no problem, we're already reading */
4441 /* case TOR_TLS_DONE:
4442 * for TOR_TLS_DONE, fall through to check if the flushlen
4443 * is empty, so we can stop writing.
4447 tor_tls_get_n_raw_bytes(or_conn
->tls
, &n_read
, &n_written
);
4448 log_debug(LD_GENERAL
, "After TLS write of %d: %ld read, %ld written",
4449 result
, (long)n_read
, (long)n_written
);
4450 or_conn
->bytes_xmitted
+= result
;
4451 or_conn
->bytes_xmitted_by_tls
+= n_written
;
4452 /* So we notice bytes were written even on error */
4453 /* XXXX This cast is safe since we can never write INT_MAX bytes in a
4454 * single set of TLS operations. But it looks kinda ugly. If we refactor
4455 * the *_buf_tls functions, we should make them return ssize_t or size_t
4457 result
= (int)(initial_size
-buf_datalen(conn
->outbuf
));
4459 CONN_LOG_PROTECT(conn
,
4460 result
= buf_flush_to_socket(conn
->outbuf
, conn
->s
,
4463 if (CONN_IS_EDGE(conn
))
4464 connection_edge_end_errno(TO_EDGE_CONN(conn
));
4465 if (conn
->type
== CONN_TYPE_AP
) {
4466 /* writing failed; we couldn't send a SOCKS reply if we wanted to */
4467 TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
4470 connection_close_immediate(conn
); /* Don't flush; connection is dead. */
4471 connection_mark_for_close(conn
);
4474 update_send_buffer_size(conn
->s
);
4475 n_written
= (size_t) result
;
4478 if (n_written
&& conn
->type
== CONN_TYPE_AP
) {
4479 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
4481 /* Check for overflow: */
4482 if (PREDICT_LIKELY(UINT32_MAX
- edge_conn
->n_written
> n_written
))
4483 edge_conn
->n_written
+= (int)n_written
;
4485 edge_conn
->n_written
= UINT32_MAX
;
4488 /* If CONN_BW events are enabled, update conn->n_written_conn_bw for
4489 * OR/DIR/EXIT connections, checking for overflow. */
4490 if (n_written
&& get_options()->TestingEnableConnBwEvent
&&
4491 (conn
->type
== CONN_TYPE_OR
||
4492 conn
->type
== CONN_TYPE_DIR
||
4493 conn
->type
== CONN_TYPE_EXIT
)) {
4494 if (PREDICT_LIKELY(UINT32_MAX
- conn
->n_written_conn_bw
> n_written
))
4495 conn
->n_written_conn_bw
+= (int)n_written
;
4497 conn
->n_written_conn_bw
= UINT32_MAX
;
4500 connection_buckets_decrement(conn
, approx_time(), n_read
, n_written
);
4503 /* If we wrote any bytes from our buffer, then call the appropriate
4505 if (connection_flushed_some(conn
) < 0) {
4506 if (connection_speaks_cells(conn
)) {
4507 connection_or_notify_error(TO_OR_CONN(conn
),
4508 END_OR_CONN_REASON_MISC
,
4509 "Got error back from "
4510 "connection_flushed_some()");
4514 * This can bypass normal channel checking since we did
4515 * connection_or_notify_error() above.
4517 connection_mark_for_close_internal(conn
);
4521 if (!connection_wants_to_flush(conn
) &&
4522 !dont_stop_writing
) { /* it's done flushing */
4523 if (connection_finished_flushing(conn
) < 0) {
4524 /* already marked */
4530 /* Call even if result is 0, since the global write bucket may
4531 * have reached 0 on a different conn, and this connection needs to
4532 * know to stop writing. */
4533 connection_consider_empty_write_buckets(conn
);
4534 if (n_read
> 0 && connection_is_reading(conn
))
4535 connection_consider_empty_read_buckets(conn
);
4540 /* DOCDOC connection_handle_write */
4542 connection_handle_write(connection_t
*conn
, int force
)
4545 update_current_time(time(NULL
));
4546 /* connection_handle_write_impl() might call connection_handle_read()
4547 * if we're in the middle of a v2 handshake, in which case it needs this
4549 conn
->in_connection_handle_write
= 1;
4550 res
= connection_handle_write_impl(conn
, force
);
4551 conn
->in_connection_handle_write
= 0;
4556 * Try to flush data that's waiting for a write on <b>conn</b>. Return
4557 * -1 on failure, 0 on success.
4559 * Don't use this function for regular writing; the buffers
4560 * system should be good enough at scheduling writes there. Instead, this
4561 * function is for cases when we're about to exit or something and we want
4562 * to report it right away.
4565 connection_flush(connection_t
*conn
)
4567 return connection_handle_write(conn
, 1);
4570 /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4572 * Return true iff it is okay to queue bytes on <b>conn</b>'s outbuf for
4576 connection_may_write_to_buf(connection_t
*conn
)
4578 /* if it's marked for close, only allow write if we mean to flush it */
4579 if (conn
->marked_for_close
&& !conn
->hold_open_until_flushed
)
4585 /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4587 * Called when an attempt to add bytes on <b>conn</b>'s outbuf has failed;
4588 * mark the connection and warn as appropriate.
4591 connection_write_to_buf_failed(connection_t
*conn
)
4593 if (CONN_IS_EDGE(conn
)) {
4594 /* if it failed, it means we have our package/delivery windows set
4595 wrong compared to our max outbuf size. close the whole circuit. */
4597 "write_to_buf failed. Closing circuit (fd %d).", (int)conn
->s
);
4598 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn
)),
4599 END_CIRC_REASON_INTERNAL
);
4600 } else if (conn
->type
== CONN_TYPE_OR
) {
4601 or_connection_t
*orconn
= TO_OR_CONN(conn
);
4603 "write_to_buf failed on an orconn; notifying of error "
4604 "(fd %d)", (int)(conn
->s
));
4605 connection_or_close_for_error(orconn
, 0);
4608 "write_to_buf failed. Closing connection (fd %d).",
4610 connection_mark_for_close(conn
);
4614 /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4616 * Called when an attempt to add bytes on <b>conn</b>'s outbuf has succeeded:
4617 * start writing if appropriate.
4620 connection_write_to_buf_commit(connection_t
*conn
)
4622 /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
4623 * state, we don't want to try to write it right away, since
4624 * conn->write_event won't be set yet. Otherwise, write data from
4625 * this conn as the socket is available. */
4626 if (conn
->write_event
) {
4627 connection_start_writing(conn
);
4631 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
4632 * outbuf, and ask it to start writing.
4634 * If <b>zlib</b> is nonzero, this is a directory connection that should get
4635 * its contents compressed or decompressed as they're written. If zlib is
4636 * negative, this is the last data to be compressed, and the connection's zlib
4637 * state should be flushed.
4640 connection_write_to_buf_impl_
,(const char *string
, size_t len
,
4641 connection_t
*conn
, int zlib
))
4643 /* XXXX This function really needs to return -1 on failure. */
4645 if (!len
&& !(zlib
<0))
4648 if (!connection_may_write_to_buf(conn
))
4652 dir_connection_t
*dir_conn
= TO_DIR_CONN(conn
);
4653 int done
= zlib
< 0;
4654 CONN_LOG_PROTECT(conn
, r
= buf_add_compress(conn
->outbuf
,
4655 dir_conn
->compress_state
,
4656 string
, len
, done
));
4658 CONN_LOG_PROTECT(conn
, r
= buf_add(conn
->outbuf
, string
, len
));
4661 connection_write_to_buf_failed(conn
);
4664 connection_write_to_buf_commit(conn
);
4668 * Write a <b>string</b> (of size <b>len</b> to directory connection
4669 * <b>dir_conn</b>. Apply compression if connection is configured to use
4670 * it and finalize it if <b>done</b> is true.
4673 connection_dir_buf_add(const char *string
, size_t len
,
4674 dir_connection_t
*dir_conn
, int done
)
4676 if (dir_conn
->compress_state
!= NULL
) {
4677 connection_buf_add_compress(string
, len
, dir_conn
, done
);
4681 connection_buf_add(string
, len
, TO_CONN(dir_conn
));
4685 connection_buf_add_compress(const char *string
, size_t len
,
4686 dir_connection_t
*conn
, int done
)
4688 connection_write_to_buf_impl_(string
, len
, TO_CONN(conn
), done
? -1 : 1);
4692 * Add all bytes from <b>buf</b> to <b>conn</b>'s outbuf, draining them
4693 * from <b>buf</b>. (If the connection is marked and will soon be closed,
4694 * nothing is drained.)
4697 connection_buf_add_buf(connection_t
*conn
, buf_t
*buf
)
4701 size_t len
= buf_datalen(buf
);
4705 if (!connection_may_write_to_buf(conn
))
4708 buf_move_all(conn
->outbuf
, buf
);
4709 connection_write_to_buf_commit(conn
);
4712 #define CONN_GET_ALL_TEMPLATE(var, test) \
4714 smartlist_t *conns = get_connection_array(); \
4715 smartlist_t *ret_conns = smartlist_new(); \
4716 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, var) { \
4717 if (var && (test) && !var->marked_for_close) \
4718 smartlist_add(ret_conns, var); \
4719 } SMARTLIST_FOREACH_END(var); \
4723 /* Return a list of connections that aren't close and matches the given type
4724 * and state. The returned list can be empty and must be freed using
4725 * smartlist_free(). The caller does NOT have ownership of the objects in the
4726 * list so it must not free them nor reference them as they can disappear. */
4728 connection_list_by_type_state(int type
, int state
)
4730 CONN_GET_ALL_TEMPLATE(conn
, (conn
->type
== type
&& conn
->state
== state
));
4733 /* Return a list of connections that aren't close and matches the given type
4734 * and purpose. The returned list can be empty and must be freed using
4735 * smartlist_free(). The caller does NOT have ownership of the objects in the
4736 * list so it must not free them nor reference them as they can disappear. */
4738 connection_list_by_type_purpose(int type
, int purpose
)
4740 CONN_GET_ALL_TEMPLATE(conn
,
4741 (conn
->type
== type
&& conn
->purpose
== purpose
));
4744 /** Return a connection_t * from get_connection_array() that satisfies test on
4745 * var, and that is not marked for close. */
4746 #define CONN_GET_TEMPLATE(var, test) \
4748 smartlist_t *conns = get_connection_array(); \
4749 SMARTLIST_FOREACH(conns, connection_t *, var, \
4751 if (var && (test) && !var->marked_for_close) \
4757 /** Return a connection with given type, address, port, and purpose;
4758 * or NULL if no such connection exists (or if all such connections are marked
4760 MOCK_IMPL(connection_t
*,
4761 connection_get_by_type_addr_port_purpose
,(int type
,
4762 const tor_addr_t
*addr
, uint16_t port
,
4765 CONN_GET_TEMPLATE(conn
,
4766 (conn
->type
== type
&&
4767 tor_addr_eq(&conn
->addr
, addr
) &&
4768 conn
->port
== port
&&
4769 conn
->purpose
== purpose
));
4772 /** Return the stream with id <b>id</b> if it is not already marked for
4776 connection_get_by_global_id(uint64_t id
)
4778 CONN_GET_TEMPLATE(conn
, conn
->global_identifier
== id
);
4781 /** Return a connection of type <b>type</b> that is not marked for close.
4784 connection_get_by_type(int type
)
4786 CONN_GET_TEMPLATE(conn
, conn
->type
== type
);
4789 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
4790 * and that is not marked for close.
4793 connection_get_by_type_state(int type
, int state
)
4795 CONN_GET_TEMPLATE(conn
, conn
->type
== type
&& conn
->state
== state
);
4799 * Return a connection of type <b>type</b> that is not an internally linked
4800 * connection, and is not marked for close.
4802 MOCK_IMPL(connection_t
*,
4803 connection_get_by_type_nonlinked
,(int type
))
4805 CONN_GET_TEMPLATE(conn
, conn
->type
== type
&& !conn
->linked
);
4808 /** Return a connection of type <b>type</b> that has rendquery equal
4809 * to <b>rendquery</b>, and that is not marked for close. If state
4810 * is non-zero, conn must be of that state too.
4813 connection_get_by_type_state_rendquery(int type
, int state
,
4814 const char *rendquery
)
4816 tor_assert(type
== CONN_TYPE_DIR
||
4817 type
== CONN_TYPE_AP
|| type
== CONN_TYPE_EXIT
);
4818 tor_assert(rendquery
);
4820 CONN_GET_TEMPLATE(conn
,
4821 (conn
->type
== type
&&
4822 (!state
|| state
== conn
->state
)) &&
4824 (type
== CONN_TYPE_DIR
&&
4825 TO_DIR_CONN(conn
)->rend_data
&&
4826 !rend_cmp_service_ids(rendquery
,
4827 rend_data_get_address(TO_DIR_CONN(conn
)->rend_data
)))
4829 (CONN_IS_EDGE(conn
) &&
4830 TO_EDGE_CONN(conn
)->rend_data
&&
4831 !rend_cmp_service_ids(rendquery
,
4832 rend_data_get_address(TO_EDGE_CONN(conn
)->rend_data
)))
4836 /** Return a new smartlist of dir_connection_t * from get_connection_array()
4837 * that satisfy conn_test on connection_t *conn_var, and dirconn_test on
4838 * dir_connection_t *dirconn_var. conn_var must be of CONN_TYPE_DIR and not
4839 * marked for close to be included in the list. */
4840 #define DIR_CONN_LIST_TEMPLATE(conn_var, conn_test, \
4841 dirconn_var, dirconn_test) \
4843 smartlist_t *conns = get_connection_array(); \
4844 smartlist_t *dir_conns = smartlist_new(); \
4845 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn_var) { \
4846 if (conn_var && (conn_test) \
4847 && conn_var->type == CONN_TYPE_DIR \
4848 && !conn_var->marked_for_close) { \
4849 dir_connection_t *dirconn_var = TO_DIR_CONN(conn_var); \
4850 if (dirconn_var && (dirconn_test)) { \
4851 smartlist_add(dir_conns, dirconn_var); \
4854 } SMARTLIST_FOREACH_END(conn_var); \
4858 /** Return a list of directory connections that are fetching the item
4859 * described by <b>purpose</b>/<b>resource</b>. If there are none,
4860 * return an empty list. This list must be freed using smartlist_free,
4861 * but the pointers in it must not be freed.
4862 * Note that this list should not be cached, as the pointers in it can be
4863 * freed if their connections close. */
4865 connection_dir_list_by_purpose_and_resource(
4867 const char *resource
)
4869 DIR_CONN_LIST_TEMPLATE(conn
,
4870 conn
->purpose
== purpose
,
4872 0 == strcmp_opt(resource
,
4873 dirconn
->requested_resource
));
4876 /** Return a list of directory connections that are fetching the item
4877 * described by <b>purpose</b>/<b>resource</b>/<b>state</b>. If there are
4878 * none, return an empty list. This list must be freed using smartlist_free,
4879 * but the pointers in it must not be freed.
4880 * Note that this list should not be cached, as the pointers in it can be
4881 * freed if their connections close. */
4883 connection_dir_list_by_purpose_resource_and_state(
4885 const char *resource
,
4888 DIR_CONN_LIST_TEMPLATE(conn
,
4889 conn
->purpose
== purpose
&& conn
->state
== state
,
4891 0 == strcmp_opt(resource
,
4892 dirconn
->requested_resource
));
4895 #undef DIR_CONN_LIST_TEMPLATE
4897 /** Return an arbitrary active OR connection that isn't <b>this_conn</b>.
4899 * We use this to guess if we should tell the controller that we
4900 * didn't manage to connect to any of our bridges. */
4901 static connection_t
*
4902 connection_get_another_active_or_conn(const or_connection_t
*this_conn
)
4904 CONN_GET_TEMPLATE(conn
,
4905 conn
!= TO_CONN(this_conn
) && conn
->type
== CONN_TYPE_OR
);
4908 /** Return 1 if there are any active OR connections apart from
4911 * We use this to guess if we should tell the controller that we
4912 * didn't manage to connect to any of our bridges. */
4914 any_other_active_or_conns(const or_connection_t
*this_conn
)
4916 connection_t
*conn
= connection_get_another_active_or_conn(this_conn
);
4918 log_debug(LD_DIR
, "%s: Found an OR connection: %s",
4919 __func__
, connection_describe(conn
));
4926 #undef CONN_GET_TEMPLATE
4928 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
4930 connection_is_listener(connection_t
*conn
)
4932 if (conn
->type
== CONN_TYPE_OR_LISTENER
||
4933 conn
->type
== CONN_TYPE_EXT_OR_LISTENER
||
4934 conn
->type
== CONN_TYPE_AP_LISTENER
||
4935 conn
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
4936 conn
->type
== CONN_TYPE_AP_DNS_LISTENER
||
4937 conn
->type
== CONN_TYPE_AP_NATD_LISTENER
||
4938 conn
->type
== CONN_TYPE_AP_HTTP_CONNECT_LISTENER
||
4939 conn
->type
== CONN_TYPE_DIR_LISTENER
||
4940 conn
->type
== CONN_TYPE_CONTROL_LISTENER
)
4945 /** Return 1 if <b>conn</b> is in state "open" and is not marked
4946 * for close, else return 0.
4949 connection_state_is_open(connection_t
*conn
)
4953 if (conn
->marked_for_close
)
4956 if ((conn
->type
== CONN_TYPE_OR
&& conn
->state
== OR_CONN_STATE_OPEN
) ||
4957 (conn
->type
== CONN_TYPE_EXT_OR
) ||
4958 (conn
->type
== CONN_TYPE_AP
&& conn
->state
== AP_CONN_STATE_OPEN
) ||
4959 (conn
->type
== CONN_TYPE_EXIT
&& conn
->state
== EXIT_CONN_STATE_OPEN
) ||
4960 (conn
->type
== CONN_TYPE_CONTROL
&&
4961 conn
->state
== CONTROL_CONN_STATE_OPEN
))
4967 /** Return 1 if conn is in 'connecting' state, else return 0. */
4969 connection_state_is_connecting(connection_t
*conn
)
4973 if (conn
->marked_for_close
)
4978 return conn
->state
== OR_CONN_STATE_CONNECTING
;
4979 case CONN_TYPE_EXIT
:
4980 return conn
->state
== EXIT_CONN_STATE_CONNECTING
;
4982 return conn
->state
== DIR_CONN_STATE_CONNECTING
;
4988 /** Allocates a base64'ed authenticator for use in http or https
4989 * auth, based on the input string <b>authenticator</b>. Returns it
4990 * if success, else returns NULL. */
4992 alloc_http_authenticator(const char *authenticator
)
4994 /* an authenticator in Basic authentication
4995 * is just the string "username:password" */
4996 const size_t authenticator_length
= strlen(authenticator
);
4997 const size_t base64_authenticator_length
=
4998 base64_encode_size(authenticator_length
, 0) + 1;
4999 char *base64_authenticator
= tor_malloc(base64_authenticator_length
);
5000 if (base64_encode(base64_authenticator
, base64_authenticator_length
,
5001 authenticator
, authenticator_length
, 0) < 0) {
5002 tor_free(base64_authenticator
); /* free and set to null */
5004 return base64_authenticator
;
5007 /** Given a socket handle, check whether the local address (sockname) of the
5008 * socket is one that we've connected from before. If so, double-check
5009 * whether our address has changed and we need to generate keys. If we do,
5013 client_check_address_changed(tor_socket_t sock
)
5015 tor_addr_t out_addr
, iface_addr
;
5016 tor_addr_t
**last_interface_ip_ptr
;
5019 if (!outgoing_addrs
)
5020 outgoing_addrs
= smartlist_new();
5022 if (tor_addr_from_getsockname(&out_addr
, sock
) < 0) {
5023 int e
= tor_socket_errno(sock
);
5024 log_warn(LD_NET
, "getsockname() to check for address change failed: %s",
5025 tor_socket_strerror(e
));
5028 family
= tor_addr_family(&out_addr
);
5030 if (family
== AF_INET
)
5031 last_interface_ip_ptr
= &last_interface_ipv4
;
5032 else if (family
== AF_INET6
)
5033 last_interface_ip_ptr
= &last_interface_ipv6
;
5037 if (! *last_interface_ip_ptr
) {
5038 tor_addr_t
*a
= tor_malloc_zero(sizeof(tor_addr_t
));
5039 if (get_interface_address6(LOG_INFO
, family
, a
)==0) {
5040 *last_interface_ip_ptr
= a
;
5046 /* If we've used this address previously, we're okay. */
5047 SMARTLIST_FOREACH(outgoing_addrs
, const tor_addr_t
*, a_ptr
,
5048 if (tor_addr_eq(a_ptr
, &out_addr
))
5052 /* Uh-oh. We haven't connected from this address before. Has the interface
5053 * address changed? */
5054 if (get_interface_address6(LOG_INFO
, family
, &iface_addr
)<0)
5057 if (tor_addr_eq(&iface_addr
, *last_interface_ip_ptr
)) {
5058 /* Nope, it hasn't changed. Add this address to the list. */
5059 smartlist_add(outgoing_addrs
, tor_memdup(&out_addr
, sizeof(tor_addr_t
)));
5061 /* The interface changed. We're a client, so we need to regenerate our
5062 * keys. First, reset the state. */
5063 log_notice(LD_NET
, "Our IP address has changed. Rotating keys...");
5064 tor_addr_copy(*last_interface_ip_ptr
, &iface_addr
);
5065 SMARTLIST_FOREACH(outgoing_addrs
, tor_addr_t
*, a_ptr
, tor_free(a_ptr
));
5066 smartlist_clear(outgoing_addrs
);
5067 smartlist_add(outgoing_addrs
, tor_memdup(&out_addr
, sizeof(tor_addr_t
)));
5068 /* We'll need to resolve ourselves again. */
5069 resolved_addr_reset_last(AF_INET
);
5070 /* Okay, now change our keys. */
5071 ip_address_changed(1);
5075 /** Some systems have limited system buffers for recv and xmit on
5076 * sockets allocated in a virtual server or similar environment. For a Tor
5077 * server this can produce the "Error creating network socket: No buffer
5078 * space available" error once all available TCP buffer space is consumed.
5079 * This method will attempt to constrain the buffers allocated for the socket
5080 * to the desired size to stay below system TCP buffer limits.
5083 set_constrained_socket_buffers(tor_socket_t sock
, int size
)
5085 void *sz
= (void*)&size
;
5086 socklen_t sz_sz
= (socklen_t
) sizeof(size
);
5087 if (setsockopt(sock
, SOL_SOCKET
, SO_SNDBUF
, sz
, sz_sz
) < 0) {
5088 int e
= tor_socket_errno(sock
);
5089 log_warn(LD_NET
, "setsockopt() to constrain send "
5090 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
5092 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
, sz
, sz_sz
) < 0) {
5093 int e
= tor_socket_errno(sock
);
5094 log_warn(LD_NET
, "setsockopt() to constrain recv "
5095 "buffer to %d bytes failed: %s", size
, tor_socket_strerror(e
));
5099 /** Process new bytes that have arrived on conn-\>inbuf.
5101 * This function just passes conn to the connection-specific
5102 * connection_*_process_inbuf() function. It also passes in
5103 * package_partial if wanted.
5106 connection_process_inbuf(connection_t
*conn
, int package_partial
)
5110 switch (conn
->type
) {
5112 return connection_or_process_inbuf(TO_OR_CONN(conn
));
5113 case CONN_TYPE_EXT_OR
:
5114 return connection_ext_or_process_inbuf(TO_OR_CONN(conn
));
5115 case CONN_TYPE_EXIT
:
5117 return connection_edge_process_inbuf(TO_EDGE_CONN(conn
),
5120 return connection_dir_process_inbuf(TO_DIR_CONN(conn
));
5121 case CONN_TYPE_CONTROL
:
5122 return connection_control_process_inbuf(TO_CONTROL_CONN(conn
));
5123 case CONN_TYPE_METRICS
:
5124 return metrics_connection_process_inbuf(conn
);
5126 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
5127 tor_fragile_assert();
5132 /** Called whenever we've written data on a connection. */
5134 connection_flushed_some(connection_t
*conn
)
5137 tor_assert(!conn
->in_flushed_some
);
5138 conn
->in_flushed_some
= 1;
5139 if (conn
->type
== CONN_TYPE_DIR
&&
5140 conn
->state
== DIR_CONN_STATE_SERVER_WRITING
) {
5141 r
= connection_dirserv_flushed_some(TO_DIR_CONN(conn
));
5142 } else if (conn
->type
== CONN_TYPE_OR
) {
5143 r
= connection_or_flushed_some(TO_OR_CONN(conn
));
5144 } else if (CONN_IS_EDGE(conn
)) {
5145 r
= connection_edge_flushed_some(TO_EDGE_CONN(conn
));
5147 conn
->in_flushed_some
= 0;
5151 /** We just finished flushing bytes to the appropriately low network layer,
5152 * and there are no more bytes remaining in conn-\>outbuf or
5153 * conn-\>tls to be flushed.
5155 * This function just passes conn to the connection-specific
5156 * connection_*_finished_flushing() function.
5159 connection_finished_flushing(connection_t
*conn
)
5163 /* If the connection is closed, don't try to do anything more here. */
5164 if (CONN_IS_CLOSED(conn
))
5167 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
5169 connection_stop_writing(conn
);
5171 switch (conn
->type
) {
5173 return connection_or_finished_flushing(TO_OR_CONN(conn
));
5174 case CONN_TYPE_EXT_OR
:
5175 return connection_ext_or_finished_flushing(TO_OR_CONN(conn
));
5177 case CONN_TYPE_EXIT
:
5178 return connection_edge_finished_flushing(TO_EDGE_CONN(conn
));
5180 return connection_dir_finished_flushing(TO_DIR_CONN(conn
));
5181 case CONN_TYPE_CONTROL
:
5182 return connection_control_finished_flushing(TO_CONTROL_CONN(conn
));
5184 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
5185 tor_fragile_assert();
5190 /** Called when our attempt to connect() to a server has just succeeded.
5192 * This function checks if the interface address has changed (clients only),
5193 * and then passes conn to the connection-specific
5194 * connection_*_finished_connecting() function.
5197 connection_finished_connecting(connection_t
*conn
)
5201 if (!server_mode(get_options())) {
5202 /* See whether getsockname() says our address changed. We need to do this
5203 * now that the connection has finished, because getsockname() on Windows
5204 * won't work until then. */
5205 client_check_address_changed(conn
->s
);
5211 return connection_or_finished_connecting(TO_OR_CONN(conn
));
5212 case CONN_TYPE_EXIT
:
5213 return connection_edge_finished_connecting(TO_EDGE_CONN(conn
));
5215 return connection_dir_finished_connecting(TO_DIR_CONN(conn
));
5217 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
5218 tor_fragile_assert();
5223 /** Callback: invoked when a connection reaches an EOF event. */
5225 connection_reached_eof(connection_t
*conn
)
5227 switch (conn
->type
) {
5229 case CONN_TYPE_EXT_OR
:
5230 return connection_or_reached_eof(TO_OR_CONN(conn
));
5232 case CONN_TYPE_EXIT
:
5233 return connection_edge_reached_eof(TO_EDGE_CONN(conn
));
5235 return connection_dir_reached_eof(TO_DIR_CONN(conn
));
5236 case CONN_TYPE_CONTROL
:
5237 return connection_control_reached_eof(TO_CONTROL_CONN(conn
));
5238 case CONN_TYPE_METRICS
:
5239 return metrics_connection_reached_eof(conn
);
5241 log_err(LD_BUG
,"got unexpected conn type %d.", conn
->type
);
5242 tor_fragile_assert();
5247 /** Comparator for the two-orconn case in OOS victim sort */
5249 oos_victim_comparator_for_orconns(or_connection_t
*a
, or_connection_t
*b
)
5251 int a_circs
, b_circs
;
5252 /* Fewer circuits == higher priority for OOS kill, sort earlier */
5254 a_circs
= connection_or_get_num_circuits(a
);
5255 b_circs
= connection_or_get_num_circuits(b
);
5257 if (a_circs
< b_circs
) return 1;
5258 else if (a_circs
> b_circs
) return -1;
5262 /** Sort comparator for OOS victims; better targets sort before worse
5265 oos_victim_comparator(const void **a_v
, const void **b_v
)
5267 connection_t
*a
= NULL
, *b
= NULL
;
5269 /* Get connection pointers out */
5271 a
= (connection_t
*)(*a_v
);
5272 b
= (connection_t
*)(*b_v
);
5274 tor_assert(a
!= NULL
);
5275 tor_assert(b
!= NULL
);
5278 * We always prefer orconns as victims currently; we won't even see
5279 * these non-orconn cases, but if we do, sort them after orconns.
5281 if (a
->type
== CONN_TYPE_OR
&& b
->type
== CONN_TYPE_OR
) {
5282 return oos_victim_comparator_for_orconns(TO_OR_CONN(a
), TO_OR_CONN(b
));
5285 * One isn't an orconn; if one is, it goes first. We currently have no
5286 * opinions about cases where neither is an orconn.
5288 if (a
->type
== CONN_TYPE_OR
) return -1;
5289 else if (b
->type
== CONN_TYPE_OR
) return 1;
5294 /** Pick n victim connections for the OOS handler and return them in a
5297 MOCK_IMPL(STATIC smartlist_t
*,
5298 pick_oos_victims
, (int n
))
5300 smartlist_t
*eligible
= NULL
, *victims
= NULL
;
5302 int conn_counts_by_type
[CONN_TYPE_MAX_
+ 1], i
;
5305 * Big damn assumption (someone improve this someday!):
5307 * Socket exhaustion normally happens on high-volume relays, and so
5308 * most of the connections involved are orconns. We should pick victims
5309 * by assembling a list of all orconns, and sorting them in order of
5310 * how much 'damage' by some metric we'd be doing by dropping them.
5312 * If we move on from orconns, we should probably think about incoming
5313 * directory connections next, or exit connections. Things we should
5314 * probably never kill are controller connections and listeners.
5316 * This function will count how many connections of different types
5317 * exist and log it for purposes of gathering data on typical OOS
5318 * situations to guide future improvements.
5321 /* First, get the connection array */
5322 conns
= get_connection_array();
5324 * Iterate it and pick out eligible connection types, and log some stats
5327 eligible
= smartlist_new();
5328 memset(conn_counts_by_type
, 0, sizeof(conn_counts_by_type
));
5329 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, c
) {
5330 /* Bump the counter */
5331 tor_assert(c
->type
<= CONN_TYPE_MAX_
);
5332 ++(conn_counts_by_type
[c
->type
]);
5334 /* Skip anything without a socket we can free */
5335 if (!(SOCKET_OK(c
->s
))) {
5339 /* Skip anything we would count as moribund */
5340 if (connection_is_moribund(c
)) {
5346 /* We've got an orconn, it's eligible to be OOSed */
5347 smartlist_add(eligible
, c
);
5350 /* We don't know what to do with it, ignore it */
5353 } SMARTLIST_FOREACH_END(c
);
5355 /* Log some stats */
5356 if (smartlist_len(conns
) > 0) {
5357 /* At least one counter must be non-zero */
5358 log_info(LD_NET
, "Some stats on conn types seen during OOS follow");
5359 for (i
= CONN_TYPE_MIN_
; i
<= CONN_TYPE_MAX_
; ++i
) {
5360 /* Did we see any? */
5361 if (conn_counts_by_type
[i
] > 0) {
5362 log_info(LD_NET
, "%s: %d conns",
5363 conn_type_to_string(i
),
5364 conn_counts_by_type
[i
]);
5367 log_info(LD_NET
, "Done with OOS conn type stats");
5370 /* Did we find more eligible targets than we want to kill? */
5371 if (smartlist_len(eligible
) > n
) {
5372 /* Sort the list in order of target preference */
5373 smartlist_sort(eligible
, oos_victim_comparator
);
5374 /* Pick first n as victims */
5375 victims
= smartlist_new();
5376 for (i
= 0; i
< n
; ++i
) {
5377 smartlist_add(victims
, smartlist_get(eligible
, i
));
5379 /* Free the original list */
5380 smartlist_free(eligible
);
5382 /* No, we can just call them all victims */
5389 /** Kill a list of connections for the OOS handler. */
5390 MOCK_IMPL(STATIC
void,
5391 kill_conn_list_for_oos
, (smartlist_t
*conns
))
5395 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, c
) {
5396 /* Make sure the channel layer gets told about orconns */
5397 if (c
->type
== CONN_TYPE_OR
) {
5398 connection_or_close_for_error(TO_OR_CONN(c
), 1);
5400 connection_mark_for_close(c
);
5402 } SMARTLIST_FOREACH_END(c
);
5405 "OOS handler marked %d connections",
5406 smartlist_len(conns
));
5409 /** Check if a connection is on the way out so the OOS handler doesn't try
5410 * to kill more than it needs. */
5412 connection_is_moribund(connection_t
*conn
)
5415 (conn
->conn_array_index
< 0 ||
5416 conn
->marked_for_close
)) {
5423 /** Out-of-Sockets handler; n_socks is the current number of open
5424 * sockets, and failed is non-zero if a socket exhaustion related
5425 * error immediately preceded this call. This is where to do
5426 * circuit-killing heuristics as needed.
5429 connection_check_oos(int n_socks
, int failed
)
5431 int target_n_socks
= 0, moribund_socks
, socks_to_kill
;
5434 /* Early exit: is OOS checking disabled? */
5435 if (get_options()->DisableOOSCheck
) {
5439 /* Sanity-check args */
5440 tor_assert(n_socks
>= 0);
5443 * Make some log noise; keep it at debug level since this gets a chance
5444 * to run on every connection attempt.
5447 "Running the OOS handler (%d open sockets, %s)",
5448 n_socks
, (failed
!= 0) ? "exhaustion seen" : "no exhaustion");
5451 * Check if we're really handling an OOS condition, and if so decide how
5452 * many sockets we want to get down to. Be sure we check if the threshold
5453 * is distinct from zero first; it's possible for this to be called a few
5454 * times before we've finished reading the config.
5456 if (n_socks
>= get_options()->ConnLimit_high_thresh
&&
5457 get_options()->ConnLimit_high_thresh
!= 0 &&
5458 get_options()->ConnLimit_
!= 0) {
5459 /* Try to get down to the low threshold */
5460 target_n_socks
= get_options()->ConnLimit_low_thresh
;
5462 "Current number of sockets %d is greater than configured "
5463 "limit %d; OOS handler trying to get down to %d",
5464 n_socks
, get_options()->ConnLimit_high_thresh
,
5466 } else if (failed
) {
5468 * If we're not at the limit but we hit a socket exhaustion error, try to
5469 * drop some (but not as aggressively as ConnLimit_low_threshold, which is
5470 * 3/4 of ConnLimit_)
5472 target_n_socks
= (n_socks
* 9) / 10;
5474 "We saw socket exhaustion at %d open sockets; OOS handler "
5475 "trying to get down to %d",
5476 n_socks
, target_n_socks
);
5479 if (target_n_socks
> 0) {
5483 * Count moribund sockets; it's be important that anything we decide
5484 * to get rid of here but don't immediately close get counted as moribund
5485 * on subsequent invocations so we don't try to kill too many things if
5486 * connection_check_oos() gets called multiple times.
5488 moribund_socks
= connection_count_moribund();
5490 if (moribund_socks
< n_socks
- target_n_socks
) {
5491 socks_to_kill
= n_socks
- target_n_socks
- moribund_socks
;
5493 conns
= pick_oos_victims(socks_to_kill
);
5495 kill_conn_list_for_oos(conns
);
5497 "OOS handler killed %d conns", smartlist_len(conns
));
5498 smartlist_free(conns
);
5500 log_notice(LD_NET
, "OOS handler failed to pick any victim conns");
5504 "Not killing any sockets for OOS because there are %d "
5505 "already moribund, and we only want to eliminate %d",
5506 moribund_socks
, n_socks
- target_n_socks
);
5511 /** Log how many bytes are used by buffers of different kinds and sizes. */
5513 connection_dump_buffer_mem_stats(int severity
)
5515 uint64_t used_by_type
[CONN_TYPE_MAX_
+1];
5516 uint64_t alloc_by_type
[CONN_TYPE_MAX_
+1];
5517 int n_conns_by_type
[CONN_TYPE_MAX_
+1];
5518 uint64_t total_alloc
= 0;
5519 uint64_t total_used
= 0;
5521 smartlist_t
*conns
= get_connection_array();
5523 memset(used_by_type
, 0, sizeof(used_by_type
));
5524 memset(alloc_by_type
, 0, sizeof(alloc_by_type
));
5525 memset(n_conns_by_type
, 0, sizeof(n_conns_by_type
));
5527 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, c
) {
5529 ++n_conns_by_type
[tp
];
5531 used_by_type
[tp
] += buf_datalen(c
->inbuf
);
5532 alloc_by_type
[tp
] += buf_allocation(c
->inbuf
);
5535 used_by_type
[tp
] += buf_datalen(c
->outbuf
);
5536 alloc_by_type
[tp
] += buf_allocation(c
->outbuf
);
5538 } SMARTLIST_FOREACH_END(c
);
5539 for (i
=0; i
<= CONN_TYPE_MAX_
; ++i
) {
5540 total_used
+= used_by_type
[i
];
5541 total_alloc
+= alloc_by_type
[i
];
5544 tor_log(severity
, LD_GENERAL
,
5545 "In buffers for %d connections: %"PRIu64
" used/%"PRIu64
" allocated",
5546 smartlist_len(conns
),
5547 (total_used
), (total_alloc
));
5548 for (i
=CONN_TYPE_MIN_
; i
<= CONN_TYPE_MAX_
; ++i
) {
5549 if (!n_conns_by_type
[i
])
5551 tor_log(severity
, LD_GENERAL
,
5552 " For %d %s connections: %"PRIu64
" used/%"PRIu64
" allocated",
5553 n_conns_by_type
[i
], conn_type_to_string(i
),
5554 (used_by_type
[i
]), (alloc_by_type
[i
]));
5558 /** Verify that connection <b>conn</b> has all of its invariants
5559 * correct. Trigger an assert if anything is invalid.
5562 assert_connection_ok(connection_t
*conn
, time_t now
)
5564 (void) now
; /* XXXX unused. */
5566 tor_assert(conn
->type
>= CONN_TYPE_MIN_
);
5567 tor_assert(conn
->type
<= CONN_TYPE_MAX_
);
5569 switch (conn
->type
) {
5571 case CONN_TYPE_EXT_OR
:
5572 tor_assert(conn
->magic
== OR_CONNECTION_MAGIC
);
5575 tor_assert(conn
->magic
== ENTRY_CONNECTION_MAGIC
);
5577 case CONN_TYPE_EXIT
:
5578 tor_assert(conn
->magic
== EDGE_CONNECTION_MAGIC
);
5581 tor_assert(conn
->magic
== DIR_CONNECTION_MAGIC
);
5583 case CONN_TYPE_CONTROL
:
5584 tor_assert(conn
->magic
== CONTROL_CONNECTION_MAGIC
);
5586 CASE_ANY_LISTENER_TYPE
:
5587 tor_assert(conn
->magic
== LISTENER_CONNECTION_MAGIC
);
5590 tor_assert(conn
->magic
== BASE_CONNECTION_MAGIC
);
5594 if (conn
->linked_conn
) {
5595 tor_assert(conn
->linked_conn
->linked_conn
== conn
);
5596 tor_assert(conn
->linked
);
5599 tor_assert(!SOCKET_OK(conn
->s
));
5601 if (conn
->hold_open_until_flushed
)
5602 tor_assert(conn
->marked_for_close
);
5604 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
5605 * marked_for_close. */
5609 buf_assert_ok(conn
->inbuf
);
5611 buf_assert_ok(conn
->outbuf
);
5613 if (conn
->type
== CONN_TYPE_OR
) {
5614 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
5615 if (conn
->state
== OR_CONN_STATE_OPEN
) {
5616 /* tor_assert(conn->bandwidth > 0); */
5617 /* the above isn't necessarily true: if we just did a TLS
5618 * handshake but we didn't recognize the other peer, or it
5619 * gave a bad cert/etc, then we won't have assigned bandwidth,
5620 * yet it will be open. -RD
5622 // tor_assert(conn->read_bucket >= 0);
5624 // tor_assert(conn->addr && conn->port);
5625 tor_assert(conn
->address
);
5626 if (conn
->state
> OR_CONN_STATE_PROXY_HANDSHAKING
)
5627 tor_assert(or_conn
->tls
);
5630 if (CONN_IS_EDGE(conn
)) {
5631 /* XXX unchecked: package window, deliver window. */
5632 if (conn
->type
== CONN_TYPE_AP
) {
5633 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(conn
);
5634 if (entry_conn
->chosen_exit_optional
|| entry_conn
->chosen_exit_retries
)
5635 tor_assert(entry_conn
->chosen_exit_name
);
5637 tor_assert(entry_conn
->socks_request
);
5638 if (conn
->state
== AP_CONN_STATE_OPEN
) {
5639 tor_assert(entry_conn
->socks_request
->has_finished
);
5640 if (!conn
->marked_for_close
) {
5641 tor_assert(ENTRY_TO_EDGE_CONN(entry_conn
)->cpath_layer
);
5642 cpath_assert_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn
)->cpath_layer
);
5646 if (conn
->type
== CONN_TYPE_EXIT
) {
5647 tor_assert(conn
->purpose
== EXIT_PURPOSE_CONNECT
||
5648 conn
->purpose
== EXIT_PURPOSE_RESOLVE
);
5650 } else if (conn
->type
== CONN_TYPE_DIR
) {
5652 /* Purpose is only used for dir and exit types currently */
5653 tor_assert(!conn
->purpose
);
5658 CASE_ANY_LISTENER_TYPE
:
5659 tor_assert(conn
->state
== LISTENER_STATE_READY
);
5662 tor_assert(conn
->state
>= OR_CONN_STATE_MIN_
);
5663 tor_assert(conn
->state
<= OR_CONN_STATE_MAX_
);
5665 case CONN_TYPE_EXT_OR
:
5666 tor_assert(conn
->state
>= EXT_OR_CONN_STATE_MIN_
);
5667 tor_assert(conn
->state
<= EXT_OR_CONN_STATE_MAX_
);
5669 case CONN_TYPE_EXIT
:
5670 tor_assert(conn
->state
>= EXIT_CONN_STATE_MIN_
);
5671 tor_assert(conn
->state
<= EXIT_CONN_STATE_MAX_
);
5672 tor_assert(conn
->purpose
>= EXIT_PURPOSE_MIN_
);
5673 tor_assert(conn
->purpose
<= EXIT_PURPOSE_MAX_
);
5676 tor_assert(conn
->state
>= AP_CONN_STATE_MIN_
);
5677 tor_assert(conn
->state
<= AP_CONN_STATE_MAX_
);
5678 tor_assert(TO_ENTRY_CONN(conn
)->socks_request
);
5681 tor_assert(conn
->state
>= DIR_CONN_STATE_MIN_
);
5682 tor_assert(conn
->state
<= DIR_CONN_STATE_MAX_
);
5683 tor_assert(conn
->purpose
>= DIR_PURPOSE_MIN_
);
5684 tor_assert(conn
->purpose
<= DIR_PURPOSE_MAX_
);
5686 case CONN_TYPE_CONTROL
:
5687 tor_assert(conn
->state
>= CONTROL_CONN_STATE_MIN_
);
5688 tor_assert(conn
->state
<= CONTROL_CONN_STATE_MAX_
);
5690 case CONN_TYPE_METRICS
:
5698 /** Fills <b>addr</b> and <b>port</b> with the details of the global
5699 * proxy server we are using. Store a 1 to the int pointed to by
5700 * <b>is_put_out</b> if the connection is using a pluggable
5701 * transport; store 0 otherwise. <b>conn</b> contains the connection
5702 * we are using the proxy for.
5704 * Return 0 on success, -1 on failure.
5707 get_proxy_addrport(tor_addr_t
*addr
, uint16_t *port
, int *proxy_type
,
5708 int *is_pt_out
, const connection_t
*conn
)
5710 const or_options_t
*options
= get_options();
5713 /* Client Transport Plugins can use another proxy, but that should be hidden
5714 * from the rest of tor (as the plugin is responsible for dealing with the
5715 * proxy), check it first, then check the rest of the proxy types to allow
5716 * the config to have unused ClientTransportPlugin entries.
5718 if (options
->ClientTransportPlugin
) {
5719 const transport_t
*transport
= NULL
;
5721 r
= get_transport_by_bridge_addrport(&conn
->addr
, conn
->port
, &transport
);
5724 if (transport
) { /* transport found */
5725 tor_addr_copy(addr
, &transport
->addr
);
5726 *port
= transport
->port
;
5727 *proxy_type
= transport
->socks_version
;
5732 /* Unused ClientTransportPlugin. */
5735 if (options
->HTTPSProxy
) {
5736 tor_addr_copy(addr
, &options
->HTTPSProxyAddr
);
5737 *port
= options
->HTTPSProxyPort
;
5738 *proxy_type
= PROXY_CONNECT
;
5740 } else if (options
->Socks4Proxy
) {
5741 tor_addr_copy(addr
, &options
->Socks4ProxyAddr
);
5742 *port
= options
->Socks4ProxyPort
;
5743 *proxy_type
= PROXY_SOCKS4
;
5745 } else if (options
->Socks5Proxy
) {
5746 tor_addr_copy(addr
, &options
->Socks5ProxyAddr
);
5747 *port
= options
->Socks5ProxyPort
;
5748 *proxy_type
= PROXY_SOCKS5
;
5750 } else if (options
->TCPProxy
) {
5751 tor_addr_copy(addr
, &options
->TCPProxyAddr
);
5752 *port
= options
->TCPProxyPort
;
5753 /* The only supported protocol in TCPProxy is haproxy. */
5754 tor_assert(options
->TCPProxyProtocol
== TCP_PROXY_PROTOCOL_HAPROXY
);
5755 *proxy_type
= PROXY_HAPROXY
;
5759 tor_addr_make_unspec(addr
);
5761 *proxy_type
= PROXY_NONE
;
5765 /** Log a failed connection to a proxy server.
5766 * <b>conn</b> is the connection we use the proxy server for. */
5768 log_failed_proxy_connection(connection_t
*conn
)
5770 tor_addr_t proxy_addr
;
5771 uint16_t proxy_port
;
5772 int proxy_type
, is_pt
;
5774 if (get_proxy_addrport(&proxy_addr
, &proxy_port
, &proxy_type
, &is_pt
,
5776 return; /* if we have no proxy set up, leave this function. */
5780 "The connection to the %s proxy server at %s just failed. "
5781 "Make sure that the proxy server is up and running.",
5782 proxy_type_to_string(proxy_type
),
5783 fmt_addrport(&proxy_addr
, proxy_port
));
5786 /** Return string representation of <b>proxy_type</b>. */
5788 proxy_type_to_string(int proxy_type
)
5790 switch (proxy_type
) {
5791 case PROXY_CONNECT
: return "HTTP";
5792 case PROXY_SOCKS4
: return "SOCKS4";
5793 case PROXY_SOCKS5
: return "SOCKS5";
5794 case PROXY_HAPROXY
: return "HAPROXY";
5795 case PROXY_PLUGGABLE
: return "pluggable transports SOCKS";
5796 case PROXY_NONE
: return "NULL";
5797 default: tor_assert(0);
5799 return NULL
; /*Unreached*/
5802 /** Call connection_free_minimal() on every connection in our array, and
5803 * release all storage held by connection.c.
5805 * Don't do the checks in connection_free(), because they will
5809 connection_free_all(void)
5811 smartlist_t
*conns
= get_connection_array();
5813 /* We don't want to log any messages to controllers. */
5814 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
5815 if (conn
->type
== CONN_TYPE_CONTROL
)
5816 TO_CONTROL_CONN(conn
)->event_mask
= 0);
5818 control_update_global_event_mask();
5820 /* Unlink everything from the identity map. */
5821 connection_or_clear_identity_map();
5823 /* Clear out our list of broken connections */
5824 clear_broken_connection_map(0);
5826 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
5827 connection_free_minimal(conn
));
5829 if (outgoing_addrs
) {
5830 SMARTLIST_FOREACH(outgoing_addrs
, tor_addr_t
*, addr
, tor_free(addr
));
5831 smartlist_free(outgoing_addrs
);
5832 outgoing_addrs
= NULL
;
5835 tor_free(last_interface_ipv4
);
5836 tor_free(last_interface_ipv6
);
5837 last_recorded_accounting_at
= 0;
5839 mainloop_event_free(reenable_blocked_connections_ev
);
5840 reenable_blocked_connections_is_scheduled
= 0;
5841 memset(&reenable_blocked_connections_delay
, 0, sizeof(struct timeval
));
5844 /** Log a warning, and possibly emit a control event, that <b>received</b> came
5845 * at a skewed time. <b>trusted</b> indicates that the <b>source</b> was one
5846 * that we had more faith in and therefore the warning level should have higher
5850 clock_skew_warning
, (const connection_t
*conn
, long apparent_skew
, int trusted
,
5851 log_domain_mask_t domain
, const char *received
,
5852 const char *source
))
5855 char *ext_source
= NULL
, *warn
= NULL
;
5856 format_time_interval(dbuf
, sizeof(dbuf
), apparent_skew
);
5858 tor_asprintf(&ext_source
, "%s:%s:%d", source
,
5859 fmt_and_decorate_addr(&conn
->addr
), conn
->port
);
5861 ext_source
= tor_strdup(source
);
5862 log_fn(trusted
? LOG_WARN
: LOG_INFO
, domain
,
5863 "Received %s with skewed time (%s): "
5864 "It seems that our clock is %s by %s, or that theirs is %s%s. "
5865 "Tor requires an accurate clock to work: please check your time, "
5866 "timezone, and date settings.", received
, ext_source
,
5867 apparent_skew
> 0 ? "ahead" : "behind", dbuf
,
5868 apparent_skew
> 0 ? "behind" : "ahead",
5869 (!conn
|| trusted
) ? "" : ", or they are sending us the wrong time");
5871 control_event_general_status(LOG_WARN
, "CLOCK_SKEW SKEW=%ld SOURCE=%s",
5872 apparent_skew
, ext_source
);
5873 tor_asprintf(&warn
, "Clock skew %ld in %s from %s", apparent_skew
,
5875 control_event_bootstrap_problem(warn
, "CLOCK_SKEW", conn
, 1);
5878 tor_free(ext_source
);