Cache control file
[tor/appveyor.git] / src / or / connection.c
blob5532551cfe069328d4df9c3d9cf2182ad927a9e1
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-2017, 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 "or.h"
59 #include "bridges.h"
60 #include "buffers.h"
61 #include "buffers_tls.h"
63 * Define this so we get channel internal functions, since we're implementing
64 * part of a subclass (channel_tls_t).
66 #define TOR_CHANNEL_INTERNAL_
67 #define CONNECTION_PRIVATE
68 #include "backtrace.h"
69 #include "channel.h"
70 #include "channeltls.h"
71 #include "circuitbuild.h"
72 #include "circuitlist.h"
73 #include "circuituse.h"
74 #include "config.h"
75 #include "connection.h"
76 #include "connection_edge.h"
77 #include "connection_or.h"
78 #include "control.h"
79 #include "directory.h"
80 #include "dirserv.h"
81 #include "dns.h"
82 #include "dnsserv.h"
83 #include "dos.h"
84 #include "entrynodes.h"
85 #include "ext_orport.h"
86 #include "geoip.h"
87 #include "main.h"
88 #include "hs_common.h"
89 #include "hs_ident.h"
90 #include "nodelist.h"
91 #include "proto_http.h"
92 #include "proto_socks.h"
93 #include "policies.h"
94 #include "reasons.h"
95 #include "relay.h"
96 #include "rendclient.h"
97 #include "rendcommon.h"
98 #include "rephist.h"
99 #include "router.h"
100 #include "routerlist.h"
101 #include "transports.h"
102 #include "routerparse.h"
103 #include "sandbox.h"
105 #ifdef HAVE_PWD_H
106 #include <pwd.h>
107 #endif
109 #ifdef HAVE_SYS_UN_H
110 #include <sys/socket.h>
111 #include <sys/un.h>
112 #endif
114 static connection_t *connection_listener_new(
115 const struct sockaddr *listensockaddr,
116 socklen_t listensocklen, int type,
117 const char *address,
118 const port_cfg_t *portcfg);
119 static void connection_init(time_t now, connection_t *conn, int type,
120 int socket_family);
121 static int connection_handle_listener_read(connection_t *conn, int new_type);
122 static int connection_bucket_should_increase(int bucket,
123 or_connection_t *conn);
124 static int connection_finished_flushing(connection_t *conn);
125 static int connection_flushed_some(connection_t *conn);
126 static int connection_finished_connecting(connection_t *conn);
127 static int connection_reached_eof(connection_t *conn);
128 static int connection_buf_read_from_socket(connection_t *conn,
129 ssize_t *max_to_read,
130 int *socket_error);
131 static int connection_process_inbuf(connection_t *conn, int package_partial);
132 static void client_check_address_changed(tor_socket_t sock);
133 static void set_constrained_socket_buffers(tor_socket_t sock, int size);
135 static const char *connection_proxy_state_to_string(int state);
136 static int connection_read_https_proxy_response(connection_t *conn);
137 static void connection_send_socks5_connect(connection_t *conn);
138 static const char *proxy_type_to_string(int proxy_type);
139 static int get_proxy_type(void);
140 const tor_addr_t *conn_get_outbound_address(sa_family_t family,
141 const or_options_t *options, unsigned int conn_type);
143 /** The last addresses that our network interface seemed to have been
144 * binding to. We use this as one way to detect when our IP changes.
146 * XXXX+ We should really use the entire list of interfaces here.
148 static tor_addr_t *last_interface_ipv4 = NULL;
149 /* DOCDOC last_interface_ipv6 */
150 static tor_addr_t *last_interface_ipv6 = NULL;
151 /** A list of tor_addr_t for addresses we've used in outgoing connections.
152 * Used to detect IP address changes. */
153 static smartlist_t *outgoing_addrs = NULL;
155 #define CASE_ANY_LISTENER_TYPE \
156 case CONN_TYPE_OR_LISTENER: \
157 case CONN_TYPE_EXT_OR_LISTENER: \
158 case CONN_TYPE_AP_LISTENER: \
159 case CONN_TYPE_DIR_LISTENER: \
160 case CONN_TYPE_CONTROL_LISTENER: \
161 case CONN_TYPE_AP_TRANS_LISTENER: \
162 case CONN_TYPE_AP_NATD_LISTENER: \
163 case CONN_TYPE_AP_DNS_LISTENER: \
164 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER
166 /**************************************************************/
169 * Return the human-readable name for the connection type <b>type</b>
171 const char *
172 conn_type_to_string(int type)
174 static char buf[64];
175 switch (type) {
176 case CONN_TYPE_OR_LISTENER: return "OR listener";
177 case CONN_TYPE_OR: return "OR";
178 case CONN_TYPE_EXIT: return "Exit";
179 case CONN_TYPE_AP_LISTENER: return "Socks listener";
180 case CONN_TYPE_AP_TRANS_LISTENER:
181 return "Transparent pf/netfilter listener";
182 case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
183 case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
184 case CONN_TYPE_AP: return "Socks";
185 case CONN_TYPE_DIR_LISTENER: return "Directory listener";
186 case CONN_TYPE_DIR: return "Directory";
187 case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
188 case CONN_TYPE_CONTROL: return "Control";
189 case CONN_TYPE_EXT_OR: return "Extended OR";
190 case CONN_TYPE_EXT_OR_LISTENER: return "Extended OR listener";
191 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER: return "HTTP tunnel listener";
192 default:
193 log_warn(LD_BUG, "unknown connection type %d", type);
194 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
195 return buf;
200 * Return the human-readable name for the connection state <b>state</b>
201 * for the connection type <b>type</b>
203 const char *
204 conn_state_to_string(int type, int state)
206 static char buf[96];
207 switch (type) {
208 CASE_ANY_LISTENER_TYPE:
209 if (state == LISTENER_STATE_READY)
210 return "ready";
211 break;
212 case CONN_TYPE_OR:
213 switch (state) {
214 case OR_CONN_STATE_CONNECTING: return "connect()ing";
215 case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
216 case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
217 case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
218 return "renegotiating (TLS, v2 handshake)";
219 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
220 return "waiting for renegotiation or V3 handshake";
221 case OR_CONN_STATE_OR_HANDSHAKING_V2:
222 return "handshaking (Tor, v2 handshake)";
223 case OR_CONN_STATE_OR_HANDSHAKING_V3:
224 return "handshaking (Tor, v3 handshake)";
225 case OR_CONN_STATE_OPEN: return "open";
227 break;
228 case CONN_TYPE_EXT_OR:
229 switch (state) {
230 case EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE:
231 return "waiting for authentication type";
232 case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE:
233 return "waiting for client nonce";
234 case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH:
235 return "waiting for client hash";
236 case EXT_OR_CONN_STATE_OPEN: return "open";
237 case EXT_OR_CONN_STATE_FLUSHING: return "flushing final OKAY";
239 break;
240 case CONN_TYPE_EXIT:
241 switch (state) {
242 case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
243 case EXIT_CONN_STATE_CONNECTING: return "connecting";
244 case EXIT_CONN_STATE_OPEN: return "open";
245 case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
247 break;
248 case CONN_TYPE_AP:
249 switch (state) {
250 case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
251 case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
252 case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
253 case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
254 case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
255 case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
256 case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
257 case AP_CONN_STATE_OPEN: return "open";
259 break;
260 case CONN_TYPE_DIR:
261 switch (state) {
262 case DIR_CONN_STATE_CONNECTING: return "connecting";
263 case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
264 case DIR_CONN_STATE_CLIENT_READING: return "client reading";
265 case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
266 case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
267 case DIR_CONN_STATE_SERVER_WRITING: return "writing";
269 break;
270 case CONN_TYPE_CONTROL:
271 switch (state) {
272 case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
273 case CONTROL_CONN_STATE_NEEDAUTH:
274 return "waiting for authentication (protocol v1)";
276 break;
279 log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
280 tor_snprintf(buf, sizeof(buf),
281 "unknown state [%d] on unknown [%s] connection",
282 state, conn_type_to_string(type));
283 return buf;
286 /** Allocate and return a new dir_connection_t, initialized as by
287 * connection_init(). */
288 dir_connection_t *
289 dir_connection_new(int socket_family)
291 dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
292 connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
293 return dir_conn;
296 /** Allocate and return a new or_connection_t, initialized as by
297 * connection_init().
299 * Initialize active_circuit_pqueue.
301 * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
303 or_connection_t *
304 or_connection_new(int type, int socket_family)
306 or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
307 time_t now = time(NULL);
308 tor_assert(type == CONN_TYPE_OR || type == CONN_TYPE_EXT_OR);
309 connection_init(now, TO_CONN(or_conn), type, socket_family);
311 connection_or_set_canonical(or_conn, 0);
313 if (type == CONN_TYPE_EXT_OR)
314 connection_or_set_ext_or_identifier(or_conn);
316 return or_conn;
319 /** Allocate and return a new entry_connection_t, initialized as by
320 * connection_init().
322 * Allocate space to store the socks_request.
324 entry_connection_t *
325 entry_connection_new(int type, int socket_family)
327 entry_connection_t *entry_conn = tor_malloc_zero(sizeof(entry_connection_t));
328 tor_assert(type == CONN_TYPE_AP);
329 connection_init(time(NULL), ENTRY_TO_CONN(entry_conn), type, socket_family);
330 entry_conn->socks_request = socks_request_new();
331 /* If this is coming from a listener, we'll set it up based on the listener
332 * in a little while. Otherwise, we're doing this as a linked connection
333 * of some kind, and we should set it up here based on the socket family */
334 if (socket_family == AF_INET)
335 entry_conn->entry_cfg.ipv4_traffic = 1;
336 else if (socket_family == AF_INET6)
337 entry_conn->entry_cfg.ipv6_traffic = 1;
338 return entry_conn;
341 /** Allocate and return a new edge_connection_t, initialized as by
342 * connection_init(). */
343 edge_connection_t *
344 edge_connection_new(int type, int socket_family)
346 edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
347 tor_assert(type == CONN_TYPE_EXIT);
348 connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
349 return edge_conn;
352 /** Allocate and return a new control_connection_t, initialized as by
353 * connection_init(). */
354 control_connection_t *
355 control_connection_new(int socket_family)
357 control_connection_t *control_conn =
358 tor_malloc_zero(sizeof(control_connection_t));
359 connection_init(time(NULL),
360 TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
361 return control_conn;
364 /** Allocate and return a new listener_connection_t, initialized as by
365 * connection_init(). */
366 listener_connection_t *
367 listener_connection_new(int type, int socket_family)
369 listener_connection_t *listener_conn =
370 tor_malloc_zero(sizeof(listener_connection_t));
371 connection_init(time(NULL), TO_CONN(listener_conn), type, socket_family);
372 return listener_conn;
375 /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
376 * to make or receive connections of address family <b>socket_family</b>. The
377 * type should be one of the CONN_TYPE_* constants. */
378 connection_t *
379 connection_new(int type, int socket_family)
381 switch (type) {
382 case CONN_TYPE_OR:
383 case CONN_TYPE_EXT_OR:
384 return TO_CONN(or_connection_new(type, socket_family));
386 case CONN_TYPE_EXIT:
387 return TO_CONN(edge_connection_new(type, socket_family));
389 case CONN_TYPE_AP:
390 return ENTRY_TO_CONN(entry_connection_new(type, socket_family));
392 case CONN_TYPE_DIR:
393 return TO_CONN(dir_connection_new(socket_family));
395 case CONN_TYPE_CONTROL:
396 return TO_CONN(control_connection_new(socket_family));
398 CASE_ANY_LISTENER_TYPE:
399 return TO_CONN(listener_connection_new(type, socket_family));
401 default: {
402 connection_t *conn = tor_malloc_zero(sizeof(connection_t));
403 connection_init(time(NULL), conn, type, socket_family);
404 return conn;
409 /** Initializes conn. (you must call connection_add() to link it into the main
410 * array).
412 * Set conn-\>magic to the correct value.
414 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
415 * -1 to signify they are not yet assigned.
417 * Initialize conn's timestamps to now.
419 static void
420 connection_init(time_t now, connection_t *conn, int type, int socket_family)
422 static uint64_t n_connections_allocated = 1;
424 switch (type) {
425 case CONN_TYPE_OR:
426 case CONN_TYPE_EXT_OR:
427 conn->magic = OR_CONNECTION_MAGIC;
428 break;
429 case CONN_TYPE_EXIT:
430 conn->magic = EDGE_CONNECTION_MAGIC;
431 break;
432 case CONN_TYPE_AP:
433 conn->magic = ENTRY_CONNECTION_MAGIC;
434 break;
435 case CONN_TYPE_DIR:
436 conn->magic = DIR_CONNECTION_MAGIC;
437 break;
438 case CONN_TYPE_CONTROL:
439 conn->magic = CONTROL_CONNECTION_MAGIC;
440 break;
441 CASE_ANY_LISTENER_TYPE:
442 conn->magic = LISTENER_CONNECTION_MAGIC;
443 break;
444 default:
445 conn->magic = BASE_CONNECTION_MAGIC;
446 break;
449 conn->s = TOR_INVALID_SOCKET; /* give it a default of 'not used' */
450 conn->conn_array_index = -1; /* also default to 'not used' */
451 conn->global_identifier = n_connections_allocated++;
453 conn->type = type;
454 conn->socket_family = socket_family;
455 if (!connection_is_listener(conn)) {
456 /* listeners never use their buf */
457 conn->inbuf = buf_new();
458 conn->outbuf = buf_new();
461 conn->timestamp_created = now;
462 conn->timestamp_last_read_allowed = now;
463 conn->timestamp_last_write_allowed = now;
466 /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
467 void
468 connection_link_connections(connection_t *conn_a, connection_t *conn_b)
470 tor_assert(! SOCKET_OK(conn_a->s));
471 tor_assert(! SOCKET_OK(conn_b->s));
473 conn_a->linked = 1;
474 conn_b->linked = 1;
475 conn_a->linked_conn = conn_b;
476 conn_b->linked_conn = conn_a;
479 /** Return true iff the provided connection listener type supports AF_UNIX
480 * sockets. */
482 conn_listener_type_supports_af_unix(int type)
484 /* For now only control ports or SOCKS ports can be Unix domain sockets
485 * and listeners at the same time */
486 switch (type) {
487 case CONN_TYPE_CONTROL_LISTENER:
488 case CONN_TYPE_AP_LISTENER:
489 return 1;
490 default:
491 return 0;
495 /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
496 * necessary, close its socket if necessary, and mark the directory as dirty
497 * if <b>conn</b> is an OR or OP connection.
499 STATIC void
500 connection_free_minimal(connection_t *conn)
502 void *mem;
503 size_t memlen;
504 if (!conn)
505 return;
507 switch (conn->type) {
508 case CONN_TYPE_OR:
509 case CONN_TYPE_EXT_OR:
510 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
511 mem = TO_OR_CONN(conn);
512 memlen = sizeof(or_connection_t);
513 break;
514 case CONN_TYPE_AP:
515 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
516 mem = TO_ENTRY_CONN(conn);
517 memlen = sizeof(entry_connection_t);
518 break;
519 case CONN_TYPE_EXIT:
520 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
521 mem = TO_EDGE_CONN(conn);
522 memlen = sizeof(edge_connection_t);
523 break;
524 case CONN_TYPE_DIR:
525 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
526 mem = TO_DIR_CONN(conn);
527 memlen = sizeof(dir_connection_t);
528 break;
529 case CONN_TYPE_CONTROL:
530 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
531 mem = TO_CONTROL_CONN(conn);
532 memlen = sizeof(control_connection_t);
533 break;
534 CASE_ANY_LISTENER_TYPE:
535 tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
536 mem = TO_LISTENER_CONN(conn);
537 memlen = sizeof(listener_connection_t);
538 break;
539 default:
540 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
541 mem = conn;
542 memlen = sizeof(connection_t);
543 break;
546 if (conn->linked) {
547 log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
548 "bytes on inbuf, %d on outbuf.",
549 conn_type_to_string(conn->type),
550 conn_state_to_string(conn->type, conn->state),
551 (int)connection_get_inbuf_len(conn),
552 (int)connection_get_outbuf_len(conn));
555 if (!connection_is_listener(conn)) {
556 buf_free(conn->inbuf);
557 buf_free(conn->outbuf);
558 } else {
559 if (conn->socket_family == AF_UNIX) {
560 /* For now only control and SOCKS ports can be Unix domain sockets
561 * and listeners at the same time */
562 tor_assert(conn_listener_type_supports_af_unix(conn->type));
564 if (unlink(conn->address) < 0 && errno != ENOENT) {
565 log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
566 strerror(errno));
571 tor_free(conn->address);
573 if (connection_speaks_cells(conn)) {
574 or_connection_t *or_conn = TO_OR_CONN(conn);
575 tor_tls_free(or_conn->tls);
576 or_conn->tls = NULL;
577 or_handshake_state_free(or_conn->handshake_state);
578 or_conn->handshake_state = NULL;
579 tor_free(or_conn->nickname);
580 if (or_conn->chan) {
581 /* Owww, this shouldn't happen, but... */
582 log_info(LD_CHANNEL,
583 "Freeing orconn at %p, saw channel %p with ID "
584 U64_FORMAT " left un-NULLed",
585 or_conn, TLS_CHAN_TO_BASE(or_conn->chan),
586 U64_PRINTF_ARG(
587 TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier));
588 if (!CHANNEL_FINISHED(TLS_CHAN_TO_BASE(or_conn->chan))) {
589 channel_close_for_error(TLS_CHAN_TO_BASE(or_conn->chan));
592 or_conn->chan->conn = NULL;
593 or_conn->chan = NULL;
596 if (conn->type == CONN_TYPE_AP) {
597 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
598 tor_free(entry_conn->chosen_exit_name);
599 tor_free(entry_conn->original_dest_address);
600 if (entry_conn->socks_request)
601 socks_request_free(entry_conn->socks_request);
602 if (entry_conn->pending_optimistic_data) {
603 buf_free(entry_conn->pending_optimistic_data);
605 if (entry_conn->sending_optimistic_data) {
606 buf_free(entry_conn->sending_optimistic_data);
609 if (CONN_IS_EDGE(conn)) {
610 rend_data_free(TO_EDGE_CONN(conn)->rend_data);
611 hs_ident_edge_conn_free(TO_EDGE_CONN(conn)->hs_ident);
613 if (conn->type == CONN_TYPE_CONTROL) {
614 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
615 tor_free(control_conn->safecookie_client_hash);
616 tor_free(control_conn->incoming_cmd);
617 if (control_conn->ephemeral_onion_services) {
618 SMARTLIST_FOREACH(control_conn->ephemeral_onion_services, char *, cp, {
619 memwipe(cp, 0, strlen(cp));
620 tor_free(cp);
622 smartlist_free(control_conn->ephemeral_onion_services);
626 /* Probably already freed by connection_free. */
627 tor_event_free(conn->read_event);
628 tor_event_free(conn->write_event);
629 conn->read_event = conn->write_event = NULL;
631 if (conn->type == CONN_TYPE_DIR) {
632 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
633 tor_free(dir_conn->requested_resource);
635 tor_compress_free(dir_conn->compress_state);
636 if (dir_conn->spool) {
637 SMARTLIST_FOREACH(dir_conn->spool, spooled_resource_t *, spooled,
638 spooled_resource_free(spooled));
639 smartlist_free(dir_conn->spool);
642 rend_data_free(dir_conn->rend_data);
643 hs_ident_dir_conn_free(dir_conn->hs_ident);
644 if (dir_conn->guard_state) {
645 /* Cancel before freeing, if it's still there. */
646 entry_guard_cancel(&dir_conn->guard_state);
648 circuit_guard_state_free(dir_conn->guard_state);
651 if (SOCKET_OK(conn->s)) {
652 log_debug(LD_NET,"closing fd %d.",(int)conn->s);
653 tor_close_socket(conn->s);
654 conn->s = TOR_INVALID_SOCKET;
657 if (conn->type == CONN_TYPE_OR &&
658 !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
659 log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
660 connection_or_clear_identity(TO_OR_CONN(conn));
662 if (conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR) {
663 connection_or_remove_from_ext_or_id_map(TO_OR_CONN(conn));
664 tor_free(TO_OR_CONN(conn)->ext_or_conn_id);
665 tor_free(TO_OR_CONN(conn)->ext_or_auth_correct_client_hash);
666 tor_free(TO_OR_CONN(conn)->ext_or_transport);
669 memwipe(mem, 0xCC, memlen); /* poison memory */
670 tor_free(mem);
673 /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
675 MOCK_IMPL(void,
676 connection_free_,(connection_t *conn))
678 if (!conn)
679 return;
680 tor_assert(!connection_is_on_closeable_list(conn));
681 tor_assert(!connection_in_array(conn));
682 if (BUG(conn->linked_conn)) {
683 conn->linked_conn->linked_conn = NULL;
684 if (! conn->linked_conn->marked_for_close &&
685 conn->linked_conn->reading_from_linked_conn)
686 connection_start_reading(conn->linked_conn);
687 conn->linked_conn = NULL;
689 if (connection_speaks_cells(conn)) {
690 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
691 connection_or_clear_identity(TO_OR_CONN(conn));
694 if (conn->type == CONN_TYPE_CONTROL) {
695 connection_control_closed(TO_CONTROL_CONN(conn));
697 #if 1
698 /* DEBUGGING */
699 if (conn->type == CONN_TYPE_AP) {
700 connection_ap_warn_and_unmark_if_pending_circ(TO_ENTRY_CONN(conn),
701 "connection_free");
703 #endif /* 1 */
705 /* Notify the circuit creation DoS mitigation subsystem that an OR client
706 * connection has been closed. And only do that if we track it. */
707 if (conn->type == CONN_TYPE_OR) {
708 dos_close_client_conn(TO_OR_CONN(conn));
711 connection_unregister_events(conn);
712 connection_free_minimal(conn);
716 * Called when we're about to finally unlink and free a connection:
717 * perform necessary accounting and cleanup
718 * - Directory conns that failed to fetch a rendezvous descriptor
719 * need to inform pending rendezvous streams.
720 * - OR conns need to call rep_hist_note_*() to record status.
721 * - AP conns need to send a socks reject if necessary.
722 * - Exit conns need to call connection_dns_remove() if necessary.
723 * - AP and Exit conns need to send an end cell if they can.
724 * - DNS conns need to fail any resolves that are pending on them.
725 * - OR and edge connections need to be unlinked from circuits.
727 void
728 connection_about_to_close_connection(connection_t *conn)
730 tor_assert(conn->marked_for_close);
732 switch (conn->type) {
733 case CONN_TYPE_DIR:
734 connection_dir_about_to_close(TO_DIR_CONN(conn));
735 break;
736 case CONN_TYPE_OR:
737 case CONN_TYPE_EXT_OR:
738 connection_or_about_to_close(TO_OR_CONN(conn));
739 break;
740 case CONN_TYPE_AP:
741 connection_ap_about_to_close(TO_ENTRY_CONN(conn));
742 break;
743 case CONN_TYPE_EXIT:
744 connection_exit_about_to_close(TO_EDGE_CONN(conn));
745 break;
749 /** Return true iff connection_close_immediate() has been called on this
750 * connection. */
751 #define CONN_IS_CLOSED(c) \
752 ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
754 /** Close the underlying socket for <b>conn</b>, so we don't try to
755 * flush it. Must be used in conjunction with (right before)
756 * connection_mark_for_close().
758 void
759 connection_close_immediate(connection_t *conn)
761 assert_connection_ok(conn,0);
762 if (CONN_IS_CLOSED(conn)) {
763 log_err(LD_BUG,"Attempt to close already-closed connection.");
764 tor_fragile_assert();
765 return;
767 if (conn->outbuf_flushlen) {
768 log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
769 (int)conn->s, conn_type_to_string(conn->type),
770 conn_state_to_string(conn->type, conn->state),
771 (int)conn->outbuf_flushlen);
774 connection_unregister_events(conn);
776 /* Prevent the event from getting unblocked. */
777 conn->read_blocked_on_bw =
778 conn->write_blocked_on_bw = 0;
780 if (SOCKET_OK(conn->s))
781 tor_close_socket(conn->s);
782 conn->s = TOR_INVALID_SOCKET;
783 if (conn->linked)
784 conn->linked_conn_is_closed = 1;
785 if (conn->outbuf)
786 buf_clear(conn->outbuf);
787 conn->outbuf_flushlen = 0;
790 /** Mark <b>conn</b> to be closed next time we loop through
791 * conn_close_if_marked() in main.c. */
792 void
793 connection_mark_for_close_(connection_t *conn, int line, const char *file)
795 assert_connection_ok(conn,0);
796 tor_assert(line);
797 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
798 tor_assert(file);
800 if (conn->type == CONN_TYPE_OR) {
802 * An or_connection should have been closed through one of the channel-
803 * aware functions in connection_or.c. We'll assume this is an error
804 * close and do that, and log a bug warning.
806 log_warn(LD_CHANNEL | LD_BUG,
807 "Something tried to close an or_connection_t without going "
808 "through channels at %s:%d",
809 file, line);
810 connection_or_close_for_error(TO_OR_CONN(conn), 0);
811 } else {
812 /* Pass it down to the real function */
813 connection_mark_for_close_internal_(conn, line, file);
817 /** Mark <b>conn</b> to be closed next time we loop through
818 * conn_close_if_marked() in main.c; the _internal version bypasses the
819 * CONN_TYPE_OR checks; this should be called when you either are sure that
820 * if this is an or_connection_t the controlling channel has been notified
821 * (e.g. with connection_or_notify_error()), or you actually are the
822 * connection_or_close_for_error() or connection_or_close_normally() function.
823 * For all other cases, use connection_mark_and_flush() instead, which
824 * checks for or_connection_t properly, instead. See below.
826 MOCK_IMPL(void,
827 connection_mark_for_close_internal_, (connection_t *conn,
828 int line, const char *file))
830 assert_connection_ok(conn,0);
831 tor_assert(line);
832 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
833 tor_assert(file);
835 if (conn->marked_for_close) {
836 log_warn(LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
837 " (first at %s:%d)", file, line, conn->marked_for_close_file,
838 conn->marked_for_close);
839 tor_fragile_assert();
840 return;
843 if (conn->type == CONN_TYPE_OR) {
845 * Bad news if this happens without telling the controlling channel; do
846 * this so we can find things that call this wrongly when the asserts hit.
848 log_debug(LD_CHANNEL,
849 "Calling connection_mark_for_close_internal_() on an OR conn "
850 "at %s:%d",
851 file, line);
854 conn->marked_for_close = line;
855 conn->marked_for_close_file = file;
856 add_connection_to_closeable_list(conn);
858 /* in case we're going to be held-open-til-flushed, reset
859 * the number of seconds since last successful write, so
860 * we get our whole 15 seconds */
861 conn->timestamp_last_write_allowed = time(NULL);
864 /** Find each connection that has hold_open_until_flushed set to
865 * 1 but hasn't written in the past 15 seconds, and set
866 * hold_open_until_flushed to 0. This means it will get cleaned
867 * up in the next loop through close_if_marked() in main.c.
869 void
870 connection_expire_held_open(void)
872 time_t now;
873 smartlist_t *conns = get_connection_array();
875 now = time(NULL);
877 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
878 /* If we've been holding the connection open, but we haven't written
879 * for 15 seconds...
881 if (conn->hold_open_until_flushed) {
882 tor_assert(conn->marked_for_close);
883 if (now - conn->timestamp_last_write_allowed >= 15) {
884 int severity;
885 if (conn->type == CONN_TYPE_EXIT ||
886 (conn->type == CONN_TYPE_DIR &&
887 conn->purpose == DIR_PURPOSE_SERVER))
888 severity = LOG_INFO;
889 else
890 severity = LOG_NOTICE;
891 log_fn(severity, LD_NET,
892 "Giving up on marked_for_close conn that's been flushing "
893 "for 15s (fd %d, type %s, state %s).",
894 (int)conn->s, conn_type_to_string(conn->type),
895 conn_state_to_string(conn->type, conn->state));
896 conn->hold_open_until_flushed = 0;
899 } SMARTLIST_FOREACH_END(conn);
902 #if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
903 /** Create an AF_UNIX listenaddr struct.
904 * <b>listenaddress</b> provides the path to the Unix socket.
906 * Eventually <b>listenaddress</b> will also optionally contain user, group,
907 * and file permissions for the new socket. But not yet. XXX
908 * Also, since we do not create the socket here the information doesn't help
909 * here.
911 * If not NULL <b>readable_address</b> will contain a copy of the path part of
912 * <b>listenaddress</b>.
914 * The listenaddr struct has to be freed by the caller.
916 static struct sockaddr_un *
917 create_unix_sockaddr(const char *listenaddress, char **readable_address,
918 socklen_t *len_out)
920 struct sockaddr_un *sockaddr = NULL;
922 sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
923 sockaddr->sun_family = AF_UNIX;
924 if (strlcpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path))
925 >= sizeof(sockaddr->sun_path)) {
926 log_warn(LD_CONFIG, "Unix socket path '%s' is too long to fit.",
927 escaped(listenaddress));
928 tor_free(sockaddr);
929 return NULL;
932 if (readable_address)
933 *readable_address = tor_strdup(listenaddress);
935 *len_out = sizeof(struct sockaddr_un);
936 return sockaddr;
938 #else /* !(defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)) */
939 static struct sockaddr *
940 create_unix_sockaddr(const char *listenaddress, char **readable_address,
941 socklen_t *len_out)
943 (void)listenaddress;
944 (void)readable_address;
945 log_fn(LOG_ERR, LD_BUG,
946 "Unix domain sockets not supported, yet we tried to create one.");
947 *len_out = 0;
948 tor_fragile_assert();
949 return NULL;
951 #endif /* defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN) */
953 /** Warn that an accept or a connect has failed because we're running out of
954 * TCP sockets we can use on current system. Rate-limit these warnings so
955 * that we don't spam the log. */
956 static void
957 warn_too_many_conns(void)
959 #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
960 static ratelim_t last_warned = RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL);
961 char *m;
962 if ((m = rate_limit_log(&last_warned, approx_time()))) {
963 int n_conns = get_n_open_sockets();
964 log_warn(LD_NET,"Failing because we have %d connections already. Please "
965 "read doc/TUNING for guidance.%s", n_conns, m);
966 tor_free(m);
967 control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
968 n_conns);
972 #ifdef HAVE_SYS_UN_H
974 #define UNIX_SOCKET_PURPOSE_CONTROL_SOCKET 0
975 #define UNIX_SOCKET_PURPOSE_SOCKS_SOCKET 1
977 /** Check if the purpose isn't one of the ones we know what to do with */
979 static int
980 is_valid_unix_socket_purpose(int purpose)
982 int valid = 0;
984 switch (purpose) {
985 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
986 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
987 valid = 1;
988 break;
991 return valid;
994 /** Return a string description of a unix socket purpose */
995 static const char *
996 unix_socket_purpose_to_string(int purpose)
998 const char *s = "unknown-purpose socket";
1000 switch (purpose) {
1001 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
1002 s = "control socket";
1003 break;
1004 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
1005 s = "SOCKS socket";
1006 break;
1009 return s;
1012 /** Check whether we should be willing to open an AF_UNIX socket in
1013 * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
1014 static int
1015 check_location_for_unix_socket(const or_options_t *options, const char *path,
1016 int purpose, const port_cfg_t *port)
1018 int r = -1;
1019 char *p = NULL;
1021 tor_assert(is_valid_unix_socket_purpose(purpose));
1023 p = tor_strdup(path);
1024 cpd_check_t flags = CPD_CHECK_MODE_ONLY;
1025 if (get_parent_directory(p)<0 || p[0] != '/') {
1026 log_warn(LD_GENERAL, "Bad unix socket address '%s'. Tor does not support "
1027 "relative paths for unix sockets.", path);
1028 goto done;
1031 if (port->is_world_writable) {
1032 /* World-writable sockets can go anywhere. */
1033 r = 0;
1034 goto done;
1037 if (port->is_group_writable) {
1038 flags |= CPD_GROUP_OK;
1041 if (port->relax_dirmode_check) {
1042 flags |= CPD_RELAX_DIRMODE_CHECK;
1045 if (check_private_dir(p, flags, options->User) < 0) {
1046 char *escpath, *escdir;
1047 escpath = esc_for_log(path);
1048 escdir = esc_for_log(p);
1049 log_warn(LD_GENERAL, "Before Tor can create a %s in %s, the directory "
1050 "%s needs to exist, and to be accessible only by the user%s "
1051 "account that is running Tor. (On some Unix systems, anybody "
1052 "who can list a socket can connect to it, so Tor is being "
1053 "careful.)",
1054 unix_socket_purpose_to_string(purpose), escpath, escdir,
1055 port->is_group_writable ? " and group" : "");
1056 tor_free(escpath);
1057 tor_free(escdir);
1058 goto done;
1061 r = 0;
1062 done:
1063 tor_free(p);
1064 return r;
1066 #endif /* defined(HAVE_SYS_UN_H) */
1068 /** Tell the TCP stack that it shouldn't wait for a long time after
1069 * <b>sock</b> has closed before reusing its port. Return 0 on success,
1070 * -1 on failure. */
1071 static int
1072 make_socket_reuseable(tor_socket_t sock)
1074 #ifdef _WIN32
1075 (void) sock;
1076 return 0;
1077 #else
1078 int one=1;
1080 /* REUSEADDR on normal places means you can rebind to the port
1081 * right after somebody else has let it go. But REUSEADDR on win32
1082 * means you can bind to the port _even when somebody else
1083 * already has it bound_. So, don't do that on Win32. */
1084 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
1085 (socklen_t)sizeof(one)) == -1) {
1086 return -1;
1088 return 0;
1089 #endif /* defined(_WIN32) */
1092 #ifdef _WIN32
1093 /** Tell the Windows TCP stack to prevent other applications from receiving
1094 * traffic from tor's open ports. Return 0 on success, -1 on failure. */
1095 static int
1096 make_win32_socket_exclusive(tor_socket_t sock)
1098 #ifdef SO_EXCLUSIVEADDRUSE
1099 int one=1;
1101 /* Any socket that sets REUSEADDR on win32 can bind to a port _even when
1102 * somebody else already has it bound_, and _even if the original socket
1103 * didn't set REUSEADDR_. Use EXCLUSIVEADDRUSE to prevent this port-stealing
1104 * on win32. */
1105 if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void*) &one,
1106 (socklen_t)sizeof(one))) {
1107 return -1;
1109 return 0;
1110 #else /* !(defined(SO_EXCLUSIVEADDRUSE)) */
1111 (void) sock;
1112 return 0;
1113 #endif /* defined(SO_EXCLUSIVEADDRUSE) */
1115 #endif /* defined(_WIN32) */
1117 /** Max backlog to pass to listen. We start at */
1118 static int listen_limit = INT_MAX;
1120 /* Listen on <b>fd</b> with appropriate backlog. Return as for listen. */
1121 static int
1122 tor_listen(tor_socket_t fd)
1124 int r;
1126 if ((r = listen(fd, listen_limit)) < 0) {
1127 if (listen_limit == SOMAXCONN)
1128 return r;
1129 if ((r = listen(fd, SOMAXCONN)) == 0) {
1130 listen_limit = SOMAXCONN;
1131 log_warn(LD_NET, "Setting listen backlog to INT_MAX connections "
1132 "didn't work, but SOMAXCONN did. Lowering backlog limit.");
1135 return r;
1138 /** Bind a new non-blocking socket listening to the socket described
1139 * by <b>listensockaddr</b>.
1141 * <b>address</b> is only used for logging purposes and to add the information
1142 * to the conn.
1144 static connection_t *
1145 connection_listener_new(const struct sockaddr *listensockaddr,
1146 socklen_t socklen,
1147 int type, const char *address,
1148 const port_cfg_t *port_cfg)
1150 listener_connection_t *lis_conn;
1151 connection_t *conn = NULL;
1152 tor_socket_t s = TOR_INVALID_SOCKET; /* the socket we're going to make */
1153 or_options_t const *options = get_options();
1154 (void) options; /* Windows doesn't use this. */
1155 #if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
1156 const struct passwd *pw = NULL;
1157 #endif
1158 uint16_t usePort = 0, gotPort = 0;
1159 int start_reading = 0;
1160 static int global_next_session_group = SESSION_GROUP_FIRST_AUTO;
1161 tor_addr_t addr;
1162 int exhaustion = 0;
1164 if (listensockaddr->sa_family == AF_INET ||
1165 listensockaddr->sa_family == AF_INET6) {
1166 int is_stream = (type != CONN_TYPE_AP_DNS_LISTENER);
1167 if (is_stream)
1168 start_reading = 1;
1170 tor_addr_from_sockaddr(&addr, listensockaddr, &usePort);
1171 log_notice(LD_NET, "Opening %s on %s",
1172 conn_type_to_string(type), fmt_addrport(&addr, usePort));
1174 s = tor_open_socket_nonblocking(tor_addr_family(&addr),
1175 is_stream ? SOCK_STREAM : SOCK_DGRAM,
1176 is_stream ? IPPROTO_TCP: IPPROTO_UDP);
1177 if (!SOCKET_OK(s)) {
1178 int e = tor_socket_errno(s);
1179 if (ERRNO_IS_RESOURCE_LIMIT(e)) {
1180 warn_too_many_conns();
1182 * We'll call the OOS handler at the error exit, so set the
1183 * exhaustion flag for it.
1185 exhaustion = 1;
1186 } else {
1187 log_warn(LD_NET, "Socket creation failed: %s",
1188 tor_socket_strerror(e));
1190 goto err;
1193 if (make_socket_reuseable(s) < 0) {
1194 log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
1195 conn_type_to_string(type),
1196 tor_socket_strerror(errno));
1199 #ifdef _WIN32
1200 if (make_win32_socket_exclusive(s) < 0) {
1201 log_warn(LD_NET, "Error setting SO_EXCLUSIVEADDRUSE flag on %s: %s",
1202 conn_type_to_string(type),
1203 tor_socket_strerror(errno));
1205 #endif /* defined(_WIN32) */
1207 #if defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT)
1208 if (options->TransProxyType_parsed == TPT_TPROXY &&
1209 type == CONN_TYPE_AP_TRANS_LISTENER) {
1210 int one = 1;
1211 if (setsockopt(s, SOL_IP, IP_TRANSPARENT, (void*)&one,
1212 (socklen_t)sizeof(one)) < 0) {
1213 const char *extra = "";
1214 int e = tor_socket_errno(s);
1215 if (e == EPERM)
1216 extra = "TransTPROXY requires root privileges or similar"
1217 " capabilities.";
1218 log_warn(LD_NET, "Error setting IP_TRANSPARENT flag: %s.%s",
1219 tor_socket_strerror(e), extra);
1222 #endif /* defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT) */
1224 #ifdef IPV6_V6ONLY
1225 if (listensockaddr->sa_family == AF_INET6) {
1226 int one = 1;
1227 /* We need to set IPV6_V6ONLY so that this socket can't get used for
1228 * IPv4 connections. */
1229 if (setsockopt(s,IPPROTO_IPV6, IPV6_V6ONLY,
1230 (void*)&one, (socklen_t)sizeof(one)) < 0) {
1231 int e = tor_socket_errno(s);
1232 log_warn(LD_NET, "Error setting IPV6_V6ONLY flag: %s",
1233 tor_socket_strerror(e));
1234 /* Keep going; probably not harmful. */
1237 #endif /* defined(IPV6_V6ONLY) */
1239 if (bind(s,listensockaddr,socklen) < 0) {
1240 const char *helpfulhint = "";
1241 int e = tor_socket_errno(s);
1242 if (ERRNO_IS_EADDRINUSE(e))
1243 helpfulhint = ". Is Tor already running?";
1244 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
1245 tor_socket_strerror(e), helpfulhint);
1246 goto err;
1249 if (is_stream) {
1250 if (tor_listen(s) < 0) {
1251 log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
1252 tor_socket_strerror(tor_socket_errno(s)));
1253 goto err;
1257 if (usePort != 0) {
1258 gotPort = usePort;
1259 } else {
1260 tor_addr_t addr2;
1261 if (tor_addr_from_getsockname(&addr2, s)<0) {
1262 log_warn(LD_NET, "getsockname() couldn't learn address for %s: %s",
1263 conn_type_to_string(type),
1264 tor_socket_strerror(tor_socket_errno(s)));
1265 gotPort = 0;
1268 #ifdef HAVE_SYS_UN_H
1270 * AF_UNIX generic setup stuff
1272 } else if (listensockaddr->sa_family == AF_UNIX) {
1273 /* We want to start reading for both AF_UNIX cases */
1274 start_reading = 1;
1276 tor_assert(conn_listener_type_supports_af_unix(type));
1278 if (check_location_for_unix_socket(options, address,
1279 (type == CONN_TYPE_CONTROL_LISTENER) ?
1280 UNIX_SOCKET_PURPOSE_CONTROL_SOCKET :
1281 UNIX_SOCKET_PURPOSE_SOCKS_SOCKET, port_cfg) < 0) {
1282 goto err;
1285 log_notice(LD_NET, "Opening %s on %s",
1286 conn_type_to_string(type), address);
1288 tor_addr_make_unspec(&addr);
1290 if (unlink(address) < 0 && errno != ENOENT) {
1291 log_warn(LD_NET, "Could not unlink %s: %s", address,
1292 strerror(errno));
1293 goto err;
1296 s = tor_open_socket_nonblocking(AF_UNIX, SOCK_STREAM, 0);
1297 if (! SOCKET_OK(s)) {
1298 int e = tor_socket_errno(s);
1299 if (ERRNO_IS_RESOURCE_LIMIT(e)) {
1300 warn_too_many_conns();
1302 * We'll call the OOS handler at the error exit, so set the
1303 * exhaustion flag for it.
1305 exhaustion = 1;
1306 } else {
1307 log_warn(LD_NET,"Socket creation failed: %s.", strerror(e));
1309 goto err;
1312 if (bind(s, listensockaddr,
1313 (socklen_t)sizeof(struct sockaddr_un)) == -1) {
1314 log_warn(LD_NET,"Bind to %s failed: %s.", address,
1315 tor_socket_strerror(tor_socket_errno(s)));
1316 goto err;
1319 #ifdef HAVE_PWD_H
1320 if (options->User) {
1321 pw = tor_getpwnam(options->User);
1322 struct stat st;
1323 if (pw == NULL) {
1324 log_warn(LD_NET,"Unable to chown() %s socket: user %s not found.",
1325 address, options->User);
1326 goto err;
1327 } else if (fstat(s, &st) == 0 &&
1328 st.st_uid == pw->pw_uid && st.st_gid == pw->pw_gid) {
1329 /* No change needed */
1330 } else if (chown(sandbox_intern_string(address),
1331 pw->pw_uid, pw->pw_gid) < 0) {
1332 log_warn(LD_NET,"Unable to chown() %s socket: %s.",
1333 address, strerror(errno));
1334 goto err;
1337 #endif /* defined(HAVE_PWD_H) */
1340 unsigned mode;
1341 const char *status;
1342 struct stat st;
1343 if (port_cfg->is_world_writable) {
1344 mode = 0666;
1345 status = "world-writable";
1346 } else if (port_cfg->is_group_writable) {
1347 mode = 0660;
1348 status = "group-writable";
1349 } else {
1350 mode = 0600;
1351 status = "private";
1353 /* We need to use chmod; fchmod doesn't work on sockets on all
1354 * platforms. */
1355 if (fstat(s, &st) == 0 && (st.st_mode & 0777) == mode) {
1356 /* no change needed */
1357 } else if (chmod(sandbox_intern_string(address), mode) < 0) {
1358 log_warn(LD_FS,"Unable to make %s %s.", address, status);
1359 goto err;
1363 if (listen(s, SOMAXCONN) < 0) {
1364 log_warn(LD_NET, "Could not listen on %s: %s", address,
1365 tor_socket_strerror(tor_socket_errno(s)));
1366 goto err;
1368 #endif /* defined(HAVE_SYS_UN_H) */
1369 } else {
1370 log_err(LD_BUG, "Got unexpected address family %d.",
1371 listensockaddr->sa_family);
1372 tor_assert(0);
1375 lis_conn = listener_connection_new(type, listensockaddr->sa_family);
1376 conn = TO_CONN(lis_conn);
1377 conn->socket_family = listensockaddr->sa_family;
1378 conn->s = s;
1379 s = TOR_INVALID_SOCKET; /* Prevent double-close */
1380 conn->address = tor_strdup(address);
1381 conn->port = gotPort;
1382 tor_addr_copy(&conn->addr, &addr);
1384 memcpy(&lis_conn->entry_cfg, &port_cfg->entry_cfg, sizeof(entry_port_cfg_t));
1386 if (port_cfg->entry_cfg.isolation_flags) {
1387 lis_conn->entry_cfg.isolation_flags = port_cfg->entry_cfg.isolation_flags;
1388 if (port_cfg->entry_cfg.session_group >= 0) {
1389 lis_conn->entry_cfg.session_group = port_cfg->entry_cfg.session_group;
1390 } else {
1391 /* This can wrap after around INT_MAX listeners are opened. But I don't
1392 * believe that matters, since you would need to open a ridiculous
1393 * number of listeners while keeping the early ones open before you ever
1394 * hit this. An OR with a dozen ports open, for example, would have to
1395 * close and re-open its listeners every second for 4 years nonstop.
1397 lis_conn->entry_cfg.session_group = global_next_session_group--;
1401 if (type != CONN_TYPE_AP_LISTENER) {
1402 lis_conn->entry_cfg.ipv4_traffic = 1;
1403 lis_conn->entry_cfg.ipv6_traffic = 1;
1404 lis_conn->entry_cfg.prefer_ipv6 = 0;
1407 if (connection_add(conn) < 0) { /* no space, forget it */
1408 log_warn(LD_NET,"connection_add for listener failed. Giving up.");
1409 goto err;
1412 log_fn(usePort==gotPort ? LOG_DEBUG : LOG_NOTICE, LD_NET,
1413 "%s listening on port %u.",
1414 conn_type_to_string(type), gotPort);
1416 conn->state = LISTENER_STATE_READY;
1417 if (start_reading) {
1418 connection_start_reading(conn);
1419 } else {
1420 tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
1421 dnsserv_configure_listener(conn);
1425 * Normal exit; call the OOS handler since connection count just changed;
1426 * the exhaustion flag will always be zero here though.
1428 connection_check_oos(get_n_open_sockets(), 0);
1430 return conn;
1432 err:
1433 if (SOCKET_OK(s))
1434 tor_close_socket(s);
1435 if (conn)
1436 connection_free(conn);
1438 /* Call the OOS handler, indicate if we saw an exhaustion-related error */
1439 connection_check_oos(get_n_open_sockets(), exhaustion);
1441 return NULL;
1444 /** Do basic sanity checking on a newly received socket. Return 0
1445 * if it looks ok, else return -1.
1447 * Notably, some TCP stacks can erroneously have accept() return successfully
1448 * with socklen 0, when the client sends an RST before the accept call (as
1449 * nmap does). We want to detect that, and not go on with the connection.
1451 static int
1452 check_sockaddr(const struct sockaddr *sa, int len, int level)
1454 int ok = 1;
1456 if (sa->sa_family == AF_INET) {
1457 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
1458 if (len != sizeof(struct sockaddr_in)) {
1459 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
1460 len,(int)sizeof(struct sockaddr_in));
1461 ok = 0;
1463 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
1464 log_fn(level, LD_NET,
1465 "Address for new connection has address/port equal to zero.");
1466 ok = 0;
1468 } else if (sa->sa_family == AF_INET6) {
1469 struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
1470 if (len != sizeof(struct sockaddr_in6)) {
1471 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
1472 len,(int)sizeof(struct sockaddr_in6));
1473 ok = 0;
1475 if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
1476 sin6->sin6_port == 0) {
1477 log_fn(level, LD_NET,
1478 "Address for new connection has address/port equal to zero.");
1479 ok = 0;
1481 } else if (sa->sa_family == AF_UNIX) {
1482 ok = 1;
1483 } else {
1484 ok = 0;
1486 return ok ? 0 : -1;
1489 /** Check whether the socket family from an accepted socket <b>got</b> is the
1490 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1491 * a useful message and return -1. Else return 0.
1493 * This is annoying, but can apparently happen on some Darwins. */
1494 static int
1495 check_sockaddr_family_match(sa_family_t got, connection_t *listener)
1497 if (got != listener->socket_family) {
1498 log_info(LD_BUG, "A listener connection returned a socket with a "
1499 "mismatched family. %s for addr_family %d gave us a socket "
1500 "with address family %d. Dropping.",
1501 conn_type_to_string(listener->type),
1502 (int)listener->socket_family,
1503 (int)got);
1504 return -1;
1506 return 0;
1509 /** The listener connection <b>conn</b> told poll() it wanted to read.
1510 * Call accept() on conn-\>s, and add the new connection if necessary.
1512 static int
1513 connection_handle_listener_read(connection_t *conn, int new_type)
1515 tor_socket_t news; /* the new socket */
1516 connection_t *newconn = 0;
1517 /* information about the remote peer when connecting to other routers */
1518 struct sockaddr_storage addrbuf;
1519 struct sockaddr *remote = (struct sockaddr*)&addrbuf;
1520 /* length of the remote address. Must be whatever accept() needs. */
1521 socklen_t remotelen = (socklen_t)sizeof(addrbuf);
1522 const or_options_t *options = get_options();
1524 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
1525 memset(&addrbuf, 0, sizeof(addrbuf));
1527 news = tor_accept_socket_nonblocking(conn->s,remote,&remotelen);
1528 if (!SOCKET_OK(news)) { /* accept() error */
1529 int e = tor_socket_errno(conn->s);
1530 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
1532 * they hung up before we could accept(). that's fine.
1534 * give the OOS handler a chance to run though
1536 connection_check_oos(get_n_open_sockets(), 0);
1537 return 0;
1538 } else if (ERRNO_IS_RESOURCE_LIMIT(e)) {
1539 warn_too_many_conns();
1540 /* Exhaustion; tell the OOS handler */
1541 connection_check_oos(get_n_open_sockets(), 1);
1542 return 0;
1544 /* else there was a real error. */
1545 log_warn(LD_NET,"accept() failed: %s. Closing listener.",
1546 tor_socket_strerror(e));
1547 connection_mark_for_close(conn);
1548 /* Tell the OOS handler about this too */
1549 connection_check_oos(get_n_open_sockets(), 0);
1550 return -1;
1552 log_debug(LD_NET,
1553 "Connection accepted on socket %d (child of fd %d).",
1554 (int)news,(int)conn->s);
1556 /* We accepted a new conn; run OOS handler */
1557 connection_check_oos(get_n_open_sockets(), 0);
1559 if (make_socket_reuseable(news) < 0) {
1560 if (tor_socket_errno(news) == EINVAL) {
1561 /* This can happen on OSX if we get a badly timed shutdown. */
1562 log_debug(LD_NET, "make_socket_reuseable returned EINVAL");
1563 } else {
1564 log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
1565 conn_type_to_string(new_type),
1566 tor_socket_strerror(errno));
1568 tor_close_socket(news);
1569 return 0;
1572 if (options->ConstrainedSockets)
1573 set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
1575 if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
1576 tor_close_socket(news);
1577 return 0;
1580 if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6 ||
1581 (conn->socket_family == AF_UNIX && new_type == CONN_TYPE_AP)) {
1582 tor_addr_t addr;
1583 uint16_t port;
1584 if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
1585 log_info(LD_NET,
1586 "accept() returned a strange address; closing connection.");
1587 tor_close_socket(news);
1588 return 0;
1591 tor_addr_from_sockaddr(&addr, remote, &port);
1593 /* process entrance policies here, before we even create the connection */
1594 if (new_type == CONN_TYPE_AP) {
1595 /* check sockspolicy to see if we should accept it */
1596 if (socks_policy_permits_address(&addr) == 0) {
1597 log_notice(LD_APP,
1598 "Denying socks connection from untrusted address %s.",
1599 fmt_and_decorate_addr(&addr));
1600 tor_close_socket(news);
1601 return 0;
1604 if (new_type == CONN_TYPE_DIR) {
1605 /* check dirpolicy to see if we should accept it */
1606 if (dir_policy_permits_address(&addr) == 0) {
1607 log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
1608 fmt_and_decorate_addr(&addr));
1609 tor_close_socket(news);
1610 return 0;
1613 if (new_type == CONN_TYPE_OR) {
1614 /* Assess with the connection DoS mitigation subsystem if this address
1615 * can open a new connection. */
1616 if (dos_conn_addr_get_defense_type(&addr) == DOS_CONN_DEFENSE_CLOSE) {
1617 tor_close_socket(news);
1618 return 0;
1622 newconn = connection_new(new_type, conn->socket_family);
1623 newconn->s = news;
1625 /* remember the remote address */
1626 tor_addr_copy(&newconn->addr, &addr);
1627 if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
1628 newconn->port = 0;
1629 newconn->address = tor_strdup(conn->address);
1630 } else {
1631 newconn->port = port;
1632 newconn->address = tor_addr_to_str_dup(&addr);
1635 if (new_type == CONN_TYPE_AP && conn->socket_family != AF_UNIX) {
1636 log_info(LD_NET, "New SOCKS connection opened from %s.",
1637 fmt_and_decorate_addr(&addr));
1639 if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
1640 log_info(LD_NET, "New SOCKS AF_UNIX connection opened");
1642 if (new_type == CONN_TYPE_CONTROL) {
1643 log_notice(LD_CONTROL, "New control connection opened from %s.",
1644 fmt_and_decorate_addr(&addr));
1647 } else if (conn->socket_family == AF_UNIX && conn->type != CONN_TYPE_AP) {
1648 tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
1649 tor_assert(new_type == CONN_TYPE_CONTROL);
1650 log_notice(LD_CONTROL, "New control connection opened.");
1652 newconn = connection_new(new_type, conn->socket_family);
1653 newconn->s = news;
1655 /* remember the remote address -- do we have anything sane to put here? */
1656 tor_addr_make_unspec(&newconn->addr);
1657 newconn->port = 1;
1658 newconn->address = tor_strdup(conn->address);
1659 } else {
1660 tor_assert(0);
1663 if (connection_add(newconn) < 0) { /* no space, forget it */
1664 connection_free(newconn);
1665 return 0; /* no need to tear down the parent */
1668 if (connection_init_accepted_conn(newconn, TO_LISTENER_CONN(conn)) < 0) {
1669 if (! newconn->marked_for_close)
1670 connection_mark_for_close(newconn);
1671 return 0;
1673 return 0;
1676 /** Initialize states for newly accepted connection <b>conn</b>.
1678 * If conn is an OR, start the TLS handshake.
1680 * If conn is a transparent AP, get its original destination
1681 * and place it in circuit_wait.
1683 * The <b>listener</b> parameter is only used for AP connections.
1686 connection_init_accepted_conn(connection_t *conn,
1687 const listener_connection_t *listener)
1689 int rv;
1691 connection_start_reading(conn);
1693 switch (conn->type) {
1694 case CONN_TYPE_EXT_OR:
1695 /* Initiate Extended ORPort authentication. */
1696 return connection_ext_or_start_auth(TO_OR_CONN(conn));
1697 case CONN_TYPE_OR:
1698 control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
1699 rv = connection_tls_start_handshake(TO_OR_CONN(conn), 1);
1700 if (rv < 0) {
1701 connection_or_close_for_error(TO_OR_CONN(conn), 0);
1703 return rv;
1704 break;
1705 case CONN_TYPE_AP:
1706 memcpy(&TO_ENTRY_CONN(conn)->entry_cfg, &listener->entry_cfg,
1707 sizeof(entry_port_cfg_t));
1708 TO_ENTRY_CONN(conn)->nym_epoch = get_signewnym_epoch();
1709 TO_ENTRY_CONN(conn)->socks_request->listener_type = listener->base_.type;
1711 switch (TO_CONN(listener)->type) {
1712 case CONN_TYPE_AP_LISTENER:
1713 conn->state = AP_CONN_STATE_SOCKS_WAIT;
1714 TO_ENTRY_CONN(conn)->socks_request->socks_prefer_no_auth =
1715 listener->entry_cfg.socks_prefer_no_auth;
1716 break;
1717 case CONN_TYPE_AP_TRANS_LISTENER:
1718 TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
1719 /* XXXX028 -- is this correct still, with the addition of
1720 * pending_entry_connections ? */
1721 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1722 return connection_ap_process_transparent(TO_ENTRY_CONN(conn));
1723 case CONN_TYPE_AP_NATD_LISTENER:
1724 TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
1725 conn->state = AP_CONN_STATE_NATD_WAIT;
1726 break;
1727 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER:
1728 conn->state = AP_CONN_STATE_HTTP_CONNECT_WAIT;
1730 break;
1731 case CONN_TYPE_DIR:
1732 conn->purpose = DIR_PURPOSE_SERVER;
1733 conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
1734 break;
1735 case CONN_TYPE_CONTROL:
1736 conn->state = CONTROL_CONN_STATE_NEEDAUTH;
1737 break;
1739 return 0;
1742 /** Take conn, make a nonblocking socket; try to connect to
1743 * sa, binding to bindaddr if sa is not localhost. If fail, return -1 and if
1744 * applicable put your best guess about errno into *<b>socket_error</b>.
1745 * If connected return 1, if EAGAIN return 0.
1747 MOCK_IMPL(STATIC int,
1748 connection_connect_sockaddr,(connection_t *conn,
1749 const struct sockaddr *sa,
1750 socklen_t sa_len,
1751 const struct sockaddr *bindaddr,
1752 socklen_t bindaddr_len,
1753 int *socket_error))
1755 tor_socket_t s;
1756 int inprogress = 0;
1757 const or_options_t *options = get_options();
1759 tor_assert(conn);
1760 tor_assert(sa);
1761 tor_assert(socket_error);
1763 if (get_options()->DisableNetwork) {
1764 /* We should never even try to connect anyplace if DisableNetwork is set.
1765 * Warn if we do, and refuse to make the connection.
1767 * We only check DisableNetwork here, not we_are_hibernating(), since
1768 * we'll still try to fulfill client requests sometimes in the latter case
1769 * (if it is soft hibernation) */
1770 static ratelim_t disablenet_violated = RATELIM_INIT(30*60);
1771 *socket_error = SOCK_ERRNO(ENETUNREACH);
1772 log_fn_ratelim(&disablenet_violated, LOG_WARN, LD_BUG,
1773 "Tried to open a socket with DisableNetwork set.");
1774 tor_fragile_assert();
1775 return -1;
1778 const int protocol_family = sa->sa_family;
1779 const int proto = (sa->sa_family == AF_INET6 ||
1780 sa->sa_family == AF_INET) ? IPPROTO_TCP : 0;
1782 s = tor_open_socket_nonblocking(protocol_family, SOCK_STREAM, proto);
1783 if (! SOCKET_OK(s)) {
1785 * Early OOS handler calls; it matters if it's an exhaustion-related
1786 * error or not.
1788 *socket_error = tor_socket_errno(s);
1789 if (ERRNO_IS_RESOURCE_LIMIT(*socket_error)) {
1790 warn_too_many_conns();
1791 connection_check_oos(get_n_open_sockets(), 1);
1792 } else {
1793 log_warn(LD_NET,"Error creating network socket: %s",
1794 tor_socket_strerror(*socket_error));
1795 connection_check_oos(get_n_open_sockets(), 0);
1797 return -1;
1800 if (make_socket_reuseable(s) < 0) {
1801 log_warn(LD_NET, "Error setting SO_REUSEADDR flag on new connection: %s",
1802 tor_socket_strerror(errno));
1806 * We've got the socket open; give the OOS handler a chance to check
1807 * against configured maximum socket number, but tell it no exhaustion
1808 * failure.
1810 connection_check_oos(get_n_open_sockets(), 0);
1812 if (bindaddr && bind(s, bindaddr, bindaddr_len) < 0) {
1813 *socket_error = tor_socket_errno(s);
1814 log_warn(LD_NET,"Error binding network socket: %s",
1815 tor_socket_strerror(*socket_error));
1816 tor_close_socket(s);
1817 return -1;
1820 tor_assert(options);
1821 if (options->ConstrainedSockets)
1822 set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
1824 if (connect(s, sa, sa_len) < 0) {
1825 int e = tor_socket_errno(s);
1826 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
1827 /* yuck. kill it. */
1828 *socket_error = e;
1829 log_info(LD_NET,
1830 "connect() to socket failed: %s",
1831 tor_socket_strerror(e));
1832 tor_close_socket(s);
1833 return -1;
1834 } else {
1835 inprogress = 1;
1839 /* it succeeded. we're connected. */
1840 log_fn(inprogress ? LOG_DEBUG : LOG_INFO, LD_NET,
1841 "Connection to socket %s (sock "TOR_SOCKET_T_FORMAT").",
1842 inprogress ? "in progress" : "established", s);
1843 conn->s = s;
1844 if (connection_add_connecting(conn) < 0) {
1845 /* no space, forget it */
1846 *socket_error = SOCK_ERRNO(ENOBUFS);
1847 return -1;
1850 return inprogress ? 0 : 1;
1853 /* Log a message if connection attempt is made when IPv4 or IPv6 is disabled.
1854 * Log a less severe message if we couldn't conform to ClientPreferIPv6ORPort
1855 * or ClientPreferIPv6ORPort. */
1856 static void
1857 connection_connect_log_client_use_ip_version(const connection_t *conn)
1859 const or_options_t *options = get_options();
1861 /* Only clients care about ClientUseIPv4/6, bail out early on servers, and
1862 * on connections we don't care about */
1863 if (server_mode(options) || !conn || conn->type == CONN_TYPE_EXIT) {
1864 return;
1867 /* We're only prepared to log OR and DIR connections here */
1868 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR) {
1869 return;
1872 const int must_ipv4 = !fascist_firewall_use_ipv6(options);
1873 const int must_ipv6 = (options->ClientUseIPv4 == 0);
1874 const int pref_ipv6 = (conn->type == CONN_TYPE_OR
1875 ? fascist_firewall_prefer_ipv6_orport(options)
1876 : fascist_firewall_prefer_ipv6_dirport(options));
1877 tor_addr_t real_addr;
1878 tor_addr_make_null(&real_addr, AF_UNSPEC);
1880 /* OR conns keep the original address in real_addr, as addr gets overwritten
1881 * with the descriptor address */
1882 if (conn->type == CONN_TYPE_OR) {
1883 const or_connection_t *or_conn = TO_OR_CONN((connection_t *)conn);
1884 tor_addr_copy(&real_addr, &or_conn->real_addr);
1885 } else if (conn->type == CONN_TYPE_DIR) {
1886 tor_addr_copy(&real_addr, &conn->addr);
1889 /* Check if we broke a mandatory address family restriction */
1890 if ((must_ipv4 && tor_addr_family(&real_addr) == AF_INET6)
1891 || (must_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
1892 static int logged_backtrace = 0;
1893 log_info(LD_BUG, "Outgoing %s connection to %s violated ClientUseIPv%s 0.",
1894 conn->type == CONN_TYPE_OR ? "OR" : "Dir",
1895 fmt_addr(&real_addr),
1896 options->ClientUseIPv4 == 0 ? "4" : "6");
1897 if (!logged_backtrace) {
1898 log_backtrace(LOG_INFO, LD_BUG, "Address came from");
1899 logged_backtrace = 1;
1903 /* Bridges are allowed to break IPv4/IPv6 ORPort preferences to connect to
1904 * the node's configured address when ClientPreferIPv6ORPort is auto */
1905 if (options->UseBridges && conn->type == CONN_TYPE_OR
1906 && options->ClientPreferIPv6ORPort == -1) {
1907 return;
1910 /* Check if we couldn't satisfy an address family preference */
1911 if ((!pref_ipv6 && tor_addr_family(&real_addr) == AF_INET6)
1912 || (pref_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
1913 log_info(LD_NET, "Outgoing connection to %s doesn't satisfy "
1914 "ClientPreferIPv6%sPort %d, with ClientUseIPv4 %d, and "
1915 "fascist_firewall_use_ipv6 %d (ClientUseIPv6 %d and UseBridges "
1916 "%d).",
1917 fmt_addr(&real_addr),
1918 conn->type == CONN_TYPE_OR ? "OR" : "Dir",
1919 conn->type == CONN_TYPE_OR ? options->ClientPreferIPv6ORPort
1920 : options->ClientPreferIPv6DirPort,
1921 options->ClientUseIPv4, fascist_firewall_use_ipv6(options),
1922 options->ClientUseIPv6, options->UseBridges);
1926 /** Retrieve the outbound address depending on the protocol (IPv4 or IPv6)
1927 * and the connection type (relay, exit, ...)
1928 * Return a socket address or NULL in case nothing is configured.
1930 const tor_addr_t *
1931 conn_get_outbound_address(sa_family_t family,
1932 const or_options_t *options, unsigned int conn_type)
1934 const tor_addr_t *ext_addr = NULL;
1936 int fam_index;
1937 switch (family) {
1938 case AF_INET:
1939 fam_index = 0;
1940 break;
1941 case AF_INET6:
1942 fam_index = 1;
1943 break;
1944 default:
1945 return NULL;
1948 // If an exit connection, use the exit address (if present)
1949 if (conn_type == CONN_TYPE_EXIT) {
1950 if (!tor_addr_is_null(
1951 &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT][fam_index])) {
1952 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT]
1953 [fam_index];
1954 } else if (!tor_addr_is_null(
1955 &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
1956 [fam_index])) {
1957 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
1958 [fam_index];
1960 } else { // All non-exit connections
1961 if (!tor_addr_is_null(
1962 &options->OutboundBindAddresses[OUTBOUND_ADDR_OR][fam_index])) {
1963 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_OR]
1964 [fam_index];
1965 } else if (!tor_addr_is_null(
1966 &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
1967 [fam_index])) {
1968 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT_AND_OR]
1969 [fam_index];
1972 return ext_addr;
1975 /** Take conn, make a nonblocking socket; try to connect to
1976 * addr:port (port arrives in *host order*). If fail, return -1 and if
1977 * applicable put your best guess about errno into *<b>socket_error</b>.
1978 * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
1980 * addr:port can be different to conn->addr:conn->port if connecting through
1981 * a proxy.
1983 * address is used to make the logs useful.
1985 * On success, add conn to the list of polled connections.
1988 connection_connect(connection_t *conn, const char *address,
1989 const tor_addr_t *addr, uint16_t port, int *socket_error)
1991 struct sockaddr_storage addrbuf;
1992 struct sockaddr_storage bind_addr_ss;
1993 struct sockaddr *bind_addr = NULL;
1994 struct sockaddr *dest_addr;
1995 int dest_addr_len, bind_addr_len = 0;
1997 /* Log if we didn't stick to ClientUseIPv4/6 or ClientPreferIPv6OR/DirPort
1999 connection_connect_log_client_use_ip_version(conn);
2001 if (!tor_addr_is_loopback(addr)) {
2002 const tor_addr_t *ext_addr = NULL;
2003 ext_addr = conn_get_outbound_address(tor_addr_family(addr), get_options(),
2004 conn->type);
2005 if (ext_addr) {
2006 memset(&bind_addr_ss, 0, sizeof(bind_addr_ss));
2007 bind_addr_len = tor_addr_to_sockaddr(ext_addr, 0,
2008 (struct sockaddr *) &bind_addr_ss,
2009 sizeof(bind_addr_ss));
2010 if (bind_addr_len == 0) {
2011 log_warn(LD_NET,
2012 "Error converting OutboundBindAddress %s into sockaddr. "
2013 "Ignoring.", fmt_and_decorate_addr(ext_addr));
2014 } else {
2015 bind_addr = (struct sockaddr *)&bind_addr_ss;
2020 memset(&addrbuf,0,sizeof(addrbuf));
2021 dest_addr = (struct sockaddr*) &addrbuf;
2022 dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
2023 tor_assert(dest_addr_len > 0);
2025 log_debug(LD_NET, "Connecting to %s:%u.",
2026 escaped_safe_str_client(address), port);
2028 return connection_connect_sockaddr(conn, dest_addr, dest_addr_len,
2029 bind_addr, bind_addr_len, socket_error);
2032 #ifdef HAVE_SYS_UN_H
2034 /** Take conn, make a nonblocking socket; try to connect to
2035 * an AF_UNIX socket at socket_path. If fail, return -1 and if applicable
2036 * put your best guess about errno into *<b>socket_error</b>. Else assign s
2037 * to conn-\>s: if connected return 1, if EAGAIN return 0.
2039 * On success, add conn to the list of polled connections.
2042 connection_connect_unix(connection_t *conn, const char *socket_path,
2043 int *socket_error)
2045 struct sockaddr_un dest_addr;
2047 tor_assert(socket_path);
2049 /* Check that we'll be able to fit it into dest_addr later */
2050 if (strlen(socket_path) + 1 > sizeof(dest_addr.sun_path)) {
2051 log_warn(LD_NET,
2052 "Path %s is too long for an AF_UNIX socket\n",
2053 escaped_safe_str_client(socket_path));
2054 *socket_error = SOCK_ERRNO(ENAMETOOLONG);
2055 return -1;
2058 memset(&dest_addr, 0, sizeof(dest_addr));
2059 dest_addr.sun_family = AF_UNIX;
2060 strlcpy(dest_addr.sun_path, socket_path, sizeof(dest_addr.sun_path));
2062 log_debug(LD_NET,
2063 "Connecting to AF_UNIX socket at %s.",
2064 escaped_safe_str_client(socket_path));
2066 return connection_connect_sockaddr(conn,
2067 (struct sockaddr *)&dest_addr, sizeof(dest_addr),
2068 NULL, 0, socket_error);
2071 #endif /* defined(HAVE_SYS_UN_H) */
2073 /** Convert state number to string representation for logging purposes.
2075 static const char *
2076 connection_proxy_state_to_string(int state)
2078 static const char *unknown = "???";
2079 static const char *states[] = {
2080 "PROXY_NONE",
2081 "PROXY_INFANT",
2082 "PROXY_HTTPS_WANT_CONNECT_OK",
2083 "PROXY_SOCKS4_WANT_CONNECT_OK",
2084 "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
2085 "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
2086 "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
2087 "PROXY_SOCKS5_WANT_CONNECT_OK",
2088 "PROXY_CONNECTED",
2091 if (state < PROXY_NONE || state > PROXY_CONNECTED)
2092 return unknown;
2094 return states[state];
2097 /** Returns the global proxy type used by tor. Use this function for
2098 * logging or high-level purposes, don't use it to fill the
2099 * <b>proxy_type</b> field of or_connection_t; use the actual proxy
2100 * protocol instead.*/
2101 static int
2102 get_proxy_type(void)
2104 const or_options_t *options = get_options();
2106 if (options->ClientTransportPlugin)
2107 return PROXY_PLUGGABLE;
2108 else if (options->HTTPSProxy)
2109 return PROXY_CONNECT;
2110 else if (options->Socks4Proxy)
2111 return PROXY_SOCKS4;
2112 else if (options->Socks5Proxy)
2113 return PROXY_SOCKS5;
2114 else
2115 return PROXY_NONE;
2118 /* One byte for the version, one for the command, two for the
2119 port, and four for the addr... and, one more for the
2120 username NUL: */
2121 #define SOCKS4_STANDARD_BUFFER_SIZE (1 + 1 + 2 + 4 + 1)
2123 /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
2124 * for conn->addr:conn->port, authenticating with the auth details given
2125 * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
2126 * support authentication.
2128 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2129 * 0 otherwise.
2131 * Use connection_read_proxy_handshake() to complete the handshake.
2134 connection_proxy_connect(connection_t *conn, int type)
2136 const or_options_t *options;
2138 tor_assert(conn);
2140 options = get_options();
2142 switch (type) {
2143 case PROXY_CONNECT: {
2144 char buf[1024];
2145 char *base64_authenticator=NULL;
2146 const char *authenticator = options->HTTPSProxyAuthenticator;
2148 /* Send HTTP CONNECT and authentication (if available) in
2149 * one request */
2151 if (authenticator) {
2152 base64_authenticator = alloc_http_authenticator(authenticator);
2153 if (!base64_authenticator)
2154 log_warn(LD_OR, "Encoding https authenticator failed");
2157 if (base64_authenticator) {
2158 const char *addrport = fmt_addrport(&conn->addr, conn->port);
2159 tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.1\r\n"
2160 "Host: %s\r\n"
2161 "Proxy-Authorization: Basic %s\r\n\r\n",
2162 addrport,
2163 addrport,
2164 base64_authenticator);
2165 tor_free(base64_authenticator);
2166 } else {
2167 tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.0\r\n\r\n",
2168 fmt_addrport(&conn->addr, conn->port));
2171 connection_buf_add(buf, strlen(buf), conn);
2172 conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
2173 break;
2176 case PROXY_SOCKS4: {
2177 unsigned char *buf;
2178 uint16_t portn;
2179 uint32_t ip4addr;
2180 size_t buf_size = 0;
2181 char *socks_args_string = NULL;
2183 /* Send a SOCKS4 connect request */
2185 if (tor_addr_family(&conn->addr) != AF_INET) {
2186 log_warn(LD_NET, "SOCKS4 client is incompatible with IPv6");
2187 return -1;
2190 { /* If we are here because we are trying to connect to a
2191 pluggable transport proxy, check if we have any SOCKS
2192 arguments to transmit. If we do, compress all arguments to
2193 a single string in 'socks_args_string': */
2195 if (get_proxy_type() == PROXY_PLUGGABLE) {
2196 socks_args_string =
2197 pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
2198 if (socks_args_string)
2199 log_debug(LD_NET, "Sending out '%s' as our SOCKS argument string.",
2200 socks_args_string);
2204 { /* Figure out the buffer size we need for the SOCKS message: */
2206 buf_size = SOCKS4_STANDARD_BUFFER_SIZE;
2208 /* If we have a SOCKS argument string, consider its size when
2209 calculating the buffer size: */
2210 if (socks_args_string)
2211 buf_size += strlen(socks_args_string);
2214 buf = tor_malloc_zero(buf_size);
2216 ip4addr = tor_addr_to_ipv4n(&conn->addr);
2217 portn = htons(conn->port);
2219 buf[0] = 4; /* version */
2220 buf[1] = SOCKS_COMMAND_CONNECT; /* command */
2221 memcpy(buf + 2, &portn, 2); /* port */
2222 memcpy(buf + 4, &ip4addr, 4); /* addr */
2224 /* Next packet field is the userid. If we have pluggable
2225 transport SOCKS arguments, we have to embed them
2226 there. Otherwise, we use an empty userid. */
2227 if (socks_args_string) { /* place the SOCKS args string: */
2228 tor_assert(strlen(socks_args_string) > 0);
2229 tor_assert(buf_size >=
2230 SOCKS4_STANDARD_BUFFER_SIZE + strlen(socks_args_string));
2231 strlcpy((char *)buf + 8, socks_args_string, buf_size - 8);
2232 tor_free(socks_args_string);
2233 } else {
2234 buf[8] = 0; /* no userid */
2237 connection_buf_add((char *)buf, buf_size, conn);
2238 tor_free(buf);
2240 conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
2241 break;
2244 case PROXY_SOCKS5: {
2245 unsigned char buf[4]; /* fields: vers, num methods, method list */
2247 /* Send a SOCKS5 greeting (connect request must wait) */
2249 buf[0] = 5; /* version */
2251 /* We have to use SOCKS5 authentication, if we have a
2252 Socks5ProxyUsername or if we want to pass arguments to our
2253 pluggable transport proxy: */
2254 if ((options->Socks5ProxyUsername) ||
2255 (get_proxy_type() == PROXY_PLUGGABLE &&
2256 (get_socks_args_by_bridge_addrport(&conn->addr, conn->port)))) {
2257 /* number of auth methods */
2258 buf[1] = 2;
2259 buf[2] = 0x00; /* no authentication */
2260 buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
2261 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
2262 } else {
2263 buf[1] = 1;
2264 buf[2] = 0x00; /* no authentication */
2265 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
2268 connection_buf_add((char *)buf, 2 + buf[1], conn);
2269 break;
2272 default:
2273 log_err(LD_BUG, "Invalid proxy protocol, %d", type);
2274 tor_fragile_assert();
2275 return -1;
2278 log_debug(LD_NET, "set state %s",
2279 connection_proxy_state_to_string(conn->proxy_state));
2281 return 0;
2284 /** Read conn's inbuf. If the http response from the proxy is all
2285 * here, make sure it's good news, then return 1. If it's bad news,
2286 * return -1. Else return 0 and hope for better luck next time.
2288 static int
2289 connection_read_https_proxy_response(connection_t *conn)
2291 char *headers;
2292 char *reason=NULL;
2293 int status_code;
2294 time_t date_header;
2296 switch (fetch_from_buf_http(conn->inbuf,
2297 &headers, MAX_HEADERS_SIZE,
2298 NULL, NULL, 10000, 0)) {
2299 case -1: /* overflow */
2300 log_warn(LD_PROTOCOL,
2301 "Your https proxy sent back an oversized response. Closing.");
2302 return -1;
2303 case 0:
2304 log_info(LD_NET,"https proxy response not all here yet. Waiting.");
2305 return 0;
2306 /* case 1, fall through */
2309 if (parse_http_response(headers, &status_code, &date_header,
2310 NULL, &reason) < 0) {
2311 log_warn(LD_NET,
2312 "Unparseable headers from proxy (connecting to '%s'). Closing.",
2313 conn->address);
2314 tor_free(headers);
2315 return -1;
2317 tor_free(headers);
2318 if (!reason) reason = tor_strdup("[no reason given]");
2320 if (status_code == 200) {
2321 log_info(LD_NET,
2322 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
2323 conn->address, escaped(reason));
2324 tor_free(reason);
2325 return 1;
2327 /* else, bad news on the status code */
2328 switch (status_code) {
2329 case 403:
2330 log_warn(LD_NET,
2331 "The https proxy refused to allow connection to %s "
2332 "(status code %d, %s). Closing.",
2333 conn->address, status_code, escaped(reason));
2334 break;
2335 default:
2336 log_warn(LD_NET,
2337 "The https proxy sent back an unexpected status code %d (%s). "
2338 "Closing.",
2339 status_code, escaped(reason));
2340 break;
2342 tor_free(reason);
2343 return -1;
2346 /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
2347 * and <b>conn->port</b> into the request.
2349 static void
2350 connection_send_socks5_connect(connection_t *conn)
2352 unsigned char buf[1024];
2353 size_t reqsize = 6;
2354 uint16_t port = htons(conn->port);
2356 buf[0] = 5; /* version */
2357 buf[1] = SOCKS_COMMAND_CONNECT; /* command */
2358 buf[2] = 0; /* reserved */
2360 if (tor_addr_family(&conn->addr) == AF_INET) {
2361 uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
2363 buf[3] = 1;
2364 reqsize += 4;
2365 memcpy(buf + 4, &addr, 4);
2366 memcpy(buf + 8, &port, 2);
2367 } else { /* AF_INET6 */
2368 buf[3] = 4;
2369 reqsize += 16;
2370 memcpy(buf + 4, tor_addr_to_in6_addr8(&conn->addr), 16);
2371 memcpy(buf + 20, &port, 2);
2374 connection_buf_add((char *)buf, reqsize, conn);
2376 conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
2379 /** Wrapper around fetch_from_buf_socks_client: see that functions
2380 * for documentation of its behavior. */
2381 static int
2382 connection_fetch_from_buf_socks_client(connection_t *conn,
2383 int state, char **reason)
2385 return fetch_from_buf_socks_client(conn->inbuf, state, reason);
2388 /** Call this from connection_*_process_inbuf() to advance the proxy
2389 * handshake.
2391 * No matter what proxy protocol is used, if this function returns 1, the
2392 * handshake is complete, and the data remaining on inbuf may contain the
2393 * start of the communication with the requested server.
2395 * Returns 0 if the current buffer contains an incomplete response, and -1
2396 * on error.
2399 connection_read_proxy_handshake(connection_t *conn)
2401 int ret = 0;
2402 char *reason = NULL;
2404 log_debug(LD_NET, "enter state %s",
2405 connection_proxy_state_to_string(conn->proxy_state));
2407 switch (conn->proxy_state) {
2408 case PROXY_HTTPS_WANT_CONNECT_OK:
2409 ret = connection_read_https_proxy_response(conn);
2410 if (ret == 1)
2411 conn->proxy_state = PROXY_CONNECTED;
2412 break;
2414 case PROXY_SOCKS4_WANT_CONNECT_OK:
2415 ret = connection_fetch_from_buf_socks_client(conn,
2416 conn->proxy_state,
2417 &reason);
2418 if (ret == 1)
2419 conn->proxy_state = PROXY_CONNECTED;
2420 break;
2422 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
2423 ret = connection_fetch_from_buf_socks_client(conn,
2424 conn->proxy_state,
2425 &reason);
2426 /* no auth needed, do connect */
2427 if (ret == 1) {
2428 connection_send_socks5_connect(conn);
2429 ret = 0;
2431 break;
2433 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
2434 ret = connection_fetch_from_buf_socks_client(conn,
2435 conn->proxy_state,
2436 &reason);
2438 /* send auth if needed, otherwise do connect */
2439 if (ret == 1) {
2440 connection_send_socks5_connect(conn);
2441 ret = 0;
2442 } else if (ret == 2) {
2443 unsigned char buf[1024];
2444 size_t reqsize, usize, psize;
2445 const char *user, *pass;
2446 char *socks_args_string = NULL;
2448 if (get_proxy_type() == PROXY_PLUGGABLE) {
2449 socks_args_string =
2450 pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
2451 if (!socks_args_string) {
2452 log_warn(LD_NET, "Could not create SOCKS args string.");
2453 ret = -1;
2454 break;
2457 log_debug(LD_NET, "SOCKS5 arguments: %s", socks_args_string);
2458 tor_assert(strlen(socks_args_string) > 0);
2459 tor_assert(strlen(socks_args_string) <= MAX_SOCKS5_AUTH_SIZE_TOTAL);
2461 if (strlen(socks_args_string) > MAX_SOCKS5_AUTH_FIELD_SIZE) {
2462 user = socks_args_string;
2463 usize = MAX_SOCKS5_AUTH_FIELD_SIZE;
2464 pass = socks_args_string + MAX_SOCKS5_AUTH_FIELD_SIZE;
2465 psize = strlen(socks_args_string) - MAX_SOCKS5_AUTH_FIELD_SIZE;
2466 } else {
2467 user = socks_args_string;
2468 usize = strlen(socks_args_string);
2469 pass = "\0";
2470 psize = 1;
2472 } else if (get_options()->Socks5ProxyUsername) {
2473 user = get_options()->Socks5ProxyUsername;
2474 pass = get_options()->Socks5ProxyPassword;
2475 tor_assert(user && pass);
2476 usize = strlen(user);
2477 psize = strlen(pass);
2478 } else {
2479 log_err(LD_BUG, "We entered %s for no reason!", __func__);
2480 tor_fragile_assert();
2481 ret = -1;
2482 break;
2485 /* Username and password lengths should have been checked
2486 above and during torrc parsing. */
2487 tor_assert(usize <= MAX_SOCKS5_AUTH_FIELD_SIZE &&
2488 psize <= MAX_SOCKS5_AUTH_FIELD_SIZE);
2489 reqsize = 3 + usize + psize;
2491 buf[0] = 1; /* negotiation version */
2492 buf[1] = usize;
2493 memcpy(buf + 2, user, usize);
2494 buf[2 + usize] = psize;
2495 memcpy(buf + 3 + usize, pass, psize);
2497 if (socks_args_string)
2498 tor_free(socks_args_string);
2500 connection_buf_add((char *)buf, reqsize, conn);
2502 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
2503 ret = 0;
2505 break;
2507 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
2508 ret = connection_fetch_from_buf_socks_client(conn,
2509 conn->proxy_state,
2510 &reason);
2511 /* send the connect request */
2512 if (ret == 1) {
2513 connection_send_socks5_connect(conn);
2514 ret = 0;
2516 break;
2518 case PROXY_SOCKS5_WANT_CONNECT_OK:
2519 ret = connection_fetch_from_buf_socks_client(conn,
2520 conn->proxy_state,
2521 &reason);
2522 if (ret == 1)
2523 conn->proxy_state = PROXY_CONNECTED;
2524 break;
2526 default:
2527 log_err(LD_BUG, "Invalid proxy_state for reading, %d",
2528 conn->proxy_state);
2529 tor_fragile_assert();
2530 ret = -1;
2531 break;
2534 log_debug(LD_NET, "leaving state %s",
2535 connection_proxy_state_to_string(conn->proxy_state));
2537 if (ret < 0) {
2538 if (reason) {
2539 log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d (%s)",
2540 conn->address, conn->port, escaped(reason));
2541 tor_free(reason);
2542 } else {
2543 log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d",
2544 conn->address, conn->port);
2546 } else if (ret == 1) {
2547 log_info(LD_NET, "Proxy Client: connection to %s:%d successful",
2548 conn->address, conn->port);
2551 return ret;
2554 /** Given a list of listener connections in <b>old_conns</b>, and list of
2555 * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
2556 * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
2558 * Remove from <b>old_conns</b> every connection that has a corresponding
2559 * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
2560 * launch.
2562 * If <b>control_listeners_only</b> is true, then we only open control
2563 * listeners, and we do not remove any noncontrol listeners from old_conns.
2565 * Return 0 on success, -1 on failure.
2567 static int
2568 retry_listener_ports(smartlist_t *old_conns,
2569 const smartlist_t *ports,
2570 smartlist_t *new_conns,
2571 int control_listeners_only)
2573 smartlist_t *launch = smartlist_new();
2574 int r = 0;
2576 if (control_listeners_only) {
2577 SMARTLIST_FOREACH(ports, port_cfg_t *, p, {
2578 if (p->type == CONN_TYPE_CONTROL_LISTENER)
2579 smartlist_add(launch, p);
2581 } else {
2582 smartlist_add_all(launch, ports);
2585 /* Iterate through old_conns, comparing it to launch: remove from both lists
2586 * each pair of elements that corresponds to the same port. */
2587 SMARTLIST_FOREACH_BEGIN(old_conns, connection_t *, conn) {
2588 const port_cfg_t *found_port = NULL;
2590 /* Okay, so this is a listener. Is it configured? */
2591 SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, wanted) {
2592 if (conn->type != wanted->type)
2593 continue;
2594 if ((conn->socket_family != AF_UNIX && wanted->is_unix_addr) ||
2595 (conn->socket_family == AF_UNIX && ! wanted->is_unix_addr))
2596 continue;
2598 if (wanted->server_cfg.no_listen)
2599 continue; /* We don't want to open a listener for this one */
2601 if (wanted->is_unix_addr) {
2602 if (conn->socket_family == AF_UNIX &&
2603 !strcmp(wanted->unix_addr, conn->address)) {
2604 found_port = wanted;
2605 break;
2607 } else {
2608 int port_matches;
2609 if (wanted->port == CFG_AUTO_PORT) {
2610 port_matches = 1;
2611 } else {
2612 port_matches = (wanted->port == conn->port);
2614 if (port_matches && tor_addr_eq(&wanted->addr, &conn->addr)) {
2615 found_port = wanted;
2616 break;
2619 } SMARTLIST_FOREACH_END(wanted);
2621 if (found_port) {
2622 /* This listener is already running; we don't need to launch it. */
2623 //log_debug(LD_NET, "Already have %s on %s:%d",
2624 // conn_type_to_string(found_port->type), conn->address, conn->port);
2625 smartlist_remove(launch, found_port);
2626 /* And we can remove the connection from old_conns too. */
2627 SMARTLIST_DEL_CURRENT(old_conns, conn);
2629 } SMARTLIST_FOREACH_END(conn);
2631 /* Now open all the listeners that are configured but not opened. */
2632 SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, port) {
2633 struct sockaddr *listensockaddr;
2634 socklen_t listensocklen = 0;
2635 char *address=NULL;
2636 connection_t *conn;
2637 int real_port = port->port == CFG_AUTO_PORT ? 0 : port->port;
2638 tor_assert(real_port <= UINT16_MAX);
2639 if (port->server_cfg.no_listen)
2640 continue;
2642 #ifndef _WIN32
2643 /* We don't need to be root to create a UNIX socket, so defer until after
2644 * setuid. */
2645 const or_options_t *options = get_options();
2646 if (port->is_unix_addr && !geteuid() && (options->User) &&
2647 strcmp(options->User, "root"))
2648 continue;
2649 #endif /* !defined(_WIN32) */
2651 if (port->is_unix_addr) {
2652 listensockaddr = (struct sockaddr *)
2653 create_unix_sockaddr(port->unix_addr,
2654 &address, &listensocklen);
2655 } else {
2656 listensockaddr = tor_malloc(sizeof(struct sockaddr_storage));
2657 listensocklen = tor_addr_to_sockaddr(&port->addr,
2658 real_port,
2659 listensockaddr,
2660 sizeof(struct sockaddr_storage));
2661 address = tor_addr_to_str_dup(&port->addr);
2664 if (listensockaddr) {
2665 conn = connection_listener_new(listensockaddr, listensocklen,
2666 port->type, address, port);
2667 tor_free(listensockaddr);
2668 tor_free(address);
2669 } else {
2670 conn = NULL;
2673 if (!conn) {
2674 r = -1;
2675 } else {
2676 if (new_conns)
2677 smartlist_add(new_conns, conn);
2679 } SMARTLIST_FOREACH_END(port);
2681 smartlist_free(launch);
2683 return r;
2686 /** Launch listeners for each port you should have open. Only launch
2687 * listeners who are not already open, and only close listeners we no longer
2688 * want.
2690 * Add all old conns that should be closed to <b>replaced_conns</b>.
2691 * Add all new connections to <b>new_conns</b>.
2693 * If <b>close_all_noncontrol</b> is true, then we only open control
2694 * listeners, and we close all other listeners.
2697 retry_all_listeners(smartlist_t *replaced_conns,
2698 smartlist_t *new_conns, int close_all_noncontrol)
2700 smartlist_t *listeners = smartlist_new();
2701 const or_options_t *options = get_options();
2702 int retval = 0;
2703 const uint16_t old_or_port = router_get_advertised_or_port(options);
2704 const uint16_t old_or_port_ipv6 =
2705 router_get_advertised_or_port_by_af(options,AF_INET6);
2706 const uint16_t old_dir_port = router_get_advertised_dir_port(options, 0);
2708 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
2709 if (connection_is_listener(conn) && !conn->marked_for_close)
2710 smartlist_add(listeners, conn);
2711 } SMARTLIST_FOREACH_END(conn);
2713 if (retry_listener_ports(listeners,
2714 get_configured_ports(),
2715 new_conns,
2716 close_all_noncontrol) < 0)
2717 retval = -1;
2719 /* Any members that were still in 'listeners' don't correspond to
2720 * any configured port. Kill 'em. */
2721 SMARTLIST_FOREACH_BEGIN(listeners, connection_t *, conn) {
2722 log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
2723 conn_type_to_string(conn->type), conn->address, conn->port);
2724 if (replaced_conns) {
2725 smartlist_add(replaced_conns, conn);
2726 } else {
2727 connection_close_immediate(conn);
2728 connection_mark_for_close(conn);
2730 } SMARTLIST_FOREACH_END(conn);
2732 smartlist_free(listeners);
2734 if (old_or_port != router_get_advertised_or_port(options) ||
2735 old_or_port_ipv6 != router_get_advertised_or_port_by_af(options,
2736 AF_INET6) ||
2737 old_dir_port != router_get_advertised_dir_port(options, 0)) {
2738 /* Our chosen ORPort or DirPort is not what it used to be: the
2739 * descriptor we had (if any) should be regenerated. (We won't
2740 * automatically notice this because of changes in the option,
2741 * since the value could be "auto".) */
2742 mark_my_descriptor_dirty("Chosen Or/DirPort changed");
2745 return retval;
2748 /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
2749 void
2750 connection_mark_all_noncontrol_listeners(void)
2752 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
2753 if (conn->marked_for_close)
2754 continue;
2755 if (conn->type == CONN_TYPE_CONTROL_LISTENER)
2756 continue;
2757 if (connection_is_listener(conn))
2758 connection_mark_for_close(conn);
2759 } SMARTLIST_FOREACH_END(conn);
2762 /** Mark every external connection not used for controllers for close. */
2763 void
2764 connection_mark_all_noncontrol_connections(void)
2766 SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
2767 if (conn->marked_for_close)
2768 continue;
2769 switch (conn->type) {
2770 case CONN_TYPE_CONTROL_LISTENER:
2771 case CONN_TYPE_CONTROL:
2772 break;
2773 case CONN_TYPE_AP:
2774 connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
2775 END_STREAM_REASON_HIBERNATING);
2776 break;
2777 case CONN_TYPE_OR:
2779 or_connection_t *orconn = TO_OR_CONN(conn);
2780 if (orconn->chan) {
2781 connection_or_close_normally(orconn, 0);
2782 } else {
2784 * There should have been one, but mark for close and hope
2785 * for the best..
2787 connection_mark_for_close(conn);
2790 break;
2791 default:
2792 connection_mark_for_close(conn);
2793 break;
2795 } SMARTLIST_FOREACH_END(conn);
2798 /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
2799 * otherwise.
2800 * Right now this just checks if it's an internal IP address or an
2801 * internal connection. We also should, but don't, check if the connection
2802 * uses pluggable transports, since we should then limit it even if it
2803 * comes from an internal IP address. */
2804 static int
2805 connection_is_rate_limited(connection_t *conn)
2807 const or_options_t *options = get_options();
2808 if (conn->linked)
2809 return 0; /* Internal connection */
2810 else if (! options->CountPrivateBandwidth &&
2811 (tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
2812 tor_addr_family(&conn->addr) == AF_UNIX || /* no address */
2813 tor_addr_is_internal(&conn->addr, 0)))
2814 return 0; /* Internal address */
2815 else
2816 return 1;
2819 /** Did either global write bucket run dry last second? If so,
2820 * we are likely to run dry again this second, so be stingy with the
2821 * tokens we just put in. */
2822 static int write_buckets_empty_last_second = 0;
2824 /** How many seconds of no active local circuits will make the
2825 * connection revert to the "relayed" bandwidth class? */
2826 #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
2828 /** Return 1 if <b>conn</b> should use tokens from the "relayed"
2829 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
2830 * class 1, and directory conns that are serving data out, count.
2832 static int
2833 connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
2835 if (conn->type == CONN_TYPE_OR &&
2836 connection_or_client_used(TO_OR_CONN(conn)) +
2837 CLIENT_IDLE_TIME_FOR_PRIORITY < now)
2838 return 1;
2839 if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
2840 return 1;
2841 return 0;
2844 /** Helper function to decide how many bytes out of <b>global_bucket</b>
2845 * we're willing to use for this transaction. <b>base</b> is the size
2846 * of a cell on the network; <b>priority</b> says whether we should
2847 * write many of them or just a few; and <b>conn_bucket</b> (if
2848 * non-negative) provides an upper limit for our answer. */
2849 static ssize_t
2850 connection_bucket_round_robin(int base, int priority,
2851 ssize_t global_bucket, ssize_t conn_bucket)
2853 ssize_t at_most;
2854 ssize_t num_bytes_high = (priority ? 32 : 16) * base;
2855 ssize_t num_bytes_low = (priority ? 4 : 2) * base;
2857 /* Do a rudimentary round-robin so one circuit can't hog a connection.
2858 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
2859 * the middle pick 1/8 of the available bandwidth. */
2860 at_most = global_bucket / 8;
2861 at_most -= (at_most % base); /* round down */
2862 if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
2863 at_most = num_bytes_high;
2864 else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
2865 at_most = num_bytes_low;
2867 if (at_most > global_bucket)
2868 at_most = global_bucket;
2870 if (conn_bucket >= 0 && at_most > conn_bucket)
2871 at_most = conn_bucket;
2873 if (at_most < 0)
2874 return 0;
2875 return at_most;
2878 /** How many bytes at most can we read onto this connection? */
2879 static ssize_t
2880 connection_bucket_read_limit(connection_t *conn, time_t now)
2882 int base = RELAY_PAYLOAD_SIZE;
2883 int priority = conn->type != CONN_TYPE_DIR;
2884 int conn_bucket = -1;
2885 int global_bucket = global_read_bucket;
2887 if (connection_speaks_cells(conn)) {
2888 or_connection_t *or_conn = TO_OR_CONN(conn);
2889 if (conn->state == OR_CONN_STATE_OPEN)
2890 conn_bucket = or_conn->read_bucket;
2891 base = get_cell_network_size(or_conn->wide_circ_ids);
2894 if (!connection_is_rate_limited(conn)) {
2895 /* be willing to read on local conns even if our buckets are empty */
2896 return conn_bucket>=0 ? conn_bucket : 1<<14;
2899 if (connection_counts_as_relayed_traffic(conn, now) &&
2900 global_relayed_read_bucket <= global_read_bucket)
2901 global_bucket = global_relayed_read_bucket;
2903 return connection_bucket_round_robin(base, priority,
2904 global_bucket, conn_bucket);
2907 /** How many bytes at most can we write onto this connection? */
2908 ssize_t
2909 connection_bucket_write_limit(connection_t *conn, time_t now)
2911 int base = RELAY_PAYLOAD_SIZE;
2912 int priority = conn->type != CONN_TYPE_DIR;
2913 int conn_bucket = (int)conn->outbuf_flushlen;
2914 int global_bucket = global_write_bucket;
2916 if (!connection_is_rate_limited(conn)) {
2917 /* be willing to write to local conns even if our buckets are empty */
2918 return conn->outbuf_flushlen;
2921 if (connection_speaks_cells(conn)) {
2922 /* use the per-conn write limit if it's lower, but if it's less
2923 * than zero just use zero */
2924 or_connection_t *or_conn = TO_OR_CONN(conn);
2925 if (conn->state == OR_CONN_STATE_OPEN)
2926 if (or_conn->write_bucket < conn_bucket)
2927 conn_bucket = or_conn->write_bucket >= 0 ?
2928 or_conn->write_bucket : 0;
2929 base = get_cell_network_size(or_conn->wide_circ_ids);
2932 if (connection_counts_as_relayed_traffic(conn, now) &&
2933 global_relayed_write_bucket <= global_write_bucket)
2934 global_bucket = global_relayed_write_bucket;
2936 return connection_bucket_round_robin(base, priority,
2937 global_bucket, conn_bucket);
2940 /** Return 1 if the global write buckets are low enough that we
2941 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
2942 * out to <b>conn</b>. Else return 0.
2944 * Priority was 1 for v1 requests (directories and running-routers),
2945 * and 2 for v2 requests and later (statuses and descriptors).
2947 * There are a lot of parameters we could use here:
2948 * - global_relayed_write_bucket. Low is bad.
2949 * - global_write_bucket. Low is bad.
2950 * - bandwidthrate. Low is bad.
2951 * - bandwidthburst. Not a big factor?
2952 * - attempt. High is bad.
2953 * - total bytes queued on outbufs. High is bad. But I'm wary of
2954 * using this, since a few slow-flushing queues will pump up the
2955 * number without meaning what we meant to mean. What we really
2956 * mean is "total directory bytes added to outbufs recently", but
2957 * that's harder to quantify and harder to keep track of.
2960 global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
2962 int smaller_bucket = global_write_bucket < global_relayed_write_bucket ?
2963 global_write_bucket : global_relayed_write_bucket;
2964 if (authdir_mode(get_options()) && priority>1)
2965 return 0; /* there's always room to answer v2 if we're an auth dir */
2967 if (!connection_is_rate_limited(conn))
2968 return 0; /* local conns don't get limited */
2970 if (smaller_bucket < (int)attempt)
2971 return 1; /* not enough space no matter the priority */
2973 if (write_buckets_empty_last_second)
2974 return 1; /* we're already hitting our limits, no more please */
2976 if (priority == 1) { /* old-style v1 query */
2977 /* Could we handle *two* of these requests within the next two seconds? */
2978 const or_options_t *options = get_options();
2979 int64_t can_write = (int64_t)smaller_bucket
2980 + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
2981 options->BandwidthRate);
2982 if (can_write < 2*(int64_t)attempt)
2983 return 1;
2984 } else { /* v2 query */
2985 /* no further constraints yet */
2987 return 0;
2990 /** Helper: adjusts our bandwidth history and informs the controller as
2991 * appropriate, given that we have just read <b>num_read</b> bytes and written
2992 * <b>num_written</b> bytes on <b>conn</b>. */
2993 static void
2994 record_num_bytes_transferred_impl(connection_t *conn,
2995 time_t now, size_t num_read, size_t num_written)
2997 /* Count bytes of answering direct and tunneled directory requests */
2998 if (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER) {
2999 if (num_read > 0)
3000 rep_hist_note_dir_bytes_read(num_read, now);
3001 if (num_written > 0)
3002 rep_hist_note_dir_bytes_written(num_written, now);
3005 if (!connection_is_rate_limited(conn))
3006 return; /* local IPs are free */
3008 if (conn->type == CONN_TYPE_OR)
3009 rep_hist_note_or_conn_bytes(conn->global_identifier, num_read,
3010 num_written, now);
3012 if (num_read > 0) {
3013 rep_hist_note_bytes_read(num_read, now);
3015 if (num_written > 0) {
3016 rep_hist_note_bytes_written(num_written, now);
3018 if (conn->type == CONN_TYPE_EXIT)
3019 rep_hist_note_exit_bytes(conn->port, num_written, num_read);
3022 /** Helper: convert given <b>tvnow</b> time value to milliseconds since
3023 * midnight. */
3024 static uint32_t
3025 msec_since_midnight(const struct timeval *tvnow)
3027 return (uint32_t)(((tvnow->tv_sec % 86400L) * 1000L) +
3028 ((uint32_t)tvnow->tv_usec / (uint32_t)1000L));
3031 /** Helper: return the time in milliseconds since <b>last_empty_time</b>
3032 * when a bucket ran empty that previously had <b>tokens_before</b> tokens
3033 * now has <b>tokens_after</b> tokens after refilling at timestamp
3034 * <b>tvnow</b>, capped at <b>milliseconds_elapsed</b> milliseconds since
3035 * last refilling that bucket. Return 0 if the bucket has not been empty
3036 * since the last refill or has not been refilled. */
3037 uint32_t
3038 bucket_millis_empty(int tokens_before, uint32_t last_empty_time,
3039 int tokens_after, int milliseconds_elapsed,
3040 const struct timeval *tvnow)
3042 uint32_t result = 0, refilled;
3043 if (tokens_before <= 0 && tokens_after > tokens_before) {
3044 refilled = msec_since_midnight(tvnow);
3045 result = (uint32_t)((refilled + 86400L * 1000L - last_empty_time) %
3046 (86400L * 1000L));
3047 if (result > (uint32_t)milliseconds_elapsed)
3048 result = (uint32_t)milliseconds_elapsed;
3050 return result;
3053 /** Check if a bucket which had <b>tokens_before</b> tokens and which got
3054 * <b>tokens_removed</b> tokens removed at timestamp <b>tvnow</b> has run
3055 * out of tokens, and if so, note the milliseconds since midnight in
3056 * <b>timestamp_var</b> for the next TB_EMPTY event. */
3057 void
3058 connection_buckets_note_empty_ts(uint32_t *timestamp_var,
3059 int tokens_before, size_t tokens_removed,
3060 const struct timeval *tvnow)
3062 if (tokens_before > 0 && (uint32_t)tokens_before <= tokens_removed)
3063 *timestamp_var = msec_since_midnight(tvnow);
3066 /** Last time at which the global or relay buckets were emptied in msec
3067 * since midnight. */
3068 static uint32_t global_relayed_read_emptied = 0,
3069 global_relayed_write_emptied = 0,
3070 global_read_emptied = 0,
3071 global_write_emptied = 0;
3073 /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
3074 * onto <b>conn</b>. Decrement buckets appropriately. */
3075 static void
3076 connection_buckets_decrement(connection_t *conn, time_t now,
3077 size_t num_read, size_t num_written)
3079 if (num_written >= INT_MAX || num_read >= INT_MAX) {
3080 log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
3081 "connection type=%s, state=%s",
3082 (unsigned long)num_read, (unsigned long)num_written,
3083 conn_type_to_string(conn->type),
3084 conn_state_to_string(conn->type, conn->state));
3085 tor_assert_nonfatal_unreached();
3086 if (num_written >= INT_MAX)
3087 num_written = 1;
3088 if (num_read >= INT_MAX)
3089 num_read = 1;
3092 record_num_bytes_transferred_impl(conn, now, num_read, num_written);
3094 if (!connection_is_rate_limited(conn))
3095 return; /* local IPs are free */
3097 /* If one or more of our token buckets ran dry just now, note the
3098 * timestamp for TB_EMPTY events. */
3099 if (get_options()->TestingEnableTbEmptyEvent) {
3100 struct timeval tvnow;
3101 tor_gettimeofday_cached(&tvnow);
3102 if (connection_counts_as_relayed_traffic(conn, now)) {
3103 connection_buckets_note_empty_ts(&global_relayed_read_emptied,
3104 global_relayed_read_bucket, num_read, &tvnow);
3105 connection_buckets_note_empty_ts(&global_relayed_write_emptied,
3106 global_relayed_write_bucket, num_written, &tvnow);
3108 connection_buckets_note_empty_ts(&global_read_emptied,
3109 global_read_bucket, num_read, &tvnow);
3110 connection_buckets_note_empty_ts(&global_write_emptied,
3111 global_write_bucket, num_written, &tvnow);
3112 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
3113 or_connection_t *or_conn = TO_OR_CONN(conn);
3114 connection_buckets_note_empty_ts(&or_conn->read_emptied_time,
3115 or_conn->read_bucket, num_read, &tvnow);
3116 connection_buckets_note_empty_ts(&or_conn->write_emptied_time,
3117 or_conn->write_bucket, num_written, &tvnow);
3121 if (connection_counts_as_relayed_traffic(conn, now)) {
3122 global_relayed_read_bucket -= (int)num_read;
3123 global_relayed_write_bucket -= (int)num_written;
3125 global_read_bucket -= (int)num_read;
3126 global_write_bucket -= (int)num_written;
3127 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
3128 TO_OR_CONN(conn)->read_bucket -= (int)num_read;
3129 TO_OR_CONN(conn)->write_bucket -= (int)num_written;
3133 /** If we have exhausted our global buckets, or the buckets for conn,
3134 * stop reading. */
3135 static void
3136 connection_consider_empty_read_buckets(connection_t *conn)
3138 const char *reason;
3140 if (!connection_is_rate_limited(conn))
3141 return; /* Always okay. */
3143 if (global_read_bucket <= 0) {
3144 reason = "global read bucket exhausted. Pausing.";
3145 } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
3146 global_relayed_read_bucket <= 0) {
3147 reason = "global relayed read bucket exhausted. Pausing.";
3148 } else if (connection_speaks_cells(conn) &&
3149 conn->state == OR_CONN_STATE_OPEN &&
3150 TO_OR_CONN(conn)->read_bucket <= 0) {
3151 reason = "connection read bucket exhausted. Pausing.";
3152 } else
3153 return; /* all good, no need to stop it */
3155 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
3156 conn->read_blocked_on_bw = 1;
3157 connection_stop_reading(conn);
3160 /** If we have exhausted our global buckets, or the buckets for conn,
3161 * stop writing. */
3162 static void
3163 connection_consider_empty_write_buckets(connection_t *conn)
3165 const char *reason;
3167 if (!connection_is_rate_limited(conn))
3168 return; /* Always okay. */
3170 if (global_write_bucket <= 0) {
3171 reason = "global write bucket exhausted. Pausing.";
3172 } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
3173 global_relayed_write_bucket <= 0) {
3174 reason = "global relayed write bucket exhausted. Pausing.";
3175 } else if (connection_speaks_cells(conn) &&
3176 conn->state == OR_CONN_STATE_OPEN &&
3177 TO_OR_CONN(conn)->write_bucket <= 0) {
3178 reason = "connection write bucket exhausted. Pausing.";
3179 } else
3180 return; /* all good, no need to stop it */
3182 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
3183 conn->write_blocked_on_bw = 1;
3184 connection_stop_writing(conn);
3187 /** Initialize the global read bucket to options-\>BandwidthBurst. */
3188 void
3189 connection_bucket_init(void)
3191 const or_options_t *options = get_options();
3192 /* start it at max traffic */
3193 global_read_bucket = (int)options->BandwidthBurst;
3194 global_write_bucket = (int)options->BandwidthBurst;
3195 if (options->RelayBandwidthRate) {
3196 global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
3197 global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
3198 } else {
3199 global_relayed_read_bucket = (int)options->BandwidthBurst;
3200 global_relayed_write_bucket = (int)options->BandwidthBurst;
3204 /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate per
3205 * second <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
3206 * <b>milliseconds_elapsed</b> milliseconds have passed since the last
3207 * call. */
3208 static void
3209 connection_bucket_refill_helper(int *bucket, int rate, int burst,
3210 int milliseconds_elapsed,
3211 const char *name)
3213 int starting_bucket = *bucket;
3214 if (starting_bucket < burst && milliseconds_elapsed > 0) {
3215 int64_t incr = (((int64_t)rate) * milliseconds_elapsed) / 1000;
3216 if ((burst - starting_bucket) < incr) {
3217 *bucket = burst; /* We would overflow the bucket; just set it to
3218 * the maximum. */
3219 } else {
3220 *bucket += (int)incr;
3221 if (*bucket > burst || *bucket < starting_bucket) {
3222 /* If we overflow the burst, or underflow our starting bucket,
3223 * cap the bucket value to burst. */
3224 /* XXXX this might be redundant now, but it doesn't show up
3225 * in profiles. Remove it after analysis. */
3226 *bucket = burst;
3229 log_debug(LD_NET,"%s now %d.", name, *bucket);
3233 /** Time has passed; increment buckets appropriately. */
3234 void
3235 connection_bucket_refill(int milliseconds_elapsed, time_t now)
3237 const or_options_t *options = get_options();
3238 smartlist_t *conns = get_connection_array();
3239 int bandwidthrate, bandwidthburst, relayrate, relayburst;
3241 int prev_global_read = global_read_bucket;
3242 int prev_global_write = global_write_bucket;
3243 int prev_relay_read = global_relayed_read_bucket;
3244 int prev_relay_write = global_relayed_write_bucket;
3245 struct timeval tvnow; /*< Only used if TB_EMPTY events are enabled. */
3247 bandwidthrate = (int)options->BandwidthRate;
3248 bandwidthburst = (int)options->BandwidthBurst;
3250 if (options->RelayBandwidthRate) {
3251 relayrate = (int)options->RelayBandwidthRate;
3252 relayburst = (int)options->RelayBandwidthBurst;
3253 } else {
3254 relayrate = bandwidthrate;
3255 relayburst = bandwidthburst;
3258 tor_assert(milliseconds_elapsed >= 0);
3260 write_buckets_empty_last_second =
3261 global_relayed_write_bucket <= 0 || global_write_bucket <= 0;
3263 /* refill the global buckets */
3264 connection_bucket_refill_helper(&global_read_bucket,
3265 bandwidthrate, bandwidthburst,
3266 milliseconds_elapsed,
3267 "global_read_bucket");
3268 connection_bucket_refill_helper(&global_write_bucket,
3269 bandwidthrate, bandwidthburst,
3270 milliseconds_elapsed,
3271 "global_write_bucket");
3272 connection_bucket_refill_helper(&global_relayed_read_bucket,
3273 relayrate, relayburst,
3274 milliseconds_elapsed,
3275 "global_relayed_read_bucket");
3276 connection_bucket_refill_helper(&global_relayed_write_bucket,
3277 relayrate, relayburst,
3278 milliseconds_elapsed,
3279 "global_relayed_write_bucket");
3281 /* If buckets were empty before and have now been refilled, tell any
3282 * interested controllers. */
3283 if (get_options()->TestingEnableTbEmptyEvent) {
3284 uint32_t global_read_empty_time, global_write_empty_time,
3285 relay_read_empty_time, relay_write_empty_time;
3286 tor_gettimeofday_cached(&tvnow);
3287 global_read_empty_time = bucket_millis_empty(prev_global_read,
3288 global_read_emptied, global_read_bucket,
3289 milliseconds_elapsed, &tvnow);
3290 global_write_empty_time = bucket_millis_empty(prev_global_write,
3291 global_write_emptied, global_write_bucket,
3292 milliseconds_elapsed, &tvnow);
3293 control_event_tb_empty("GLOBAL", global_read_empty_time,
3294 global_write_empty_time, milliseconds_elapsed);
3295 relay_read_empty_time = bucket_millis_empty(prev_relay_read,
3296 global_relayed_read_emptied,
3297 global_relayed_read_bucket,
3298 milliseconds_elapsed, &tvnow);
3299 relay_write_empty_time = bucket_millis_empty(prev_relay_write,
3300 global_relayed_write_emptied,
3301 global_relayed_write_bucket,
3302 milliseconds_elapsed, &tvnow);
3303 control_event_tb_empty("RELAY", relay_read_empty_time,
3304 relay_write_empty_time, milliseconds_elapsed);
3307 /* refill the per-connection buckets */
3308 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
3309 if (connection_speaks_cells(conn)) {
3310 or_connection_t *or_conn = TO_OR_CONN(conn);
3311 int orbandwidthrate = or_conn->bandwidthrate;
3312 int orbandwidthburst = or_conn->bandwidthburst;
3314 int prev_conn_read = or_conn->read_bucket;
3315 int prev_conn_write = or_conn->write_bucket;
3317 if (connection_bucket_should_increase(or_conn->read_bucket, or_conn)) {
3318 connection_bucket_refill_helper(&or_conn->read_bucket,
3319 orbandwidthrate,
3320 orbandwidthburst,
3321 milliseconds_elapsed,
3322 "or_conn->read_bucket");
3324 if (connection_bucket_should_increase(or_conn->write_bucket, or_conn)) {
3325 connection_bucket_refill_helper(&or_conn->write_bucket,
3326 orbandwidthrate,
3327 orbandwidthburst,
3328 milliseconds_elapsed,
3329 "or_conn->write_bucket");
3332 /* If buckets were empty before and have now been refilled, tell any
3333 * interested controllers. */
3334 if (get_options()->TestingEnableTbEmptyEvent) {
3335 char *bucket;
3336 uint32_t conn_read_empty_time, conn_write_empty_time;
3337 tor_asprintf(&bucket, "ORCONN ID="U64_FORMAT,
3338 U64_PRINTF_ARG(or_conn->base_.global_identifier));
3339 conn_read_empty_time = bucket_millis_empty(prev_conn_read,
3340 or_conn->read_emptied_time,
3341 or_conn->read_bucket,
3342 milliseconds_elapsed, &tvnow);
3343 conn_write_empty_time = bucket_millis_empty(prev_conn_write,
3344 or_conn->write_emptied_time,
3345 or_conn->write_bucket,
3346 milliseconds_elapsed, &tvnow);
3347 control_event_tb_empty(bucket, conn_read_empty_time,
3348 conn_write_empty_time,
3349 milliseconds_elapsed);
3350 tor_free(bucket);
3354 if (conn->read_blocked_on_bw == 1 /* marked to turn reading back on now */
3355 && global_read_bucket > 0 /* and we're allowed to read */
3356 && (!connection_counts_as_relayed_traffic(conn, now) ||
3357 global_relayed_read_bucket > 0) /* even if we're relayed traffic */
3358 && (!connection_speaks_cells(conn) ||
3359 conn->state != OR_CONN_STATE_OPEN ||
3360 TO_OR_CONN(conn)->read_bucket > 0)) {
3361 /* and either a non-cell conn or a cell conn with non-empty bucket */
3362 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
3363 "waking up conn (fd %d) for read", (int)conn->s));
3364 conn->read_blocked_on_bw = 0;
3365 connection_start_reading(conn);
3368 if (conn->write_blocked_on_bw == 1
3369 && global_write_bucket > 0 /* and we're allowed to write */
3370 && (!connection_counts_as_relayed_traffic(conn, now) ||
3371 global_relayed_write_bucket > 0) /* even if it's relayed traffic */
3372 && (!connection_speaks_cells(conn) ||
3373 conn->state != OR_CONN_STATE_OPEN ||
3374 TO_OR_CONN(conn)->write_bucket > 0)) {
3375 LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
3376 "waking up conn (fd %d) for write", (int)conn->s));
3377 conn->write_blocked_on_bw = 0;
3378 connection_start_writing(conn);
3380 } SMARTLIST_FOREACH_END(conn);
3383 /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
3384 * should add another pile of tokens to it?
3386 static int
3387 connection_bucket_should_increase(int bucket, or_connection_t *conn)
3389 tor_assert(conn);
3391 if (conn->base_.state != OR_CONN_STATE_OPEN)
3392 return 0; /* only open connections play the rate limiting game */
3393 if (bucket >= conn->bandwidthburst)
3394 return 0;
3396 return 1;
3399 /** Read bytes from conn-\>s and process them.
3401 * It calls connection_buf_read_from_socket() to bring in any new bytes,
3402 * and then calls connection_process_inbuf() to process them.
3404 * Mark the connection and return -1 if you want to close it, else
3405 * return 0.
3407 static int
3408 connection_handle_read_impl(connection_t *conn)
3410 ssize_t max_to_read=-1, try_to_read;
3411 size_t before, n_read = 0;
3412 int socket_error = 0;
3414 if (conn->marked_for_close)
3415 return 0; /* do nothing */
3417 conn->timestamp_last_read_allowed = approx_time();
3419 switch (conn->type) {
3420 case CONN_TYPE_OR_LISTENER:
3421 return connection_handle_listener_read(conn, CONN_TYPE_OR);
3422 case CONN_TYPE_EXT_OR_LISTENER:
3423 return connection_handle_listener_read(conn, CONN_TYPE_EXT_OR);
3424 case CONN_TYPE_AP_LISTENER:
3425 case CONN_TYPE_AP_TRANS_LISTENER:
3426 case CONN_TYPE_AP_NATD_LISTENER:
3427 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER:
3428 return connection_handle_listener_read(conn, CONN_TYPE_AP);
3429 case CONN_TYPE_DIR_LISTENER:
3430 return connection_handle_listener_read(conn, CONN_TYPE_DIR);
3431 case CONN_TYPE_CONTROL_LISTENER:
3432 return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
3433 case CONN_TYPE_AP_DNS_LISTENER:
3434 /* This should never happen; eventdns.c handles the reads here. */
3435 tor_fragile_assert();
3436 return 0;
3439 loop_again:
3440 try_to_read = max_to_read;
3441 tor_assert(!conn->marked_for_close);
3443 before = buf_datalen(conn->inbuf);
3444 if (connection_buf_read_from_socket(conn, &max_to_read, &socket_error) < 0) {
3445 /* There's a read error; kill the connection.*/
3446 if (conn->type == CONN_TYPE_OR) {
3447 connection_or_notify_error(TO_OR_CONN(conn),
3448 socket_error != 0 ?
3449 errno_to_orconn_end_reason(socket_error) :
3450 END_OR_CONN_REASON_CONNRESET,
3451 socket_error != 0 ?
3452 tor_socket_strerror(socket_error) :
3453 "(unknown, errno was 0)");
3455 if (CONN_IS_EDGE(conn)) {
3456 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
3457 connection_edge_end_errno(edge_conn);
3458 if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
3459 /* broken, don't send a socks reply back */
3460 TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
3463 connection_close_immediate(conn); /* Don't flush; connection is dead. */
3465 * This can bypass normal channel checking since we did
3466 * connection_or_notify_error() above.
3468 connection_mark_for_close_internal(conn);
3469 return -1;
3471 n_read += buf_datalen(conn->inbuf) - before;
3472 if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
3473 /* instruct it not to try to package partial cells. */
3474 if (connection_process_inbuf(conn, 0) < 0) {
3475 return -1;
3477 if (!conn->marked_for_close &&
3478 connection_is_reading(conn) &&
3479 !conn->inbuf_reached_eof &&
3480 max_to_read > 0)
3481 goto loop_again; /* try reading again, in case more is here now */
3483 /* one last try, packaging partial cells and all. */
3484 if (!conn->marked_for_close &&
3485 connection_process_inbuf(conn, 1) < 0) {
3486 return -1;
3488 if (conn->linked_conn) {
3489 /* The other side's handle_write() will never actually get called, so
3490 * we need to invoke the appropriate callbacks ourself. */
3491 connection_t *linked = conn->linked_conn;
3493 if (n_read) {
3494 /* Probably a no-op, since linked conns typically don't count for
3495 * bandwidth rate limiting. But do it anyway so we can keep stats
3496 * accurately. Note that since we read the bytes from conn, and
3497 * we're writing the bytes onto the linked connection, we count
3498 * these as <i>written</i> bytes. */
3499 connection_buckets_decrement(linked, approx_time(), 0, n_read);
3501 if (connection_flushed_some(linked) < 0)
3502 connection_mark_for_close(linked);
3503 if (!connection_wants_to_flush(linked))
3504 connection_finished_flushing(linked);
3507 if (!buf_datalen(linked->outbuf) && conn->active_on_link)
3508 connection_stop_reading_from_linked_conn(conn);
3510 /* If we hit the EOF, call connection_reached_eof(). */
3511 if (!conn->marked_for_close &&
3512 conn->inbuf_reached_eof &&
3513 connection_reached_eof(conn) < 0) {
3514 return -1;
3516 return 0;
3519 /* DOCDOC connection_handle_read */
3521 connection_handle_read(connection_t *conn)
3523 int res;
3525 tor_gettimeofday_cache_clear();
3526 res = connection_handle_read_impl(conn);
3527 return res;
3530 /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
3531 * either directly or via TLS. Reduce the token buckets by the number of bytes
3532 * read.
3534 * If *max_to_read is -1, then decide it ourselves, else go with the
3535 * value passed to us. When returning, if it's changed, subtract the
3536 * number of bytes we read from *max_to_read.
3538 * Return -1 if we want to break conn, else return 0.
3540 static int
3541 connection_buf_read_from_socket(connection_t *conn, ssize_t *max_to_read,
3542 int *socket_error)
3544 int result;
3545 ssize_t at_most = *max_to_read;
3546 size_t slack_in_buf, more_to_read;
3547 size_t n_read = 0, n_written = 0;
3549 if (at_most == -1) { /* we need to initialize it */
3550 /* how many bytes are we allowed to read? */
3551 at_most = connection_bucket_read_limit(conn, approx_time());
3554 slack_in_buf = buf_slack(conn->inbuf);
3555 again:
3556 if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
3557 more_to_read = at_most - slack_in_buf;
3558 at_most = slack_in_buf;
3559 } else {
3560 more_to_read = 0;
3563 if (connection_speaks_cells(conn) &&
3564 conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
3565 int pending;
3566 or_connection_t *or_conn = TO_OR_CONN(conn);
3567 size_t initial_size;
3568 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
3569 conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
3570 /* continue handshaking even if global token bucket is empty */
3571 return connection_tls_continue_handshake(or_conn);
3574 log_debug(LD_NET,
3575 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
3576 " at_most %ld.",
3577 (int)conn->s,(long)buf_datalen(conn->inbuf),
3578 tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
3580 initial_size = buf_datalen(conn->inbuf);
3581 /* else open, or closing */
3582 result = buf_read_from_tls(conn->inbuf, or_conn->tls, at_most);
3583 if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
3584 or_conn->tls_error = result;
3585 else
3586 or_conn->tls_error = 0;
3588 switch (result) {
3589 case TOR_TLS_CLOSE:
3590 case TOR_TLS_ERROR_IO:
3591 log_debug(LD_NET,"TLS connection closed %son read. Closing. "
3592 "(Nickname %s, address %s)",
3593 result == TOR_TLS_CLOSE ? "cleanly " : "",
3594 or_conn->nickname ? or_conn->nickname : "not set",
3595 conn->address);
3596 return result;
3597 CASE_TOR_TLS_ERROR_ANY_NONIO:
3598 log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
3599 tor_tls_err_to_string(result),
3600 or_conn->nickname ? or_conn->nickname : "not set",
3601 conn->address);
3602 return result;
3603 case TOR_TLS_WANTWRITE:
3604 connection_start_writing(conn);
3605 return 0;
3606 case TOR_TLS_WANTREAD:
3607 if (conn->in_connection_handle_write) {
3608 /* We've been invoked from connection_handle_write, because we're
3609 * waiting for a TLS renegotiation, the renegotiation started, and
3610 * SSL_read returned WANTWRITE. But now SSL_read is saying WANTREAD
3611 * again. Stop waiting for write events now, or else we'll
3612 * busy-loop until data arrives for us to read. */
3613 connection_stop_writing(conn);
3614 if (!connection_is_reading(conn))
3615 connection_start_reading(conn);
3617 /* we're already reading, one hopes */
3618 break;
3619 case TOR_TLS_DONE: /* no data read, so nothing to process */
3620 break; /* so we call bucket_decrement below */
3621 default:
3622 break;
3624 pending = tor_tls_get_pending_bytes(or_conn->tls);
3625 if (pending) {
3626 /* If we have any pending bytes, we read them now. This *can*
3627 * take us over our read allotment, but really we shouldn't be
3628 * believing that SSL bytes are the same as TCP bytes anyway. */
3629 int r2 = buf_read_from_tls(conn->inbuf, or_conn->tls, pending);
3630 if (BUG(r2<0)) {
3631 log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
3632 return -1;
3635 result = (int)(buf_datalen(conn->inbuf)-initial_size);
3636 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
3637 log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
3638 result, (long)n_read, (long)n_written);
3639 } else if (conn->linked) {
3640 if (conn->linked_conn) {
3641 result = buf_move_to_buf(conn->inbuf, conn->linked_conn->outbuf,
3642 &conn->linked_conn->outbuf_flushlen);
3643 } else {
3644 result = 0;
3646 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
3647 /* If the other side has disappeared, or if it's been marked for close and
3648 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
3649 if (!conn->linked_conn ||
3650 (conn->linked_conn->marked_for_close &&
3651 buf_datalen(conn->linked_conn->outbuf) == 0))
3652 conn->inbuf_reached_eof = 1;
3654 n_read = (size_t) result;
3655 } else {
3656 /* !connection_speaks_cells, !conn->linked_conn. */
3657 int reached_eof = 0;
3658 CONN_LOG_PROTECT(conn,
3659 result = buf_read_from_socket(conn->inbuf, conn->s,
3660 at_most,
3661 &reached_eof,
3662 socket_error));
3663 if (reached_eof)
3664 conn->inbuf_reached_eof = 1;
3666 // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
3668 if (result < 0)
3669 return -1;
3670 n_read = (size_t) result;
3673 if (n_read > 0) {
3674 /* change *max_to_read */
3675 *max_to_read = at_most - n_read;
3677 /* Update edge_conn->n_read and ocirc->n_read_circ_bw */
3678 if (conn->type == CONN_TYPE_AP) {
3679 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
3680 circuit_t *circ = circuit_get_by_edge_conn(edge_conn);
3681 origin_circuit_t *ocirc;
3683 /* Check for overflow: */
3684 if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_read > n_read))
3685 edge_conn->n_read += (int)n_read;
3686 else
3687 edge_conn->n_read = UINT32_MAX;
3689 if (circ && CIRCUIT_IS_ORIGIN(circ)) {
3690 ocirc = TO_ORIGIN_CIRCUIT(circ);
3691 if (PREDICT_LIKELY(UINT32_MAX - ocirc->n_read_circ_bw > n_read))
3692 ocirc->n_read_circ_bw += (int)n_read;
3693 else
3694 ocirc->n_read_circ_bw = UINT32_MAX;
3698 /* If CONN_BW events are enabled, update conn->n_read_conn_bw for
3699 * OR/DIR/EXIT connections, checking for overflow. */
3700 if (get_options()->TestingEnableConnBwEvent &&
3701 (conn->type == CONN_TYPE_OR ||
3702 conn->type == CONN_TYPE_DIR ||
3703 conn->type == CONN_TYPE_EXIT)) {
3704 if (PREDICT_LIKELY(UINT32_MAX - conn->n_read_conn_bw > n_read))
3705 conn->n_read_conn_bw += (int)n_read;
3706 else
3707 conn->n_read_conn_bw = UINT32_MAX;
3711 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
3713 if (more_to_read && result == at_most) {
3714 slack_in_buf = buf_slack(conn->inbuf);
3715 at_most = more_to_read;
3716 goto again;
3719 /* Call even if result is 0, since the global read bucket may
3720 * have reached 0 on a different conn, and this connection needs to
3721 * know to stop reading. */
3722 connection_consider_empty_read_buckets(conn);
3723 if (n_written > 0 && connection_is_writing(conn))
3724 connection_consider_empty_write_buckets(conn);
3726 return 0;
3729 /** A pass-through to fetch_from_buf. */
3731 connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
3733 return buf_get_bytes(conn->inbuf, string, len);
3736 /** As buf_get_line(), but read from a connection's input buffer. */
3738 connection_buf_get_line(connection_t *conn, char *data,
3739 size_t *data_len)
3741 return buf_get_line(conn->inbuf, data, data_len);
3744 /** As fetch_from_buf_http, but fetches from a connection's input buffer_t as
3745 * appropriate. */
3747 connection_fetch_from_buf_http(connection_t *conn,
3748 char **headers_out, size_t max_headerlen,
3749 char **body_out, size_t *body_used,
3750 size_t max_bodylen, int force_complete)
3752 return fetch_from_buf_http(conn->inbuf, headers_out, max_headerlen,
3753 body_out, body_used, max_bodylen, force_complete);
3756 /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
3757 * from its outbuf. */
3759 connection_wants_to_flush(connection_t *conn)
3761 return conn->outbuf_flushlen > 0;
3764 /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
3765 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
3766 * connection_edge_consider_sending_sendme().
3769 connection_outbuf_too_full(connection_t *conn)
3771 return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
3775 * On Windows Vista and Windows 7, tune the send buffer size according to a
3776 * hint from the OS.
3778 * This should help fix slow upload rates.
3780 static void
3782 update_send_buffer_size(tor_socket_t sock)
3784 #ifdef _WIN32
3785 /* We only do this on Vista and 7, because earlier versions of Windows
3786 * don't have the SIO_IDEAL_SEND_BACKLOG_QUERY functionality, and on
3787 * later versions it isn't necessary. */
3788 static int isVistaOr7 = -1;
3789 if (isVistaOr7 == -1) {
3790 isVistaOr7 = 0;
3791 OSVERSIONINFO osvi = { 0 };
3792 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
3793 GetVersionEx(&osvi);
3794 if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion < 2)
3795 isVistaOr7 = 1;
3797 if (!isVistaOr7)
3798 return;
3799 if (get_options()->ConstrainedSockets)
3800 return;
3801 ULONG isb = 0;
3802 DWORD bytesReturned = 0;
3803 if (!WSAIoctl(sock, SIO_IDEAL_SEND_BACKLOG_QUERY, NULL, 0,
3804 &isb, sizeof(isb), &bytesReturned, NULL, NULL)) {
3805 setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (const char*)&isb, sizeof(isb));
3807 #else
3808 (void) sock;
3809 #endif
3812 /** Try to flush more bytes onto <b>conn</b>-\>s.
3814 * This function gets called either from conn_write_callback() in main.c
3815 * when libevent tells us that conn wants to write, or below
3816 * from connection_buf_add() when an entire TLS record is ready.
3818 * Update <b>conn</b>-\>timestamp_last_write_allowed to now, and call flush_buf
3819 * or flush_buf_tls appropriately. If it succeeds and there are no more
3820 * more bytes on <b>conn</b>-\>outbuf, then call connection_finished_flushing
3821 * on it too.
3823 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
3824 * limits. (Used for flushing messages to controller connections on fatal
3825 * errors.)
3827 * Mark the connection and return -1 if you want to close it, else
3828 * return 0.
3830 static int
3831 connection_handle_write_impl(connection_t *conn, int force)
3833 int e;
3834 socklen_t len=(socklen_t)sizeof(e);
3835 int result;
3836 ssize_t max_to_write;
3837 time_t now = approx_time();
3838 size_t n_read = 0, n_written = 0;
3839 int dont_stop_writing = 0;
3841 tor_assert(!connection_is_listener(conn));
3843 if (conn->marked_for_close || !SOCKET_OK(conn->s))
3844 return 0; /* do nothing */
3846 if (conn->in_flushed_some) {
3847 log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
3848 return 0;
3851 conn->timestamp_last_write_allowed = now;
3853 /* Sometimes, "writable" means "connected". */
3854 if (connection_state_is_connecting(conn)) {
3855 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
3856 log_warn(LD_BUG, "getsockopt() syscall failed");
3857 if (conn->type == CONN_TYPE_OR) {
3858 or_connection_t *orconn = TO_OR_CONN(conn);
3859 connection_or_close_for_error(orconn, 0);
3860 } else {
3861 if (CONN_IS_EDGE(conn)) {
3862 connection_edge_end_errno(TO_EDGE_CONN(conn));
3864 connection_mark_for_close(conn);
3866 return -1;
3868 if (e) {
3869 /* some sort of error, but maybe just inprogress still */
3870 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
3871 log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
3872 tor_socket_strerror(e));
3873 if (CONN_IS_EDGE(conn))
3874 connection_edge_end_errno(TO_EDGE_CONN(conn));
3875 if (conn->type == CONN_TYPE_OR)
3876 connection_or_notify_error(TO_OR_CONN(conn),
3877 errno_to_orconn_end_reason(e),
3878 tor_socket_strerror(e));
3880 connection_close_immediate(conn);
3882 * This can bypass normal channel checking since we did
3883 * connection_or_notify_error() above.
3885 connection_mark_for_close_internal(conn);
3886 return -1;
3887 } else {
3888 return 0; /* no change, see if next time is better */
3891 /* The connection is successful. */
3892 if (connection_finished_connecting(conn)<0)
3893 return -1;
3896 max_to_write = force ? (ssize_t)conn->outbuf_flushlen
3897 : connection_bucket_write_limit(conn, now);
3899 if (connection_speaks_cells(conn) &&
3900 conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
3901 or_connection_t *or_conn = TO_OR_CONN(conn);
3902 size_t initial_size;
3903 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
3904 conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
3905 connection_stop_writing(conn);
3906 if (connection_tls_continue_handshake(or_conn) < 0) {
3907 /* Don't flush; connection is dead. */
3908 connection_or_notify_error(or_conn,
3909 END_OR_CONN_REASON_MISC,
3910 "TLS error in connection_tls_"
3911 "continue_handshake()");
3912 connection_close_immediate(conn);
3914 * This can bypass normal channel checking since we did
3915 * connection_or_notify_error() above.
3917 connection_mark_for_close_internal(conn);
3918 return -1;
3920 return 0;
3921 } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
3922 return connection_handle_read(conn);
3925 /* else open, or closing */
3926 initial_size = buf_datalen(conn->outbuf);
3927 result = buf_flush_to_tls(conn->outbuf, or_conn->tls,
3928 max_to_write, &conn->outbuf_flushlen);
3930 if (result >= 0)
3931 update_send_buffer_size(conn->s);
3933 /* If we just flushed the last bytes, tell the channel on the
3934 * or_conn to check if it needs to geoip_change_dirreq_state() */
3935 /* XXXX move this to flushed_some or finished_flushing -NM */
3936 if (buf_datalen(conn->outbuf) == 0 && or_conn->chan)
3937 channel_notify_flushed(TLS_CHAN_TO_BASE(or_conn->chan));
3939 switch (result) {
3940 CASE_TOR_TLS_ERROR_ANY:
3941 case TOR_TLS_CLOSE:
3942 log_info(LD_NET, result != TOR_TLS_CLOSE ?
3943 "tls error. breaking.":"TLS connection closed on flush");
3944 /* Don't flush; connection is dead. */
3945 connection_or_notify_error(or_conn,
3946 END_OR_CONN_REASON_MISC,
3947 result != TOR_TLS_CLOSE ?
3948 "TLS error in during flush" :
3949 "TLS closed during flush");
3950 connection_close_immediate(conn);
3952 * This can bypass normal channel checking since we did
3953 * connection_or_notify_error() above.
3955 connection_mark_for_close_internal(conn);
3956 return -1;
3957 case TOR_TLS_WANTWRITE:
3958 log_debug(LD_NET,"wanted write.");
3959 /* we're already writing */
3960 dont_stop_writing = 1;
3961 break;
3962 case TOR_TLS_WANTREAD:
3963 /* Make sure to avoid a loop if the receive buckets are empty. */
3964 log_debug(LD_NET,"wanted read.");
3965 if (!connection_is_reading(conn)) {
3966 connection_stop_writing(conn);
3967 conn->write_blocked_on_bw = 1;
3968 /* we'll start reading again when we get more tokens in our
3969 * read bucket; then we'll start writing again too.
3972 /* else no problem, we're already reading */
3973 return 0;
3974 /* case TOR_TLS_DONE:
3975 * for TOR_TLS_DONE, fall through to check if the flushlen
3976 * is empty, so we can stop writing.
3980 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
3981 log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
3982 result, (long)n_read, (long)n_written);
3983 or_conn->bytes_xmitted += result;
3984 or_conn->bytes_xmitted_by_tls += n_written;
3985 /* So we notice bytes were written even on error */
3986 /* XXXX This cast is safe since we can never write INT_MAX bytes in a
3987 * single set of TLS operations. But it looks kinda ugly. If we refactor
3988 * the *_buf_tls functions, we should make them return ssize_t or size_t
3989 * or something. */
3990 result = (int)(initial_size-buf_datalen(conn->outbuf));
3991 } else {
3992 CONN_LOG_PROTECT(conn,
3993 result = buf_flush_to_socket(conn->outbuf, conn->s,
3994 max_to_write, &conn->outbuf_flushlen));
3995 if (result < 0) {
3996 if (CONN_IS_EDGE(conn))
3997 connection_edge_end_errno(TO_EDGE_CONN(conn));
3998 if (conn->type == CONN_TYPE_AP) {
3999 /* writing failed; we couldn't send a SOCKS reply if we wanted to */
4000 TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
4003 connection_close_immediate(conn); /* Don't flush; connection is dead. */
4004 connection_mark_for_close(conn);
4005 return -1;
4007 update_send_buffer_size(conn->s);
4008 n_written = (size_t) result;
4011 if (n_written && conn->type == CONN_TYPE_AP) {
4012 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
4013 circuit_t *circ = circuit_get_by_edge_conn(edge_conn);
4014 origin_circuit_t *ocirc;
4016 /* Check for overflow: */
4017 if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_written > n_written))
4018 edge_conn->n_written += (int)n_written;
4019 else
4020 edge_conn->n_written = UINT32_MAX;
4022 if (circ && CIRCUIT_IS_ORIGIN(circ)) {
4023 ocirc = TO_ORIGIN_CIRCUIT(circ);
4024 if (PREDICT_LIKELY(UINT32_MAX - ocirc->n_written_circ_bw > n_written))
4025 ocirc->n_written_circ_bw += (int)n_written;
4026 else
4027 ocirc->n_written_circ_bw = UINT32_MAX;
4031 /* If CONN_BW events are enabled, update conn->n_written_conn_bw for
4032 * OR/DIR/EXIT connections, checking for overflow. */
4033 if (n_written && get_options()->TestingEnableConnBwEvent &&
4034 (conn->type == CONN_TYPE_OR ||
4035 conn->type == CONN_TYPE_DIR ||
4036 conn->type == CONN_TYPE_EXIT)) {
4037 if (PREDICT_LIKELY(UINT32_MAX - conn->n_written_conn_bw > n_written))
4038 conn->n_written_conn_bw += (int)n_written;
4039 else
4040 conn->n_written_conn_bw = UINT32_MAX;
4043 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
4045 if (result > 0) {
4046 /* If we wrote any bytes from our buffer, then call the appropriate
4047 * functions. */
4048 if (connection_flushed_some(conn) < 0) {
4049 if (connection_speaks_cells(conn)) {
4050 connection_or_notify_error(TO_OR_CONN(conn),
4051 END_OR_CONN_REASON_MISC,
4052 "Got error back from "
4053 "connection_flushed_some()");
4057 * This can bypass normal channel checking since we did
4058 * connection_or_notify_error() above.
4060 connection_mark_for_close_internal(conn);
4064 if (!connection_wants_to_flush(conn) &&
4065 !dont_stop_writing) { /* it's done flushing */
4066 if (connection_finished_flushing(conn) < 0) {
4067 /* already marked */
4068 return -1;
4070 return 0;
4073 /* Call even if result is 0, since the global write bucket may
4074 * have reached 0 on a different conn, and this connection needs to
4075 * know to stop writing. */
4076 connection_consider_empty_write_buckets(conn);
4077 if (n_read > 0 && connection_is_reading(conn))
4078 connection_consider_empty_read_buckets(conn);
4080 return 0;
4083 /* DOCDOC connection_handle_write */
4085 connection_handle_write(connection_t *conn, int force)
4087 int res;
4088 tor_gettimeofday_cache_clear();
4089 conn->in_connection_handle_write = 1;
4090 res = connection_handle_write_impl(conn, force);
4091 conn->in_connection_handle_write = 0;
4092 return res;
4096 * Try to flush data that's waiting for a write on <b>conn</b>. Return
4097 * -1 on failure, 0 on success.
4099 * Don't use this function for regular writing; the buffers
4100 * system should be good enough at scheduling writes there. Instead, this
4101 * function is for cases when we're about to exit or something and we want
4102 * to report it right away.
4105 connection_flush(connection_t *conn)
4107 return connection_handle_write(conn, 1);
4110 /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4112 * Return true iff it is okay to queue bytes on <b>conn</b>'s outbuf for
4113 * writing.
4115 static int
4116 connection_may_write_to_buf(connection_t *conn)
4118 /* if it's marked for close, only allow write if we mean to flush it */
4119 if (conn->marked_for_close && !conn->hold_open_until_flushed)
4120 return 0;
4122 return 1;
4125 /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4127 * Called when an attempt to add bytes on <b>conn</b>'s outbuf has failed;
4128 * mark the connection and warn as appropriate.
4130 static void
4131 connection_write_to_buf_failed(connection_t *conn)
4133 if (CONN_IS_EDGE(conn)) {
4134 /* if it failed, it means we have our package/delivery windows set
4135 wrong compared to our max outbuf size. close the whole circuit. */
4136 log_warn(LD_NET,
4137 "write_to_buf failed. Closing circuit (fd %d).", (int)conn->s);
4138 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
4139 END_CIRC_REASON_INTERNAL);
4140 } else if (conn->type == CONN_TYPE_OR) {
4141 or_connection_t *orconn = TO_OR_CONN(conn);
4142 log_warn(LD_NET,
4143 "write_to_buf failed on an orconn; notifying of error "
4144 "(fd %d)", (int)(conn->s));
4145 connection_or_close_for_error(orconn, 0);
4146 } else {
4147 log_warn(LD_NET,
4148 "write_to_buf failed. Closing connection (fd %d).",
4149 (int)conn->s);
4150 connection_mark_for_close(conn);
4154 /** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4156 * Called when an attempt to add bytes on <b>conn</b>'s outbuf has succeeded:
4157 * record the number of bytes added.
4159 static void
4160 connection_write_to_buf_commit(connection_t *conn, size_t len)
4162 /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
4163 * state, we don't want to try to write it right away, since
4164 * conn->write_event won't be set yet. Otherwise, write data from
4165 * this conn as the socket is available. */
4166 if (conn->write_event) {
4167 connection_start_writing(conn);
4169 conn->outbuf_flushlen += len;
4172 /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
4173 * outbuf, and ask it to start writing.
4175 * If <b>zlib</b> is nonzero, this is a directory connection that should get
4176 * its contents compressed or decompressed as they're written. If zlib is
4177 * negative, this is the last data to be compressed, and the connection's zlib
4178 * state should be flushed.
4180 MOCK_IMPL(void,
4181 connection_write_to_buf_impl_,(const char *string, size_t len,
4182 connection_t *conn, int zlib))
4184 /* XXXX This function really needs to return -1 on failure. */
4185 int r;
4186 if (!len && !(zlib<0))
4187 return;
4189 if (!connection_may_write_to_buf(conn))
4190 return;
4192 size_t written;
4194 if (zlib) {
4195 size_t old_datalen = buf_datalen(conn->outbuf);
4196 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
4197 int done = zlib < 0;
4198 CONN_LOG_PROTECT(conn, r = buf_add_compress(conn->outbuf,
4199 dir_conn->compress_state,
4200 string, len, done));
4201 written = buf_datalen(conn->outbuf) - old_datalen;
4202 } else {
4203 CONN_LOG_PROTECT(conn, r = buf_add(conn->outbuf, string, len));
4204 written = len;
4206 if (r < 0) {
4207 connection_write_to_buf_failed(conn);
4208 return;
4210 connection_write_to_buf_commit(conn, written);
4214 * Add all bytes from <b>buf</b> to <b>conn</b>'s outbuf, draining them
4215 * from <b>buf</b>. (If the connection is marked and will soon be closed,
4216 * nothing is drained.)
4218 void
4219 connection_buf_add_buf(connection_t *conn, buf_t *buf)
4221 tor_assert(conn);
4222 tor_assert(buf);
4223 size_t len = buf_datalen(buf);
4224 if (len == 0)
4225 return;
4227 if (!connection_may_write_to_buf(conn))
4228 return;
4230 buf_move_all(conn->outbuf, buf);
4231 connection_write_to_buf_commit(conn, len);
4234 #define CONN_GET_ALL_TEMPLATE(var, test) \
4235 STMT_BEGIN \
4236 smartlist_t *conns = get_connection_array(); \
4237 smartlist_t *ret_conns = smartlist_new(); \
4238 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, var) { \
4239 if (var && (test) && !var->marked_for_close) \
4240 smartlist_add(ret_conns, var); \
4241 } SMARTLIST_FOREACH_END(var); \
4242 return ret_conns; \
4243 STMT_END
4245 /* Return a list of connections that aren't close and matches the given type
4246 * and state. The returned list can be empty and must be freed using
4247 * smartlist_free(). The caller does NOT have ownership of the objects in the
4248 * list so it must not free them nor reference them as they can disappear. */
4249 smartlist_t *
4250 connection_list_by_type_state(int type, int state)
4252 CONN_GET_ALL_TEMPLATE(conn, (conn->type == type && conn->state == state));
4255 /* Return a list of connections that aren't close and matches the given type
4256 * and purpose. The returned list can be empty and must be freed using
4257 * smartlist_free(). The caller does NOT have ownership of the objects in the
4258 * list so it must not free them nor reference them as they can disappear. */
4259 smartlist_t *
4260 connection_list_by_type_purpose(int type, int purpose)
4262 CONN_GET_ALL_TEMPLATE(conn,
4263 (conn->type == type && conn->purpose == purpose));
4266 /** Return a connection_t * from get_connection_array() that satisfies test on
4267 * var, and that is not marked for close. */
4268 #define CONN_GET_TEMPLATE(var, test) \
4269 STMT_BEGIN \
4270 smartlist_t *conns = get_connection_array(); \
4271 SMARTLIST_FOREACH(conns, connection_t *, var, \
4273 if (var && (test) && !var->marked_for_close) \
4274 return var; \
4275 }); \
4276 return NULL; \
4277 STMT_END
4279 /** Return a connection with given type, address, port, and purpose;
4280 * or NULL if no such connection exists (or if all such connections are marked
4281 * for close). */
4282 MOCK_IMPL(connection_t *,
4283 connection_get_by_type_addr_port_purpose,(int type,
4284 const tor_addr_t *addr, uint16_t port,
4285 int purpose))
4287 CONN_GET_TEMPLATE(conn,
4288 (conn->type == type &&
4289 tor_addr_eq(&conn->addr, addr) &&
4290 conn->port == port &&
4291 conn->purpose == purpose));
4294 /** Return the stream with id <b>id</b> if it is not already marked for
4295 * close.
4297 connection_t *
4298 connection_get_by_global_id(uint64_t id)
4300 CONN_GET_TEMPLATE(conn, conn->global_identifier == id);
4303 /** Return a connection of type <b>type</b> that is not marked for close.
4305 connection_t *
4306 connection_get_by_type(int type)
4308 CONN_GET_TEMPLATE(conn, conn->type == type);
4311 /** Return a connection of type <b>type</b> that is in state <b>state</b>,
4312 * and that is not marked for close.
4314 connection_t *
4315 connection_get_by_type_state(int type, int state)
4317 CONN_GET_TEMPLATE(conn, conn->type == type && conn->state == state);
4320 /** Return a connection of type <b>type</b> that has rendquery equal
4321 * to <b>rendquery</b>, and that is not marked for close. If state
4322 * is non-zero, conn must be of that state too.
4324 connection_t *
4325 connection_get_by_type_state_rendquery(int type, int state,
4326 const char *rendquery)
4328 tor_assert(type == CONN_TYPE_DIR ||
4329 type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
4330 tor_assert(rendquery);
4332 CONN_GET_TEMPLATE(conn,
4333 (conn->type == type &&
4334 (!state || state == conn->state)) &&
4336 (type == CONN_TYPE_DIR &&
4337 TO_DIR_CONN(conn)->rend_data &&
4338 !rend_cmp_service_ids(rendquery,
4339 rend_data_get_address(TO_DIR_CONN(conn)->rend_data)))
4341 (CONN_IS_EDGE(conn) &&
4342 TO_EDGE_CONN(conn)->rend_data &&
4343 !rend_cmp_service_ids(rendquery,
4344 rend_data_get_address(TO_EDGE_CONN(conn)->rend_data)))
4348 /** Return a new smartlist of dir_connection_t * from get_connection_array()
4349 * that satisfy conn_test on connection_t *conn_var, and dirconn_test on
4350 * dir_connection_t *dirconn_var. conn_var must be of CONN_TYPE_DIR and not
4351 * marked for close to be included in the list. */
4352 #define DIR_CONN_LIST_TEMPLATE(conn_var, conn_test, \
4353 dirconn_var, dirconn_test) \
4354 STMT_BEGIN \
4355 smartlist_t *conns = get_connection_array(); \
4356 smartlist_t *dir_conns = smartlist_new(); \
4357 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn_var) { \
4358 if (conn_var && (conn_test) \
4359 && conn_var->type == CONN_TYPE_DIR \
4360 && !conn_var->marked_for_close) { \
4361 dir_connection_t *dirconn_var = TO_DIR_CONN(conn_var); \
4362 if (dirconn_var && (dirconn_test)) { \
4363 smartlist_add(dir_conns, dirconn_var); \
4366 } SMARTLIST_FOREACH_END(conn_var); \
4367 return dir_conns; \
4368 STMT_END
4370 /** Return a list of directory connections that are fetching the item
4371 * described by <b>purpose</b>/<b>resource</b>. If there are none,
4372 * return an empty list. This list must be freed using smartlist_free,
4373 * but the pointers in it must not be freed.
4374 * Note that this list should not be cached, as the pointers in it can be
4375 * freed if their connections close. */
4376 smartlist_t *
4377 connection_dir_list_by_purpose_and_resource(
4378 int purpose,
4379 const char *resource)
4381 DIR_CONN_LIST_TEMPLATE(conn,
4382 conn->purpose == purpose,
4383 dirconn,
4384 0 == strcmp_opt(resource,
4385 dirconn->requested_resource));
4388 /** Return a list of directory connections that are fetching the item
4389 * described by <b>purpose</b>/<b>resource</b>/<b>state</b>. If there are
4390 * none, return an empty list. This list must be freed using smartlist_free,
4391 * but the pointers in it must not be freed.
4392 * Note that this list should not be cached, as the pointers in it can be
4393 * freed if their connections close. */
4394 smartlist_t *
4395 connection_dir_list_by_purpose_resource_and_state(
4396 int purpose,
4397 const char *resource,
4398 int state)
4400 DIR_CONN_LIST_TEMPLATE(conn,
4401 conn->purpose == purpose && conn->state == state,
4402 dirconn,
4403 0 == strcmp_opt(resource,
4404 dirconn->requested_resource));
4407 #undef DIR_CONN_LIST_TEMPLATE
4409 /** Return an arbitrary active OR connection that isn't <b>this_conn</b>.
4411 * We use this to guess if we should tell the controller that we
4412 * didn't manage to connect to any of our bridges. */
4413 static connection_t *
4414 connection_get_another_active_or_conn(const or_connection_t *this_conn)
4416 CONN_GET_TEMPLATE(conn,
4417 conn != TO_CONN(this_conn) && conn->type == CONN_TYPE_OR);
4420 /** Return 1 if there are any active OR connections apart from
4421 * <b>this_conn</b>.
4423 * We use this to guess if we should tell the controller that we
4424 * didn't manage to connect to any of our bridges. */
4426 any_other_active_or_conns(const or_connection_t *this_conn)
4428 connection_t *conn = connection_get_another_active_or_conn(this_conn);
4429 if (conn != NULL) {
4430 log_debug(LD_DIR, "%s: Found an OR connection: %s",
4431 __func__, conn->address);
4432 return 1;
4435 return 0;
4438 #undef CONN_GET_TEMPLATE
4440 /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
4442 connection_is_listener(connection_t *conn)
4444 if (conn->type == CONN_TYPE_OR_LISTENER ||
4445 conn->type == CONN_TYPE_EXT_OR_LISTENER ||
4446 conn->type == CONN_TYPE_AP_LISTENER ||
4447 conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
4448 conn->type == CONN_TYPE_AP_DNS_LISTENER ||
4449 conn->type == CONN_TYPE_AP_NATD_LISTENER ||
4450 conn->type == CONN_TYPE_AP_HTTP_CONNECT_LISTENER ||
4451 conn->type == CONN_TYPE_DIR_LISTENER ||
4452 conn->type == CONN_TYPE_CONTROL_LISTENER)
4453 return 1;
4454 return 0;
4457 /** Return 1 if <b>conn</b> is in state "open" and is not marked
4458 * for close, else return 0.
4461 connection_state_is_open(connection_t *conn)
4463 tor_assert(conn);
4465 if (conn->marked_for_close)
4466 return 0;
4468 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
4469 (conn->type == CONN_TYPE_EXT_OR) ||
4470 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
4471 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
4472 (conn->type == CONN_TYPE_CONTROL &&
4473 conn->state == CONTROL_CONN_STATE_OPEN))
4474 return 1;
4476 return 0;
4479 /** Return 1 if conn is in 'connecting' state, else return 0. */
4481 connection_state_is_connecting(connection_t *conn)
4483 tor_assert(conn);
4485 if (conn->marked_for_close)
4486 return 0;
4487 switch (conn->type)
4489 case CONN_TYPE_OR:
4490 return conn->state == OR_CONN_STATE_CONNECTING;
4491 case CONN_TYPE_EXIT:
4492 return conn->state == EXIT_CONN_STATE_CONNECTING;
4493 case CONN_TYPE_DIR:
4494 return conn->state == DIR_CONN_STATE_CONNECTING;
4497 return 0;
4500 /** Allocates a base64'ed authenticator for use in http or https
4501 * auth, based on the input string <b>authenticator</b>. Returns it
4502 * if success, else returns NULL. */
4503 char *
4504 alloc_http_authenticator(const char *authenticator)
4506 /* an authenticator in Basic authentication
4507 * is just the string "username:password" */
4508 const size_t authenticator_length = strlen(authenticator);
4509 const size_t base64_authenticator_length =
4510 base64_encode_size(authenticator_length, 0) + 1;
4511 char *base64_authenticator = tor_malloc(base64_authenticator_length);
4512 if (base64_encode(base64_authenticator, base64_authenticator_length,
4513 authenticator, authenticator_length, 0) < 0) {
4514 tor_free(base64_authenticator); /* free and set to null */
4516 return base64_authenticator;
4519 /** Given a socket handle, check whether the local address (sockname) of the
4520 * socket is one that we've connected from before. If so, double-check
4521 * whether our address has changed and we need to generate keys. If we do,
4522 * call init_keys().
4524 static void
4525 client_check_address_changed(tor_socket_t sock)
4527 tor_addr_t out_addr, iface_addr;
4528 tor_addr_t **last_interface_ip_ptr;
4529 sa_family_t family;
4531 if (!outgoing_addrs)
4532 outgoing_addrs = smartlist_new();
4534 if (tor_addr_from_getsockname(&out_addr, sock) < 0) {
4535 int e = tor_socket_errno(sock);
4536 log_warn(LD_NET, "getsockname() to check for address change failed: %s",
4537 tor_socket_strerror(e));
4538 return;
4540 family = tor_addr_family(&out_addr);
4542 if (family == AF_INET)
4543 last_interface_ip_ptr = &last_interface_ipv4;
4544 else if (family == AF_INET6)
4545 last_interface_ip_ptr = &last_interface_ipv6;
4546 else
4547 return;
4549 if (! *last_interface_ip_ptr) {
4550 tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
4551 if (get_interface_address6(LOG_INFO, family, a)==0) {
4552 *last_interface_ip_ptr = a;
4553 } else {
4554 tor_free(a);
4558 /* If we've used this address previously, we're okay. */
4559 SMARTLIST_FOREACH(outgoing_addrs, const tor_addr_t *, a_ptr,
4560 if (tor_addr_eq(a_ptr, &out_addr))
4561 return;
4564 /* Uh-oh. We haven't connected from this address before. Has the interface
4565 * address changed? */
4566 if (get_interface_address6(LOG_INFO, family, &iface_addr)<0)
4567 return;
4569 if (tor_addr_eq(&iface_addr, *last_interface_ip_ptr)) {
4570 /* Nope, it hasn't changed. Add this address to the list. */
4571 smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
4572 } else {
4573 /* The interface changed. We're a client, so we need to regenerate our
4574 * keys. First, reset the state. */
4575 log_notice(LD_NET, "Our IP address has changed. Rotating keys...");
4576 tor_addr_copy(*last_interface_ip_ptr, &iface_addr);
4577 SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t*, a_ptr, tor_free(a_ptr));
4578 smartlist_clear(outgoing_addrs);
4579 smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
4580 /* We'll need to resolve ourselves again. */
4581 reset_last_resolved_addr();
4582 /* Okay, now change our keys. */
4583 ip_address_changed(1);
4587 /** Some systems have limited system buffers for recv and xmit on
4588 * sockets allocated in a virtual server or similar environment. For a Tor
4589 * server this can produce the "Error creating network socket: No buffer
4590 * space available" error once all available TCP buffer space is consumed.
4591 * This method will attempt to constrain the buffers allocated for the socket
4592 * to the desired size to stay below system TCP buffer limits.
4594 static void
4595 set_constrained_socket_buffers(tor_socket_t sock, int size)
4597 void *sz = (void*)&size;
4598 socklen_t sz_sz = (socklen_t) sizeof(size);
4599 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
4600 int e = tor_socket_errno(sock);
4601 log_warn(LD_NET, "setsockopt() to constrain send "
4602 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
4604 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
4605 int e = tor_socket_errno(sock);
4606 log_warn(LD_NET, "setsockopt() to constrain recv "
4607 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
4611 /** Process new bytes that have arrived on conn-\>inbuf.
4613 * This function just passes conn to the connection-specific
4614 * connection_*_process_inbuf() function. It also passes in
4615 * package_partial if wanted.
4617 static int
4618 connection_process_inbuf(connection_t *conn, int package_partial)
4620 tor_assert(conn);
4622 switch (conn->type) {
4623 case CONN_TYPE_OR:
4624 return connection_or_process_inbuf(TO_OR_CONN(conn));
4625 case CONN_TYPE_EXT_OR:
4626 return connection_ext_or_process_inbuf(TO_OR_CONN(conn));
4627 case CONN_TYPE_EXIT:
4628 case CONN_TYPE_AP:
4629 return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
4630 package_partial);
4631 case CONN_TYPE_DIR:
4632 return connection_dir_process_inbuf(TO_DIR_CONN(conn));
4633 case CONN_TYPE_CONTROL:
4634 return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
4635 default:
4636 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
4637 tor_fragile_assert();
4638 return -1;
4642 /** Called whenever we've written data on a connection. */
4643 static int
4644 connection_flushed_some(connection_t *conn)
4646 int r = 0;
4647 tor_assert(!conn->in_flushed_some);
4648 conn->in_flushed_some = 1;
4649 if (conn->type == CONN_TYPE_DIR &&
4650 conn->state == DIR_CONN_STATE_SERVER_WRITING) {
4651 r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
4652 } else if (conn->type == CONN_TYPE_OR) {
4653 r = connection_or_flushed_some(TO_OR_CONN(conn));
4654 } else if (CONN_IS_EDGE(conn)) {
4655 r = connection_edge_flushed_some(TO_EDGE_CONN(conn));
4657 conn->in_flushed_some = 0;
4658 return r;
4661 /** We just finished flushing bytes to the appropriately low network layer,
4662 * and there are no more bytes remaining in conn-\>outbuf or
4663 * conn-\>tls to be flushed.
4665 * This function just passes conn to the connection-specific
4666 * connection_*_finished_flushing() function.
4668 static int
4669 connection_finished_flushing(connection_t *conn)
4671 tor_assert(conn);
4673 /* If the connection is closed, don't try to do anything more here. */
4674 if (CONN_IS_CLOSED(conn))
4675 return 0;
4677 // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
4679 connection_stop_writing(conn);
4681 switch (conn->type) {
4682 case CONN_TYPE_OR:
4683 return connection_or_finished_flushing(TO_OR_CONN(conn));
4684 case CONN_TYPE_EXT_OR:
4685 return connection_ext_or_finished_flushing(TO_OR_CONN(conn));
4686 case CONN_TYPE_AP:
4687 case CONN_TYPE_EXIT:
4688 return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
4689 case CONN_TYPE_DIR:
4690 return connection_dir_finished_flushing(TO_DIR_CONN(conn));
4691 case CONN_TYPE_CONTROL:
4692 return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
4693 default:
4694 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
4695 tor_fragile_assert();
4696 return -1;
4700 /** Called when our attempt to connect() to another server has just
4701 * succeeded.
4703 * This function just passes conn to the connection-specific
4704 * connection_*_finished_connecting() function.
4706 static int
4707 connection_finished_connecting(connection_t *conn)
4709 tor_assert(conn);
4711 if (!server_mode(get_options())) {
4712 /* See whether getsockname() says our address changed. We need to do this
4713 * now that the connection has finished, because getsockname() on Windows
4714 * won't work until then. */
4715 client_check_address_changed(conn->s);
4718 switch (conn->type)
4720 case CONN_TYPE_OR:
4721 return connection_or_finished_connecting(TO_OR_CONN(conn));
4722 case CONN_TYPE_EXIT:
4723 return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
4724 case CONN_TYPE_DIR:
4725 return connection_dir_finished_connecting(TO_DIR_CONN(conn));
4726 default:
4727 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
4728 tor_fragile_assert();
4729 return -1;
4733 /** Callback: invoked when a connection reaches an EOF event. */
4734 static int
4735 connection_reached_eof(connection_t *conn)
4737 switch (conn->type) {
4738 case CONN_TYPE_OR:
4739 case CONN_TYPE_EXT_OR:
4740 return connection_or_reached_eof(TO_OR_CONN(conn));
4741 case CONN_TYPE_AP:
4742 case CONN_TYPE_EXIT:
4743 return connection_edge_reached_eof(TO_EDGE_CONN(conn));
4744 case CONN_TYPE_DIR:
4745 return connection_dir_reached_eof(TO_DIR_CONN(conn));
4746 case CONN_TYPE_CONTROL:
4747 return connection_control_reached_eof(TO_CONTROL_CONN(conn));
4748 default:
4749 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
4750 tor_fragile_assert();
4751 return -1;
4755 /** Comparator for the two-orconn case in OOS victim sort */
4756 static int
4757 oos_victim_comparator_for_orconns(or_connection_t *a, or_connection_t *b)
4759 int a_circs, b_circs;
4760 /* Fewer circuits == higher priority for OOS kill, sort earlier */
4762 a_circs = connection_or_get_num_circuits(a);
4763 b_circs = connection_or_get_num_circuits(b);
4765 if (a_circs < b_circs) return 1;
4766 else if (a_circs > b_circs) return -1;
4767 else return 0;
4770 /** Sort comparator for OOS victims; better targets sort before worse
4771 * ones. */
4772 static int
4773 oos_victim_comparator(const void **a_v, const void **b_v)
4775 connection_t *a = NULL, *b = NULL;
4777 /* Get connection pointers out */
4779 a = (connection_t *)(*a_v);
4780 b = (connection_t *)(*b_v);
4782 tor_assert(a != NULL);
4783 tor_assert(b != NULL);
4786 * We always prefer orconns as victims currently; we won't even see
4787 * these non-orconn cases, but if we do, sort them after orconns.
4789 if (a->type == CONN_TYPE_OR && b->type == CONN_TYPE_OR) {
4790 return oos_victim_comparator_for_orconns(TO_OR_CONN(a), TO_OR_CONN(b));
4791 } else {
4793 * One isn't an orconn; if one is, it goes first. We currently have no
4794 * opinions about cases where neither is an orconn.
4796 if (a->type == CONN_TYPE_OR) return -1;
4797 else if (b->type == CONN_TYPE_OR) return 1;
4798 else return 0;
4802 /** Pick n victim connections for the OOS handler and return them in a
4803 * smartlist.
4805 MOCK_IMPL(STATIC smartlist_t *,
4806 pick_oos_victims, (int n))
4808 smartlist_t *eligible = NULL, *victims = NULL;
4809 smartlist_t *conns;
4810 int conn_counts_by_type[CONN_TYPE_MAX_ + 1], i;
4813 * Big damn assumption (someone improve this someday!):
4815 * Socket exhaustion normally happens on high-volume relays, and so
4816 * most of the connections involved are orconns. We should pick victims
4817 * by assembling a list of all orconns, and sorting them in order of
4818 * how much 'damage' by some metric we'd be doing by dropping them.
4820 * If we move on from orconns, we should probably think about incoming
4821 * directory connections next, or exit connections. Things we should
4822 * probably never kill are controller connections and listeners.
4824 * This function will count how many connections of different types
4825 * exist and log it for purposes of gathering data on typical OOS
4826 * situations to guide future improvements.
4829 /* First, get the connection array */
4830 conns = get_connection_array();
4832 * Iterate it and pick out eligible connection types, and log some stats
4833 * along the way.
4835 eligible = smartlist_new();
4836 memset(conn_counts_by_type, 0, sizeof(conn_counts_by_type));
4837 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
4838 /* Bump the counter */
4839 tor_assert(c->type <= CONN_TYPE_MAX_);
4840 ++(conn_counts_by_type[c->type]);
4842 /* Skip anything without a socket we can free */
4843 if (!(SOCKET_OK(c->s))) {
4844 continue;
4847 /* Skip anything we would count as moribund */
4848 if (connection_is_moribund(c)) {
4849 continue;
4852 switch (c->type) {
4853 case CONN_TYPE_OR:
4854 /* We've got an orconn, it's eligible to be OOSed */
4855 smartlist_add(eligible, c);
4856 break;
4857 default:
4858 /* We don't know what to do with it, ignore it */
4859 break;
4861 } SMARTLIST_FOREACH_END(c);
4863 /* Log some stats */
4864 if (smartlist_len(conns) > 0) {
4865 /* At least one counter must be non-zero */
4866 log_info(LD_NET, "Some stats on conn types seen during OOS follow");
4867 for (i = CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
4868 /* Did we see any? */
4869 if (conn_counts_by_type[i] > 0) {
4870 log_info(LD_NET, "%s: %d conns",
4871 conn_type_to_string(i),
4872 conn_counts_by_type[i]);
4875 log_info(LD_NET, "Done with OOS conn type stats");
4878 /* Did we find more eligible targets than we want to kill? */
4879 if (smartlist_len(eligible) > n) {
4880 /* Sort the list in order of target preference */
4881 smartlist_sort(eligible, oos_victim_comparator);
4882 /* Pick first n as victims */
4883 victims = smartlist_new();
4884 for (i = 0; i < n; ++i) {
4885 smartlist_add(victims, smartlist_get(eligible, i));
4887 /* Free the original list */
4888 smartlist_free(eligible);
4889 } else {
4890 /* No, we can just call them all victims */
4891 victims = eligible;
4894 return victims;
4897 /** Kill a list of connections for the OOS handler. */
4898 MOCK_IMPL(STATIC void,
4899 kill_conn_list_for_oos, (smartlist_t *conns))
4901 if (!conns) return;
4903 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
4904 /* Make sure the channel layer gets told about orconns */
4905 if (c->type == CONN_TYPE_OR) {
4906 connection_or_close_for_error(TO_OR_CONN(c), 1);
4907 } else {
4908 connection_mark_for_close(c);
4910 } SMARTLIST_FOREACH_END(c);
4912 log_notice(LD_NET,
4913 "OOS handler marked %d connections",
4914 smartlist_len(conns));
4917 /** Out-of-Sockets handler; n_socks is the current number of open
4918 * sockets, and failed is non-zero if a socket exhaustion related
4919 * error immediately preceded this call. This is where to do
4920 * circuit-killing heuristics as needed.
4922 void
4923 connection_check_oos(int n_socks, int failed)
4925 int target_n_socks = 0, moribund_socks, socks_to_kill;
4926 smartlist_t *conns;
4928 /* Early exit: is OOS checking disabled? */
4929 if (get_options()->DisableOOSCheck) {
4930 return;
4933 /* Sanity-check args */
4934 tor_assert(n_socks >= 0);
4937 * Make some log noise; keep it at debug level since this gets a chance
4938 * to run on every connection attempt.
4940 log_debug(LD_NET,
4941 "Running the OOS handler (%d open sockets, %s)",
4942 n_socks, (failed != 0) ? "exhaustion seen" : "no exhaustion");
4945 * Check if we're really handling an OOS condition, and if so decide how
4946 * many sockets we want to get down to. Be sure we check if the threshold
4947 * is distinct from zero first; it's possible for this to be called a few
4948 * times before we've finished reading the config.
4950 if (n_socks >= get_options()->ConnLimit_high_thresh &&
4951 get_options()->ConnLimit_high_thresh != 0 &&
4952 get_options()->ConnLimit_ != 0) {
4953 /* Try to get down to the low threshold */
4954 target_n_socks = get_options()->ConnLimit_low_thresh;
4955 log_notice(LD_NET,
4956 "Current number of sockets %d is greater than configured "
4957 "limit %d; OOS handler trying to get down to %d",
4958 n_socks, get_options()->ConnLimit_high_thresh,
4959 target_n_socks);
4960 } else if (failed) {
4962 * If we're not at the limit but we hit a socket exhaustion error, try to
4963 * drop some (but not as aggressively as ConnLimit_low_threshold, which is
4964 * 3/4 of ConnLimit_)
4966 target_n_socks = (n_socks * 9) / 10;
4967 log_notice(LD_NET,
4968 "We saw socket exhaustion at %d open sockets; OOS handler "
4969 "trying to get down to %d",
4970 n_socks, target_n_socks);
4973 if (target_n_socks > 0) {
4975 * It's an OOS!
4977 * Count moribund sockets; it's be important that anything we decide
4978 * to get rid of here but don't immediately close get counted as moribund
4979 * on subsequent invocations so we don't try to kill too many things if
4980 * connection_check_oos() gets called multiple times.
4982 moribund_socks = connection_count_moribund();
4984 if (moribund_socks < n_socks - target_n_socks) {
4985 socks_to_kill = n_socks - target_n_socks - moribund_socks;
4987 conns = pick_oos_victims(socks_to_kill);
4988 if (conns) {
4989 kill_conn_list_for_oos(conns);
4990 log_notice(LD_NET,
4991 "OOS handler killed %d conns", smartlist_len(conns));
4992 smartlist_free(conns);
4993 } else {
4994 log_notice(LD_NET, "OOS handler failed to pick any victim conns");
4996 } else {
4997 log_notice(LD_NET,
4998 "Not killing any sockets for OOS because there are %d "
4999 "already moribund, and we only want to eliminate %d",
5000 moribund_socks, n_socks - target_n_socks);
5005 /** Log how many bytes are used by buffers of different kinds and sizes. */
5006 void
5007 connection_dump_buffer_mem_stats(int severity)
5009 uint64_t used_by_type[CONN_TYPE_MAX_+1];
5010 uint64_t alloc_by_type[CONN_TYPE_MAX_+1];
5011 int n_conns_by_type[CONN_TYPE_MAX_+1];
5012 uint64_t total_alloc = 0;
5013 uint64_t total_used = 0;
5014 int i;
5015 smartlist_t *conns = get_connection_array();
5017 memset(used_by_type, 0, sizeof(used_by_type));
5018 memset(alloc_by_type, 0, sizeof(alloc_by_type));
5019 memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
5021 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
5022 int tp = c->type;
5023 ++n_conns_by_type[tp];
5024 if (c->inbuf) {
5025 used_by_type[tp] += buf_datalen(c->inbuf);
5026 alloc_by_type[tp] += buf_allocation(c->inbuf);
5028 if (c->outbuf) {
5029 used_by_type[tp] += buf_datalen(c->outbuf);
5030 alloc_by_type[tp] += buf_allocation(c->outbuf);
5032 } SMARTLIST_FOREACH_END(c);
5033 for (i=0; i <= CONN_TYPE_MAX_; ++i) {
5034 total_used += used_by_type[i];
5035 total_alloc += alloc_by_type[i];
5038 tor_log(severity, LD_GENERAL,
5039 "In buffers for %d connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
5040 smartlist_len(conns),
5041 U64_PRINTF_ARG(total_used), U64_PRINTF_ARG(total_alloc));
5042 for (i=CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
5043 if (!n_conns_by_type[i])
5044 continue;
5045 tor_log(severity, LD_GENERAL,
5046 " For %d %s connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
5047 n_conns_by_type[i], conn_type_to_string(i),
5048 U64_PRINTF_ARG(used_by_type[i]), U64_PRINTF_ARG(alloc_by_type[i]));
5052 /** Verify that connection <b>conn</b> has all of its invariants
5053 * correct. Trigger an assert if anything is invalid.
5055 void
5056 assert_connection_ok(connection_t *conn, time_t now)
5058 (void) now; /* XXXX unused. */
5059 tor_assert(conn);
5060 tor_assert(conn->type >= CONN_TYPE_MIN_);
5061 tor_assert(conn->type <= CONN_TYPE_MAX_);
5063 switch (conn->type) {
5064 case CONN_TYPE_OR:
5065 case CONN_TYPE_EXT_OR:
5066 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
5067 break;
5068 case CONN_TYPE_AP:
5069 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
5070 break;
5071 case CONN_TYPE_EXIT:
5072 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
5073 break;
5074 case CONN_TYPE_DIR:
5075 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
5076 break;
5077 case CONN_TYPE_CONTROL:
5078 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
5079 break;
5080 CASE_ANY_LISTENER_TYPE:
5081 tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
5082 break;
5083 default:
5084 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
5085 break;
5088 if (conn->linked_conn) {
5089 tor_assert(conn->linked_conn->linked_conn == conn);
5090 tor_assert(conn->linked);
5092 if (conn->linked)
5093 tor_assert(!SOCKET_OK(conn->s));
5095 if (conn->outbuf_flushlen > 0) {
5096 /* With optimistic data, we may have queued data in
5097 * EXIT_CONN_STATE_RESOLVING while the conn is not yet marked to writing.
5098 * */
5099 tor_assert((conn->type == CONN_TYPE_EXIT &&
5100 conn->state == EXIT_CONN_STATE_RESOLVING) ||
5101 connection_is_writing(conn) ||
5102 conn->write_blocked_on_bw ||
5103 (CONN_IS_EDGE(conn) &&
5104 TO_EDGE_CONN(conn)->edge_blocked_on_circ));
5107 if (conn->hold_open_until_flushed)
5108 tor_assert(conn->marked_for_close);
5110 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
5111 * marked_for_close. */
5113 /* buffers */
5114 if (conn->inbuf)
5115 buf_assert_ok(conn->inbuf);
5116 if (conn->outbuf)
5117 buf_assert_ok(conn->outbuf);
5119 if (conn->type == CONN_TYPE_OR) {
5120 or_connection_t *or_conn = TO_OR_CONN(conn);
5121 if (conn->state == OR_CONN_STATE_OPEN) {
5122 /* tor_assert(conn->bandwidth > 0); */
5123 /* the above isn't necessarily true: if we just did a TLS
5124 * handshake but we didn't recognize the other peer, or it
5125 * gave a bad cert/etc, then we won't have assigned bandwidth,
5126 * yet it will be open. -RD
5128 // tor_assert(conn->read_bucket >= 0);
5130 // tor_assert(conn->addr && conn->port);
5131 tor_assert(conn->address);
5132 if (conn->state > OR_CONN_STATE_PROXY_HANDSHAKING)
5133 tor_assert(or_conn->tls);
5136 if (CONN_IS_EDGE(conn)) {
5137 /* XXX unchecked: package window, deliver window. */
5138 if (conn->type == CONN_TYPE_AP) {
5139 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
5140 if (entry_conn->chosen_exit_optional || entry_conn->chosen_exit_retries)
5141 tor_assert(entry_conn->chosen_exit_name);
5143 tor_assert(entry_conn->socks_request);
5144 if (conn->state == AP_CONN_STATE_OPEN) {
5145 tor_assert(entry_conn->socks_request->has_finished);
5146 if (!conn->marked_for_close) {
5147 tor_assert(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
5148 assert_cpath_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
5152 if (conn->type == CONN_TYPE_EXIT) {
5153 tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
5154 conn->purpose == EXIT_PURPOSE_RESOLVE);
5156 } else if (conn->type == CONN_TYPE_DIR) {
5157 } else {
5158 /* Purpose is only used for dir and exit types currently */
5159 tor_assert(!conn->purpose);
5162 switch (conn->type)
5164 CASE_ANY_LISTENER_TYPE:
5165 tor_assert(conn->state == LISTENER_STATE_READY);
5166 break;
5167 case CONN_TYPE_OR:
5168 tor_assert(conn->state >= OR_CONN_STATE_MIN_);
5169 tor_assert(conn->state <= OR_CONN_STATE_MAX_);
5170 break;
5171 case CONN_TYPE_EXT_OR:
5172 tor_assert(conn->state >= EXT_OR_CONN_STATE_MIN_);
5173 tor_assert(conn->state <= EXT_OR_CONN_STATE_MAX_);
5174 break;
5175 case CONN_TYPE_EXIT:
5176 tor_assert(conn->state >= EXIT_CONN_STATE_MIN_);
5177 tor_assert(conn->state <= EXIT_CONN_STATE_MAX_);
5178 tor_assert(conn->purpose >= EXIT_PURPOSE_MIN_);
5179 tor_assert(conn->purpose <= EXIT_PURPOSE_MAX_);
5180 break;
5181 case CONN_TYPE_AP:
5182 tor_assert(conn->state >= AP_CONN_STATE_MIN_);
5183 tor_assert(conn->state <= AP_CONN_STATE_MAX_);
5184 tor_assert(TO_ENTRY_CONN(conn)->socks_request);
5185 break;
5186 case CONN_TYPE_DIR:
5187 tor_assert(conn->state >= DIR_CONN_STATE_MIN_);
5188 tor_assert(conn->state <= DIR_CONN_STATE_MAX_);
5189 tor_assert(conn->purpose >= DIR_PURPOSE_MIN_);
5190 tor_assert(conn->purpose <= DIR_PURPOSE_MAX_);
5191 break;
5192 case CONN_TYPE_CONTROL:
5193 tor_assert(conn->state >= CONTROL_CONN_STATE_MIN_);
5194 tor_assert(conn->state <= CONTROL_CONN_STATE_MAX_);
5195 break;
5196 default:
5197 tor_assert(0);
5201 /** Fills <b>addr</b> and <b>port</b> with the details of the global
5202 * proxy server we are using.
5203 * <b>conn</b> contains the connection we are using the proxy for.
5205 * Return 0 on success, -1 on failure.
5208 get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type,
5209 const connection_t *conn)
5211 const or_options_t *options = get_options();
5213 /* Client Transport Plugins can use another proxy, but that should be hidden
5214 * from the rest of tor (as the plugin is responsible for dealing with the
5215 * proxy), check it first, then check the rest of the proxy types to allow
5216 * the config to have unused ClientTransportPlugin entries.
5218 if (options->ClientTransportPlugin) {
5219 const transport_t *transport = NULL;
5220 int r;
5221 r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
5222 if (r<0)
5223 return -1;
5224 if (transport) { /* transport found */
5225 tor_addr_copy(addr, &transport->addr);
5226 *port = transport->port;
5227 *proxy_type = transport->socks_version;
5228 return 0;
5231 /* Unused ClientTransportPlugin. */
5234 if (options->HTTPSProxy) {
5235 tor_addr_copy(addr, &options->HTTPSProxyAddr);
5236 *port = options->HTTPSProxyPort;
5237 *proxy_type = PROXY_CONNECT;
5238 return 0;
5239 } else if (options->Socks4Proxy) {
5240 tor_addr_copy(addr, &options->Socks4ProxyAddr);
5241 *port = options->Socks4ProxyPort;
5242 *proxy_type = PROXY_SOCKS4;
5243 return 0;
5244 } else if (options->Socks5Proxy) {
5245 tor_addr_copy(addr, &options->Socks5ProxyAddr);
5246 *port = options->Socks5ProxyPort;
5247 *proxy_type = PROXY_SOCKS5;
5248 return 0;
5251 tor_addr_make_unspec(addr);
5252 *port = 0;
5253 *proxy_type = PROXY_NONE;
5254 return 0;
5257 /** Log a failed connection to a proxy server.
5258 * <b>conn</b> is the connection we use the proxy server for. */
5259 void
5260 log_failed_proxy_connection(connection_t *conn)
5262 tor_addr_t proxy_addr;
5263 uint16_t proxy_port;
5264 int proxy_type;
5266 if (get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, conn) != 0)
5267 return; /* if we have no proxy set up, leave this function. */
5269 log_warn(LD_NET,
5270 "The connection to the %s proxy server at %s just failed. "
5271 "Make sure that the proxy server is up and running.",
5272 proxy_type_to_string(proxy_type),
5273 fmt_addrport(&proxy_addr, proxy_port));
5276 /** Return string representation of <b>proxy_type</b>. */
5277 static const char *
5278 proxy_type_to_string(int proxy_type)
5280 switch (proxy_type) {
5281 case PROXY_CONNECT: return "HTTP";
5282 case PROXY_SOCKS4: return "SOCKS4";
5283 case PROXY_SOCKS5: return "SOCKS5";
5284 case PROXY_PLUGGABLE: return "pluggable transports SOCKS";
5285 case PROXY_NONE: return "NULL";
5286 default: tor_assert(0);
5288 return NULL; /*Unreached*/
5291 /** Call connection_free_minimal() on every connection in our array, and
5292 * release all storage held by connection.c.
5294 * Don't do the checks in connection_free(), because they will
5295 * fail.
5297 void
5298 connection_free_all(void)
5300 smartlist_t *conns = get_connection_array();
5302 /* We don't want to log any messages to controllers. */
5303 SMARTLIST_FOREACH(conns, connection_t *, conn,
5304 if (conn->type == CONN_TYPE_CONTROL)
5305 TO_CONTROL_CONN(conn)->event_mask = 0);
5307 control_update_global_event_mask();
5309 /* Unlink everything from the identity map. */
5310 connection_or_clear_identity_map();
5311 connection_or_clear_ext_or_id_map();
5313 /* Clear out our list of broken connections */
5314 clear_broken_connection_map(0);
5316 SMARTLIST_FOREACH(conns, connection_t *, conn,
5317 connection_free_minimal(conn));
5319 if (outgoing_addrs) {
5320 SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t *, addr, tor_free(addr));
5321 smartlist_free(outgoing_addrs);
5322 outgoing_addrs = NULL;
5325 tor_free(last_interface_ipv4);
5326 tor_free(last_interface_ipv6);
5329 /** Log a warning, and possibly emit a control event, that <b>received</b> came
5330 * at a skewed time. <b>trusted</b> indicates that the <b>source</b> was one
5331 * that we had more faith in and therefore the warning level should have higher
5332 * severity.
5334 void
5335 clock_skew_warning(const connection_t *conn, long apparent_skew, int trusted,
5336 log_domain_mask_t domain, const char *received,
5337 const char *source)
5339 char dbuf[64];
5340 char *ext_source = NULL, *warn = NULL;
5341 format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
5342 if (conn)
5343 tor_asprintf(&ext_source, "%s:%s:%d", source, conn->address, conn->port);
5344 else
5345 ext_source = tor_strdup(source);
5346 log_fn(trusted ? LOG_WARN : LOG_INFO, domain,
5347 "Received %s with skewed time (%s): "
5348 "It seems that our clock is %s by %s, or that theirs is %s%s. "
5349 "Tor requires an accurate clock to work: please check your time, "
5350 "timezone, and date settings.", received, ext_source,
5351 apparent_skew > 0 ? "ahead" : "behind", dbuf,
5352 apparent_skew > 0 ? "behind" : "ahead",
5353 (!conn || trusted) ? "" : ", or they are sending us the wrong time");
5354 if (trusted) {
5355 control_event_general_status(LOG_WARN, "CLOCK_SKEW SKEW=%ld SOURCE=%s",
5356 apparent_skew, ext_source);
5357 tor_asprintf(&warn, "Clock skew %ld in %s from %s", apparent_skew,
5358 received, source);
5359 control_event_bootstrap_problem(warn, "CLOCK_SKEW", conn, 1);
5361 tor_free(warn);
5362 tor_free(ext_source);