Merge branch 'maint-0.4.5'
[tor.git] / src / core / mainloop / connection.c
blob5370ad899a1b6a7419c27799e1b6302fe044ed34
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 */
7 /**
8 * \file connection.c
9 * \brief General high-level functions to handle reading and writing
10 * on connections.
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:
18 * <ul>
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
23 * its subtype(s):
24 * <ul><li>entry_connection_t, also implemented in connection_edge.c
25 * </ul>
26 * <li>control_connection_t, implemented in control.c
27 * </ul>
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:
49 * <ul>
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
54 * </ul>
55 **/
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"
125 #ifdef HAVE_PWD_H
126 #include <pwd.h>
127 #endif
129 #ifdef HAVE_UNISTD_H
130 #include <unistd.h>
131 #endif
132 #ifdef HAVE_SYS_STAT_H
133 #include <sys/stat.h>
134 #endif
136 #ifdef HAVE_SYS_UN_H
137 #include <sys/socket.h>
138 #include <sys/un.h>
139 #endif
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
158 * routine that:
159 * 1) Checks if first attempt to bind() a new socket failed with
160 * EADDRINUSE.
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,
172 const char *address,
173 const port_cfg_t *portcfg,
174 int *addr_in_use);
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,
179 int socket_family);
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,
187 int *socket_error);
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);
253 size_t
254 connection_get_inbuf_len(connection_t *conn)
256 return conn->inbuf ? buf_datalen(conn->inbuf) : 0;
259 size_t
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>
268 const char *
269 conn_type_to_string(int type)
271 static char buf[64];
272 switch (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";
291 default:
292 log_warn(LD_BUG, "unknown connection type %d", type);
293 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
294 return buf;
299 * Return the human-readable name for the connection state <b>state</b>
300 * for the connection type <b>type</b>
302 const char *
303 conn_state_to_string(int type, int state)
305 static char buf[96];
306 switch (type) {
307 CASE_ANY_LISTENER_TYPE:
308 if (state == LISTENER_STATE_READY)
309 return "ready";
310 break;
311 case CONN_TYPE_OR:
312 switch (state) {
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";
326 break;
327 case CONN_TYPE_EXT_OR:
328 switch (state) {
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";
338 break;
339 case CONN_TYPE_EXIT:
340 switch (state) {
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";
346 break;
347 case CONN_TYPE_AP:
348 switch (state) {
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";
358 break;
359 case CONN_TYPE_DIR:
360 switch (state) {
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";
368 break;
369 case CONN_TYPE_CONTROL:
370 switch (state) {
371 case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
372 case CONTROL_CONN_STATE_NEEDAUTH:
373 return "waiting for authentication (protocol v1)";
375 break;
378 if (state == 0) {
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();
387 return buf;
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
398 * peer address.
400 * Nobody should parse the output of this function; it can and will change in
401 * future versions of tor.
403 static const char *
404 connection_describe_peer_internal(const connection_t *conn,
405 bool include_preposition)
407 IF_BUG_ONCE(!conn) {
408 return "null peer";
411 static char peer_buf[256];
412 const tor_addr_t *addr = &conn->addr;
413 const char *address = NULL;
414 const char *prep;
415 bool scrub = false;
416 char extra_buf[128];
417 extra_buf[0] = 0;
419 /* First, figure out the preposition to use */
420 switch (conn->type) {
421 CASE_ANY_LISTENER_TYPE:
422 prep = "on";
423 break;
424 case CONN_TYPE_EXIT:
425 prep = "to";
426 break;
427 case CONN_TYPE_CONTROL:
428 case CONN_TYPE_AP:
429 case CONN_TYPE_EXT_OR:
430 prep = "from";
431 break;
432 default:
433 prep = "with";
434 break;
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.
447 scrub = true;
448 } else {
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];
453 if (ed_id) {
454 ed25519_public_to_base64(ed_id_buf, ed_id);
455 } else {
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,
472 canonical_addr_buf,
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) {
487 address = "<unset>";
488 } else {
489 address = tor_addr_to_str(addr_buf, addr, sizeof(addr_buf), 1);
490 if (!address) {
491 address = "<can't format!>";
492 tor_assert_nonfatal_unreached_once();
497 char portbuf[7];
498 portbuf[0]=0;
499 if (scrub && get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE) {
500 address = "[scrubbed]";
501 } else {
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)
510 prep = "";
512 tor_snprintf(peer_buf, sizeof(peer_buf),
513 "%s%s%s%s%s", prep, sp, address, portbuf, extra_buf);
514 return peer_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
523 * buffer.
525 * Nobody should parse the output of this function; it can and will change in
526 * future versions of tor.
528 const char *
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.
543 const char *
544 connection_describe(const connection_t *conn)
546 IF_BUG_ONCE(!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),
555 peer);
556 return desc_buf;
559 /** Allocate and return a new dir_connection_t, initialized as by
560 * connection_init(). */
561 dir_connection_t *
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);
566 return dir_conn;
569 /** Allocate and return a new or_connection_t, initialized as by
570 * connection_init().
572 * Initialize active_circuit_pqueue.
574 * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
576 or_connection_t *
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);
594 return or_conn;
597 /** Allocate and return a new entry_connection_t, initialized as by
598 * connection_init().
600 * Allocate space to store the socks_request.
602 entry_connection_t *
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;
616 return entry_conn;
619 /** Allocate and return a new edge_connection_t, initialized as by
620 * connection_init(). */
621 edge_connection_t *
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);
627 return edge_conn;
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);
639 return control_conn;
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. */
656 connection_t *
657 connection_new(int type, int socket_family)
659 switch (type) {
660 case CONN_TYPE_OR:
661 case CONN_TYPE_EXT_OR:
662 return TO_CONN(or_connection_new(type, socket_family));
664 case CONN_TYPE_EXIT:
665 return TO_CONN(edge_connection_new(type, socket_family));
667 case CONN_TYPE_AP:
668 return ENTRY_TO_CONN(entry_connection_new(type, socket_family));
670 case CONN_TYPE_DIR:
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));
679 default: {
680 connection_t *conn = tor_malloc_zero(sizeof(connection_t));
681 connection_init(time(NULL), conn, type, socket_family);
682 return conn;
687 /** Initializes conn. (you must call connection_add() to link it into the main
688 * array).
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.
697 static void
698 connection_init(time_t now, connection_t *conn, int type, int socket_family)
700 static uint64_t n_connections_allocated = 1;
702 switch (type) {
703 case CONN_TYPE_OR:
704 case CONN_TYPE_EXT_OR:
705 conn->magic = OR_CONNECTION_MAGIC;
706 break;
707 case CONN_TYPE_EXIT:
708 conn->magic = EDGE_CONNECTION_MAGIC;
709 break;
710 case CONN_TYPE_AP:
711 conn->magic = ENTRY_CONNECTION_MAGIC;
712 break;
713 case CONN_TYPE_DIR:
714 conn->magic = DIR_CONNECTION_MAGIC;
715 break;
716 case CONN_TYPE_CONTROL:
717 conn->magic = CONTROL_CONNECTION_MAGIC;
718 break;
719 CASE_ANY_LISTENER_TYPE:
720 conn->magic = LISTENER_CONNECTION_MAGIC;
721 break;
722 default:
723 conn->magic = BASE_CONNECTION_MAGIC;
724 break;
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++;
731 conn->type = type;
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>. */
745 void
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));
751 conn_a->linked = 1;
752 conn_b->linked = 1;
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
758 * sockets. */
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 */
764 switch (type) {
765 case CONN_TYPE_CONTROL_LISTENER:
766 case CONN_TYPE_AP_LISTENER:
767 return 1;
768 default:
769 return 0;
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.
777 STATIC void
778 connection_free_minimal(connection_t *conn)
780 void *mem;
781 size_t memlen;
782 if (!conn)
783 return;
785 switch (conn->type) {
786 case CONN_TYPE_OR:
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);
791 break;
792 case CONN_TYPE_AP:
793 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
794 mem = TO_ENTRY_CONN(conn);
795 memlen = sizeof(entry_connection_t);
796 break;
797 case CONN_TYPE_EXIT:
798 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
799 mem = TO_EDGE_CONN(conn);
800 memlen = sizeof(edge_connection_t);
801 break;
802 case CONN_TYPE_DIR:
803 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
804 mem = TO_DIR_CONN(conn);
805 memlen = sizeof(dir_connection_t);
806 break;
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);
811 break;
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);
816 break;
817 default:
818 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
819 mem = conn;
820 memlen = sizeof(connection_t);
821 break;
824 if (conn->linked) {
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);
836 } else {
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,
844 strerror(errno));
849 tor_str_wipe_and_free(conn->address);
851 if (connection_speaks_cells(conn)) {
852 or_connection_t *or_conn = TO_OR_CONN(conn);
853 if (or_conn->tls) {
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);
858 } else {
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);
865 or_conn->tls = NULL;
867 or_handshake_state_free(or_conn->handshake_state);
868 or_conn->handshake_state = NULL;
869 tor_str_wipe_and_free(or_conn->nickname);
870 if (or_conn->chan) {
871 /* Owww, this shouldn't happen, but... */
872 channel_t *base_chan = TLS_CHAN_TO_BASE(or_conn->chan);
873 tor_assert(base_chan);
874 log_info(LD_CHANNEL,
875 "Freeing orconn at %p, saw channel %p with ID "
876 "%"PRIu64 " left un-NULLed",
877 or_conn, base_chan,
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));
912 tor_free(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 */
957 tor_free(mem);
960 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
962 MOCK_IMPL(void,
963 connection_free_,(connection_t *conn))
965 if (!conn)
966 return;
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));
984 #if 1
985 /* DEBUGGING */
986 if (conn->type == CONN_TYPE_AP) {
987 connection_ap_warn_and_unmark_if_pending_circ(TO_ENTRY_CONN(conn),
988 "connection_free");
990 #endif /* 1 */
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.
1014 void
1015 connection_about_to_close_connection(connection_t *conn)
1017 tor_assert(conn->marked_for_close);
1019 switch (conn->type) {
1020 case CONN_TYPE_DIR:
1021 connection_dir_about_to_close(TO_DIR_CONN(conn));
1022 break;
1023 case CONN_TYPE_OR:
1024 case CONN_TYPE_EXT_OR:
1025 connection_or_about_to_close(TO_OR_CONN(conn));
1026 break;
1027 case CONN_TYPE_AP:
1028 connection_ap_about_to_close(TO_ENTRY_CONN(conn));
1029 break;
1030 case CONN_TYPE_EXIT:
1031 connection_exit_about_to_close(TO_EDGE_CONN(conn));
1032 break;
1036 /** Return true iff connection_close_immediate() has been called on this
1037 * connection. */
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().
1045 void
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();
1052 return;
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;
1070 if (conn->linked)
1071 conn->linked_conn_is_closed = 1;
1072 if (conn->outbuf)
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. */
1078 void
1079 connection_mark_for_close_(connection_t *conn, int line, const char *file)
1081 assert_connection_ok(conn,0);
1082 tor_assert(line);
1083 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
1084 tor_assert(file);
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",
1095 file, line);
1096 connection_or_close_for_error(TO_OR_CONN(conn), 0);
1097 } else {
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.
1118 MOCK_IMPL(void,
1119 connection_mark_for_close_internal_, (connection_t *conn,
1120 int line, const char *file))
1122 assert_connection_ok(conn,0);
1123 tor_assert(line);
1124 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
1125 tor_assert(file);
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();
1132 return;
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 "
1142 "at %s:%d",
1143 file, line);
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.
1161 void
1162 connection_expire_held_open(void)
1164 time_t now;
1165 smartlist_t *conns = get_connection_array();
1167 now = time(NULL);
1169 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1170 /* If we've been holding the connection open, but we haven't written
1171 * for 15 seconds...
1173 if (conn->hold_open_until_flushed) {
1174 tor_assert(conn->marked_for_close);
1175 if (now - conn->timestamp_last_write_allowed >= 15) {
1176 int severity;
1177 if (conn->type == CONN_TYPE_EXIT ||
1178 (conn->type == CONN_TYPE_DIR &&
1179 conn->purpose == DIR_PURPOSE_SERVER))
1180 severity = LOG_INFO;
1181 else
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
1201 * here.
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,
1210 socklen_t *len_out)
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));
1220 tor_free(sockaddr);
1221 return NULL;
1224 if (readable_address)
1225 *readable_address = tor_strdup(listenaddress);
1227 *len_out = sizeof(struct sockaddr_un);
1228 return sockaddr;
1230 #else /* !(defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)) */
1231 static struct sockaddr *
1232 create_unix_sockaddr(const char *listenaddress, char **readable_address,
1233 socklen_t *len_out)
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.");
1239 *len_out = 0;
1240 tor_fragile_assert();
1241 return NULL;
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. */
1248 static void
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);
1253 char *m;
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);
1258 tor_free(m);
1259 control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
1260 n_conns);
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 */
1271 static int
1272 is_valid_unix_socket_purpose(int purpose)
1274 int valid = 0;
1276 switch (purpose) {
1277 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
1278 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
1279 valid = 1;
1280 break;
1283 return valid;
1286 /** Return a string description of a unix socket purpose */
1287 static const char *
1288 unix_socket_purpose_to_string(int purpose)
1290 const char *s = "unknown-purpose socket";
1292 switch (purpose) {
1293 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
1294 s = "control socket";
1295 break;
1296 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
1297 s = "SOCKS socket";
1298 break;
1301 return s;
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. */
1306 static int
1307 check_location_for_unix_socket(const or_options_t *options, const char *path,
1308 int purpose, const port_cfg_t *port)
1310 int r = -1;
1311 char *p = NULL;
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);
1320 goto done;
1323 if (port->is_world_writable) {
1324 /* World-writable sockets can go anywhere. */
1325 r = 0;
1326 goto done;
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 "
1345 "careful.)",
1346 unix_socket_purpose_to_string(purpose), escpath, escdir,
1347 port->is_group_writable ? " and group" : "");
1348 tor_free(escpath);
1349 tor_free(escdir);
1350 goto done;
1353 r = 0;
1354 done:
1355 tor_free(p);
1356 return r;
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,
1362 * -1 on failure. */
1363 static int
1364 make_socket_reuseable(tor_socket_t sock)
1366 #ifdef _WIN32
1367 (void) sock;
1368 return 0;
1369 #else
1370 int one=1;
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) {
1378 return -1;
1380 return 0;
1381 #endif /* defined(_WIN32) */
1384 #ifdef _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. */
1387 static int
1388 make_win32_socket_exclusive(tor_socket_t sock)
1390 #ifdef SO_EXCLUSIVEADDRUSE
1391 int one=1;
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
1396 * on win32. */
1397 if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void*) &one,
1398 (socklen_t)sizeof(one))) {
1399 return -1;
1401 return 0;
1402 #else /* !defined(SO_EXCLUSIVEADDRUSE) */
1403 (void) sock;
1404 return 0;
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. */
1413 static int
1414 tor_listen(tor_socket_t fd)
1416 int r;
1418 if ((r = listen(fd, listen_limit)) < 0) {
1419 if (listen_limit == SOMAXCONN)
1420 return r;
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.");
1427 return r;
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
1434 * to the conn.
1436 * Set <b>addr_in_use</b> to true in case socket binding fails with
1437 * EADDRINUSE.
1439 static connection_t *
1440 connection_listener_new(const struct sockaddr *listensockaddr,
1441 socklen_t socklen,
1442 int type, const char *address,
1443 const port_cfg_t *port_cfg,
1444 int *addr_in_use)
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;
1453 #endif
1454 uint16_t usePort = 0, gotPort = 0;
1455 int start_reading = 0;
1456 static int global_next_session_group = SESSION_GROUP_FIRST_AUTO;
1457 tor_addr_t addr;
1458 int exhaustion = 0;
1460 if (addr_in_use)
1461 *addr_in_use = 0;
1463 if (listensockaddr->sa_family == AF_INET ||
1464 listensockaddr->sa_family == AF_INET6) {
1465 int is_stream = (type != CONN_TYPE_AP_DNS_LISTENER);
1466 if (is_stream)
1467 start_reading = 1;
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.
1484 exhaustion = 1;
1485 } else {
1486 log_warn(LD_NET, "Socket creation failed: %s",
1487 tor_socket_strerror(e));
1489 goto err;
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));
1498 #ifdef _WIN32
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) {
1509 int one = 1;
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);
1514 if (e == EPERM)
1515 extra = "TransTPROXY requires root privileges or similar"
1516 " capabilities.";
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) */
1523 #ifdef IPV6_V6ONLY
1524 if (listensockaddr->sa_family == AF_INET6) {
1525 int one = 1;
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?";
1543 if (addr_in_use)
1544 *addr_in_use = 1;
1546 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
1547 tor_socket_strerror(e), helpfulhint);
1548 goto err;
1551 if (is_stream) {
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)));
1555 goto err;
1559 if (usePort != 0) {
1560 gotPort = usePort;
1561 } else {
1562 tor_addr_t addr2;
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)));
1569 gotPort = 0;
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 */
1579 start_reading = 1;
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) {
1587 goto err;
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,
1597 strerror(errno));
1598 goto err;
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.
1610 exhaustion = 1;
1611 } else {
1612 log_warn(LD_NET,"Socket creation failed: %s.", strerror(e));
1614 goto err;
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)));
1621 goto err;
1624 #ifdef HAVE_PWD_H
1625 if (options->User) {
1626 pw = tor_getpwnam(options->User);
1627 struct stat st;
1628 if (pw == NULL) {
1629 log_warn(LD_NET,"Unable to chown() %s socket: user %s not found.",
1630 address, options->User);
1631 goto err;
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));
1639 goto err;
1642 #endif /* defined(HAVE_PWD_H) */
1645 unsigned mode;
1646 const char *status;
1647 struct stat st;
1648 if (port_cfg->is_world_writable) {
1649 mode = 0666;
1650 status = "world-writable";
1651 } else if (port_cfg->is_group_writable) {
1652 mode = 0660;
1653 status = "group-writable";
1654 } else {
1655 mode = 0600;
1656 status = "private";
1658 /* We need to use chmod; fchmod doesn't work on sockets on all
1659 * platforms. */
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);
1664 goto err;
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)));
1671 goto err;
1674 #ifndef __APPLE__
1675 /* This code was introduced to help debug #28229. */
1676 int value;
1677 socklen_t len = sizeof(value);
1679 if (!getsockopt(s, SOL_SOCKET, SO_ACCEPTCONN, &value, &len)) {
1680 if (value == 0) {
1681 log_err(LD_NET, "Could not listen on %s - "
1682 "getsockopt(.,SO_ACCEPTCONN,.) yields 0.", address);
1683 goto err;
1686 #endif /* !defined(__APPLE__) */
1687 #endif /* defined(HAVE_SYS_UN_H) */
1688 } else {
1689 log_err(LD_BUG, "Got unexpected address family %d.",
1690 listensockaddr->sa_family);
1691 tor_assert(0);
1694 lis_conn = listener_connection_new(type, listensockaddr->sa_family);
1695 conn = TO_CONN(lis_conn);
1696 conn->socket_family = listensockaddr->sa_family;
1697 conn->s = s;
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;
1709 } else {
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.");
1722 goto err;
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);
1732 } else {
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));
1745 return conn;
1747 err:
1748 if (SOCKET_OK(s))
1749 tor_close_socket(s);
1750 if (conn)
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);
1756 return NULL;
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)
1769 connection_t *conn;
1770 struct sockaddr *listensockaddr;
1771 socklen_t listensocklen = 0;
1772 char *address=NULL;
1773 int real_port = port->port == CFG_AUTO_PORT ? 0 : port->port;
1774 tor_assert(real_port <= UINT16_MAX);
1776 if (defer)
1777 *defer = 0;
1779 if (port->server_cfg.no_listen) {
1780 if (defer)
1781 *defer = 1;
1782 return NULL;
1785 #ifndef _WIN32
1786 /* We don't need to be root to create a UNIX socket, so defer until after
1787 * setuid. */
1788 const or_options_t *options = get_options();
1789 if (port->is_unix_addr && !geteuid() && (options->User) &&
1790 strcmp(options->User, "root")) {
1791 if (defer)
1792 *defer = 1;
1793 return NULL;
1795 #endif /* !defined(_WIN32) */
1797 if (port->is_unix_addr) {
1798 listensockaddr = (struct sockaddr *)
1799 create_unix_sockaddr(port->unix_addr,
1800 &address, &listensocklen);
1801 } else {
1802 listensockaddr = tor_malloc(sizeof(struct sockaddr_storage));
1803 listensocklen = tor_addr_to_sockaddr(&port->addr,
1804 real_port,
1805 listensockaddr,
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,
1813 addr_in_use);
1814 tor_free(listensockaddr);
1815 tor_free(address);
1816 } else {
1817 conn = NULL;
1820 return conn;
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.
1830 static int
1831 check_sockaddr(const struct sockaddr *sa, int len, int level)
1833 int ok = 1;
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));
1840 ok = 0;
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.");
1845 ok = 0;
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));
1852 ok = 0;
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.");
1858 ok = 0;
1860 } else if (sa->sa_family == AF_UNIX) {
1861 ok = 1;
1862 } else {
1863 ok = 0;
1865 return ok ? 0 : -1;
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. */
1873 static int
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,
1882 (int)got);
1883 return -1;
1885 return 0;
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.
1891 static int
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);
1916 return 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);
1921 return 0;
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);
1929 return -1;
1931 log_debug(LD_NET,
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");
1942 } else {
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);
1948 return 0;
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);
1956 return 0;
1959 if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6 ||
1960 (conn->socket_family == AF_UNIX && new_type == CONN_TYPE_AP)) {
1961 tor_addr_t addr;
1962 uint16_t port;
1963 if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
1964 log_info(LD_NET,
1965 "accept() returned a strange address; closing connection.");
1966 tor_close_socket(news);
1967 return 0;
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) {
1976 log_notice(LD_APP,
1977 "Denying socks connection from untrusted address %s.",
1978 fmt_and_decorate_addr(&addr));
1979 tor_close_socket(news);
1980 return 0;
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);
1989 return 0;
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);
1997 return 0;
2001 newconn = connection_new(new_type, conn->socket_family);
2002 newconn->s = news;
2004 /* remember the remote address */
2005 tor_addr_copy(&newconn->addr, &addr);
2006 if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
2007 newconn->port = 0;
2008 newconn->address = tor_strdup(conn->address);
2009 } else {
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);
2036 newconn->s = news;
2038 /* remember the remote address -- do we have anything sane to put here? */
2039 tor_addr_make_unspec(&newconn->addr);
2040 newconn->port = 1;
2041 newconn->address = tor_strdup(conn->address);
2042 } else {
2043 tor_assert(0);
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);
2054 return 0;
2057 note_connection(true /* inbound */, conn->socket_family);
2059 return 0;
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)
2075 int rv;
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));
2083 case CONN_TYPE_OR:
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);
2086 if (rv < 0) {
2087 connection_or_close_for_error(TO_OR_CONN(conn), 0);
2089 return rv;
2090 break;
2091 case CONN_TYPE_AP:
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;
2107 break;
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;
2117 break;
2118 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER:
2119 conn->state = AP_CONN_STATE_HTTP_CONNECT_WAIT;
2121 break;
2122 case CONN_TYPE_DIR:
2123 conn->purpose = DIR_PURPOSE_SERVER;
2124 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2125 break;
2126 case CONN_TYPE_CONTROL:
2127 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
2128 break;
2130 return 0;
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,
2141 socklen_t sa_len,
2142 const struct sockaddr *bindaddr,
2143 socklen_t bindaddr_len,
2144 int *socket_error))
2146 tor_socket_t s;
2147 int inprogress = 0;
2148 const or_options_t *options = get_options();
2150 tor_assert(conn);
2151 tor_assert(sa);
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();
2166 return -1;
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
2177 * error or not.
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);
2183 } else {
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);
2188 return -1;
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
2199 * failure.
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);
2208 return -1;
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. */
2219 *socket_error = e;
2220 log_info(LD_NET,
2221 "connect() to socket failed: %s",
2222 tor_socket_strerror(e));
2223 tor_close_socket(s);
2224 return -1;
2225 } else {
2226 inprogress = 1;
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);
2236 conn->s = s;
2237 if (connection_add_connecting(conn) < 0) {
2238 /* no space, forget it */
2239 *socket_error = SOCK_ERRNO(ENOBUFS);
2240 return -1;
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. */
2249 static void
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) {
2257 return;
2260 /* We're only prepared to log OR and DIR connections here */
2261 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR) {
2262 return;
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) {
2291 return;
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 "
2305 "%d).",
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.
2319 const tor_addr_t *
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;
2325 int fam_index;
2326 switch (family) {
2327 case AF_INET:
2328 fam_index = 0;
2329 break;
2330 case AF_INET6:
2331 fam_index = 1;
2332 break;
2333 default:
2334 return 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]
2342 [fam_index];
2343 } else if (!tor_addr_is_null(
2344 &options->OutboundBindAddresses[OUTBOUND_ADDR_ANY]
2345 [fam_index])) {
2346 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_ANY]
2347 [fam_index];
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]
2353 [fam_index];
2354 } else if (!tor_addr_is_null(
2355 &options->OutboundBindAddresses[OUTBOUND_ADDR_ANY]
2356 [fam_index])) {
2357 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_ANY]
2358 [fam_index];
2361 return ext_addr;
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
2370 * a proxy.
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(),
2393 conn->type);
2394 if (ext_addr) {
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) {
2400 log_warn(LD_NET,
2401 "Error converting OutboundBindAddress %s into sockaddr. "
2402 "Ignoring.", fmt_and_decorate_addr(ext_addr));
2403 } else {
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,
2432 int *socket_error)
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)) {
2440 log_warn(LD_NET,
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);
2444 return -1;
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));
2451 log_debug(LD_NET,
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.
2464 static const char *
2465 connection_proxy_state_to_string(int state)
2467 static const char *unknown = "???";
2468 static const char *states[] = {
2469 "PROXY_NONE",
2470 "PROXY_INFANT",
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",
2478 "PROXY_CONNECTED",
2481 CTASSERT(ARRAY_LENGTH(states) == PROXY_CONNECTED+1);
2483 if (state < PROXY_NONE || state > PROXY_CONNECTED)
2484 return unknown;
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.*/
2493 static int
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;
2502 int r;
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;
2519 } else
2520 return PROXY_NONE;
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
2525 username NUL: */
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
2530 * (if available).
2532 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2533 * 0 otherwise.
2535 static int
2536 connection_https_proxy_connect(connection_t *conn)
2538 tor_assert(conn);
2540 const or_options_t *options = get_options();
2541 char buf[1024];
2542 char *base64_authenticator = NULL;
2543 const char *authenticator = options->HTTPSProxyAuthenticator;
2545 /* Send HTTP CONNECT and authentication (if available) in
2546 * one request */
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"
2557 "Host: %s\r\n"
2558 "Proxy-Authorization: Basic %s\r\n\r\n",
2559 addrport,
2560 addrport,
2561 base64_authenticator);
2562 tor_free(base64_authenticator);
2563 } else {
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;
2571 return 0;
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
2577 * 0 otherwise.
2579 static int
2580 connection_socks4_proxy_connect(connection_t *conn)
2582 tor_assert(conn);
2584 unsigned char *buf;
2585 uint16_t portn;
2586 uint32_t ip4addr;
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");
2594 return -1;
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) {
2603 socks_args_string =
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.",
2607 socks_args_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);
2640 } else {
2641 buf[8] = 0; /* no userid */
2644 connection_buf_add((char *)buf, buf_size, conn);
2645 tor_free(buf);
2647 conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
2648 return 0;
2651 /** Write a proxy request of socks5 to conn for conn->addr:conn->port,
2652 * authenticating with the auth details given in the configuration
2653 * (if available).
2655 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2656 * 0 otherwise.
2658 static int
2659 connection_socks5_proxy_connect(connection_t *conn)
2661 tor_assert(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 */
2677 buf[1] = 2;
2678 buf[2] = 0x00; /* no authentication */
2679 buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
2680 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
2681 } else {
2682 buf[1] = 1;
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);
2688 return 0;
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
2694 * 0 otherwise.
2696 static int
2697 connection_haproxy_proxy_connect(connection_t *conn)
2699 int ret = 0;
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);
2703 if (buf == NULL) {
2704 ret = -1;
2705 goto done;
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;
2713 ret = 0;
2714 done:
2715 tor_free(buf);
2716 tor_free(addr_port);
2717 return ret;
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
2726 * 0 otherwise.
2728 * Use connection_read_proxy_handshake() to complete the handshake.
2731 connection_proxy_connect(connection_t *conn, int type)
2733 int ret = 0;
2735 tor_assert(conn);
2737 switch (type) {
2738 case PROXY_CONNECT:
2739 ret = connection_https_proxy_connect(conn);
2740 break;
2742 case PROXY_SOCKS4:
2743 ret = connection_socks4_proxy_connect(conn);
2744 break;
2746 case PROXY_SOCKS5:
2747 ret = connection_socks5_proxy_connect(conn);
2748 break;
2750 case PROXY_HAPROXY:
2751 ret = connection_haproxy_proxy_connect(conn);
2752 break;
2754 default:
2755 log_err(LD_BUG, "Invalid proxy protocol, %d", type);
2756 tor_fragile_assert();
2757 ret = -1;
2758 break;
2761 if (ret == 0) {
2762 log_debug(LD_NET, "set state %s",
2763 connection_proxy_state_to_string(conn->proxy_state));
2766 return ret;
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.
2773 static int
2774 connection_read_https_proxy_response(connection_t *conn)
2776 char *headers;
2777 char *reason=NULL;
2778 int status_code;
2779 time_t date_header;
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.");
2787 return -1;
2788 case 0:
2789 log_info(LD_NET,"https proxy response not all here yet. Waiting.");
2790 return 0;
2791 /* case 1, fall through */
2794 if (parse_http_response(headers, &status_code, &date_header,
2795 NULL, &reason) < 0) {
2796 log_warn(LD_NET,
2797 "Unparseable headers from proxy (%s). Closing.",
2798 connection_describe(conn));
2799 tor_free(headers);
2800 return -1;
2802 tor_free(headers);
2803 if (!reason) reason = tor_strdup("[no reason given]");
2805 if (status_code == 200) {
2806 log_info(LD_NET,
2807 "HTTPS connect for %s successful! (200 %s) Starting TLS.",
2808 connection_describe(conn), escaped(reason));
2809 tor_free(reason);
2810 return 1;
2812 /* else, bad news on the status code */
2813 switch (status_code) {
2814 case 403:
2815 log_warn(LD_NET,
2816 "The https proxy refused to allow connection to %s "
2817 "(status code %d, %s). Closing.",
2818 conn->address, status_code, escaped(reason));
2819 break;
2820 default:
2821 log_warn(LD_NET,
2822 "The https proxy sent back an unexpected status code %d (%s). "
2823 "Closing.",
2824 status_code, escaped(reason));
2825 break;
2827 tor_free(reason);
2828 return -1;
2831 /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
2832 * and <b>conn->port</b> into the request.
2834 static void
2835 connection_send_socks5_connect(connection_t *conn)
2837 unsigned char buf[1024];
2838 size_t reqsize = 6;
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);
2848 buf[3] = 1;
2849 reqsize += 4;
2850 memcpy(buf + 4, &addr, 4);
2851 memcpy(buf + 8, &port, 2);
2852 } else { /* AF_INET6 */
2853 buf[3] = 4;
2854 reqsize += 16;
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. */
2866 static int
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
2874 * handshake.
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
2881 * on error.
2884 connection_read_proxy_handshake(connection_t *conn)
2886 int ret = 0;
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);
2895 if (ret == 1)
2896 conn->proxy_state = PROXY_CONNECTED;
2897 break;
2899 case PROXY_SOCKS4_WANT_CONNECT_OK:
2900 ret = connection_fetch_from_buf_socks_client(conn,
2901 conn->proxy_state,
2902 &reason);
2903 if (ret == 1)
2904 conn->proxy_state = PROXY_CONNECTED;
2905 break;
2907 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
2908 ret = connection_fetch_from_buf_socks_client(conn,
2909 conn->proxy_state,
2910 &reason);
2911 /* no auth needed, do connect */
2912 if (ret == 1) {
2913 connection_send_socks5_connect(conn);
2914 ret = 0;
2916 break;
2918 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
2919 ret = connection_fetch_from_buf_socks_client(conn,
2920 conn->proxy_state,
2921 &reason);
2923 /* send auth if needed, otherwise do connect */
2924 if (ret == 1) {
2925 connection_send_socks5_connect(conn);
2926 ret = 0;
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) {
2934 socks_args_string =
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.");
2938 ret = -1;
2939 break;
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;
2951 } else {
2952 user = socks_args_string;
2953 usize = strlen(socks_args_string);
2954 pass = "\0";
2955 psize = 1;
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);
2963 } else {
2964 log_err(LD_BUG, "We entered %s for no reason!", __func__);
2965 tor_fragile_assert();
2966 ret = -1;
2967 break;
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 */
2977 buf[1] = usize;
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;
2988 ret = 0;
2990 break;
2992 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
2993 ret = connection_fetch_from_buf_socks_client(conn,
2994 conn->proxy_state,
2995 &reason);
2996 /* send the connect request */
2997 if (ret == 1) {
2998 connection_send_socks5_connect(conn);
2999 ret = 0;
3001 break;
3003 case PROXY_SOCKS5_WANT_CONNECT_OK:
3004 ret = connection_fetch_from_buf_socks_client(conn,
3005 conn->proxy_state,
3006 &reason);
3007 if (ret == 1)
3008 conn->proxy_state = PROXY_CONNECTED;
3009 break;
3011 default:
3012 log_err(LD_BUG, "Invalid proxy_state for reading, %d",
3013 conn->proxy_state);
3014 tor_fragile_assert();
3015 ret = -1;
3016 break;
3019 log_debug(LD_NET, "leaving state %s",
3020 connection_proxy_state_to_string(conn->proxy_state));
3022 if (ret < 0) {
3023 if (reason) {
3024 log_warn(LD_NET, "Proxy Client: unable to connect %s (%s)",
3025 connection_describe(conn), escaped(reason));
3026 tor_free(reason);
3027 } else {
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));
3036 return ret;
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
3051 * old_conns.
3053 * Return 0 on success, -1 on failure.
3055 static int
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
3063 (void)replacements;
3064 #endif
3066 smartlist_t *launch = smartlist_new();
3067 int r = 0;
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);
3074 } else {
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)
3091 continue;
3092 if ((conn->socket_family != AF_UNIX && wanted->is_unix_addr) ||
3093 (conn->socket_family == AF_UNIX && ! wanted->is_unix_addr))
3094 continue;
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;
3103 break;
3105 } else {
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;
3116 break;
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);
3142 break;
3144 #endif /* defined(ENABLE_LISTENER_REBIND) */
3146 } SMARTLIST_FOREACH_END(wanted);
3148 if (found_port) {
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) {
3160 int skip = 0;
3161 connection_t *conn = connection_listener_new_for_port(port, &skip, NULL);
3163 if (conn && new_conns)
3164 smartlist_add(new_conns, conn);
3165 else if (!skip)
3166 r = -1;
3167 } SMARTLIST_FOREACH_END(port);
3169 smartlist_free(launch);
3171 return r;
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
3176 * want.
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();
3189 int retval = 0;
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(),
3202 new_conns,
3203 replacements,
3204 close_all_noncontrol) < 0)
3205 retval = -1;
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;
3214 int skip = 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;
3223 if (skip) {
3224 log_debug(LD_NET, "Skipping creating new listener for %s",
3225 connection_describe(old_conn));
3226 continue;
3229 connection_close_immediate(old_conn);
3230 connection_mark_for_close(old_conn);
3232 if (addr_in_use) {
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. */
3239 if (!new_conn) {
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);
3242 retval = -1;
3243 break;
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 "
3250 "(replaced by %s)",
3251 old_desc, connection_describe(new_conn));
3252 tor_free(old_desc);
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");
3281 return retval;
3284 /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
3285 void
3286 connection_mark_all_noncontrol_listeners(void)
3288 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
3289 if (conn->marked_for_close)
3290 continue;
3291 if (conn->type == CONN_TYPE_CONTROL_LISTENER)
3292 continue;
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. */
3299 void
3300 connection_mark_all_noncontrol_connections(void)
3302 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
3303 if (conn->marked_for_close)
3304 continue;
3305 switch (conn->type) {
3306 case CONN_TYPE_CONTROL_LISTENER:
3307 case CONN_TYPE_CONTROL:
3308 break;
3309 case CONN_TYPE_AP:
3310 connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
3311 END_STREAM_REASON_HIBERNATING);
3312 break;
3313 case CONN_TYPE_OR:
3315 or_connection_t *orconn = TO_OR_CONN(conn);
3316 if (orconn->chan) {
3317 connection_or_close_normally(orconn, 0);
3318 } else {
3320 * There should have been one, but mark for close and hope
3321 * for the best..
3323 connection_mark_for_close(conn);
3326 break;
3327 default:
3328 connection_mark_for_close(conn);
3329 break;
3331 } SMARTLIST_FOREACH_END(conn);
3334 /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
3335 * otherwise.
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. */
3340 static int
3341 connection_is_rate_limited(const connection_t *conn)
3343 const or_options_t *options = get_options();
3344 if (conn->linked)
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 */
3352 else
3353 return 1;
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
3358 * usage. */
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.
3369 static int
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)
3375 return 1;
3376 if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
3377 return 1;
3378 return 0;
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. */
3386 static ssize_t
3387 connection_bucket_get_share(int base, int priority,
3388 ssize_t global_bucket_val, ssize_t conn_bucket)
3390 ssize_t at_most;
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;
3410 if (at_most < 0)
3411 return 0;
3412 return at_most;
3415 /** How many bytes at most can we read onto this connection? */
3416 static ssize_t
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? */
3446 ssize_t
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 */
3456 return conn_bucket;
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
3482 * always returned.
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.
3496 bool
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. */
3508 return false;
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)) {
3514 return false;
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;
3526 if (diff <= 1)
3527 return true; /* we're already hitting our limits, no more please */
3529 return false;
3532 /** When did we last tell the accounting subsystem about transmitted
3533 * bandwidth? */
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>. */
3539 static void
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) {
3545 if (num_read > 0)
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
3552 * accounting:
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
3558 * internal bytes.
3560 if (!connection_is_rate_limited(conn))
3561 return;
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);
3568 if (num_read > 0) {
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));
3585 } else {
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. */
3594 static void
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)
3606 num_written = 1;
3607 if (num_read >= INT_MAX)
3608 num_read = 1;
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 */
3616 unsigned flags = 0;
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.
3637 void
3638 connection_read_bw_exhausted(connection_t *conn, bool is_global_bw)
3640 (void)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.
3652 void
3653 connection_write_bw_exhausted(connection_t *conn, bool is_global_bw)
3655 (void)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,
3662 * stop reading. */
3663 void
3664 connection_consider_empty_read_buckets(connection_t *conn)
3666 const char *reason;
3668 if (!connection_is_rate_limited(conn))
3669 return; /* Always okay. */
3671 int is_global = 1;
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.";
3682 is_global = false;
3683 } else
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,
3691 * stop writing. */
3692 void
3693 connection_consider_empty_write_buckets(connection_t *conn)
3695 const char *reason;
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.";
3710 is_global = false;
3711 } else
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
3719 * options */
3720 void
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,
3728 now_ts);
3729 if (options->RelayBandwidthRate) {
3730 token_bucket_rw_init(&global_relayed_bucket,
3731 (int32_t)options->RelayBandwidthRate,
3732 (int32_t)options->RelayBandwidthBurst,
3733 now_ts);
3734 } else {
3735 token_bucket_rw_init(&global_relayed_bucket,
3736 (int32_t)options->BandwidthRate,
3737 (int32_t)options->BandwidthBurst,
3738 now_ts);
3741 reenable_blocked_connection_init(options);
3744 /** Update the global connection bucket settings to a new value. */
3745 void
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);
3755 } else {
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
3764 * global buckets.
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.
3772 static void
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
3777 * need to. */
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
3792 * write.
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.
3807 static void
3808 reenable_blocked_connections_cb(mainloop_event_t *ev, void *arg)
3810 (void)ev;
3811 (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.
3830 static void
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
3847 * scheduled.
3849 static void
3850 reenable_blocked_connection_schedule(void)
3852 if (reenable_blocked_connections_is_scheduled)
3853 return;
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
3868 * return 0.
3870 static int
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();
3903 return 0;
3906 loop_again:
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),
3915 socket_error != 0 ?
3916 errno_to_orconn_end_reason(socket_error) :
3917 END_OR_CONN_REASON_CONNRESET,
3918 socket_error != 0 ?
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);
3936 return -1;
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) {
3942 return -1;
3944 if (!conn->marked_for_close &&
3945 connection_is_reading(conn) &&
3946 !conn->inbuf_reached_eof &&
3947 max_to_read > 0)
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) {
3953 return -1;
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;
3960 if (n_read) {
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) {
3981 return -1;
3983 return 0;
3986 /* DOCDOC connection_handle_read */
3988 connection_handle_read(connection_t *conn)
3990 int res;
3991 update_current_time(time(NULL));
3992 res = connection_handle_read_impl(conn);
3993 return res;
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
3998 * read.
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.
4006 static int
4007 connection_buf_read_from_socket(connection_t *conn, ssize_t *max_to_read,
4008 int *socket_error)
4010 int result;
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) {
4023 at_most = maximum;
4026 slack_in_buf = buf_slack(conn->inbuf);
4027 again:
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;
4031 } else {
4032 more_to_read = 0;
4035 if (connection_speaks_cells(conn) &&
4036 conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
4037 int pending;
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);
4046 log_debug(LD_NET,
4047 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
4048 " at_most %ld.",
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;
4057 else
4058 or_conn->tls_error = 0;
4060 switch (result) {
4061 case TOR_TLS_CLOSE:
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 " : "");
4066 return result;
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));
4071 return result;
4072 case TOR_TLS_WANTWRITE:
4073 connection_start_writing(conn);
4074 return 0;
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 */
4088 break;
4089 case TOR_TLS_DONE: /* no data read, so nothing to process */
4090 break; /* so we call bucket_decrement below */
4091 default:
4092 break;
4094 pending = tor_tls_get_pending_bytes(or_conn->tls);
4095 if (pending) {
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);
4100 if (BUG(r2<0)) {
4101 log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
4102 return -1;
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);
4112 } else {
4113 result = 0;
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;
4124 } else {
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,
4129 at_most,
4130 &reached_eof,
4131 socket_error));
4132 if (reached_eof)
4133 conn->inbuf_reached_eof = 1;
4135 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
4137 if (result < 0)
4138 return -1;
4139 n_read = (size_t) result;
4142 if (n_read > 0) {
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,
4151 n_read);
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;
4161 else
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;
4173 else
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;
4183 goto again;
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);
4193 return 0;
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,
4206 size_t *data_len)
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
4212 * appropriate. */
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
4242 * hint from the OS.
4244 * This should help fix slow upload rates.
4246 static void
4247 update_send_buffer_size(tor_socket_t sock)
4249 #ifdef _WIN32
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) {
4255 isVistaOr7 = 0;
4256 OSVERSIONINFO osvi = { 0 };
4257 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
4258 GetVersionEx(&osvi);
4259 if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion < 2)
4260 isVistaOr7 = 1;
4262 if (!isVistaOr7)
4263 return;
4264 if (get_options()->ConstrainedSockets)
4265 return;
4266 ULONG isb = 0;
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) */
4273 (void) sock;
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
4286 * on it too.
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
4290 * errors.)
4292 * Mark the connection and return -1 if you want to close it, else
4293 * return 0.
4295 static int
4296 connection_handle_write_impl(connection_t *conn, int force)
4298 int e;
4299 socklen_t len=(socklen_t)sizeof(e);
4300 int result;
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");
4313 return 0;
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);
4327 } else {
4328 if (CONN_IS_EDGE(conn)) {
4329 connection_edge_end_errno(TO_EDGE_CONN(conn));
4331 connection_mark_for_close(conn);
4333 return -1;
4335 if (e) {
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);
4353 return -1;
4354 } else {
4355 return 0; /* no change, see if next time is better */
4358 /* The connection is successful. */
4359 if (connection_finished_connecting(conn)<0)
4360 return -1;
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);
4385 return -1;
4387 return 0;
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,
4395 max_to_write);
4397 if (result >= 0)
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));
4406 switch (result) {
4407 CASE_TOR_TLS_ERROR_ANY:
4408 case TOR_TLS_CLOSE:
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);
4424 return -1;
4425 case TOR_TLS_WANTWRITE:
4426 log_debug(LD_NET,"wanted write.");
4427 /* we're already writing */
4428 dont_stop_writing = 1;
4429 break;
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 */
4440 return 0;
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
4456 * or something. */
4457 result = (int)(initial_size-buf_datalen(conn->outbuf));
4458 } else {
4459 CONN_LOG_PROTECT(conn,
4460 result = buf_flush_to_socket(conn->outbuf, conn->s,
4461 max_to_write));
4462 if (result < 0) {
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);
4472 return -1;
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;
4484 else
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;
4496 else
4497 conn->n_written_conn_bw = UINT32_MAX;
4500 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
4502 if (result > 0) {
4503 /* If we wrote any bytes from our buffer, then call the appropriate
4504 * functions. */
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 */
4525 return -1;
4527 return 0;
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);
4537 return 0;
4540 /* DOCDOC connection_handle_write */
4542 connection_handle_write(connection_t *conn, int force)
4544 int res;
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
4548 * flag set. */
4549 conn->in_connection_handle_write = 1;
4550 res = connection_handle_write_impl(conn, force);
4551 conn->in_connection_handle_write = 0;
4552 return res;
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
4573 * writing.
4575 static int
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)
4580 return 0;
4582 return 1;
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.
4590 static void
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. */
4596 log_warn(LD_NET,
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);
4602 log_warn(LD_NET,
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);
4606 } else {
4607 log_warn(LD_NET,
4608 "write_to_buf failed. Closing connection (fd %d).",
4609 (int)conn->s);
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.
4619 static void
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.
4639 MOCK_IMPL(void,
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. */
4644 int r;
4645 if (!len && !(zlib<0))
4646 return;
4648 if (!connection_may_write_to_buf(conn))
4649 return;
4651 if (zlib) {
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));
4657 } else {
4658 CONN_LOG_PROTECT(conn, r = buf_add(conn->outbuf, string, len));
4660 if (r < 0) {
4661 connection_write_to_buf_failed(conn);
4662 return;
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.
4672 void
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);
4678 return;
4681 connection_buf_add(string, len, TO_CONN(dir_conn));
4684 void
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.)
4696 void
4697 connection_buf_add_buf(connection_t *conn, buf_t *buf)
4699 tor_assert(conn);
4700 tor_assert(buf);
4701 size_t len = buf_datalen(buf);
4702 if (len == 0)
4703 return;
4705 if (!connection_may_write_to_buf(conn))
4706 return;
4708 buf_move_all(conn->outbuf, buf);
4709 connection_write_to_buf_commit(conn);
4712 #define CONN_GET_ALL_TEMPLATE(var, test) \
4713 STMT_BEGIN \
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); \
4720 return ret_conns; \
4721 STMT_END
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. */
4727 smartlist_t *
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. */
4737 smartlist_t *
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) \
4747 STMT_BEGIN \
4748 smartlist_t *conns = get_connection_array(); \
4749 SMARTLIST_FOREACH(conns, connection_t *, var, \
4751 if (var && (test) && !var->marked_for_close) \
4752 return var; \
4753 }); \
4754 return NULL; \
4755 STMT_END
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
4759 * for close). */
4760 MOCK_IMPL(connection_t *,
4761 connection_get_by_type_addr_port_purpose,(int type,
4762 const tor_addr_t *addr, uint16_t port,
4763 int purpose))
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
4773 * close.
4775 connection_t *
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.
4783 connection_t *
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.
4792 connection_t *
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.
4812 connection_t *
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) \
4842 STMT_BEGIN \
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); \
4855 return dir_conns; \
4856 STMT_END
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. */
4864 smartlist_t *
4865 connection_dir_list_by_purpose_and_resource(
4866 int purpose,
4867 const char *resource)
4869 DIR_CONN_LIST_TEMPLATE(conn,
4870 conn->purpose == purpose,
4871 dirconn,
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. */
4882 smartlist_t *
4883 connection_dir_list_by_purpose_resource_and_state(
4884 int purpose,
4885 const char *resource,
4886 int state)
4888 DIR_CONN_LIST_TEMPLATE(conn,
4889 conn->purpose == purpose && conn->state == state,
4890 dirconn,
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
4909 * <b>this_conn</b>.
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);
4917 if (conn != NULL) {
4918 log_debug(LD_DIR, "%s: Found an OR connection: %s",
4919 __func__, connection_describe(conn));
4920 return 1;
4923 return 0;
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)
4941 return 1;
4942 return 0;
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)
4951 tor_assert(conn);
4953 if (conn->marked_for_close)
4954 return 0;
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))
4962 return 1;
4964 return 0;
4967 /** Return 1 if conn is in 'connecting' state, else return 0. */
4969 connection_state_is_connecting(connection_t *conn)
4971 tor_assert(conn);
4973 if (conn->marked_for_close)
4974 return 0;
4975 switch (conn->type)
4977 case CONN_TYPE_OR:
4978 return conn->state == OR_CONN_STATE_CONNECTING;
4979 case CONN_TYPE_EXIT:
4980 return conn->state == EXIT_CONN_STATE_CONNECTING;
4981 case CONN_TYPE_DIR:
4982 return conn->state == DIR_CONN_STATE_CONNECTING;
4985 return 0;
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. */
4991 char *
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,
5010 * call init_keys().
5012 static void
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;
5017 sa_family_t family;
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));
5026 return;
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;
5034 else
5035 return;
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;
5041 } else {
5042 tor_free(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))
5049 return;
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)
5055 return;
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)));
5060 } else {
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.
5082 static void
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.
5105 static int
5106 connection_process_inbuf(connection_t *conn, int package_partial)
5108 tor_assert(conn);
5110 switch (conn->type) {
5111 case CONN_TYPE_OR:
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:
5116 case CONN_TYPE_AP:
5117 return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
5118 package_partial);
5119 case CONN_TYPE_DIR:
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);
5125 default:
5126 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5127 tor_fragile_assert();
5128 return -1;
5132 /** Called whenever we've written data on a connection. */
5133 static int
5134 connection_flushed_some(connection_t *conn)
5136 int r = 0;
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;
5148 return r;
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.
5158 static int
5159 connection_finished_flushing(connection_t *conn)
5161 tor_assert(conn);
5163 /* If the connection is closed, don't try to do anything more here. */
5164 if (CONN_IS_CLOSED(conn))
5165 return 0;
5167 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
5169 connection_stop_writing(conn);
5171 switch (conn->type) {
5172 case CONN_TYPE_OR:
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));
5176 case CONN_TYPE_AP:
5177 case CONN_TYPE_EXIT:
5178 return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
5179 case CONN_TYPE_DIR:
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));
5183 default:
5184 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5185 tor_fragile_assert();
5186 return -1;
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.
5196 static int
5197 connection_finished_connecting(connection_t *conn)
5199 tor_assert(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);
5208 switch (conn->type)
5210 case CONN_TYPE_OR:
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));
5214 case CONN_TYPE_DIR:
5215 return connection_dir_finished_connecting(TO_DIR_CONN(conn));
5216 default:
5217 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5218 tor_fragile_assert();
5219 return -1;
5223 /** Callback: invoked when a connection reaches an EOF event. */
5224 static int
5225 connection_reached_eof(connection_t *conn)
5227 switch (conn->type) {
5228 case CONN_TYPE_OR:
5229 case CONN_TYPE_EXT_OR:
5230 return connection_or_reached_eof(TO_OR_CONN(conn));
5231 case CONN_TYPE_AP:
5232 case CONN_TYPE_EXIT:
5233 return connection_edge_reached_eof(TO_EDGE_CONN(conn));
5234 case CONN_TYPE_DIR:
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);
5240 default:
5241 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5242 tor_fragile_assert();
5243 return -1;
5247 /** Comparator for the two-orconn case in OOS victim sort */
5248 static int
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;
5259 else return 0;
5262 /** Sort comparator for OOS victims; better targets sort before worse
5263 * ones. */
5264 static int
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));
5283 } else {
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;
5290 else return 0;
5294 /** Pick n victim connections for the OOS handler and return them in a
5295 * smartlist.
5297 MOCK_IMPL(STATIC smartlist_t *,
5298 pick_oos_victims, (int n))
5300 smartlist_t *eligible = NULL, *victims = NULL;
5301 smartlist_t *conns;
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
5325 * along the way.
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))) {
5336 continue;
5339 /* Skip anything we would count as moribund */
5340 if (connection_is_moribund(c)) {
5341 continue;
5344 switch (c->type) {
5345 case CONN_TYPE_OR:
5346 /* We've got an orconn, it's eligible to be OOSed */
5347 smartlist_add(eligible, c);
5348 break;
5349 default:
5350 /* We don't know what to do with it, ignore it */
5351 break;
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);
5381 } else {
5382 /* No, we can just call them all victims */
5383 victims = eligible;
5386 return 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))
5393 if (!conns) return;
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);
5399 } else {
5400 connection_mark_for_close(c);
5402 } SMARTLIST_FOREACH_END(c);
5404 log_notice(LD_NET,
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)
5414 if (conn != NULL &&
5415 (conn->conn_array_index < 0 ||
5416 conn->marked_for_close)) {
5417 return 1;
5418 } else {
5419 return 0;
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.
5428 void
5429 connection_check_oos(int n_socks, int failed)
5431 int target_n_socks = 0, moribund_socks, socks_to_kill;
5432 smartlist_t *conns;
5434 /* Early exit: is OOS checking disabled? */
5435 if (get_options()->DisableOOSCheck) {
5436 return;
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.
5446 log_debug(LD_NET,
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;
5461 log_notice(LD_NET,
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,
5465 target_n_socks);
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;
5473 log_notice(LD_NET,
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) {
5481 * It's an OOS!
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);
5494 if (conns) {
5495 kill_conn_list_for_oos(conns);
5496 log_notice(LD_NET,
5497 "OOS handler killed %d conns", smartlist_len(conns));
5498 smartlist_free(conns);
5499 } else {
5500 log_notice(LD_NET, "OOS handler failed to pick any victim conns");
5502 } else {
5503 log_notice(LD_NET,
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. */
5512 void
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;
5520 int i;
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) {
5528 int tp = c->type;
5529 ++n_conns_by_type[tp];
5530 if (c->inbuf) {
5531 used_by_type[tp] += buf_datalen(c->inbuf);
5532 alloc_by_type[tp] += buf_allocation(c->inbuf);
5534 if (c->outbuf) {
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])
5550 continue;
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.
5561 void
5562 assert_connection_ok(connection_t *conn, time_t now)
5564 (void) now; /* XXXX unused. */
5565 tor_assert(conn);
5566 tor_assert(conn->type >= CONN_TYPE_MIN_);
5567 tor_assert(conn->type <= CONN_TYPE_MAX_);
5569 switch (conn->type) {
5570 case CONN_TYPE_OR:
5571 case CONN_TYPE_EXT_OR:
5572 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
5573 break;
5574 case CONN_TYPE_AP:
5575 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
5576 break;
5577 case CONN_TYPE_EXIT:
5578 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
5579 break;
5580 case CONN_TYPE_DIR:
5581 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
5582 break;
5583 case CONN_TYPE_CONTROL:
5584 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
5585 break;
5586 CASE_ANY_LISTENER_TYPE:
5587 tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
5588 break;
5589 default:
5590 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
5591 break;
5594 if (conn->linked_conn) {
5595 tor_assert(conn->linked_conn->linked_conn == conn);
5596 tor_assert(conn->linked);
5598 if (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. */
5607 /* buffers */
5608 if (conn->inbuf)
5609 buf_assert_ok(conn->inbuf);
5610 if (conn->outbuf)
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) {
5651 } else {
5652 /* Purpose is only used for dir and exit types currently */
5653 tor_assert(!conn->purpose);
5656 switch (conn->type)
5658 CASE_ANY_LISTENER_TYPE:
5659 tor_assert(conn->state == LISTENER_STATE_READY);
5660 break;
5661 case CONN_TYPE_OR:
5662 tor_assert(conn->state >= OR_CONN_STATE_MIN_);
5663 tor_assert(conn->state <= OR_CONN_STATE_MAX_);
5664 break;
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_);
5668 break;
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_);
5674 break;
5675 case CONN_TYPE_AP:
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);
5679 break;
5680 case CONN_TYPE_DIR:
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_);
5685 break;
5686 case CONN_TYPE_CONTROL:
5687 tor_assert(conn->state >= CONTROL_CONN_STATE_MIN_);
5688 tor_assert(conn->state <= CONTROL_CONN_STATE_MAX_);
5689 break;
5690 case CONN_TYPE_METRICS:
5691 /* No state. */
5692 break;
5693 default:
5694 tor_assert(0);
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();
5712 *is_pt_out = 0;
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;
5720 int r;
5721 r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
5722 if (r<0)
5723 return -1;
5724 if (transport) { /* transport found */
5725 tor_addr_copy(addr, &transport->addr);
5726 *port = transport->port;
5727 *proxy_type = transport->socks_version;
5728 *is_pt_out = 1;
5729 return 0;
5732 /* Unused ClientTransportPlugin. */
5735 if (options->HTTPSProxy) {
5736 tor_addr_copy(addr, &options->HTTPSProxyAddr);
5737 *port = options->HTTPSProxyPort;
5738 *proxy_type = PROXY_CONNECT;
5739 return 0;
5740 } else if (options->Socks4Proxy) {
5741 tor_addr_copy(addr, &options->Socks4ProxyAddr);
5742 *port = options->Socks4ProxyPort;
5743 *proxy_type = PROXY_SOCKS4;
5744 return 0;
5745 } else if (options->Socks5Proxy) {
5746 tor_addr_copy(addr, &options->Socks5ProxyAddr);
5747 *port = options->Socks5ProxyPort;
5748 *proxy_type = PROXY_SOCKS5;
5749 return 0;
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;
5756 return 0;
5759 tor_addr_make_unspec(addr);
5760 *port = 0;
5761 *proxy_type = PROXY_NONE;
5762 return 0;
5765 /** Log a failed connection to a proxy server.
5766 * <b>conn</b> is the connection we use the proxy server for. */
5767 void
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,
5775 conn) != 0)
5776 return; /* if we have no proxy set up, leave this function. */
5778 (void)is_pt;
5779 log_warn(LD_NET,
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>. */
5787 static const char *
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
5806 * fail.
5808 void
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
5847 * severity.
5849 MOCK_IMPL(void,
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))
5854 char dbuf[64];
5855 char *ext_source = NULL, *warn = NULL;
5856 format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
5857 if (conn)
5858 tor_asprintf(&ext_source, "%s:%s:%d", source,
5859 fmt_and_decorate_addr(&conn->addr), conn->port);
5860 else
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");
5870 if (trusted) {
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,
5874 received, source);
5875 control_event_bootstrap_problem(warn, "CLOCK_SKEW", conn, 1);
5877 tor_free(warn);
5878 tor_free(ext_source);