Tor 0.4.9.13
Loading...
Searching...
No Matches
connection.c
Go to the documentation of this file.
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-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file connection.c
9 * \brief General high-level functions to handle reading and writing
10 * on connections.
11 *
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.)
16 *
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>
28 *
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).
32 *
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().
38 *
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.
47 *
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 **/
56
57#define CONNECTION_PRIVATE
58#include "core/or/or.h"
60#include "lib/buf/buffers.h"
61#include "lib/tls/buffers_tls.h"
62#include "lib/err/backtrace.h"
63
64/*
65 * Define this so we get channel internal functions, since we're implementing
66 * part of a subclass (channel_tls_t).
67 */
68#define CHANNEL_OBJECT_PRIVATE
69#include "app/config/config.h"
74#include "core/or/channel.h"
75#include "core/or/channeltls.h"
77#include "core/or/circuitlist.h"
78#include "core/or/circuituse.h"
81#include "core/or/dos.h"
82#include "core/or/policies.h"
83#include "core/or/reasons.h"
84#include "core/or/relay.h"
85#include "core/or/status.h"
86#include "core/or/crypt_path.h"
87#include "core/proto/proto_haproxy.h"
100#include "feature/hs/hs_common.h"
101#include "feature/hs/hs_ident.h"
106#include "feature/relay/dns.h"
112#include "feature/stats/bwhist.h"
115#include "lib/geoip/geoip.h"
116
117#include "lib/cc/ctassert.h"
118#include "lib/sandbox/sandbox.h"
119#include "lib/net/buffers_net.h"
120#include "lib/net/address.h"
121#include "lib/tls/tortls.h"
124
125#ifdef HAVE_PWD_H
126#include <pwd.h>
127#endif
128
129#ifdef HAVE_UNISTD_H
130#include <unistd.h>
131#endif
132#ifdef HAVE_SYS_STAT_H
133#include <sys/stat.h>
134#endif
135
136#ifdef HAVE_SYS_UN_H
137#include <sys/socket.h>
138#include <sys/un.h>
139#endif
140
146#include "core/or/port_cfg_st.h"
149
151
152/**
153 * On Windows and Linux we cannot reliably bind() a socket to an
154 * address and port if: 1) There's already a socket bound to wildcard
155 * address (0.0.0.0 or ::) with the same port; 2) We try to bind()
156 * to wildcard address and there's another socket bound to a
157 * specific address and the same port.
158 *
159 * To address this problem on these two platforms we implement a
160 * routine that:
161 * 1) Checks if first attempt to bind() a new socket failed with
162 * EADDRINUSE.
163 * 2) If so, it will close the appropriate old listener connection and
164 * 3) Attempts bind()'ing the new listener socket again.
165 *
166 * Just to be safe, we are enabling listener rebind code on all platforms,
167 * to account for unexpected cases where it may be needed.
168 */
169#define ENABLE_LISTENER_REBIND
170
172 const struct sockaddr *listensockaddr,
173 socklen_t listensocklen, int type,
174 const char *address,
175 const port_cfg_t *portcfg,
176 int *addr_in_use);
178 const port_cfg_t *port,
179 int *defer, int *addr_in_use);
180static void connection_init(time_t now, connection_t *conn, int type,
181 int socket_family);
182static int connection_handle_listener_read(connection_t *conn, int new_type);
184static int connection_flushed_some(connection_t *conn);
186static int connection_reached_eof(connection_t *conn);
188static void set_constrained_socket_buffers(tor_socket_t sock, int size);
189
190static const char *connection_proxy_state_to_string(int state);
193static const char *proxy_type_to_string(int proxy_type);
194static int conn_get_proxy_type(const connection_t *conn);
196 const or_options_t *options, unsigned int conn_type);
197static void reenable_blocked_connection_init(const or_options_t *options);
199
200/** The last addresses that our network interface seemed to have been
201 * binding to. We use this as one way to detect when our IP changes.
202 *
203 * XXXX+ We should really use the entire list of interfaces here.
204 **/
206/* DOCDOC last_interface_ipv6 */
207static tor_addr_t *last_interface_ipv6 = NULL;
208/** A list of tor_addr_t for addresses we've used in outgoing connections.
209 * Used to detect IP address changes. */
211
212#define CASE_ANY_LISTENER_TYPE \
213 case CONN_TYPE_OR_LISTENER: \
214 case CONN_TYPE_EXT_OR_LISTENER: \
215 case CONN_TYPE_AP_LISTENER: \
216 case CONN_TYPE_DIR_LISTENER: \
217 case CONN_TYPE_CONTROL_LISTENER: \
218 case CONN_TYPE_AP_TRANS_LISTENER: \
219 case CONN_TYPE_AP_NATD_LISTENER: \
220 case CONN_TYPE_AP_DNS_LISTENER: \
221 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER: \
222 case CONN_TYPE_METRICS_LISTENER
223
224/**************************************************************/
225
226/**
227 * Cast a `connection_t *` to a `listener_connection_t *`.
228 *
229 * Exit with an assertion failure if the input is not a
230 * `listener_connection_t`.
231 **/
234{
235 tor_assert(c->magic == LISTENER_CONNECTION_MAGIC);
237}
238
239/**
240 * Cast a `const connection_t *` to a `const listener_connection_t *`.
241 *
242 * Exit with an assertion failure if the input is not a
243 * `listener_connection_t`.
244 **/
250
251size_t
252connection_get_inbuf_len(const connection_t *conn)
253{
254 return conn->inbuf ? buf_datalen(conn->inbuf) : 0;
255}
256
257size_t
258connection_get_outbuf_len(const connection_t *conn)
259{
260 return conn->outbuf ? buf_datalen(conn->outbuf) : 0;
261}
262
263/**
264 * Return the human-readable name for the connection type <b>type</b>
265 */
266const char *
268{
269 static char buf[64];
270 switch (type) {
271 case CONN_TYPE_OR_LISTENER: return "OR listener";
272 case CONN_TYPE_OR: return "OR";
273 case CONN_TYPE_EXIT: return "Exit";
274 case CONN_TYPE_AP_LISTENER: return "Socks listener";
276 return "Transparent pf/netfilter listener";
277 case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
278 case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
279 case CONN_TYPE_AP: return "Socks";
280 case CONN_TYPE_DIR_LISTENER: return "Directory listener";
281 case CONN_TYPE_DIR: return "Directory";
282 case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
283 case CONN_TYPE_CONTROL: return "Control";
284 case CONN_TYPE_EXT_OR: return "Extended OR";
285 case CONN_TYPE_EXT_OR_LISTENER: return "Extended OR listener";
286 case CONN_TYPE_AP_HTTP_CONNECT_LISTENER: return "HTTP tunnel listener";
287 case CONN_TYPE_METRICS_LISTENER: return "Metrics listener";
288 case CONN_TYPE_METRICS: return "Metrics";
289 default:
290 log_warn(LD_BUG, "unknown connection type %d", type);
291 tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
292 return buf;
293 }
294}
295
296/**
297 * Return the human-readable name for the connection state <b>state</b>
298 * for the connection type <b>type</b>
299 */
300const char *
301conn_state_to_string(int type, int state)
302{
303 static char buf[96];
304 switch (type) {
305 CASE_ANY_LISTENER_TYPE:
306 if (state == LISTENER_STATE_READY)
307 return "ready";
308 break;
309 case CONN_TYPE_OR:
310 switch (state) {
311 case OR_CONN_STATE_CONNECTING: return "connect()ing";
312 case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
313 case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
315 return "waiting for V3+ handshake";
317 return "handshaking (Tor, v3 handshake)";
318 case OR_CONN_STATE_OPEN: return "open";
319 }
320 break;
321 case CONN_TYPE_EXT_OR:
322 switch (state) {
324 return "waiting for authentication type";
326 return "waiting for client nonce";
328 return "waiting for client hash";
329 case EXT_OR_CONN_STATE_OPEN: return "open";
330 case EXT_OR_CONN_STATE_FLUSHING: return "flushing final OKAY";
331 }
332 break;
333 case CONN_TYPE_EXIT:
334 switch (state) {
335 case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
336 case EXIT_CONN_STATE_CONNECTING: return "connecting";
337 case EXIT_CONN_STATE_OPEN: return "open";
338 case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
339 }
340 break;
341 case CONN_TYPE_AP:
342 switch (state) {
343 case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
344 case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
345 case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
346 case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
347 case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
348 case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
349 case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
350 case AP_CONN_STATE_OPEN: return "open";
351 }
352 break;
353 case CONN_TYPE_DIR:
354 switch (state) {
355 case DIR_CONN_STATE_CONNECTING: return "connecting";
356 case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
357 case DIR_CONN_STATE_CLIENT_READING: return "client reading";
358 case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
359 case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
360 case DIR_CONN_STATE_SERVER_WRITING: return "writing";
361 }
362 break;
364 switch (state) {
365 case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
367 return "waiting for authentication (protocol v1)";
368 }
369 break;
370 }
371
372 if (state == 0) {
373 return "uninitialized";
374 }
375
376 log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
377 tor_snprintf(buf, sizeof(buf),
378 "unknown state [%d] on unknown [%s] connection",
379 state, conn_type_to_string(type));
380 tor_assert_nonfatal_unreached_once();
381 return buf;
382}
383
384/**
385 * Helper: describe the peer or address of connection @a conn in a
386 * human-readable manner.
387 *
388 * Returns a pointer to a static buffer; future calls to
389 * connection_describe_peer_internal() will invalidate this buffer.
390 *
391 * If <b>include_preposition</b> is true, include a preposition before the
392 * peer address.
393 *
394 * Nobody should parse the output of this function; it can and will change in
395 * future versions of tor.
396 **/
397static const char *
399 bool include_preposition)
400{
401 IF_BUG_ONCE(!conn) {
402 return "null peer";
403 }
404
405 static char peer_buf[256];
406 const tor_addr_t *addr = &conn->addr;
407 const char *address = NULL;
408 const char *prep;
409 bool scrub = false;
410 char extra_buf[128];
411 extra_buf[0] = 0;
412
413 /* First, figure out the preposition to use */
414 switch (conn->type) {
415 CASE_ANY_LISTENER_TYPE:
416 prep = "on";
417 break;
418 case CONN_TYPE_EXIT:
419 prep = "to";
420 break;
422 case CONN_TYPE_AP:
423 case CONN_TYPE_EXT_OR:
424 prep = "from";
425 break;
426 default:
427 prep = "with";
428 break;
429 }
430
431 /* Now figure out the address. */
432 if (conn->socket_family == AF_UNIX) {
433 /* For unix sockets, we always use the `address` string. */
434 address = conn->address ? conn->address : "unix socket";
435 } else if (conn->type == CONN_TYPE_OR) {
436 /* For OR connections, we have a lot to do. */
437 const or_connection_t *or_conn = CONST_TO_OR_CONN(conn);
438 /* We report the IDs we're talking to... */
439 if (fast_digest_is_zero(or_conn->identity_digest)) {
440 // This could be a client, so scrub it. No identity to report.
441 scrub = true;
442 } else {
443 const ed25519_public_key_t *ed_id =
445 char ed_id_buf[ED25519_BASE64_LEN+1];
446 char rsa_id_buf[HEX_DIGEST_LEN+1];
447 if (ed_id) {
448 ed25519_public_to_base64(ed_id_buf, ed_id);
449 } else {
450 strlcpy(ed_id_buf, "<none>", sizeof(ed_id_buf));
451 }
452 base16_encode(rsa_id_buf, sizeof(rsa_id_buf),
453 or_conn->identity_digest, DIGEST_LEN);
454 tor_snprintf(extra_buf, sizeof(extra_buf),
455 " ID=%s RSA_ID=%s", ed_id_buf, rsa_id_buf);
456 }
457 if (! scrub && (! tor_addr_eq(addr, &or_conn->canonical_orport.addr) ||
458 conn->port != or_conn->canonical_orport.port)) {
459 /* We report canonical address, if it's different */
460 char canonical_addr_buf[TOR_ADDR_BUF_LEN];
461 if (tor_addr_to_str(canonical_addr_buf, &or_conn->canonical_orport.addr,
462 sizeof(canonical_addr_buf), 1)) {
463 tor_snprintf(extra_buf+strlen(extra_buf),
464 sizeof(extra_buf)-strlen(extra_buf),
465 " canonical_addr=%s:%"PRIu16,
466 canonical_addr_buf,
467 or_conn->canonical_orport.port);
468 }
469 }
470 } else if (conn->type == CONN_TYPE_EXIT) {
471 scrub = true; /* This is a client's request; scrub it with SafeLogging. */
472 if (tor_addr_is_null(addr)) {
473 address = conn->address;
474 strlcpy(extra_buf, " (DNS lookup pending)", sizeof(extra_buf));
475 }
476 }
477
478 char addr_buf[TOR_ADDR_BUF_LEN];
479 if (address == NULL) {
480 if (tor_addr_family(addr) == 0) {
481 address = "<unset>";
482 } else {
483 address = tor_addr_to_str(addr_buf, addr, sizeof(addr_buf), 1);
484 if (!address) {
485 address = "<can't format!>";
486 tor_assert_nonfatal_unreached_once();
487 }
488 }
489 }
490
491 char portbuf[7];
492 portbuf[0]=0;
493 if (scrub && get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE) {
494 address = "[scrubbed]";
495 } else {
496 /* Only set the port if we're not scrubbing the address. */
497 if (conn->port != 0) {
498 tor_snprintf(portbuf, sizeof(portbuf), ":%d", conn->port);
499 }
500 }
501
502 const char *sp = include_preposition ? " " : "";
503 if (! include_preposition)
504 prep = "";
505
506 tor_snprintf(peer_buf, sizeof(peer_buf),
507 "%s%s%s%s%s", prep, sp, address, portbuf, extra_buf);
508 return peer_buf;
509}
510
511/**
512 * Describe the peer or address of connection @a conn in a
513 * human-readable manner.
514 *
515 * Returns a pointer to a static buffer; future calls to
516 * connection_describe_peer() or connection_describe() will invalidate this
517 * buffer.
518 *
519 * Nobody should parse the output of this function; it can and will change in
520 * future versions of tor.
521 **/
522const char *
524{
525 return connection_describe_peer_internal(conn, false);
526}
527
528/**
529 * Describe a connection for logging purposes.
530 *
531 * Returns a pointer to a static buffer; future calls to connection_describe()
532 * will invalidate this buffer.
533 *
534 * Nobody should parse the output of this function; it can and will change in
535 * future versions of tor.
536 **/
537const char *
539{
540 IF_BUG_ONCE(!conn) {
541 return "null connection";
542 }
543 static char desc_buf[256];
544 const char *peer = connection_describe_peer_internal(conn, true);
545 tor_snprintf(desc_buf, sizeof(desc_buf),
546 "%s connection (%s) %s",
548 conn_state_to_string(conn->type, conn->state),
549 peer);
550 return desc_buf;
551}
552
553/** Allocate and return a new dir_connection_t, initialized as by
554 * connection_init(). */
556dir_connection_new(int socket_family)
557{
558 dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
559 connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
560 return dir_conn;
561}
562
563/** Allocate and return a new or_connection_t, initialized as by
564 * connection_init().
565 *
566 * Initialize active_circuit_pqueue.
567 *
568 * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
569 */
571or_connection_new(int type, int socket_family)
572{
573 or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
574 time_t now = time(NULL);
575 tor_assert(type == CONN_TYPE_OR || type == CONN_TYPE_EXT_OR);
576 connection_init(now, TO_CONN(or_conn), type, socket_family);
577
579 connection_or_set_canonical(or_conn, 0);
580
581 if (type == CONN_TYPE_EXT_OR) {
582 /* If we aren't told an address for this connection, we should
583 * presume it isn't local, and should be rate-limited. */
584 TO_CONN(or_conn)->always_rate_limit_as_remote = 1;
585 }
586
587 return or_conn;
588}
589
590/** Allocate and return a new entry_connection_t, initialized as by
591 * connection_init().
592 *
593 * Allocate space to store the socks_request.
594 */
596entry_connection_new(int type, int socket_family)
597{
598 entry_connection_t *entry_conn = tor_malloc_zero(sizeof(entry_connection_t));
599 tor_assert(type == CONN_TYPE_AP);
600 connection_init(time(NULL), ENTRY_TO_CONN(entry_conn), type, socket_family);
601 entry_conn->socks_request = socks_request_new();
602 /* If this is coming from a listener, we'll set it up based on the listener
603 * in a little while. Otherwise, we're doing this as a linked connection
604 * of some kind, and we should set it up here based on the socket family */
605 if (socket_family == AF_INET)
606 entry_conn->entry_cfg.ipv4_traffic = 1;
607 else if (socket_family == AF_INET6)
608 entry_conn->entry_cfg.ipv6_traffic = 1;
609
610 /* Initialize the read token bucket to the maximum value which is the same as
611 * no rate limiting. */
612 token_bucket_rw_init(&ENTRY_TO_EDGE_CONN(entry_conn)->bucket, INT32_MAX,
613 INT32_MAX, monotime_coarse_get_stamp());
614 return entry_conn;
615}
616
617/** Allocate and return a new edge_connection_t, initialized as by
618 * connection_init(). */
620edge_connection_new(int type, int socket_family)
621{
622 edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
623 tor_assert(type == CONN_TYPE_EXIT);
624 connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
625 /* Initialize the read token bucket to the maximum value which is the same as
626 * no rate limiting. */
627 token_bucket_rw_init(&edge_conn->bucket, INT32_MAX, INT32_MAX,
629 return edge_conn;
630}
631
632/** Allocate and return a new control_connection_t, initialized as by
633 * connection_init(). */
635control_connection_new(int socket_family)
636{
637 control_connection_t *control_conn =
638 tor_malloc_zero(sizeof(control_connection_t));
639 connection_init(time(NULL),
640 TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
641 return control_conn;
642}
643
644/** Allocate and return a new listener_connection_t, initialized as by
645 * connection_init(). */
647listener_connection_new(int type, int socket_family)
648{
649 listener_connection_t *listener_conn =
650 tor_malloc_zero(sizeof(listener_connection_t));
651 connection_init(time(NULL), TO_CONN(listener_conn), type, socket_family);
652 /* Listener connections aren't accounted for with note_connection() so do
653 * this explicitly so to count them. */
654 rep_hist_note_conn_opened(false, type, socket_family);
655 return listener_conn;
656}
657
658/** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
659 * to make or receive connections of address family <b>socket_family</b>. The
660 * type should be one of the CONN_TYPE_* constants. */
662connection_new(int type, int socket_family)
663{
664 switch (type) {
665 case CONN_TYPE_OR:
666 case CONN_TYPE_EXT_OR:
667 return TO_CONN(or_connection_new(type, socket_family));
668
669 case CONN_TYPE_EXIT:
670 return TO_CONN(edge_connection_new(type, socket_family));
671
672 case CONN_TYPE_AP:
673 return ENTRY_TO_CONN(entry_connection_new(type, socket_family));
674
675 case CONN_TYPE_DIR:
676 return TO_CONN(dir_connection_new(socket_family));
677
679 return TO_CONN(control_connection_new(socket_family));
680
681 CASE_ANY_LISTENER_TYPE:
682 return TO_CONN(listener_connection_new(type, socket_family));
683
684 default: {
685 connection_t *conn = tor_malloc_zero(sizeof(connection_t));
686 connection_init(time(NULL), conn, type, socket_family);
687 return conn;
688 }
689 }
690}
691
692/** Initializes conn. (you must call connection_add() to link it into the main
693 * array).
694 *
695 * Set conn->magic to the correct value.
696 *
697 * Set conn->type to <b>type</b>. Set conn->s and conn->conn_array_index to
698 * -1 to signify they are not yet assigned.
699 *
700 * Initialize conn's timestamps to now.
701 */
702static void
703connection_init(time_t now, connection_t *conn, int type, int socket_family)
704{
705 static uint64_t n_connections_allocated = 1;
706
707 switch (type) {
708 case CONN_TYPE_OR:
709 case CONN_TYPE_EXT_OR:
710 conn->magic = OR_CONNECTION_MAGIC;
711 break;
712 case CONN_TYPE_EXIT:
713 conn->magic = EDGE_CONNECTION_MAGIC;
714 break;
715 case CONN_TYPE_AP:
716 conn->magic = ENTRY_CONNECTION_MAGIC;
717 break;
718 case CONN_TYPE_DIR:
719 conn->magic = DIR_CONNECTION_MAGIC;
720 break;
722 conn->magic = CONTROL_CONNECTION_MAGIC;
723 break;
724 CASE_ANY_LISTENER_TYPE:
725 conn->magic = LISTENER_CONNECTION_MAGIC;
726 break;
727 default:
728 conn->magic = BASE_CONNECTION_MAGIC;
729 break;
730 }
731
732 conn->s = TOR_INVALID_SOCKET; /* give it a default of 'not used' */
733 conn->conn_array_index = -1; /* also default to 'not used' */
734 conn->global_identifier = n_connections_allocated++;
735
736 conn->type = type;
737 conn->socket_family = socket_family;
738 if (!connection_is_listener(conn)) {
739 /* listeners never use their buf */
740 conn->inbuf = buf_new();
741 conn->outbuf = buf_new();
742 }
743
744 conn->timestamp_created = now;
745 conn->timestamp_last_read_allowed = now;
747}
748
749/** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
750void
752{
753 tor_assert(! SOCKET_OK(conn_a->s));
754 tor_assert(! SOCKET_OK(conn_b->s));
755
756 conn_a->linked = 1;
757 conn_b->linked = 1;
758 conn_a->linked_conn = conn_b;
759 conn_b->linked_conn = conn_a;
760}
761
762/** Return true iff the provided connection listener type supports AF_UNIX
763 * sockets. */
764int
766{
767 /* For now only control ports or SOCKS ports can be Unix domain sockets
768 * and listeners at the same time */
769 switch (type) {
772 return 1;
773 default:
774 return 0;
775 }
776}
777
778/** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
779 * necessary, close its socket if necessary, and mark the directory as dirty
780 * if <b>conn</b> is an OR or OP connection.
781 */
782STATIC void
784{
785 void *mem;
786 size_t memlen;
787 if (!conn)
788 return;
789
790 switch (conn->type) {
791 case CONN_TYPE_OR:
792 case CONN_TYPE_EXT_OR:
793 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
794 mem = TO_OR_CONN(conn);
795 memlen = sizeof(or_connection_t);
796 break;
797 case CONN_TYPE_AP:
798 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
799 mem = TO_ENTRY_CONN(conn);
800 memlen = sizeof(entry_connection_t);
801 break;
802 case CONN_TYPE_EXIT:
803 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
804 mem = TO_EDGE_CONN(conn);
805 memlen = sizeof(edge_connection_t);
806 break;
807 case CONN_TYPE_DIR:
808 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
809 mem = TO_DIR_CONN(conn);
810 memlen = sizeof(dir_connection_t);
811 break;
813 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
814 mem = TO_CONTROL_CONN(conn);
815 memlen = sizeof(control_connection_t);
816 break;
817 CASE_ANY_LISTENER_TYPE:
818 tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
819 mem = TO_LISTENER_CONN(conn);
820 memlen = sizeof(listener_connection_t);
821 break;
822 default:
823 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
824 mem = conn;
825 memlen = sizeof(connection_t);
826 break;
827 }
828
829 if (conn->linked) {
830 log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
831 "bytes on inbuf, %d on outbuf.",
833 conn_state_to_string(conn->type, conn->state),
834 (int)connection_get_inbuf_len(conn),
835 (int)connection_get_outbuf_len(conn));
836 }
837
838 if (!connection_is_listener(conn)) {
839 buf_free(conn->inbuf);
840 buf_free(conn->outbuf);
841 } else {
842 if (conn->socket_family == AF_UNIX) {
843 /* For now only control and SOCKS ports can be Unix domain sockets
844 * and listeners at the same time */
846
847 if (unlink(conn->address) < 0 && errno != ENOENT) {
848 log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
849 strerror(errno));
850 }
851 }
852 }
853
855
856 if (connection_speaks_cells(conn)) {
857 or_connection_t *or_conn = TO_OR_CONN(conn);
858 if (or_conn->tls) {
859 if (! SOCKET_OK(conn->s)) {
860 /* The socket has been closed by somebody else; we must tell the
861 * TLS object not to close it. */
862 tor_tls_release_socket(or_conn->tls);
863 } else {
864 /* The tor_tls_free() call below will close the socket; we must tell
865 * the code below not to close it a second time. */
867 conn->s = TOR_INVALID_SOCKET;
868 }
869 tor_tls_free(or_conn->tls);
870 or_conn->tls = NULL;
871 }
872 or_handshake_state_free(or_conn->handshake_state);
873 or_conn->handshake_state = NULL;
875 if (or_conn->chan) {
876 /* Owww, this shouldn't happen, but... */
877 channel_t *base_chan = TLS_CHAN_TO_BASE(or_conn->chan);
878 tor_assert(base_chan);
879 log_info(LD_CHANNEL,
880 "Freeing orconn at %p, saw channel %p with ID "
881 "%"PRIu64 " left un-NULLed",
882 or_conn, base_chan,
883 base_chan->global_identifier);
884 if (!CHANNEL_FINISHED(base_chan)) {
885 channel_close_for_error(base_chan);
886 }
887
888 or_conn->chan->conn = NULL;
889 or_conn->chan = NULL;
890 }
891 }
892 if (conn->type == CONN_TYPE_AP) {
893 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
896 if (entry_conn->socks_request)
897 socks_request_free(entry_conn->socks_request);
898 if (entry_conn->pending_optimistic_data) {
899 buf_free(entry_conn->pending_optimistic_data);
900 }
901 if (entry_conn->sending_optimistic_data) {
902 buf_free(entry_conn->sending_optimistic_data);
903 }
904 }
905 if (CONN_IS_EDGE(conn)) {
906 hs_ident_edge_conn_free(TO_EDGE_CONN(conn)->hs_ident);
907 }
908 if (conn->type == CONN_TYPE_CONTROL) {
909 control_connection_t *control_conn = TO_CONTROL_CONN(conn);
910 tor_free(control_conn->safecookie_client_hash);
911 tor_free(control_conn->incoming_cmd);
912 tor_free(control_conn->current_cmd);
913 if (control_conn->ephemeral_onion_services) {
914 SMARTLIST_FOREACH(control_conn->ephemeral_onion_services, char *, cp, {
915 memwipe(cp, 0, strlen(cp));
916 tor_free(cp);
917 });
918 smartlist_free(control_conn->ephemeral_onion_services);
919 }
920 }
921
922 /* Probably already freed by connection_free. */
923 tor_event_free(conn->read_event);
924 tor_event_free(conn->write_event);
925 conn->read_event = conn->write_event = NULL;
926
927 if (conn->type == CONN_TYPE_DIR) {
928 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
929 tor_free(dir_conn->requested_resource);
930
931 tor_compress_free(dir_conn->compress_state);
932 dir_conn_clear_spool(dir_conn);
933
934 hs_ident_dir_conn_free(dir_conn->hs_ident);
935 if (dir_conn->guard_state) {
936 /* Cancel before freeing, if it's still there. */
938 }
939 circuit_guard_state_free(dir_conn->guard_state);
940 }
941
942 if (SOCKET_OK(conn->s)) {
943 log_debug(LD_NET,"closing fd %d.",(int)conn->s);
944 tor_close_socket(conn->s);
945 conn->s = TOR_INVALID_SOCKET;
946 }
947
948 if (conn->type == CONN_TYPE_OR &&
949 !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
950 log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
952 }
953 if (conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR) {
954 tor_free(TO_OR_CONN(conn)->ext_or_auth_correct_client_hash);
955 tor_free(TO_OR_CONN(conn)->ext_or_transport);
956 }
957
958 memwipe(mem, 0xCC, memlen); /* poison memory */
959 tor_free(mem);
960}
961
962/** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
963 */
964MOCK_IMPL(void,
966{
967 if (!conn)
968 return;
971 /* Direct free can bypass normal closure. This releases the channel's guard
972 * attribution handle before cleanup callbacks can report another error.
973 * Destruction itself is not evidence of establishment failure; any eligible
974 * failure must already have been reported before reaching this cleanup. */
975 if (conn->type == CONN_TYPE_OR && TO_OR_CONN(conn)->chan)
977 TLS_CHAN_TO_BASE(TO_OR_CONN(conn)->chan));
978 if (conn->linked_conn) {
979 conn->linked_conn->linked_conn = NULL;
980 if (! conn->linked_conn->marked_for_close &&
983 conn->linked_conn = NULL;
984 }
985 if (connection_speaks_cells(conn)) {
986 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
988 }
989 }
990 if (conn->type == CONN_TYPE_CONTROL) {
992 }
993#if 1
994 /* DEBUGGING */
995 if (conn->type == CONN_TYPE_AP) {
996 connection_ap_warn_and_unmark_if_pending_circ(TO_ENTRY_CONN(conn),
997 "connection_free");
998 }
999#endif /* 1 */
1000
1001 /* Notify the circuit creation DoS mitigation subsystem that an OR client
1002 * connection has been closed. And only do that if we track it. */
1003 if (conn->type == CONN_TYPE_OR) {
1004 dos_close_client_conn(TO_OR_CONN(conn));
1005 }
1006
1009}
1010
1011/**
1012 * Called when we're about to finally unlink and free a connection:
1013 * perform necessary accounting and cleanup
1014 * - Directory conns that failed to fetch a rendezvous descriptor
1015 * need to inform pending rendezvous streams.
1016 * - OR conns need to call rep_hist_note_*() to record status.
1017 * - AP conns need to send a socks reject if necessary.
1018 * - Exit conns need to call connection_dns_remove() if necessary.
1019 * - AP and Exit conns need to send an end cell if they can.
1020 * - DNS conns need to fail any resolves that are pending on them.
1021 * - OR and edge connections need to be unlinked from circuits.
1022 */
1023void
1025{
1027
1028 switch (conn->type) {
1029 case CONN_TYPE_DIR:
1031 break;
1032 case CONN_TYPE_OR:
1033 case CONN_TYPE_EXT_OR:
1035 break;
1036 case CONN_TYPE_AP:
1038 break;
1039 case CONN_TYPE_EXIT:
1041 break;
1042 }
1043}
1044
1045/** Return true iff connection_close_immediate() has been called on this
1046 * connection. */
1047#define CONN_IS_CLOSED(c) \
1048 ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
1049
1050/** Close the underlying socket for <b>conn</b>, so we don't try to
1051 * flush it. Must be used in conjunction with (right before)
1052 * connection_mark_for_close().
1053 */
1054void
1056{
1057 assert_connection_ok(conn,0);
1058 if (CONN_IS_CLOSED(conn)) {
1059 log_err(LD_BUG,"Attempt to close already-closed connection.");
1061 return;
1062 }
1063 /* Socket disposal ends the attempt and clears attribution before later
1064 * EOF/error handling. Callers reporting a failure must do so before closing
1065 * the socket. */
1066 if (conn->type == CONN_TYPE_OR && TO_OR_CONN(conn)->chan)
1068 TLS_CHAN_TO_BASE(TO_OR_CONN(conn)->chan));
1069 if (connection_get_outbuf_len(conn)) {
1070 log_info(LD_NET,"fd %d, type %s, state %s, %"TOR_PRIuSZ" bytes on outbuf.",
1071 (int)conn->s, conn_type_to_string(conn->type),
1072 conn_state_to_string(conn->type, conn->state),
1073 buf_datalen(conn->outbuf));
1074 }
1075
1077
1078 /* Prevent the event from getting unblocked. */
1079 conn->read_blocked_on_bw = 0;
1080 conn->write_blocked_on_bw = 0;
1081
1082 if (SOCKET_OK(conn->s))
1083 tor_close_socket(conn->s);
1084 conn->s = TOR_INVALID_SOCKET;
1085 if (conn->linked)
1086 conn->linked_conn_is_closed = 1;
1087 if (conn->outbuf)
1088 buf_clear(conn->outbuf);
1089}
1090
1091/** Mark <b>conn</b> to be closed next time we loop through
1092 * conn_close_if_marked() in main.c. */
1093void
1094connection_mark_for_close_(connection_t *conn, int line, const char *file)
1095{
1096 assert_connection_ok(conn,0);
1097 tor_assert(line);
1098 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
1099 tor_assert(file);
1100
1101 if (conn->type == CONN_TYPE_OR) {
1102 /*
1103 * An or_connection should have been closed through one of the channel-
1104 * aware functions in connection_or.c. We'll assume this is an error
1105 * close and do that, and log a bug warning.
1106 */
1107 log_warn(LD_CHANNEL | LD_BUG,
1108 "Something tried to close an or_connection_t without going "
1109 "through channels at %s:%d",
1110 file, line);
1112 } else {
1113 /* Pass it down to the real function */
1114 connection_mark_for_close_internal_(conn, line, file);
1115 }
1116}
1117
1118/** Mark <b>conn</b> to be closed next time we loop through
1119 * conn_close_if_marked() in main.c.
1120 *
1121 * This _internal version bypasses the CONN_TYPE_OR checks; this should be
1122 * called when you either are sure that if this is an or_connection_t the
1123 * controlling channel has been notified (e.g. with
1124 * connection_or_notify_error()), or you actually are the
1125 * connection_or_close_for_error() or connection_or_close_normally() function.
1126 * For all other cases, use connection_mark_and_flush() which checks for
1127 * or_connection_t properly, instead. See below.
1128 *
1129 * We want to keep this function simple and quick, since it can be called from
1130 * quite deep in the call chain, and hence it should avoid having side-effects
1131 * that interfere with its callers view of the connection.
1132 */
1133MOCK_IMPL(void,
1135 int line, const char *file))
1136{
1137 assert_connection_ok(conn,0);
1138 tor_assert(line);
1139 tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
1140 tor_assert(file);
1141
1142 if (conn->marked_for_close) {
1143 log_warn(LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
1144 " (first at %s:%d)", file, line, conn->marked_for_close_file,
1145 conn->marked_for_close);
1147 return;
1148 }
1149
1150 /* Both normal and error closes reach this shared marking function. Error
1151 * callers must report eligible establishment failure first, consuming the
1152 * handle. This discards any remaining attribution permission before
1153 * bookkeeping can invoke callbacks; it cannot undo an already-reported
1154 * failure. */
1155 if (conn->type == CONN_TYPE_OR && TO_OR_CONN(conn)->chan)
1157 TLS_CHAN_TO_BASE(TO_OR_CONN(conn)->chan));
1158
1159 if (conn->type == CONN_TYPE_OR) {
1160 /*
1161 * Bad news if this happens without telling the controlling channel; do
1162 * this so we can find things that call this wrongly when the asserts hit.
1163 */
1164 log_debug(LD_CHANNEL,
1165 "Calling connection_mark_for_close_internal_() on an OR conn "
1166 "at %s:%d",
1167 file, line);
1168 }
1169
1170 conn->marked_for_close = line;
1171 conn->marked_for_close_file = file;
1173
1174 /* in case we're going to be held-open-til-flushed, reset
1175 * the number of seconds since last successful write, so
1176 * we get our whole 15 seconds */
1177 conn->timestamp_last_write_allowed = time(NULL);
1178
1179 /* Note the connection close. */
1181 conn->socket_family);
1182}
1183
1184/** Find each connection that has hold_open_until_flushed set to
1185 * 1 but hasn't written in the past 15 seconds, and set
1186 * hold_open_until_flushed to 0. This means it will get cleaned
1187 * up in the next loop through close_if_marked() in main.c.
1188 */
1189void
1191{
1192 time_t now;
1194
1195 now = time(NULL);
1196
1197 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1198 /* If we've been holding the connection open, but we haven't written
1199 * for 15 seconds...
1200 */
1201 if (conn->hold_open_until_flushed) {
1203 if (now - conn->timestamp_last_write_allowed >= 15) {
1204 int severity;
1205 if (conn->type == CONN_TYPE_EXIT ||
1206 (conn->type == CONN_TYPE_DIR &&
1207 conn->purpose == DIR_PURPOSE_SERVER))
1208 severity = LOG_INFO;
1209 else
1210 severity = LOG_NOTICE;
1211 log_fn(severity, LD_NET,
1212 "Giving up on marked_for_close conn that's been flushing "
1213 "for 15s (fd %d, type %s, state %s).",
1214 (int)conn->s, conn_type_to_string(conn->type),
1215 conn_state_to_string(conn->type, conn->state));
1216 conn->hold_open_until_flushed = 0;
1217 }
1218 }
1219 } SMARTLIST_FOREACH_END(conn);
1220}
1221
1222#if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
1223/** Create an AF_UNIX listenaddr struct.
1224 * <b>listenaddress</b> provides the path to the Unix socket.
1225 *
1226 * Eventually <b>listenaddress</b> will also optionally contain user, group,
1227 * and file permissions for the new socket. But not yet. XXX
1228 * Also, since we do not create the socket here the information doesn't help
1229 * here.
1230 *
1231 * If not NULL <b>readable_address</b> will contain a copy of the path part of
1232 * <b>listenaddress</b>.
1233 *
1234 * The listenaddr struct has to be freed by the caller.
1235 */
1236static struct sockaddr_un *
1237create_unix_sockaddr(const char *listenaddress, char **readable_address,
1238 socklen_t *len_out)
1239{
1240 struct sockaddr_un *sockaddr = NULL;
1241
1242 sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
1243 sockaddr->sun_family = AF_UNIX;
1244 if (strlcpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path))
1245 >= sizeof(sockaddr->sun_path)) {
1246 log_warn(LD_CONFIG, "Unix socket path '%s' is too long to fit.",
1247 escaped(listenaddress));
1248 tor_free(sockaddr);
1249 return NULL;
1250 }
1251
1252 if (readable_address)
1253 *readable_address = tor_strdup(listenaddress);
1254
1255 *len_out = sizeof(struct sockaddr_un);
1256 return sockaddr;
1257}
1258#else /* !(defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)) */
1259static struct sockaddr *
1260create_unix_sockaddr(const char *listenaddress, char **readable_address,
1261 socklen_t *len_out)
1262{
1263 (void)listenaddress;
1264 (void)readable_address;
1266 "Unix domain sockets not supported, yet we tried to create one.");
1267 *len_out = 0;
1269 return NULL;
1270}
1271#endif /* defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN) */
1272
1273/* Log a rate-limited warning about resource exhaustion */
1274static void
1275warn_about_resource_exhaution(void)
1276{
1277#define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
1278 static ratelim_t last_warned = RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL);
1279 char *m;
1280 if ((m = rate_limit_log(&last_warned, approx_time()))) {
1281 int n_conns = get_n_open_sockets();
1282 log_warn(LD_NET,"Failing because we have %d connections already. Please "
1283 "read doc/TUNING for guidance.%s", n_conns, m);
1284 tor_free(m);
1285 control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
1286 n_conns);
1287 }
1288}
1289
1290/**
1291 * A socket failed from file descriptor exhaustion.
1292 *
1293 * Note down file descriptor exhaustion and log a warning. */
1294static inline void
1296{
1297 rep_hist_note_overload(OVERLOAD_FD_EXHAUSTED);
1298 warn_about_resource_exhaution();
1299}
1300
1301/**
1302 * A socket failed from TCP port exhaustion.
1303 *
1304 * Note down TCP port exhaustion and log a warning. */
1305static inline void
1307{
1309 warn_about_resource_exhaution();
1310}
1311
1312#ifdef HAVE_SYS_UN_H
1313
1314#define UNIX_SOCKET_PURPOSE_CONTROL_SOCKET 0
1315#define UNIX_SOCKET_PURPOSE_SOCKS_SOCKET 1
1316
1317/** Check if the purpose isn't one of the ones we know what to do with */
1318
1319static int
1320is_valid_unix_socket_purpose(int purpose)
1321{
1322 int valid = 0;
1323
1324 switch (purpose) {
1325 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
1326 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
1327 valid = 1;
1328 break;
1329 }
1330
1331 return valid;
1332}
1333
1334/** Return a string description of a unix socket purpose */
1335static const char *
1336unix_socket_purpose_to_string(int purpose)
1337{
1338 const char *s = "unknown-purpose socket";
1339
1340 switch (purpose) {
1341 case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
1342 s = "control socket";
1343 break;
1344 case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
1345 s = "SOCKS socket";
1346 break;
1347 }
1348
1349 return s;
1350}
1351
1352/** Check whether we should be willing to open an AF_UNIX socket in
1353 * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
1354static int
1355check_location_for_unix_socket(const or_options_t *options, const char *path,
1356 int purpose, const port_cfg_t *port)
1357{
1358 int r = -1;
1359 char *p = NULL;
1360
1361 tor_assert(is_valid_unix_socket_purpose(purpose));
1362
1363 p = tor_strdup(path);
1364 cpd_check_t flags = CPD_CHECK_MODE_ONLY;
1365 if (get_parent_directory(p)<0 || p[0] != '/') {
1366 log_warn(LD_GENERAL, "Bad unix socket address '%s'. Tor does not support "
1367 "relative paths for unix sockets.", path);
1368 goto done;
1369 }
1370
1371 if (port->is_world_writable) {
1372 /* World-writable sockets can go anywhere. */
1373 r = 0;
1374 goto done;
1375 }
1376
1377 if (port->is_group_writable) {
1378 flags |= CPD_GROUP_OK;
1379 }
1380
1381 if (port->relax_dirmode_check) {
1382 flags |= CPD_RELAX_DIRMODE_CHECK;
1383 }
1384
1385 if (check_private_dir(p, flags, options->User) < 0) {
1386 char *escpath, *escdir;
1387 escpath = esc_for_log(path);
1388 escdir = esc_for_log(p);
1389 log_warn(LD_GENERAL, "Before Tor can create a %s in %s, the directory "
1390 "%s needs to exist, and to be accessible only by the user%s "
1391 "account that is running Tor. (On some Unix systems, anybody "
1392 "who can list a socket can connect to it, so Tor is being "
1393 "careful.)",
1394 unix_socket_purpose_to_string(purpose), escpath, escdir,
1395 port->is_group_writable ? " and group" : "");
1396 tor_free(escpath);
1397 tor_free(escdir);
1398 goto done;
1399 }
1400
1401 r = 0;
1402 done:
1403 tor_free(p);
1404 return r;
1405}
1406#endif /* defined(HAVE_SYS_UN_H) */
1407
1408/** Tell the TCP stack that it shouldn't wait for a long time after
1409 * <b>sock</b> has closed before reusing its port. Return 0 on success,
1410 * -1 on failure. */
1411static int
1413{
1414#ifdef _WIN32
1415 (void) sock;
1416 return 0;
1417#else
1418 int one=1;
1419
1420 /* REUSEADDR on normal places means you can rebind to the port
1421 * right after somebody else has let it go. But REUSEADDR on win32
1422 * means you can bind to the port _even when somebody else
1423 * already has it bound_. So, don't do that on Win32. */
1424 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
1425 (socklen_t)sizeof(one)) == -1) {
1426 return -1;
1427 }
1428 return 0;
1429#endif /* defined(_WIN32) */
1430}
1431
1432#ifdef _WIN32
1433/** Tell the Windows TCP stack to prevent other applications from receiving
1434 * traffic from tor's open ports. Return 0 on success, -1 on failure. */
1435static int
1436make_win32_socket_exclusive(tor_socket_t sock)
1437{
1438#ifdef SO_EXCLUSIVEADDRUSE
1439 int one=1;
1440
1441 /* Any socket that sets REUSEADDR on win32 can bind to a port _even when
1442 * somebody else already has it bound_, and _even if the original socket
1443 * didn't set REUSEADDR_. Use EXCLUSIVEADDRUSE to prevent this port-stealing
1444 * on win32. */
1445 if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void*) &one,
1446 (socklen_t)sizeof(one))) {
1447 return -1;
1448 }
1449 return 0;
1450#else /* !defined(SO_EXCLUSIVEADDRUSE) */
1451 (void) sock;
1452 return 0;
1453#endif /* defined(SO_EXCLUSIVEADDRUSE) */
1454}
1455#endif /* defined(_WIN32) */
1456
1457/** Max backlog to pass to listen. We start at */
1458static int listen_limit = INT_MAX;
1459
1460/* Listen on <b>fd</b> with appropriate backlog. Return as for listen. */
1461static int
1462tor_listen(tor_socket_t fd)
1463{
1464 int r;
1465
1466 if ((r = listen(fd, listen_limit)) < 0) {
1467 if (listen_limit == SOMAXCONN)
1468 return r;
1469 if ((r = listen(fd, SOMAXCONN)) == 0) {
1470 listen_limit = SOMAXCONN;
1471 log_warn(LD_NET, "Setting listen backlog to INT_MAX connections "
1472 "didn't work, but SOMAXCONN did. Lowering backlog limit.");
1473 }
1474 }
1475 return r;
1476}
1477
1478/** Bind a new non-blocking socket listening to the socket described
1479 * by <b>listensockaddr</b>.
1480 *
1481 * <b>address</b> is only used for logging purposes and to add the information
1482 * to the conn.
1483 *
1484 * Set <b>addr_in_use</b> to true in case socket binding fails with
1485 * EADDRINUSE.
1486 */
1487static connection_t *
1488connection_listener_new(const struct sockaddr *listensockaddr,
1489 socklen_t socklen,
1490 int type, const char *address,
1491 const port_cfg_t *port_cfg,
1492 int *addr_in_use)
1493{
1494 listener_connection_t *lis_conn;
1495 connection_t *conn = NULL;
1496 tor_socket_t s = TOR_INVALID_SOCKET; /* the socket we're going to make */
1497 or_options_t const *options = get_options();
1498 (void) options; /* Windows doesn't use this. */
1499#if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
1500 const struct passwd *pw = NULL;
1501#endif
1502 uint16_t usePort = 0, gotPort = 0;
1503 int start_reading = 0;
1504 static int global_next_session_group = SESSION_GROUP_FIRST_AUTO;
1505 tor_addr_t addr;
1506 int exhaustion = 0;
1507
1508 if (addr_in_use)
1509 *addr_in_use = 0;
1510
1511 if (listensockaddr->sa_family == AF_INET ||
1512 listensockaddr->sa_family == AF_INET6) {
1513 int is_stream = (type != CONN_TYPE_AP_DNS_LISTENER);
1514 if (is_stream)
1515 start_reading = 1;
1516
1517 tor_addr_from_sockaddr(&addr, listensockaddr, &usePort);
1518 log_notice(LD_NET, "Opening %s on %s",
1519 conn_type_to_string(type), fmt_addrport(&addr, usePort));
1520
1522 is_stream ? SOCK_STREAM : SOCK_DGRAM,
1523 is_stream ? IPPROTO_TCP: IPPROTO_UDP);
1524 if (!SOCKET_OK(s)) {
1525 int e = tor_socket_errno(s);
1526 if (ERRNO_IS_RESOURCE_LIMIT(e)) {
1528 /*
1529 * We'll call the OOS handler at the error exit, so set the
1530 * exhaustion flag for it.
1531 */
1532 exhaustion = 1;
1533 } else {
1534 log_warn(LD_NET, "Socket creation failed: %s",
1535 tor_socket_strerror(e));
1536 }
1537 goto err;
1538 }
1539
1540 if (make_socket_reuseable(s) < 0) {
1541 log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
1542 conn_type_to_string(type),
1543 tor_socket_strerror(errno));
1544 }
1545
1546#ifdef _WIN32
1547 if (make_win32_socket_exclusive(s) < 0) {
1548 log_warn(LD_NET, "Error setting SO_EXCLUSIVEADDRUSE flag on %s: %s",
1549 conn_type_to_string(type),
1550 tor_socket_strerror(errno));
1551 }
1552#endif /* defined(_WIN32) */
1553
1554#if defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT)
1555 if (options->TransProxyType_parsed == TPT_TPROXY &&
1557 int one = 1;
1558 if (setsockopt(s, SOL_IP, IP_TRANSPARENT, (void*)&one,
1559 (socklen_t)sizeof(one)) < 0) {
1560 const char *extra = "";
1561 int e = tor_socket_errno(s);
1562 if (e == EPERM)
1563 extra = "TransTPROXY requires root privileges or similar"
1564 " capabilities.";
1565 log_warn(LD_NET, "Error setting IP_TRANSPARENT flag: %s.%s",
1566 tor_socket_strerror(e), extra);
1567 }
1568 }
1569#endif /* defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT) */
1570
1571#ifdef IPV6_V6ONLY
1572 if (listensockaddr->sa_family == AF_INET6) {
1573 int one = 1;
1574 /* We need to set IPV6_V6ONLY so that this socket can't get used for
1575 * IPv4 connections. */
1576 if (setsockopt(s,IPPROTO_IPV6, IPV6_V6ONLY,
1577 (void*)&one, (socklen_t)sizeof(one)) < 0) {
1578 int e = tor_socket_errno(s);
1579 log_warn(LD_NET, "Error setting IPV6_V6ONLY flag: %s",
1580 tor_socket_strerror(e));
1581 /* Keep going; probably not harmful. */
1582 }
1583 }
1584#endif /* defined(IPV6_V6ONLY) */
1585
1586 if (bind(s,listensockaddr,socklen) < 0) {
1587 const char *helpfulhint = "";
1588 int e = tor_socket_errno(s);
1589 if (ERRNO_IS_EADDRINUSE(e)) {
1590 helpfulhint = ". Is Tor already running?";
1591 if (addr_in_use)
1592 *addr_in_use = 1;
1593 }
1594 log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
1595 tor_socket_strerror(e), helpfulhint);
1596 goto err;
1597 }
1598
1599 if (is_stream) {
1600 if (tor_listen(s) < 0) {
1601 log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
1602 tor_socket_strerror(tor_socket_errno(s)));
1603 goto err;
1604 }
1605 }
1606
1607 if (usePort != 0) {
1608 gotPort = usePort;
1609 } else {
1610 tor_addr_t addr2;
1611 struct sockaddr_storage ss;
1612 socklen_t ss_len=sizeof(ss);
1613 if (getsockname(s, (struct sockaddr*)&ss, &ss_len)<0) {
1614 log_warn(LD_NET, "getsockname() couldn't learn address for %s: %s",
1615 conn_type_to_string(type),
1616 tor_socket_strerror(tor_socket_errno(s)));
1617 gotPort = 0;
1618 }
1619 tor_addr_from_sockaddr(&addr2, (struct sockaddr*)&ss, &gotPort);
1620 }
1621#ifdef HAVE_SYS_UN_H
1622 /*
1623 * AF_UNIX generic setup stuff
1624 */
1625 } else if (listensockaddr->sa_family == AF_UNIX) {
1626 /* We want to start reading for both AF_UNIX cases */
1627 start_reading = 1;
1628
1630
1631 if (check_location_for_unix_socket(options, address,
1632 (type == CONN_TYPE_CONTROL_LISTENER) ?
1633 UNIX_SOCKET_PURPOSE_CONTROL_SOCKET :
1634 UNIX_SOCKET_PURPOSE_SOCKS_SOCKET, port_cfg) < 0) {
1635 goto err;
1636 }
1637
1638 log_notice(LD_NET, "Opening %s on %s",
1639 conn_type_to_string(type), address);
1640
1641 tor_addr_make_unspec(&addr);
1642
1643 if (unlink(address) < 0 && errno != ENOENT) {
1644 log_warn(LD_NET, "Could not unlink %s: %s", address,
1645 strerror(errno));
1646 goto err;
1647 }
1648
1649 s = tor_open_socket_nonblocking(AF_UNIX, SOCK_STREAM, 0);
1650 if (! SOCKET_OK(s)) {
1651 int e = tor_socket_errno(s);
1652 if (ERRNO_IS_RESOURCE_LIMIT(e)) {
1654 /*
1655 * We'll call the OOS handler at the error exit, so set the
1656 * exhaustion flag for it.
1657 */
1658 exhaustion = 1;
1659 } else {
1660 log_warn(LD_NET,"Socket creation failed: %s.", strerror(e));
1661 }
1662 goto err;
1663 }
1664
1665 if (bind(s, listensockaddr,
1666 (socklen_t)sizeof(struct sockaddr_un)) == -1) {
1667 log_warn(LD_NET,"Bind to %s failed: %s.", address,
1668 tor_socket_strerror(tor_socket_errno(s)));
1669 goto err;
1670 }
1671
1672#ifdef HAVE_PWD_H
1673 if (options->User) {
1674 pw = tor_getpwnam(options->User);
1675 struct stat st;
1676 if (pw == NULL) {
1677 log_warn(LD_NET,"Unable to chown() %s socket: user %s not found.",
1678 address, options->User);
1679 goto err;
1680 } else if (fstat(s, &st) == 0 &&
1681 st.st_uid == pw->pw_uid && st.st_gid == pw->pw_gid) {
1682 /* No change needed */
1683 } else if (chown(sandbox_intern_string(address),
1684 pw->pw_uid, pw->pw_gid) < 0) {
1685 log_warn(LD_NET,"Unable to chown() %s socket: %s.",
1686 address, strerror(errno));
1687 goto err;
1688 }
1689 }
1690#endif /* defined(HAVE_PWD_H) */
1691
1692 {
1693 unsigned mode;
1694 const char *status;
1695 struct stat st;
1696 if (port_cfg->is_world_writable) {
1697 mode = 0666;
1698 status = "world-writable";
1699 } else if (port_cfg->is_group_writable) {
1700 mode = 0660;
1701 status = "group-writable";
1702 } else {
1703 mode = 0600;
1704 status = "private";
1705 }
1706 /* We need to use chmod; fchmod doesn't work on sockets on all
1707 * platforms. */
1708 if (fstat(s, &st) == 0 && (st.st_mode & 0777) == mode) {
1709 /* no change needed */
1710 } else if (chmod(sandbox_intern_string(address), mode) < 0) {
1711 log_warn(LD_FS,"Unable to make %s %s.", address, status);
1712 goto err;
1713 }
1714 }
1715
1716 if (listen(s, SOMAXCONN) < 0) {
1717 log_warn(LD_NET, "Could not listen on %s: %s", address,
1718 tor_socket_strerror(tor_socket_errno(s)));
1719 goto err;
1720 }
1721
1722#ifndef __APPLE__
1723 /* This code was introduced to help debug #28229. */
1724 int value;
1725 socklen_t len = sizeof(value);
1726
1727 if (!getsockopt(s, SOL_SOCKET, SO_ACCEPTCONN, &value, &len)) {
1728 if (value == 0) {
1729 log_err(LD_NET, "Could not listen on %s - "
1730 "getsockopt(.,SO_ACCEPTCONN,.) yields 0.", address);
1731 goto err;
1732 }
1733 }
1734#endif /* !defined(__APPLE__) */
1735#endif /* defined(HAVE_SYS_UN_H) */
1736 } else {
1737 log_err(LD_BUG, "Got unexpected address family %d.",
1738 listensockaddr->sa_family);
1739 tor_assert(0);
1740 }
1741
1742 lis_conn = listener_connection_new(type, listensockaddr->sa_family);
1743 conn = TO_CONN(lis_conn);
1744 conn->socket_family = listensockaddr->sa_family;
1745 conn->s = s;
1746 s = TOR_INVALID_SOCKET; /* Prevent double-close */
1747 conn->address = tor_strdup(address);
1748 conn->port = gotPort;
1749 tor_addr_copy(&conn->addr, &addr);
1750
1751 memcpy(&lis_conn->entry_cfg, &port_cfg->entry_cfg, sizeof(entry_port_cfg_t));
1752
1753 if (port_cfg->entry_cfg.isolation_flags) {
1754 lis_conn->entry_cfg.isolation_flags = port_cfg->entry_cfg.isolation_flags;
1755 if (port_cfg->entry_cfg.session_group >= 0) {
1756 lis_conn->entry_cfg.session_group = port_cfg->entry_cfg.session_group;
1757 } else {
1758 /* This can wrap after around INT_MAX listeners are opened. But I don't
1759 * believe that matters, since you would need to open a ridiculous
1760 * number of listeners while keeping the early ones open before you ever
1761 * hit this. An OR with a dozen ports open, for example, would have to
1762 * close and re-open its listeners every second for 4 years nonstop.
1763 */
1764 lis_conn->entry_cfg.session_group = global_next_session_group--;
1765 }
1766 }
1767
1768 if (connection_add(conn) < 0) { /* no space, forget it */
1769 log_warn(LD_NET,"connection_add for listener failed. Giving up.");
1770 goto err;
1771 }
1772
1773 log_fn(usePort==gotPort ? LOG_DEBUG : LOG_NOTICE, LD_NET,
1774 "%s listening on port %u.",
1775 conn_type_to_string(type), gotPort);
1776
1778 if (start_reading) {
1780 } else {
1783 }
1784
1785 /*
1786 * Normal exit; call the OOS handler since connection count just changed;
1787 * the exhaustion flag will always be zero here though.
1788 */
1790
1791 log_notice(LD_NET, "Opened %s", connection_describe(conn));
1792
1793 return conn;
1794
1795 err:
1796 if (SOCKET_OK(s))
1798 if (conn)
1799 connection_free(conn);
1800
1801 /* Call the OOS handler, indicate if we saw an exhaustion-related error */
1803
1804 return NULL;
1805}
1806
1807/**
1808 * Create a new listener connection for a given <b>port</b>. In case we
1809 * for a reason that is not an error condition, set <b>defer</b>
1810 * to true. If we cannot bind listening socket because address is already
1811 * in use, set <b>addr_in_use</b> to true.
1812 */
1813static connection_t *
1815 int *defer, int *addr_in_use)
1816{
1817 connection_t *conn;
1818 struct sockaddr *listensockaddr;
1819 socklen_t listensocklen = 0;
1820 char *address=NULL;
1821 int real_port = port->port == CFG_AUTO_PORT ? 0 : port->port;
1822 tor_assert(real_port <= UINT16_MAX);
1823
1824 if (defer)
1825 *defer = 0;
1826
1827 if (port->server_cfg.no_listen) {
1828 if (defer)
1829 *defer = 1;
1830 return NULL;
1831 }
1832
1833#ifndef _WIN32
1834 /* We don't need to be root to create a UNIX socket, so defer until after
1835 * setuid. */
1836 const or_options_t *options = get_options();
1837 if (port->is_unix_addr && !geteuid() && (options->User) &&
1838 strcmp(options->User, "root")) {
1839 if (defer)
1840 *defer = 1;
1841 return NULL;
1842 }
1843#endif /* !defined(_WIN32) */
1844
1845 if (port->is_unix_addr) {
1846 listensockaddr = (struct sockaddr *)
1847 create_unix_sockaddr(port->unix_addr,
1848 &address, &listensocklen);
1849 } else {
1850 listensockaddr = tor_malloc(sizeof(struct sockaddr_storage));
1851 listensocklen = tor_addr_to_sockaddr(&port->addr,
1852 real_port,
1853 listensockaddr,
1854 sizeof(struct sockaddr_storage));
1855 address = tor_addr_to_str_dup(&port->addr);
1856 }
1857
1858 if (listensockaddr) {
1859 conn = connection_listener_new(listensockaddr, listensocklen,
1860 port->type, address, port,
1861 addr_in_use);
1862 tor_free(listensockaddr);
1863 tor_free(address);
1864 } else {
1865 conn = NULL;
1866 }
1867
1868 return conn;
1869}
1870
1871/** Do basic sanity checking on a newly received socket. Return 0
1872 * if it looks ok, else return -1.
1873 *
1874 * Notably, some TCP stacks can erroneously have accept() return successfully
1875 * with socklen 0, when the client sends an RST before the accept call (as
1876 * nmap does). We want to detect that, and not go on with the connection.
1877 */
1878static int
1879check_sockaddr(const struct sockaddr *sa, int len, int level)
1880{
1881 int ok = 1;
1882
1883 if (sa->sa_family == AF_INET) {
1884 struct sockaddr_in *sin=(struct sockaddr_in*)sa;
1885 if (len != sizeof(struct sockaddr_in)) {
1886 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
1887 len,(int)sizeof(struct sockaddr_in));
1888 ok = 0;
1889 }
1890 if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
1891 log_fn(level, LD_NET,
1892 "Address for new connection has address/port equal to zero.");
1893 ok = 0;
1894 }
1895 } else if (sa->sa_family == AF_INET6) {
1896 struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
1897 if (len != sizeof(struct sockaddr_in6)) {
1898 log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
1899 len,(int)sizeof(struct sockaddr_in6));
1900 ok = 0;
1901 }
1902 if (fast_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
1903 sin6->sin6_port == 0) {
1904 log_fn(level, LD_NET,
1905 "Address for new connection has address/port equal to zero.");
1906 ok = 0;
1907 }
1908 } else if (sa->sa_family == AF_UNIX) {
1909 ok = 1;
1910 } else {
1911 ok = 0;
1912 }
1913 return ok ? 0 : -1;
1914}
1915
1916/** Check whether the socket family from an accepted socket <b>got</b> is the
1917 * same as the one that <b>listener</b> is waiting for. If it isn't, log
1918 * a useful message and return -1. Else return 0.
1919 *
1920 * This is annoying, but can apparently happen on some Darwins. */
1921static int
1923{
1924 if (got != listener->socket_family) {
1925 log_info(LD_BUG, "A listener connection returned a socket with a "
1926 "mismatched family. %s for addr_family %d gave us a socket "
1927 "with address family %d. Dropping.",
1928 conn_type_to_string(listener->type),
1929 (int)listener->socket_family,
1930 (int)got);
1931 return -1;
1932 }
1933 return 0;
1934}
1935
1936/** The listener connection <b>conn</b> told poll() it wanted to read.
1937 * Call accept() on conn->s, and add the new connection if necessary.
1938 */
1939static int
1941{
1942 tor_socket_t news; /* the new socket */
1943 connection_t *newconn = 0;
1944 /* information about the remote peer when connecting to other routers */
1945 struct sockaddr_storage addrbuf;
1946 struct sockaddr *remote = (struct sockaddr*)&addrbuf;
1947 /* length of the remote address. Must be whatever accept() needs. */
1948 socklen_t remotelen = (socklen_t)sizeof(addrbuf);
1949 const or_options_t *options = get_options();
1950
1951 tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
1952 memset(&addrbuf, 0, sizeof(addrbuf));
1953
1954 news = tor_accept_socket_nonblocking(conn->s,remote,&remotelen);
1955 if (!SOCKET_OK(news)) { /* accept() error */
1956 int e = tor_socket_errno(conn->s);
1957 if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
1958 /*
1959 * they hung up before we could accept(). that's fine.
1960 *
1961 * give the OOS handler a chance to run though
1962 */
1964 return 0;
1965 } else if (ERRNO_IS_RESOURCE_LIMIT(e)) {
1967 /* Exhaustion; tell the OOS handler */
1969 return 0;
1970 }
1971 /* else there was a real error. */
1972 log_warn(LD_NET,"accept() failed: %s. Closing listener.",
1973 tor_socket_strerror(e));
1974 connection_mark_for_close(conn);
1975 /* Tell the OOS handler about this too */
1977 return -1;
1978 }
1979 log_debug(LD_NET,
1980 "Connection accepted on socket %d (child of fd %d).",
1981 (int)news,(int)conn->s);
1982
1983 /* We accepted a new conn; run OOS handler */
1985
1986 if (make_socket_reuseable(news) < 0) {
1987 if (tor_socket_errno(news) == EINVAL) {
1988 /* This can happen on OSX if we get a badly timed shutdown. */
1989 log_debug(LD_NET, "make_socket_reuseable returned EINVAL");
1990 } else {
1991 log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
1992 conn_type_to_string(new_type),
1993 tor_socket_strerror(errno));
1994 }
1995 tor_close_socket(news);
1996 return 0;
1997 }
1998
1999 if (options->ConstrainedSockets)
2001
2002 if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
2003 tor_close_socket(news);
2004 return 0;
2005 }
2006
2007 if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6 ||
2008 (conn->socket_family == AF_UNIX && new_type == CONN_TYPE_AP)) {
2009 tor_addr_t addr;
2010 uint16_t port;
2011 if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
2012 log_info(LD_NET,
2013 "accept() returned a strange address; closing connection.");
2014 tor_close_socket(news);
2015 return 0;
2016 }
2017
2018 tor_addr_from_sockaddr(&addr, remote, &port);
2019
2020 /* process entrance policies here, before we even create the connection */
2021 if (new_type == CONN_TYPE_AP) {
2022 /* check sockspolicy to see if we should accept it */
2023 if (socks_policy_permits_address(&addr) == 0) {
2024 log_notice(LD_APP,
2025 "Denying socks connection from untrusted address %s.",
2026 fmt_and_decorate_addr(&addr));
2028 tor_close_socket(news);
2029 return 0;
2030 }
2031 }
2032 if (new_type == CONN_TYPE_DIR) {
2033 /* check dirpolicy to see if we should accept it */
2034 if (dir_policy_permits_address(&addr) == 0) {
2035 log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
2036 fmt_and_decorate_addr(&addr));
2038 tor_close_socket(news);
2039 return 0;
2040 }
2041 }
2042 if (new_type == CONN_TYPE_OR) {
2043 /* Assess with the connection DoS mitigation subsystem if this address
2044 * can open a new connection. */
2045 if (dos_conn_addr_get_defense_type(&addr) == DOS_CONN_DEFENSE_CLOSE) {
2047 tor_close_socket(news);
2048 return 0;
2049 }
2050 }
2051
2052 newconn = connection_new(new_type, conn->socket_family);
2053 newconn->s = news;
2054
2055 /* remember the remote address */
2056 tor_addr_copy(&newconn->addr, &addr);
2057 if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
2058 newconn->port = 0;
2059 newconn->address = tor_strdup(conn->address);
2060 } else {
2061 newconn->port = port;
2062 newconn->address = tor_addr_to_str_dup(&addr);
2063 }
2064
2065 if (new_type == CONN_TYPE_AP && conn->socket_family != AF_UNIX) {
2066 log_info(LD_NET, "New SOCKS connection opened from %s.",
2067 fmt_and_decorate_addr(&addr));
2068 }
2069 if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
2070 log_info(LD_NET, "New SOCKS AF_UNIX connection opened");
2071 }
2072 if (new_type == CONN_TYPE_CONTROL) {
2073 log_notice(LD_CONTROL, "New control connection opened from %s.",
2074 fmt_and_decorate_addr(&addr));
2075 }
2076 if (new_type == CONN_TYPE_METRICS) {
2077 log_info(LD_CONTROL, "New metrics connection opened from %s.",
2078 fmt_and_decorate_addr(&addr));
2079 }
2080
2081 } else if (conn->socket_family == AF_UNIX && conn->type != CONN_TYPE_AP) {
2083 tor_assert(new_type == CONN_TYPE_CONTROL);
2084 log_notice(LD_CONTROL, "New control connection opened.");
2085
2086 newconn = connection_new(new_type, conn->socket_family);
2087 newconn->s = news;
2088
2089 /* remember the remote address -- do we have anything sane to put here? */
2090 tor_addr_make_unspec(&newconn->addr);
2091 newconn->port = 1;
2092 newconn->address = tor_strdup(conn->address);
2093 } else {
2094 tor_assert(0);
2095 };
2096
2097 /* We are receiving this connection. */
2098 newconn->from_listener = 1;
2099
2100 if (connection_add(newconn) < 0) { /* no space, forget it */
2101 connection_free(newconn);
2102 return 0; /* no need to tear down the parent */
2103 }
2104
2105 if (connection_init_accepted_conn(newconn, TO_LISTENER_CONN(conn)) < 0) {
2106 if (! newconn->marked_for_close)
2107 connection_mark_for_close(newconn);
2108 return 0;
2109 }
2110
2111 note_connection(true /* inbound */, newconn);
2112
2113 return 0;
2114}
2115
2116/** Initialize states for newly accepted connection <b>conn</b>.
2117 *
2118 * If conn is an OR, start the TLS handshake.
2119 *
2120 * If conn is a transparent AP, get its original destination
2121 * and place it in circuit_wait.
2122 *
2123 * The <b>listener</b> parameter is only used for AP connections.
2124 */
2125int
2127 const listener_connection_t *listener)
2128{
2129 int rv;
2130
2132
2133 switch (conn->type) {
2134 case CONN_TYPE_EXT_OR:
2135 /* Initiate Extended ORPort authentication. */
2137 case CONN_TYPE_OR:
2138 connection_or_event_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
2140 if (rv < 0) {
2142 }
2143 return rv;
2144 break;
2145 case CONN_TYPE_AP:
2146 memcpy(&TO_ENTRY_CONN(conn)->entry_cfg, &listener->entry_cfg,
2147 sizeof(entry_port_cfg_t));
2149 TO_ENTRY_CONN(conn)->socks_request->listener_type = listener->base_.type;
2150
2151 /* Any incoming connection on an entry port counts as user activity. */
2153
2154 switch (TO_CONN(listener)->type) {
2158 listener->entry_cfg.socks_prefer_no_auth;
2160 listener->entry_cfg.extended_socks5_codes;
2161 break;
2164 /* XXXX028 -- is this correct still, with the addition of
2165 * pending_entry_connections ? */
2171 break;
2174 }
2175 break;
2176 case CONN_TYPE_DIR:
2179 break;
2180 case CONN_TYPE_CONTROL:
2182 break;
2183 }
2184 return 0;
2185}
2186
2187/** Take conn, make a nonblocking socket; try to connect to
2188 * sa, binding to bindaddr if sa is not localhost. If fail, return -1 and if
2189 * applicable put your best guess about errno into *<b>socket_error</b>.
2190 * If connected return 1, if EAGAIN return 0.
2191 */
2192MOCK_IMPL(STATIC int,
2194 const struct sockaddr *sa,
2195 socklen_t sa_len,
2196 const struct sockaddr *bindaddr,
2197 socklen_t bindaddr_len,
2198 int *socket_error))
2199{
2200 tor_socket_t s;
2201 int inprogress = 0;
2202 const or_options_t *options = get_options();
2203
2204 tor_assert(conn);
2205 tor_assert(sa);
2206 tor_assert(socket_error);
2207
2209 /* We should never even try to connect anyplace if the network is
2210 * completely shut off.
2211 *
2212 * (We don't check net_is_disabled() here, since we still sometimes
2213 * want to open connections when we're in soft hibernation.)
2214 */
2215 static ratelim_t disablenet_violated = RATELIM_INIT(30*60);
2216 *socket_error = SOCK_ERRNO(ENETUNREACH);
2217 log_fn_ratelim(&disablenet_violated, LOG_WARN, LD_BUG,
2218 "Tried to open a socket with DisableNetwork set.");
2220 return -1;
2221 }
2222
2223 const int protocol_family = sa->sa_family;
2224 const int proto = (sa->sa_family == AF_INET6 ||
2225 sa->sa_family == AF_INET) ? IPPROTO_TCP : 0;
2226
2227 s = tor_open_socket_nonblocking(protocol_family, SOCK_STREAM, proto);
2228 if (! SOCKET_OK(s)) {
2229 /*
2230 * Early OOS handler calls; it matters if it's an exhaustion-related
2231 * error or not.
2232 */
2233 *socket_error = tor_socket_errno(s);
2234 if (ERRNO_IS_RESOURCE_LIMIT(*socket_error)) {
2237 } else {
2238 log_warn(LD_NET,"Error creating network socket: %s",
2239 tor_socket_strerror(*socket_error));
2241 }
2242 return -1;
2243 }
2244
2245 if (make_socket_reuseable(s) < 0) {
2246 log_warn(LD_NET, "Error setting SO_REUSEADDR flag on new connection: %s",
2247 tor_socket_strerror(errno));
2248 }
2249
2250 /* From ip(7): Inform the kernel to not reserve an ephemeral port when using
2251 * bind(2) with a port number of 0. The port will later be automatically
2252 * chosen at connect(2) time, in a way that allows sharing a source port as
2253 * long as the 4-tuple is unique.
2254 *
2255 * This is needed for relays using OutboundBindAddresses because the port
2256 * value in the bind address is set to 0. */
2257#ifdef IP_BIND_ADDRESS_NO_PORT
2258 static int try_ip_bind_address_no_port = 1;
2259 if (bindaddr && try_ip_bind_address_no_port &&
2260 setsockopt(s, SOL_IP, IP_BIND_ADDRESS_NO_PORT, &(int){1}, sizeof(int))) {
2261 if (errno == EINVAL) {
2262 log_notice(LD_NET, "Tor was built with support for "
2263 "IP_BIND_ADDRESS_NO_PORT, but the current kernel "
2264 "doesn't support it. This might cause Tor to run out "
2265 "of ephemeral ports more quickly.");
2266 try_ip_bind_address_no_port = 0;
2267 } else {
2268 log_warn(LD_NET, "Error setting IP_BIND_ADDRESS_NO_PORT on new "
2269 "connection: %s", tor_socket_strerror(errno));
2270 }
2271 }
2272#endif
2273
2274 if (bindaddr && bind(s, bindaddr, bindaddr_len) < 0) {
2275 *socket_error = tor_socket_errno(s);
2276 if (ERRNO_IS_EADDRINUSE(*socket_error)) {
2279 } else {
2280 log_warn(LD_NET,"Error binding network socket: %s",
2281 tor_socket_strerror(*socket_error));
2283 }
2285 return -1;
2286 }
2287
2288 /*
2289 * We've got the socket open and bound; give the OOS handler a chance to
2290 * check against configured maximum socket number, but tell it no exhaustion
2291 * failure.
2292 */
2294
2295 tor_assert(options);
2296 if (options->ConstrainedSockets)
2298
2299 if (tor_connect_socket(s, sa, sa_len) == TOR_INVALID_SOCKET) {
2300 int e = tor_socket_errno(s);
2301 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
2302 /* yuck. kill it. */
2303 *socket_error = e;
2304 if (conn->type == CONN_TYPE_OR)
2306 log_info(LD_NET,
2307 "connect() to socket failed: %s",
2308 tor_socket_strerror(e));
2310 return -1;
2311 } else {
2312 inprogress = 1;
2313 }
2314 }
2315
2316 note_connection(false /* outbound */, conn);
2317
2318 /* it succeeded. we're connected. */
2319 log_fn(inprogress ? LOG_DEBUG : LOG_INFO, LD_NET,
2320 "Connection to socket %s (sock "TOR_SOCKET_T_FORMAT").",
2321 inprogress ? "in progress" : "established", s);
2322 conn->s = s;
2323 if (connection_add_connecting(conn) < 0) {
2324 /* no space, forget it */
2325 *socket_error = SOCK_ERRNO(ENOBUFS);
2326 return -1;
2327 }
2328
2329 return inprogress ? 0 : 1;
2330}
2331
2332/* Log a message if connection attempt is made when IPv4 or IPv6 is disabled.
2333 * Log a less severe message if we couldn't conform to ClientPreferIPv6ORPort
2334 * or ClientPreferIPv6ORPort. */
2335static void
2336connection_connect_log_client_use_ip_version(const connection_t *conn)
2337{
2338 const or_options_t *options = get_options();
2339
2340 /* Only clients care about ClientUseIPv4/6, bail out early on servers, and
2341 * on connections we don't care about */
2342 if (server_mode(options) || !conn || conn->type == CONN_TYPE_EXIT) {
2343 return;
2344 }
2345
2346 /* We're only prepared to log OR and DIR connections here */
2347 if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR) {
2348 return;
2349 }
2350
2351 const int must_ipv4 = !reachable_addr_use_ipv6(options);
2352 const int must_ipv6 = (options->ClientUseIPv4 == 0);
2353 const int pref_ipv6 = (conn->type == CONN_TYPE_OR
2356 tor_addr_t real_addr;
2357 tor_addr_copy(&real_addr, &conn->addr);
2358
2359 /* Check if we broke a mandatory address family restriction */
2360 if ((must_ipv4 && tor_addr_family(&real_addr) == AF_INET6)
2361 || (must_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
2362 log_info(LD_BUG, "Outgoing %s connection to %s violated ClientUseIPv%s 0.",
2363 conn->type == CONN_TYPE_OR ? "OR" : "Dir",
2364 fmt_addr(&real_addr),
2365 options->ClientUseIPv4 == 0 ? "4" : "6");
2366 log_backtrace_once(LOG_INFO, LD_BUG, "Address came from");
2367 }
2368
2369 /* Bridges are allowed to break IPv4/IPv6 ORPort preferences to connect to
2370 * the node's configured address when ClientPreferIPv6ORPort is auto */
2371 if (options->UseBridges && conn->type == CONN_TYPE_OR
2372 && options->ClientPreferIPv6ORPort == -1) {
2373 return;
2374 }
2375
2376 if (reachable_addr_use_ipv6(options)) {
2377 log_info(LD_NET, "Our outgoing connection is using IPv%d.",
2378 tor_addr_family(&real_addr) == AF_INET6 ? 6 : 4);
2379 }
2380
2381 /* Check if we couldn't satisfy an address family preference */
2382 if ((!pref_ipv6 && tor_addr_family(&real_addr) == AF_INET6)
2383 || (pref_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
2384 log_info(LD_NET, "Outgoing connection to %s doesn't satisfy "
2385 "ClientPreferIPv6%sPort %d, with ClientUseIPv4 %d, and "
2386 "reachable_addr_use_ipv6 %d (ClientUseIPv6 %d and UseBridges "
2387 "%d).",
2388 fmt_addr(&real_addr),
2389 conn->type == CONN_TYPE_OR ? "OR" : "Dir",
2390 conn->type == CONN_TYPE_OR ? options->ClientPreferIPv6ORPort
2391 : options->ClientPreferIPv6DirPort,
2392 options->ClientUseIPv4, reachable_addr_use_ipv6(options),
2393 options->ClientUseIPv6, options->UseBridges);
2394 }
2395}
2396
2397/** Retrieve the outbound address depending on the protocol (IPv4 or IPv6)
2398 * and the connection type (relay, exit, ...)
2399 * Return a socket address or NULL in case nothing is configured.
2400 **/
2401const tor_addr_t *
2403 const or_options_t *options, unsigned int conn_type)
2404{
2405 const tor_addr_t *ext_addr = NULL;
2406
2407 int fam_index;
2408 switch (family) {
2409 case AF_INET:
2410 fam_index = 0;
2411 break;
2412 case AF_INET6:
2413 fam_index = 1;
2414 break;
2415 default:
2416 return NULL;
2417 }
2418
2419 // If an exit connection, use the exit address (if present)
2420 if (conn_type == CONN_TYPE_EXIT) {
2421 if (!tor_addr_is_null(
2422 &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT][fam_index])) {
2423 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_EXIT]
2424 [fam_index];
2425 } else if (!tor_addr_is_null(
2427 [fam_index])) {
2428 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_ANY]
2429 [fam_index];
2430 }
2431 } else { // All non-exit connections
2432 if (!tor_addr_is_null(
2433 &options->OutboundBindAddresses[OUTBOUND_ADDR_OR][fam_index])) {
2434 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_OR]
2435 [fam_index];
2436 } else if (!tor_addr_is_null(
2438 [fam_index])) {
2439 ext_addr = &options->OutboundBindAddresses[OUTBOUND_ADDR_ANY]
2440 [fam_index];
2441 }
2442 }
2443 return ext_addr;
2444}
2445
2446/** Take conn, make a nonblocking socket; try to connect to
2447 * addr:port (port arrives in *host order*). If fail, return -1 and if
2448 * applicable put your best guess about errno into *<b>socket_error</b>.
2449 * Else assign s to conn->s: if connected return 1, if EAGAIN return 0.
2450 *
2451 * addr:port can be different to conn->addr:conn->port if connecting through
2452 * a proxy.
2453 *
2454 * address is used to make the logs useful.
2455 *
2456 * On success, add conn to the list of polled connections.
2457 */
2458int
2459connection_connect(connection_t *conn, const char *address,
2460 const tor_addr_t *addr, uint16_t port, int *socket_error)
2461{
2462 struct sockaddr_storage addrbuf;
2463 struct sockaddr_storage bind_addr_ss;
2464 struct sockaddr *bind_addr = NULL;
2465 struct sockaddr *dest_addr;
2466 int dest_addr_len, bind_addr_len = 0;
2467
2468 /* Log if we didn't stick to ClientUseIPv4/6 or ClientPreferIPv6OR/DirPort
2469 */
2470 connection_connect_log_client_use_ip_version(conn);
2471
2472 if (!tor_addr_is_loopback(addr)) {
2473 const tor_addr_t *ext_addr = NULL;
2475 conn->type);
2476 if (ext_addr) {
2477 memset(&bind_addr_ss, 0, sizeof(bind_addr_ss));
2478 bind_addr_len = tor_addr_to_sockaddr(ext_addr, 0,
2479 (struct sockaddr *) &bind_addr_ss,
2480 sizeof(bind_addr_ss));
2481 if (bind_addr_len == 0) {
2482 log_warn(LD_NET,
2483 "Error converting OutboundBindAddress %s into sockaddr. "
2484 "Ignoring.", fmt_and_decorate_addr(ext_addr));
2485 } else {
2486 bind_addr = (struct sockaddr *)&bind_addr_ss;
2487 }
2488 }
2489 }
2490
2491 memset(&addrbuf,0,sizeof(addrbuf));
2492 dest_addr = (struct sockaddr*) &addrbuf;
2493 dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
2494 tor_assert(dest_addr_len > 0);
2495
2496 log_debug(LD_NET, "Connecting to %s:%u.",
2497 escaped_safe_str_client(address), port);
2498
2499 return connection_connect_sockaddr(conn, dest_addr, dest_addr_len,
2500 bind_addr, bind_addr_len, socket_error);
2501}
2502
2503#ifdef HAVE_SYS_UN_H
2504
2505/** Take conn, make a nonblocking socket; try to connect to
2506 * an AF_UNIX socket at socket_path. If fail, return -1 and if applicable
2507 * put your best guess about errno into *<b>socket_error</b>. Else assign s
2508 * to conn->s: if connected return 1, if EAGAIN return 0.
2509 *
2510 * On success, add conn to the list of polled connections.
2511 */
2512int
2513connection_connect_unix(connection_t *conn, const char *socket_path,
2514 int *socket_error)
2515{
2516 struct sockaddr_un dest_addr;
2517
2518 tor_assert(socket_path);
2519
2520 /* Check that we'll be able to fit it into dest_addr later */
2521 if (strlen(socket_path) + 1 > sizeof(dest_addr.sun_path)) {
2522 log_warn(LD_NET,
2523 "Path %s is too long for an AF_UNIX socket\n",
2524 escaped_safe_str_client(socket_path));
2525 *socket_error = SOCK_ERRNO(ENAMETOOLONG);
2526 return -1;
2527 }
2528
2529 memset(&dest_addr, 0, sizeof(dest_addr));
2530 dest_addr.sun_family = AF_UNIX;
2531 strlcpy(dest_addr.sun_path, socket_path, sizeof(dest_addr.sun_path));
2532
2533 log_debug(LD_NET,
2534 "Connecting to AF_UNIX socket at %s.",
2535 escaped_safe_str_client(socket_path));
2536
2537 return connection_connect_sockaddr(conn,
2538 (struct sockaddr *)&dest_addr, sizeof(dest_addr),
2539 NULL, 0, socket_error);
2540}
2541
2542#endif /* defined(HAVE_SYS_UN_H) */
2543
2544/** Convert state number to string representation for logging purposes.
2545 */
2546static const char *
2548{
2549 static const char *unknown = "???";
2550 static const char *states[] = {
2551 "PROXY_NONE",
2552 "PROXY_INFANT",
2553 "PROXY_HTTPS_WANT_CONNECT_OK",
2554 "PROXY_SOCKS4_WANT_CONNECT_OK",
2555 "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
2556 "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
2557 "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
2558 "PROXY_SOCKS5_WANT_CONNECT_OK",
2559 "PROXY_HAPROXY_WAIT_FOR_FLUSH",
2560 "PROXY_CONNECTED",
2561 };
2562
2563 CTASSERT(ARRAY_LENGTH(states) == PROXY_CONNECTED+1);
2564
2565 if (state < PROXY_NONE || state > PROXY_CONNECTED)
2566 return unknown;
2567
2568 return states[state];
2569}
2570
2571/** Returns the proxy type used by tor for a single connection, for
2572 * logging or high-level purposes. Don't use it to fill the
2573 * <b>proxy_type</b> field of or_connection_t; use the actual proxy
2574 * protocol instead.*/
2575static int
2577{
2578 const or_options_t *options = get_options();
2579
2580 if (options->ClientTransportPlugin) {
2581 /* If we have plugins configured *and* this addr/port is a known bridge
2582 * with a transport, then we should be PROXY_PLUGGABLE. */
2583 const transport_t *transport = NULL;
2584 int r;
2585 r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
2586 if (r == 0 && transport)
2587 return PROXY_PLUGGABLE;
2588 }
2589
2590 /* In all other cases, we're using a global proxy. */
2591 if (options->HTTPSProxy)
2592 return PROXY_CONNECT;
2593 else if (options->Socks4Proxy)
2594 return PROXY_SOCKS4;
2595 else if (options->Socks5Proxy)
2596 return PROXY_SOCKS5;
2597 else if (options->TCPProxy) {
2598 /* The only supported protocol in TCPProxy is haproxy. */
2600 return PROXY_HAPROXY;
2601 } else
2602 return PROXY_NONE;
2603}
2604
2605/* One byte for the version, one for the command, two for the
2606 port, and four for the addr... and, one more for the
2607 username NUL: */
2608#define SOCKS4_STANDARD_BUFFER_SIZE (1 + 1 + 2 + 4 + 1)
2609
2610/** Write a proxy request of https to conn for conn->addr:conn->port,
2611 * authenticating with the auth details given in the configuration
2612 * (if available).
2613 *
2614 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2615 * 0 otherwise.
2616 */
2617static int
2619{
2620 tor_assert(conn);
2621
2622 const or_options_t *options = get_options();
2623 char buf[1024];
2624 char *base64_authenticator = NULL;
2625 const char *authenticator = options->HTTPSProxyAuthenticator;
2626
2627 /* Send HTTP CONNECT and authentication (if available) in
2628 * one request */
2629
2630 if (authenticator) {
2631 base64_authenticator = alloc_http_authenticator(authenticator);
2632 if (!base64_authenticator)
2633 log_warn(LD_OR, "Encoding https authenticator failed");
2634 }
2635
2636 if (base64_authenticator) {
2637 const char *addrport = fmt_addrport(&conn->addr, conn->port);
2638 tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.1\r\n"
2639 "Host: %s\r\n"
2640 "Proxy-Authorization: Basic %s\r\n\r\n",
2641 addrport,
2642 addrport,
2643 base64_authenticator);
2644 tor_free(base64_authenticator);
2645 } else {
2646 tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.0\r\n\r\n",
2647 fmt_addrport(&conn->addr, conn->port));
2648 }
2649
2650 connection_buf_add(buf, strlen(buf), conn);
2651 conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
2652
2653 return 0;
2654}
2655
2656/** Write a proxy request of socks4 to conn for conn->addr:conn->port.
2657 *
2658 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2659 * 0 otherwise.
2660 */
2661static int
2663{
2664 tor_assert(conn);
2665
2666 unsigned char *buf;
2667 uint16_t portn;
2668 uint32_t ip4addr;
2669 size_t buf_size = 0;
2670 char *socks_args_string = NULL;
2671
2672 /* Send a SOCKS4 connect request */
2673
2674 if (tor_addr_family(&conn->addr) != AF_INET) {
2675 log_warn(LD_NET, "SOCKS4 client is incompatible with IPv6");
2676 return -1;
2677 }
2678
2679 { /* If we are here because we are trying to connect to a
2680 pluggable transport proxy, check if we have any SOCKS
2681 arguments to transmit. If we do, compress all arguments to
2682 a single string in 'socks_args_string': */
2683
2684 if (conn_get_proxy_type(conn) == PROXY_PLUGGABLE) {
2685 socks_args_string =
2687 if (socks_args_string)
2688 log_debug(LD_NET, "Sending out '%s' as our SOCKS argument string.",
2689 socks_args_string);
2690 }
2691 }
2692
2693 { /* Figure out the buffer size we need for the SOCKS message: */
2694
2695 buf_size = SOCKS4_STANDARD_BUFFER_SIZE;
2696
2697 /* If we have a SOCKS argument string, consider its size when
2698 calculating the buffer size: */
2699 if (socks_args_string)
2700 buf_size += strlen(socks_args_string);
2701 }
2702
2703 buf = tor_malloc_zero(buf_size);
2704
2705 ip4addr = tor_addr_to_ipv4n(&conn->addr);
2706 portn = htons(conn->port);
2707
2708 buf[0] = 4; /* version */
2709 buf[1] = SOCKS_COMMAND_CONNECT; /* command */
2710 memcpy(buf + 2, &portn, 2); /* port */
2711 memcpy(buf + 4, &ip4addr, 4); /* addr */
2712
2713 /* Next packet field is the userid. If we have pluggable
2714 transport SOCKS arguments, we have to embed them
2715 there. Otherwise, we use an empty userid. */
2716 if (socks_args_string) { /* place the SOCKS args string: */
2717 tor_assert(strlen(socks_args_string) > 0);
2718 tor_assert(buf_size >=
2719 SOCKS4_STANDARD_BUFFER_SIZE + strlen(socks_args_string));
2720 strlcpy((char *)buf + 8, socks_args_string, buf_size - 8);
2721 tor_free(socks_args_string);
2722 } else {
2723 buf[8] = 0; /* no userid */
2724 }
2725
2726 connection_buf_add((char *)buf, buf_size, conn);
2727 tor_free(buf);
2728
2729 conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
2730 return 0;
2731}
2732
2733/** Write a proxy request of socks5 to conn for conn->addr:conn->port,
2734 * authenticating with the auth details given in the configuration
2735 * (if available).
2736 *
2737 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2738 * 0 otherwise.
2739 */
2740static int
2742{
2743 tor_assert(conn);
2744
2745 const or_options_t *options = get_options();
2746 unsigned char buf[4]; /* fields: vers, num methods, method list */
2747
2748 /* Send a SOCKS5 greeting (connect request must wait) */
2749
2750 buf[0] = 5; /* version */
2751
2752 /* We have to use SOCKS5 authentication, if we have a
2753 Socks5ProxyUsername or if we want to pass arguments to our
2754 pluggable transport proxy: */
2755 if ((options->Socks5ProxyUsername) ||
2756 (conn_get_proxy_type(conn) == PROXY_PLUGGABLE &&
2757 (get_socks_args_by_bridge_addrport(&conn->addr, conn->port)))) {
2758 /* number of auth methods */
2759 buf[1] = 2;
2760 buf[2] = 0x00; /* no authentication */
2761 buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
2762 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
2763 } else {
2764 buf[1] = 1;
2765 buf[2] = 0x00; /* no authentication */
2766 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
2767 }
2768
2769 connection_buf_add((char *)buf, 2 + buf[1], conn);
2770 return 0;
2771}
2772
2773/** Write a proxy request of haproxy to conn for conn->addr:conn->port.
2774 *
2775 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2776 * 0 otherwise.
2777 */
2778static int
2780{
2781 int ret = 0;
2782 tor_addr_port_t *addr_port = tor_addr_port_new(&conn->addr, conn->port);
2783 char *buf = haproxy_format_proxy_header_line(addr_port);
2784
2785 if (buf == NULL) {
2786 ret = -1;
2787 goto done;
2788 }
2789
2790 connection_buf_add(buf, strlen(buf), conn);
2791 /* In haproxy, we don't have to wait for the response, but we wait for ack.
2792 * So we can set the state to be PROXY_HAPROXY_WAIT_FOR_FLUSH. */
2793 conn->proxy_state = PROXY_HAPROXY_WAIT_FOR_FLUSH;
2794
2795 ret = 0;
2796 done:
2797 tor_free(buf);
2798 tor_free(addr_port);
2799 return ret;
2800}
2801
2802/** Write a proxy request of <b>type</b> (socks4, socks5, https, haproxy)
2803 * to conn for conn->addr:conn->port, authenticating with the auth details
2804 * given in the configuration (if available). SOCKS 5 and HTTP CONNECT
2805 * proxies support authentication.
2806 *
2807 * Returns -1 if conn->addr is incompatible with the proxy protocol, and
2808 * 0 otherwise.
2809 *
2810 * Use connection_read_proxy_handshake() to complete the handshake.
2811 */
2812int
2814{
2815 int ret = 0;
2816
2817 tor_assert(conn);
2818
2819 switch (type) {
2820 case PROXY_CONNECT:
2822 break;
2823
2824 case PROXY_SOCKS4:
2826 break;
2827
2828 case PROXY_SOCKS5:
2830 break;
2831
2832 case PROXY_HAPROXY:
2834 break;
2835
2836 default:
2837 log_err(LD_BUG, "Invalid proxy protocol, %d", type);
2839 ret = -1;
2840 break;
2841 }
2842
2843 if (ret == 0) {
2844 log_debug(LD_NET, "set state %s",
2846 }
2847
2848 return ret;
2849}
2850
2851/** Read conn's inbuf. If the http response from the proxy is all
2852 * here, make sure it's good news, then return 1. If it's bad news,
2853 * return -1. Else return 0 and hope for better luck next time.
2854 */
2855static int
2857{
2858 char *headers;
2859 char *reason=NULL;
2860 int status_code;
2861 time_t date_header;
2862
2863 switch (fetch_from_buf_http(conn->inbuf,
2864 &headers, MAX_HEADERS_SIZE,
2865 NULL, NULL, 10000, 0)) {
2866 case -1: /* overflow */
2867 log_warn(LD_PROTOCOL,
2868 "Your https proxy sent back an oversized response. Closing.");
2869 return -1;
2870 case 0:
2871 log_info(LD_NET,"https proxy response not all here yet. Waiting.");
2872 return 0;
2873 /* case 1, fall through */
2874 }
2875
2876 if (parse_http_response(headers, &status_code, &date_header,
2877 NULL, &reason) < 0) {
2878 log_warn(LD_NET,
2879 "Unparseable headers from proxy (%s). Closing.",
2880 connection_describe(conn));
2881 tor_free(headers);
2882 return -1;
2883 }
2884 tor_free(headers);
2885 if (!reason) reason = tor_strdup("[no reason given]");
2886
2887 if (status_code == 200) {
2888 log_info(LD_NET,
2889 "HTTPS connect for %s successful! (200 %s) Starting TLS.",
2890 connection_describe(conn), escaped(reason));
2891 tor_free(reason);
2892 return 1;
2893 }
2894 /* else, bad news on the status code */
2895 switch (status_code) {
2896 case 403:
2897 log_warn(LD_NET,
2898 "The https proxy refused to allow connection to %s "
2899 "(status code %d, %s). Closing.",
2900 conn->address, status_code, escaped(reason));
2901 break;
2902 default:
2903 log_warn(LD_NET,
2904 "The https proxy sent back an unexpected status code %d (%s). "
2905 "Closing.",
2906 status_code, escaped(reason));
2907 break;
2908 }
2909 tor_free(reason);
2910 return -1;
2911}
2912
2913/** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
2914 * and <b>conn->port</b> into the request.
2915 */
2916static void
2918{
2919 unsigned char buf[1024];
2920 size_t reqsize = 6;
2921 uint16_t port = htons(conn->port);
2922
2923 buf[0] = 5; /* version */
2924 buf[1] = SOCKS_COMMAND_CONNECT; /* command */
2925 buf[2] = 0; /* reserved */
2926
2927 if (tor_addr_family(&conn->addr) == AF_INET) {
2928 uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
2929
2930 buf[3] = 1;
2931 reqsize += 4;
2932 memcpy(buf + 4, &addr, 4);
2933 memcpy(buf + 8, &port, 2);
2934 } else { /* AF_INET6 */
2935 buf[3] = 4;
2936 reqsize += 16;
2937 memcpy(buf + 4, tor_addr_to_in6_addr8(&conn->addr), 16);
2938 memcpy(buf + 20, &port, 2);
2939 }
2940
2941 connection_buf_add((char *)buf, reqsize, conn);
2942
2943 conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
2944}
2945
2946/** Wrapper around fetch_from_buf_socks_client: see that functions
2947 * for documentation of its behavior. */
2948static int
2950 int state, char **reason)
2951{
2952 return fetch_from_buf_socks_client(conn->inbuf, state, reason);
2953}
2954
2955/** Call this from connection_*_process_inbuf() to advance the proxy
2956 * handshake.
2957 *
2958 * No matter what proxy protocol is used, if this function returns 1, the
2959 * handshake is complete, and the data remaining on inbuf may contain the
2960 * start of the communication with the requested server.
2961 *
2962 * Returns 0 if the current buffer contains an incomplete response, and -1
2963 * on error.
2964 */
2965int
2967{
2968 int ret = 0;
2969 char *reason = NULL;
2970
2971 log_debug(LD_NET, "enter state %s",
2973
2974 switch (conn->proxy_state) {
2975 case PROXY_HTTPS_WANT_CONNECT_OK:
2977 if (ret == 1)
2978 conn->proxy_state = PROXY_CONNECTED;
2979 break;
2980
2981 case PROXY_SOCKS4_WANT_CONNECT_OK:
2983 conn->proxy_state,
2984 &reason);
2985 if (ret == 1)
2986 conn->proxy_state = PROXY_CONNECTED;
2987 break;
2988
2989 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
2991 conn->proxy_state,
2992 &reason);
2993 /* no auth needed, do connect */
2994 if (ret == 1) {
2996 ret = 0;
2997 }
2998 break;
2999
3000 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
3002 conn->proxy_state,
3003 &reason);
3004
3005 /* send auth if needed, otherwise do connect */
3006 if (ret == 1) {
3008 ret = 0;
3009 } else if (ret == 2) {
3010 unsigned char buf[1024];
3011 size_t reqsize, usize, psize;
3012 const char *user, *pass;
3013 char *socks_args_string = NULL;
3014
3015 if (conn_get_proxy_type(conn) == PROXY_PLUGGABLE) {
3016 socks_args_string =
3018 if (!socks_args_string) {
3019 log_warn(LD_NET, "Could not create SOCKS args string for PT.");
3020 ret = -1;
3021 break;
3022 }
3023
3024 log_debug(LD_NET, "PT SOCKS5 arguments: %s", socks_args_string);
3025 tor_assert(strlen(socks_args_string) > 0);
3026 tor_assert(strlen(socks_args_string) <= MAX_SOCKS5_AUTH_SIZE_TOTAL);
3027
3028 if (strlen(socks_args_string) > MAX_SOCKS5_AUTH_FIELD_SIZE) {
3029 user = socks_args_string;
3031 pass = socks_args_string + MAX_SOCKS5_AUTH_FIELD_SIZE;
3032 psize = strlen(socks_args_string) - MAX_SOCKS5_AUTH_FIELD_SIZE;
3033 } else {
3034 user = socks_args_string;
3035 usize = strlen(socks_args_string);
3036 pass = "\0";
3037 psize = 1;
3038 }
3039 } else if (get_options()->Socks5ProxyUsername) {
3042 tor_assert(user && pass);
3043 usize = strlen(user);
3044 psize = strlen(pass);
3045 } else {
3046 log_err(LD_BUG, "We entered %s for no reason!", __func__);
3048 ret = -1;
3049 break;
3050 }
3051
3052 /* Username and password lengths should have been checked
3053 above and during torrc parsing. */
3056 reqsize = 3 + usize + psize;
3057
3058 buf[0] = 1; /* negotiation version */
3059 buf[1] = usize;
3060 memcpy(buf + 2, user, usize);
3061 buf[2 + usize] = psize;
3062 memcpy(buf + 3 + usize, pass, psize);
3063
3064 if (socks_args_string)
3065 tor_free(socks_args_string);
3066
3067 connection_buf_add((char *)buf, reqsize, conn);
3068
3069 conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
3070 ret = 0;
3071 }
3072 break;
3073
3074 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
3076 conn->proxy_state,
3077 &reason);
3078 /* send the connect request */
3079 if (ret == 1) {
3081 ret = 0;
3082 }
3083 break;
3084
3085 case PROXY_SOCKS5_WANT_CONNECT_OK:
3087 conn->proxy_state,
3088 &reason);
3089 if (ret == 1)
3090 conn->proxy_state = PROXY_CONNECTED;
3091 break;
3092
3093 default:
3094 log_err(LD_BUG, "Invalid proxy_state for reading, %d",
3095 conn->proxy_state);
3097 ret = -1;
3098 break;
3099 }
3100
3101 log_debug(LD_NET, "leaving state %s",
3103
3104 if (ret < 0) {
3105 if (reason) {
3106 log_warn(LD_NET, "Proxy Client: unable to connect %s (%s)",
3107 connection_describe(conn), escaped(reason));
3108 tor_free(reason);
3109 } else {
3110 log_warn(LD_NET, "Proxy Client: unable to connect %s",
3111 connection_describe(conn));
3112 }
3113 } else if (ret == 1) {
3114 log_info(LD_NET, "Proxy Client: %s successful",
3115 connection_describe(conn));
3116 }
3117
3118 return ret;
3119}
3120
3121/** Given a list of listener connections in <b>old_conns</b>, and list of
3122 * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
3123 * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
3124 *
3125 * Remove from <b>old_conns</b> every connection that has a corresponding
3126 * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
3127 * launch. If we may need to perform socket rebind when creating new
3128 * listener that replaces old one, create a <b>listener_replacement_t</b>
3129 * struct for affected pair and add it to <b>replacements</b>.
3130 *
3131 * If <b>control_listeners_only</b> is true, then we only open control
3132 * listeners, and we do not remove any noncontrol listeners from
3133 * old_conns.
3134 *
3135 * Return 0 on success, -1 on failure.
3136 **/
3137static int
3139 const smartlist_t *ports,
3140 smartlist_t *new_conns,
3141 smartlist_t *replacements,
3142 int control_listeners_only)
3143{
3144#ifndef ENABLE_LISTENER_REBIND
3145 (void)replacements;
3146#endif
3147
3148 smartlist_t *launch = smartlist_new();
3149 int r = 0;
3150
3151 if (control_listeners_only) {
3152 SMARTLIST_FOREACH(ports, port_cfg_t *, p, {
3153 if (p->type == CONN_TYPE_CONTROL_LISTENER)
3154 smartlist_add(launch, p);
3155 });
3156 } else {
3157 smartlist_add_all(launch, ports);
3158 }
3159
3160 /* Iterate through old_conns, comparing it to launch: remove from both lists
3161 * each pair of elements that corresponds to the same port. */
3162 SMARTLIST_FOREACH_BEGIN(old_conns, connection_t *, conn) {
3163 const port_cfg_t *found_port = NULL;
3164
3165 /* Okay, so this is a listener. Is it configured? */
3166 /* That is, is it either: 1) exact match - address and port
3167 * pair match exactly between old listener and new port; or 2)
3168 * wildcard match - port matches exactly, but *one* of the
3169 * addresses is wildcard (0.0.0.0 or ::)?
3170 */
3171 SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, wanted) {
3172 if (conn->type != wanted->type)
3173 continue;
3174 if ((conn->socket_family != AF_UNIX && wanted->is_unix_addr) ||
3175 (conn->socket_family == AF_UNIX && ! wanted->is_unix_addr))
3176 continue;
3177
3178 if (wanted->server_cfg.no_listen)
3179 continue; /* We don't want to open a listener for this one */
3180
3181 if (wanted->is_unix_addr) {
3182 if (conn->socket_family == AF_UNIX &&
3183 !strcmp(wanted->unix_addr, conn->address)) {
3184 found_port = wanted;
3185 break;
3186 }
3187 } else {
3188 /* Numeric values of old and new port match exactly. */
3189 const int port_matches_exact = (wanted->port == conn->port);
3190 /* Ports match semantically - either their specific values
3191 match exactly, or new port is 'auto'.
3192 */
3193 const int port_matches = (wanted->port == CFG_AUTO_PORT ||
3194 port_matches_exact);
3195
3196 if (port_matches && tor_addr_eq(&wanted->addr, &conn->addr)) {
3197 found_port = wanted;
3198 break;
3199 }
3200#ifdef ENABLE_LISTENER_REBIND
3201 /* Rebinding may be needed if all of the following are true:
3202 * 1) Address family is the same in old and new listeners.
3203 * 2) Port number matches exactly (numeric value is the same).
3204 * 3) *One* of listeners (either old one or new one) has a
3205 * wildcard IP address (0.0.0.0 or [::]).
3206 *
3207 * These are the exact conditions for a first bind() syscall
3208 * to fail with EADDRINUSE.
3209 */
3210 const int may_need_rebind =
3211 tor_addr_family(&wanted->addr) == tor_addr_family(&conn->addr) &&
3212 port_matches_exact && bool_neq(tor_addr_is_null(&wanted->addr),
3213 tor_addr_is_null(&conn->addr));
3214 if (replacements && may_need_rebind) {
3215 listener_replacement_t *replacement =
3216 tor_malloc(sizeof(listener_replacement_t));
3217
3218 replacement->old_conn = conn;
3219 replacement->new_port = wanted;
3220 smartlist_add(replacements, replacement);
3221
3222 SMARTLIST_DEL_CURRENT(launch, wanted);
3223 SMARTLIST_DEL_CURRENT(old_conns, conn);
3224 break;
3225 }
3226#endif /* defined(ENABLE_LISTENER_REBIND) */
3227 }
3228 } SMARTLIST_FOREACH_END(wanted);
3229
3230 if (found_port) {
3231 /* This listener is already running; we don't need to launch it. */
3232 //log_debug(LD_NET, "Already have %s on %s:%d",
3233 // conn_type_to_string(found_port->type), conn->address, conn->port);
3234 smartlist_remove(launch, found_port);
3235 /* And we can remove the connection from old_conns too. */
3236 SMARTLIST_DEL_CURRENT(old_conns, conn);
3237 }
3238 } SMARTLIST_FOREACH_END(conn);
3239
3240 /* Now open all the listeners that are configured but not opened. */
3241 SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, port) {
3242 int skip = 0;
3243 connection_t *conn = connection_listener_new_for_port(port, &skip, NULL);
3244
3245 if (conn && new_conns)
3246 smartlist_add(new_conns, conn);
3247 else if (!skip)
3248 r = -1;
3249 } SMARTLIST_FOREACH_END(port);
3250
3251 smartlist_free(launch);
3252
3253 return r;
3254}
3255
3256/** Launch listeners for each port you should have open. Only launch
3257 * listeners who are not already open, and only close listeners we no longer
3258 * want.
3259 *
3260 * Add all new connections to <b>new_conns</b>.
3261 *
3262 * If <b>close_all_noncontrol</b> is true, then we only open control
3263 * listeners, and we close all other listeners.
3264 */
3265int
3266retry_all_listeners(smartlist_t *new_conns, int close_all_noncontrol)
3267{
3268 smartlist_t *listeners = smartlist_new();
3269 smartlist_t *replacements = smartlist_new();
3270 const or_options_t *options = get_options();
3271 int retval = 0;
3272 const uint16_t old_or_port = routerconf_find_or_port(options, AF_INET);
3273 const uint16_t old_or_port_ipv6 =
3274 routerconf_find_or_port(options,AF_INET6);
3275 const uint16_t old_dir_port = routerconf_find_dir_port(options, 0);
3276
3278 if (connection_is_listener(conn) && !conn->marked_for_close)
3279 smartlist_add(listeners, conn);
3280 } SMARTLIST_FOREACH_END(conn);
3281
3282 if (retry_listener_ports(listeners,
3284 new_conns,
3285 replacements,
3286 close_all_noncontrol) < 0)
3287 retval = -1;
3288
3289#ifdef ENABLE_LISTENER_REBIND
3290 if (smartlist_len(replacements))
3291 log_debug(LD_NET, "%d replacements - starting rebinding loop.",
3292 smartlist_len(replacements));
3293
3295 int addr_in_use = 0;
3296 int skip = 0;
3297
3298 tor_assert(r->new_port);
3299 tor_assert(r->old_conn);
3300
3301 connection_t *new_conn =
3302 connection_listener_new_for_port(r->new_port, &skip, &addr_in_use);
3303 connection_t *old_conn = r->old_conn;
3304
3305 if (skip) {
3306 log_debug(LD_NET, "Skipping creating new listener for %s",
3307 connection_describe(old_conn));
3308 continue;
3309 }
3310
3312 connection_mark_for_close(old_conn);
3313
3314 if (addr_in_use) {
3315 new_conn = connection_listener_new_for_port(r->new_port,
3316 &skip, &addr_in_use);
3317 }
3318
3319 /* There are many reasons why we can't open a new listener port so in case
3320 * we hit those, bail early so tor can stop. */
3321 if (!new_conn) {
3322 log_warn(LD_NET, "Unable to create listener port: %s:%d",
3323 fmt_and_decorate_addr(&r->new_port->addr), r->new_port->port);
3324 retval = -1;
3325 break;
3326 }
3327
3328 smartlist_add(new_conns, new_conn);
3329
3330 char *old_desc = tor_strdup(connection_describe(old_conn));
3331 log_notice(LD_NET, "Closed no-longer-configured %s "
3332 "(replaced by %s)",
3333 old_desc, connection_describe(new_conn));
3334 tor_free(old_desc);
3335 } SMARTLIST_FOREACH_END(r);
3336#endif /* defined(ENABLE_LISTENER_REBIND) */
3337
3338 /* Any members that were still in 'listeners' don't correspond to
3339 * any configured port. Kill 'em. */
3340 SMARTLIST_FOREACH_BEGIN(listeners, connection_t *, conn) {
3341 log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
3343 fmt_and_decorate_addr(&conn->addr), conn->port);
3345 connection_mark_for_close(conn);
3346 } SMARTLIST_FOREACH_END(conn);
3347
3348 smartlist_free(listeners);
3349 /* Cleanup any remaining listener replacement. */
3350 SMARTLIST_FOREACH(replacements, listener_replacement_t *, r, tor_free(r));
3351 smartlist_free(replacements);
3352
3353 if (old_or_port != routerconf_find_or_port(options, AF_INET) ||
3354 old_or_port_ipv6 != routerconf_find_or_port(options, AF_INET6) ||
3355 old_dir_port != routerconf_find_dir_port(options, 0)) {
3356 /* Our chosen ORPort or DirPort is not what it used to be: the
3357 * descriptor we had (if any) should be regenerated. (We won't
3358 * automatically notice this because of changes in the option,
3359 * since the value could be "auto".) */
3360 mark_my_descriptor_dirty("Chosen Or/DirPort changed");
3361 }
3362
3363 return retval;
3364}
3365
3366/** Mark every listener of type other than CONTROL_LISTENER to be closed. */
3367void
3369{
3371 if (conn->marked_for_close)
3372 continue;
3373 if (conn->type == CONN_TYPE_CONTROL_LISTENER)
3374 continue;
3375 if (connection_is_listener(conn))
3376 connection_mark_for_close(conn);
3377 } SMARTLIST_FOREACH_END(conn);
3378}
3379
3380/** Mark every external connection not used for controllers for close. */
3381void
3383{
3385 if (conn->marked_for_close)
3386 continue;
3387 switch (conn->type) {
3389 case CONN_TYPE_CONTROL:
3390 break;
3391 case CONN_TYPE_AP:
3392 connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
3393 END_STREAM_REASON_HIBERNATING);
3394 break;
3395 case CONN_TYPE_OR:
3396 {
3397 or_connection_t *orconn = TO_OR_CONN(conn);
3398 if (orconn->chan) {
3400 } else {
3401 /*
3402 * There should have been one, but mark for close and hope
3403 * for the best..
3404 */
3405 connection_mark_for_close(conn);
3406 }
3407 }
3408 break;
3409 default:
3410 connection_mark_for_close(conn);
3411 break;
3412 }
3413 } SMARTLIST_FOREACH_END(conn);
3414}
3415
3416/** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
3417 * otherwise.
3418 * Right now this just checks if it's an internal IP address or an
3419 * internal connection. We also should, but don't, check if the connection
3420 * uses pluggable transports, since we should then limit it even if it
3421 * comes from an internal IP address. */
3422static int
3424{
3425 const or_options_t *options = get_options();
3426 if (conn->linked)
3427 return 0; /* Internal connection */
3428 else if (! options->CountPrivateBandwidth &&
3430 (tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
3431 tor_addr_family(&conn->addr) == AF_UNIX || /* no address */
3432 tor_addr_is_internal(&conn->addr, 0)))
3433 return 0; /* Internal address */
3434 else
3435 return 1;
3436}
3437
3438/** When was either global write bucket last empty? If this was recent, then
3439 * we're probably low on bandwidth, and we should be stingy with our bandwidth
3440 * usage. */
3441static time_t write_buckets_last_empty_at = -100;
3442
3443/** How many seconds of no active local circuits will make the
3444 * connection revert to the "relayed" bandwidth class? */
3445#define CLIENT_IDLE_TIME_FOR_PRIORITY 30
3446
3447/** Return 1 if <b>conn</b> should use tokens from the "relayed"
3448 * bandwidth rates, else 0. Currently, only OR conns with bandwidth
3449 * class 1, and directory conns that are serving data out, count.
3450 */
3451static int
3453{
3454 if (conn->type == CONN_TYPE_OR &&
3457 return 1;
3458 if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
3459 return 1;
3460 return 0;
3461}
3462
3463/** Helper function to decide how many bytes out of <b>global_bucket</b>
3464 * we're willing to use for this transaction. <b>base</b> is the size
3465 * of a cell on the network; <b>priority</b> says whether we should
3466 * write many of them or just a few; and <b>conn_bucket</b> (if
3467 * non-negative) provides an upper limit for our answer. */
3468static ssize_t
3469connection_bucket_get_share(int base, int priority,
3470 ssize_t global_bucket_val, ssize_t conn_bucket)
3471{
3472 ssize_t at_most;
3473 ssize_t num_bytes_high = (priority ? 32 : 16) * base;
3474 ssize_t num_bytes_low = (priority ? 4 : 2) * base;
3475
3476 /* Do a rudimentary limiting so one circuit can't hog a connection.
3477 * Pick at most 32 cells, at least 4 cells if possible, and if we're in
3478 * the middle pick 1/8 of the available bandwidth. */
3479 at_most = global_bucket_val / 8;
3480 at_most -= (at_most % base); /* round down */
3481 if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
3482 at_most = num_bytes_high;
3483 else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
3484 at_most = num_bytes_low;
3485
3486 if (at_most > global_bucket_val)
3487 at_most = global_bucket_val;
3488
3489 if (conn_bucket >= 0 && at_most > conn_bucket)
3490 at_most = conn_bucket;
3491
3492 if (at_most < 0)
3493 return 0;
3494 return at_most;
3495}
3496
3497/** How many bytes at most can we read onto this connection? */
3498static ssize_t
3500{
3501 int base = RELAY_PAYLOAD_SIZE_MAX;
3502 int priority = conn->type != CONN_TYPE_DIR;
3503 ssize_t conn_bucket = -1;
3504 size_t global_bucket_val = token_bucket_rw_get_read(&global_bucket);
3505 if (global_bucket_val == 0) {
3506 /* We reached our global read limit: count this as an overload.
3507 *
3508 * The token bucket is always initialized (see connection_bucket_init() and
3509 * options_validate_relay_bandwidth()) and hence we can assume that if the
3510 * token ever hits zero, it's a limit that got popped and not the bucket
3511 * being uninitialized.
3512 */
3513 rep_hist_note_overload(OVERLOAD_READ);
3514 }
3515
3516 if (connection_speaks_cells(conn)) {
3517 or_connection_t *or_conn = TO_OR_CONN(conn);
3518 if (conn->state == OR_CONN_STATE_OPEN)
3519 conn_bucket = token_bucket_rw_get_read(&or_conn->bucket);
3520 base = get_cell_network_size(or_conn->wide_circ_ids);
3521 }
3522
3523 /* Edge connection have their own read bucket due to flow control being able
3524 * to set a rate limit for them. However, for exit connections, we still need
3525 * to honor the global bucket as well. */
3526 if (CONN_IS_EDGE(conn)) {
3527 const edge_connection_t *edge_conn = CONST_TO_EDGE_CONN(conn);
3528 conn_bucket = token_bucket_rw_get_read(&edge_conn->bucket);
3529 if (conn->type == CONN_TYPE_EXIT) {
3530 /* Decide between our limit and the global one. */
3531 goto end;
3532 }
3533 return conn_bucket;
3534 }
3535
3536 if (!connection_is_rate_limited(conn)) {
3537 /* be willing to read on local conns even if our buckets are empty */
3538 return conn_bucket>=0 ? conn_bucket : 1<<14;
3539 }
3540
3541 if (connection_counts_as_relayed_traffic(conn, now)) {
3542 size_t relayed = token_bucket_rw_get_read(&global_relayed_bucket);
3543 global_bucket_val = MIN(global_bucket_val, relayed);
3544 }
3545
3546 end:
3547 return connection_bucket_get_share(base, priority,
3548 global_bucket_val, conn_bucket);
3549}
3550
3551/** How many bytes at most can we write onto this connection? */
3552ssize_t
3554{
3555 int base = RELAY_PAYLOAD_SIZE_MAX;
3556 int priority = conn->type != CONN_TYPE_DIR;
3557 size_t conn_bucket = buf_datalen(conn->outbuf);
3558 size_t global_bucket_val = token_bucket_rw_get_write(&global_bucket);
3559 if (global_bucket_val == 0) {
3560 /* We reached our global write limit: We should count this as an overload.
3561 * See above function for more information */
3562 rep_hist_note_overload(OVERLOAD_WRITE);
3563 }
3564
3565 if (!connection_is_rate_limited(conn)) {
3566 /* be willing to write to local conns even if our buckets are empty */
3567 return conn_bucket;
3568 }
3569
3570 if (connection_speaks_cells(conn)) {
3571 /* use the per-conn write limit if it's lower */
3572 or_connection_t *or_conn = TO_OR_CONN(conn);
3573 if (conn->state == OR_CONN_STATE_OPEN)
3574 conn_bucket = MIN(conn_bucket,
3575 token_bucket_rw_get_write(&or_conn->bucket));
3576 base = get_cell_network_size(or_conn->wide_circ_ids);
3577 }
3578
3579 if (connection_counts_as_relayed_traffic(conn, now)) {
3580 size_t relayed = token_bucket_rw_get_write(&global_relayed_bucket);
3581 global_bucket_val = MIN(global_bucket_val, relayed);
3582 }
3583
3584 return connection_bucket_get_share(base, priority,
3585 global_bucket_val, conn_bucket);
3586}
3587
3588/** Return true iff the global write buckets are low enough that we
3589 * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
3590 * out to <b>conn</b>.
3591 *
3592 * If we are a directory authority, always answer dir requests thus true is
3593 * always returned.
3594 *
3595 * Note: There are a lot of parameters we could use here:
3596 * - global_relayed_write_bucket. Low is bad.
3597 * - global_write_bucket. Low is bad.
3598 * - bandwidthrate. Low is bad.
3599 * - bandwidthburst. Not a big factor?
3600 * - attempt. High is bad.
3601 * - total bytes queued on outbufs. High is bad. But I'm wary of
3602 * using this, since a few slow-flushing queues will pump up the
3603 * number without meaning what we meant to mean. What we really
3604 * mean is "total directory bytes added to outbufs recently", but
3605 * that's harder to quantify and harder to keep track of.
3606 */
3607bool
3609{
3610 size_t smaller_bucket =
3611 MIN(token_bucket_rw_get_write(&global_bucket),
3612 token_bucket_rw_get_write(&global_relayed_bucket));
3613
3614 /* Special case for authorities (directory only). */
3615 if (authdir_mode_v3(get_options())) {
3616 /* Are we configured to possibly reject requests under load? */
3617 if (!dirauth_should_reject_requests_under_load()) {
3618 /* Answer request no matter what. */
3619 return false;
3620 }
3621 /* Always answer requests from a known relay which includes the other
3622 * authorities. The following looks up the addresses for relays that we
3623 * have their descriptor _and_ any configured trusted directories. */
3625 return false;
3626 }
3627 }
3628
3629 if (!connection_is_rate_limited(conn))
3630 return false; /* local conns don't get limited */
3631
3632 if (smaller_bucket < attempt)
3633 return true; /* not enough space. */
3634
3635 {
3636 const time_t diff = approx_time() - write_buckets_last_empty_at;
3637 if (diff <= 1)
3638 return true; /* we're already hitting our limits, no more please */
3639 }
3640 return false;
3641}
3642
3643/** When did we last tell the accounting subsystem about transmitted
3644 * bandwidth? */
3646
3647/** Helper: adjusts our bandwidth history and informs the controller as
3648 * appropriate, given that we have just read <b>num_read</b> bytes and written
3649 * <b>num_written</b> bytes on <b>conn</b>. */
3650static void
3652 time_t now, size_t num_read, size_t num_written)
3653{
3654 /* Count bytes of answering direct and tunneled directory requests */
3655 if (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER) {
3656 if (num_read > 0)
3657 bwhist_note_dir_bytes_read(num_read, now);
3658 if (num_written > 0)
3659 bwhist_note_dir_bytes_written(num_written, now);
3660 }
3661
3662 /* Linked connections and internal IPs aren't counted for statistics or
3663 * accounting:
3664 * - counting linked connections would double-count BEGINDIR bytes, because
3665 * they are sent as Dir bytes on the linked connection, and OR bytes on
3666 * the OR connection;
3667 * - relays and clients don't connect to internal IPs, unless specifically
3668 * configured to do so. If they are configured that way, we don't count
3669 * internal bytes.
3670 */
3671 if (!connection_is_rate_limited(conn))
3672 return;
3673
3674 const bool is_ipv6 = (conn->socket_family == AF_INET6);
3675 if (conn->type == CONN_TYPE_OR)
3677 num_written, now, is_ipv6);
3678
3679 if (num_read > 0) {
3680 bwhist_note_bytes_read(num_read, now, is_ipv6);
3681 }
3682 if (num_written > 0) {
3683 bwhist_note_bytes_written(num_written, now, is_ipv6);
3684 }
3685 if (conn->type == CONN_TYPE_EXIT)
3686 rep_hist_note_exit_bytes(conn->port, num_written, num_read);
3687
3688 /* Remember these bytes towards statistics. */
3689 stats_increment_bytes_read_and_written(num_read, num_written);
3690
3691 /* Remember these bytes towards accounting. */
3694 accounting_add_bytes(num_read, num_written,
3695 (int)(now - last_recorded_accounting_at));
3696 } else {
3697 accounting_add_bytes(num_read, num_written, 0);
3698 }
3700 }
3701}
3702
3703/** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
3704 * onto <b>conn</b>. Decrement buckets appropriately. */
3705static void
3707 size_t num_read, size_t num_written)
3708{
3709 if (num_written >= INT_MAX || num_read >= INT_MAX) {
3710 log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
3711 "connection type=%s, state=%s",
3712 (unsigned long)num_read, (unsigned long)num_written,
3714 conn_state_to_string(conn->type, conn->state));
3716 if (num_written >= INT_MAX)
3717 num_written = 1;
3718 if (num_read >= INT_MAX)
3719 num_read = 1;
3720 }
3721
3722 record_num_bytes_transferred_impl(conn, now, num_read, num_written);
3723
3724 /* Edge connection need to decrement the read side of the bucket used by our
3725 * congestion control. */
3726 if (CONN_IS_EDGE(conn) && num_read > 0) {
3727 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
3728 token_bucket_rw_dec(&edge_conn->bucket, num_read, 0);
3729 }
3730
3731 if (!connection_is_rate_limited(conn))
3732 return; /* local IPs are free */
3733
3734 unsigned flags = 0;
3735 if (connection_counts_as_relayed_traffic(conn, now)) {
3736 flags = token_bucket_rw_dec(&global_relayed_bucket, num_read, num_written);
3737 }
3738 flags |= token_bucket_rw_dec(&global_bucket, num_read, num_written);
3739
3740 if (flags & TB_WRITE) {
3742 }
3743 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
3744 or_connection_t *or_conn = TO_OR_CONN(conn);
3745 token_bucket_rw_dec(&or_conn->bucket, num_read, num_written);
3746 }
3747}
3748
3749/**
3750 * Mark <b>conn</b> as needing to stop reading because bandwidth has been
3751 * exhausted. If <b>is_global_bw</b>, it is closing because global bandwidth
3752 * limit has been exhausted. Otherwise, it is closing because its own
3753 * bandwidth limit has been exhausted.
3754 */
3755void
3757{
3758 (void)is_global_bw;
3759 // Double-calls to stop-reading are correlated with stalling for
3760 // ssh uploads. Might as well prevent this from happening,
3761 // especially the read_blocked_on_bw flag. That was clearly getting
3762 // set when it should not be, during an already-blocked XOFF
3763 // condition.
3764 if (!CONN_IS_EDGE(conn) || !TO_EDGE_CONN(conn)->xoff_received) {
3765 conn->read_blocked_on_bw = 1;
3768 }
3769}
3770
3771/**
3772 * Mark <b>conn</b> as needing to stop reading because write bandwidth has
3773 * been exhausted. If <b>is_global_bw</b>, it is closing because global
3774 * bandwidth limit has been exhausted. Otherwise, it is closing because its
3775 * own bandwidth limit has been exhausted.
3776*/
3777void
3779{
3780 (void)is_global_bw;
3781 conn->write_blocked_on_bw = 1;
3784}
3785
3786/** If we have exhausted our global buckets, or the buckets for conn,
3787 * stop reading. */
3788void
3790{
3791 int is_global = 1;
3792 const char *reason;
3793
3794 if (CONN_IS_EDGE(conn) &&
3795 token_bucket_rw_get_read(&TO_EDGE_CONN(conn)->bucket) <= 0) {
3796 reason = "edge connection read bucket exhausted. Pausing.";
3797 is_global = false;
3798 } else if (!connection_is_rate_limited(conn)) {
3799 return; /* Always okay. */
3800 } else if (token_bucket_rw_get_read(&global_bucket) <= 0) {
3801 reason = "global read bucket exhausted. Pausing.";
3803 token_bucket_rw_get_read(&global_relayed_bucket) <= 0) {
3804 reason = "global relayed read bucket exhausted. Pausing.";
3805 } else if (connection_speaks_cells(conn) &&
3806 conn->state == OR_CONN_STATE_OPEN &&
3807 token_bucket_rw_get_read(&TO_OR_CONN(conn)->bucket) <= 0) {
3808 reason = "connection read bucket exhausted. Pausing.";
3809 is_global = false;
3810 } else {
3811 return; /* all good, no need to stop it */
3812 }
3813
3814 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
3815 connection_read_bw_exhausted(conn, is_global);
3816}
3817
3818/** If we have exhausted our global buckets, or the buckets for conn,
3819 * stop writing. */
3820void
3822{
3823 const char *reason;
3824
3825 if (!connection_is_rate_limited(conn))
3826 return; /* Always okay. */
3827
3828 bool is_global = true;
3829 if (token_bucket_rw_get_write(&global_bucket) <= 0) {
3830 reason = "global write bucket exhausted. Pausing.";
3832 token_bucket_rw_get_write(&global_relayed_bucket) <= 0) {
3833 reason = "global relayed write bucket exhausted. Pausing.";
3834 } else if (connection_speaks_cells(conn) &&
3835 conn->state == OR_CONN_STATE_OPEN &&
3836 token_bucket_rw_get_write(&TO_OR_CONN(conn)->bucket) <= 0) {
3837 reason = "connection write bucket exhausted. Pausing.";
3838 is_global = false;
3839 } else
3840 return; /* all good, no need to stop it */
3841
3842 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
3843 connection_write_bw_exhausted(conn, is_global);
3844}
3845
3846/** Initialize the global buckets to the values configured in the
3847 * options */
3848void
3850{
3851 const or_options_t *options = get_options();
3852 const uint32_t now_ts = monotime_coarse_get_stamp();
3853 token_bucket_rw_init(&global_bucket,
3854 (int32_t)options->BandwidthRate,
3855 (int32_t)options->BandwidthBurst,
3856 now_ts);
3857 if (options->RelayBandwidthRate) {
3858 token_bucket_rw_init(&global_relayed_bucket,
3859 (int32_t)options->RelayBandwidthRate,
3860 (int32_t)options->RelayBandwidthBurst,
3861 now_ts);
3862 } else {
3863 token_bucket_rw_init(&global_relayed_bucket,
3864 (int32_t)options->BandwidthRate,
3865 (int32_t)options->BandwidthBurst,
3866 now_ts);
3867 }
3868
3870}
3871
3872/** Update the global connection bucket settings to a new value. */
3873void
3875{
3876 token_bucket_rw_adjust(&global_bucket,
3877 (int32_t)options->BandwidthRate,
3878 (int32_t)options->BandwidthBurst);
3879 if (options->RelayBandwidthRate) {
3880 token_bucket_rw_adjust(&global_relayed_bucket,
3881 (int32_t)options->RelayBandwidthRate,
3882 (int32_t)options->RelayBandwidthBurst);
3883 } else {
3884 token_bucket_rw_adjust(&global_relayed_bucket,
3885 (int32_t)options->BandwidthRate,
3886 (int32_t)options->BandwidthBurst);
3887 }
3888}
3889
3890/**
3891 * Cached value of the last coarse-timestamp when we refilled the
3892 * global buckets.
3893 */
3895/**
3896 * Refill the token buckets for a single connection <b>conn</b>, and the
3897 * global token buckets as appropriate. Requires that <b>now_ts</b> is
3898 * the time in coarse timestamp units.
3899 */
3900static void
3902{
3903 /* Note that we only check for equality here: the underlying
3904 * token bucket functions can handle moving backwards in time if they
3905 * need to. */
3906 if (now_ts != last_refilled_global_buckets_ts) {
3907 token_bucket_rw_refill(&global_bucket, now_ts);
3908 token_bucket_rw_refill(&global_relayed_bucket, now_ts);
3910 }
3911
3912 if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
3913 or_connection_t *or_conn = TO_OR_CONN(conn);
3914 token_bucket_rw_refill(&or_conn->bucket, now_ts);
3915 }
3916
3917 if (CONN_IS_EDGE(conn)) {
3918 token_bucket_rw_refill(&TO_EDGE_CONN(conn)->bucket, now_ts);
3919 }
3920}
3921
3922/**
3923 * Event to re-enable all connections that were previously blocked on read or
3924 * write.
3925 */
3927
3928/** True iff reenable_blocked_connections_ev is currently scheduled. */
3930
3931/** Delay after which to run reenable_blocked_connections_ev. */
3933
3934/**
3935 * Re-enable all connections that were previously blocked on read or write.
3936 * This event is scheduled after enough time has elapsed to be sure
3937 * that the buckets will refill when the connections have something to do.
3938 */
3939static void
3941{
3942 (void)ev;
3943 (void)arg;
3945 /* For conflux, we noticed logs of connection_start_reading() called
3946 * multiple times while we were blocked from a previous XOFF, and this
3947 * was log was correlated with stalls during ssh uploads. So we added
3948 * this additional check, to avoid connection_start_reading() without
3949 * getting an XON. The most important piece is always allowing
3950 * the read_blocked_on_bw to get cleared, either way. */
3951 if (conn->read_blocked_on_bw == 1 &&
3952 (!CONN_IS_EDGE(conn) || !TO_EDGE_CONN(conn)->xoff_received)) {
3954 }
3955 conn->read_blocked_on_bw = 0;
3956 if (conn->write_blocked_on_bw == 1) {
3958 conn->write_blocked_on_bw = 0;
3959 }
3960 } SMARTLIST_FOREACH_END(conn);
3961
3963}
3964
3965/**
3966 * Initialize the mainloop event that we use to wake up connections that
3967 * find themselves blocked on bandwidth.
3968 */
3969static void
3982
3983/**
3984 * Called when we have blocked a connection for being low on bandwidth:
3985 * schedule an event to reenable such connections, if it is not already
3986 * scheduled.
3987 */
3988static void
4000
4001/** Read bytes from conn->s and process them.
4002 *
4003 * It calls connection_buf_read_from_socket() to bring in any new bytes,
4004 * and then calls connection_process_inbuf() to process them.
4005 *
4006 * Mark the connection and return -1 if you want to close it, else
4007 * return 0.
4008 */
4009static int
4011{
4012 ssize_t max_to_read=-1, try_to_read;
4013 size_t before, n_read = 0;
4014 int socket_error = 0;
4015
4016 if (conn->marked_for_close)
4017 return 0; /* do nothing */
4018
4020
4022
4023 switch (conn->type) {
4040 /* This should never happen; eventdns.c handles the reads here. */
4042 return 0;
4043 }
4044
4045 loop_again:
4046 try_to_read = max_to_read;
4048
4049 before = buf_datalen(conn->inbuf);
4050 if (connection_buf_read_from_socket(conn, &max_to_read, &socket_error) < 0) {
4051 /* There's a read error; kill the connection.*/
4052 if (conn->type == CONN_TYPE_OR) {
4054 socket_error != 0 ?
4055 errno_to_orconn_end_reason(socket_error) :
4056 END_OR_CONN_REASON_CONNRESET,
4057 socket_error != 0 ?
4058 tor_socket_strerror(socket_error) :
4059 "(unknown, errno was 0)");
4060 }
4061 if (CONN_IS_EDGE(conn)) {
4062 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
4063 connection_edge_end_errno(edge_conn);
4064 if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
4065 /* broken, don't send a socks reply back */
4067 }
4068 }
4069 connection_close_immediate(conn); /* Don't flush; connection is dead. */
4070 /*
4071 * This can bypass normal channel checking since we did
4072 * connection_or_notify_error() above.
4073 */
4074 connection_mark_for_close_internal(conn);
4075 return -1;
4076 }
4077 n_read += buf_datalen(conn->inbuf) - before;
4078 if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
4079 /* instruct it not to try to package partial cells. */
4080 if (connection_process_inbuf(conn, 0) < 0) {
4081 return -1;
4082 }
4083 if (!conn->marked_for_close &&
4084 connection_is_reading(conn) &&
4085 !conn->inbuf_reached_eof &&
4086 max_to_read > 0)
4087 goto loop_again; /* try reading again, in case more is here now */
4088 }
4089 /* one last try, packaging partial cells and all. */
4090 if (!conn->marked_for_close &&
4091 connection_process_inbuf(conn, 1) < 0) {
4092 return -1;
4093 }
4094 if (conn->linked_conn) {
4095 /* The other side's handle_write() will never actually get called, so
4096 * we need to invoke the appropriate callbacks ourself. */
4097 connection_t *linked = conn->linked_conn;
4098
4099 if (n_read) {
4100 /* Probably a no-op, since linked conns typically don't count for
4101 * bandwidth rate limiting. But do it anyway so we can keep stats
4102 * accurately. Note that since we read the bytes from conn, and
4103 * we're writing the bytes onto the linked connection, we count
4104 * these as <i>written</i> bytes. */
4105 connection_buckets_decrement(linked, approx_time(), 0, n_read);
4106
4107 if (connection_flushed_some(linked) < 0)
4108 connection_mark_for_close(linked);
4109 if (!connection_wants_to_flush(linked))
4111 }
4112
4113 if (!buf_datalen(linked->outbuf) && conn->active_on_link)
4115 }
4116 /* If we hit the EOF, call connection_reached_eof(). */
4117 if (!conn->marked_for_close &&
4118 conn->inbuf_reached_eof &&
4119 connection_reached_eof(conn) < 0) {
4120 return -1;
4121 }
4122 return 0;
4123}
4124
4125/* DOCDOC connection_handle_read */
4126int
4127connection_handle_read(connection_t *conn)
4128{
4129 int res;
4130 update_current_time(time(NULL));
4131 res = connection_handle_read_impl(conn);
4132 return res;
4133}
4134
4135/** Pull in new bytes from conn->s or conn->linked_conn onto conn->inbuf,
4136 * either directly or via TLS. Reduce the token buckets by the number of bytes
4137 * read.
4138 *
4139 * If *max_to_read is -1, then decide it ourselves, else go with the
4140 * value passed to us. When returning, if it's changed, subtract the
4141 * number of bytes we read from *max_to_read.
4142 *
4143 * Return -1 if we want to break conn, else return 0.
4144 */
4145STATIC int
4147 int *socket_error)
4148{
4149 int result;
4150 ssize_t at_most = *max_to_read;
4151 size_t slack_in_buf, more_to_read;
4152 size_t n_read = 0, n_written = 0;
4153
4154 if (at_most == -1) { /* we need to initialize it */
4155 /* how many bytes are we allowed to read? */
4156 at_most = connection_bucket_read_limit(conn, approx_time());
4157 }
4158
4159 /* Do not allow inbuf to grow past BUF_MAX_LEN. */
4160 const ssize_t maximum = BUF_MAX_LEN - buf_datalen(conn->inbuf);
4161 if (at_most > maximum) {
4162 at_most = maximum;
4163 }
4164
4165 slack_in_buf = buf_slack(conn->inbuf);
4166 again:
4167 if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
4168 more_to_read = at_most - slack_in_buf;
4169 at_most = slack_in_buf;
4170 } else {
4171 more_to_read = 0;
4172 }
4173
4174 if (connection_speaks_cells(conn) &&
4176 int pending;
4177 or_connection_t *or_conn = TO_OR_CONN(conn);
4178 size_t initial_size;
4179 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING) {
4180 /* continue handshaking even if global token bucket is empty */
4181 return connection_tls_continue_handshake(or_conn);
4182 }
4183
4184 log_debug(LD_NET,
4185 "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
4186 " at_most %ld.",
4187 (int)conn->s,(long)buf_datalen(conn->inbuf),
4188 tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
4189
4190 initial_size = buf_datalen(conn->inbuf);
4191 /* else open, or closing */
4192 result = buf_read_from_tls(conn->inbuf, or_conn->tls, at_most);
4193 if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
4194 or_conn->tls_error = result;
4195 else
4196 or_conn->tls_error = 0;
4197
4198 switch (result) {
4199 case TOR_TLS_CLOSE:
4200 case TOR_TLS_ERROR_IO:
4201 log_debug(LD_NET,"TLS %s closed %son read. Closing.",
4202 connection_describe(conn),
4203 result == TOR_TLS_CLOSE ? "cleanly " : "");
4204 return result;
4206 log_debug(LD_NET,"tls error [%s] from %s. Breaking.",
4207 tor_tls_err_to_string(result),
4208 connection_describe(conn));
4209 return result;
4210 case TOR_TLS_WANTWRITE:
4212 return 0;
4213 case TOR_TLS_WANTREAD:
4214 if (conn->in_connection_handle_write) {
4215 /* We've been invoked from connection_handle_write, because we're
4216 * waiting for a TLS renegotiation, the renegotiation started, and
4217 * SSL_read returned WANTWRITE. But now SSL_read is saying WANTREAD
4218 * again. Stop waiting for write events now, or else we'll
4219 * busy-loop until data arrives for us to read.
4220 * XXX: remove this when v2 handshakes support is dropped. */
4221 // XXXX Try to make sense of what is going on here.
4223 if (!connection_is_reading(conn))
4225 }
4226 /* we're already reading, one hopes */
4227 break;
4228 case TOR_TLS_DONE: /* no data read, so nothing to process */
4229 break; /* so we call bucket_decrement below */
4230 default:
4231 break;
4232 }
4233 pending = tor_tls_get_pending_bytes(or_conn->tls);
4234 if (pending) {
4235 /* If we have any pending bytes, we read them now. This *can*
4236 * take us over our read allotment, but really we shouldn't be
4237 * believing that SSL bytes are the same as TCP bytes anyway. */
4238 int r2 = buf_read_from_tls(conn->inbuf, or_conn->tls, pending);
4239 if (BUG(r2<0)) {
4240 log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
4241 return -1;
4242 }
4243 }
4244 result = (int)(buf_datalen(conn->inbuf)-initial_size);
4245 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
4246 log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
4247 result, (long)n_read, (long)n_written);
4248 } else if (conn->linked) {
4249 if (conn->linked_conn) {
4250 result = (int) buf_move_all(conn->inbuf, conn->linked_conn->outbuf);
4251 } else {
4252 result = 0;
4253 }
4254 //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
4255 /* If the other side has disappeared, or if it's been marked for close and
4256 * we flushed its outbuf, then we should set our inbuf_reached_eof. */
4257 if (!conn->linked_conn ||
4258 (conn->linked_conn->marked_for_close &&
4259 buf_datalen(conn->linked_conn->outbuf) == 0))
4260 conn->inbuf_reached_eof = 1;
4261
4262 n_read = (size_t) result;
4263 } else {
4264 /* !connection_speaks_cells, !conn->linked_conn. */
4265 int reached_eof = 0;
4266 CONN_LOG_PROTECT(conn,
4267 result = buf_read_from_socket(conn->inbuf, conn->s,
4268 at_most,
4269 &reached_eof,
4270 socket_error));
4271 if (reached_eof)
4272 conn->inbuf_reached_eof = 1;
4273
4274// log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
4275
4276 if (result < 0)
4277 return -1;
4278 n_read = (size_t) result;
4279 }
4280
4281 if (n_read > 0) {
4282 /* change *max_to_read */
4283 *max_to_read = at_most - n_read;
4284
4285 /* Onion service application connection. Note read bytes for metrics. */
4286 if (CONN_IS_EDGE(conn) && TO_EDGE_CONN(conn)->hs_ident) {
4287 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
4288 hs_metrics_app_read_bytes(&edge_conn->hs_ident->identity_pk,
4289 edge_conn->hs_ident->orig_virtual_port,
4290 n_read);
4291 }
4292
4293 /* Update edge_conn->n_read */
4294 if (conn->type == CONN_TYPE_AP) {
4295 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
4296
4297 /* Check for overflow: */
4298 if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_read > n_read))
4299 edge_conn->n_read += (int)n_read;
4300 else
4301 edge_conn->n_read = UINT32_MAX;
4302 }
4303
4304 /* If CONN_BW events are enabled, update conn->n_read_conn_bw for
4305 * OR/DIR/EXIT connections, checking for overflow. */
4306 if (get_options()->TestingEnableConnBwEvent &&
4307 (conn->type == CONN_TYPE_OR ||
4308 conn->type == CONN_TYPE_DIR ||
4309 conn->type == CONN_TYPE_EXIT)) {
4310 if (PREDICT_LIKELY(UINT32_MAX - conn->n_read_conn_bw > n_read))
4311 conn->n_read_conn_bw += (int)n_read;
4312 else
4313 conn->n_read_conn_bw = UINT32_MAX;
4314 }
4315 }
4316
4317 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
4318
4319 if (more_to_read && result == at_most) {
4320 slack_in_buf = buf_slack(conn->inbuf);
4321 at_most = more_to_read;
4322 goto again;
4323 }
4324
4325 /* Call even if result is 0, since the global read bucket may
4326 * have reached 0 on a different conn, and this connection needs to
4327 * know to stop reading. */
4329 if (n_written > 0 && connection_is_writing(conn))
4331
4332 return 0;
4333}
4334
4335/** A pass-through to fetch_from_buf. */
4336int
4337connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
4338{
4339 return buf_get_bytes(conn->inbuf, string, len);
4340}
4341
4342/** As buf_get_line(), but read from a connection's input buffer. */
4343int
4345 size_t *data_len)
4346{
4347 return buf_get_line(conn->inbuf, data, data_len);
4348}
4349
4350/** As fetch_from_buf_http, but fetches from a connection's input buffer_t as
4351 * appropriate. */
4352int
4354 char **headers_out, size_t max_headerlen,
4355 char **body_out, size_t *body_used,
4356 size_t max_bodylen, int force_complete)
4357{
4358 return fetch_from_buf_http(conn->inbuf, headers_out, max_headerlen,
4359 body_out, body_used, max_bodylen, force_complete);
4360}
4361
4362/** Return true if this connection has data to flush. */
4363int
4365{
4366 return connection_get_outbuf_len(conn) > 0;
4367}
4368
4369/** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
4370 * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
4371 * connection_edge_consider_sending_sendme().
4372 */
4373int
4375{
4376 return connection_get_outbuf_len(conn) > 10*CELL_PAYLOAD_SIZE;
4377}
4378
4379/**
4380 * On Windows Vista and Windows 7, tune the send buffer size according to a
4381 * hint from the OS.
4382 *
4383 * This should help fix slow upload rates.
4384 */
4385static void
4387{
4388#ifdef _WIN32
4389 /* We only do this on Vista and 7, because earlier versions of Windows
4390 * don't have the SIO_IDEAL_SEND_BACKLOG_QUERY functionality, and on
4391 * later versions it isn't necessary. */
4392 static int isVistaOr7 = -1;
4393 if (isVistaOr7 == -1) {
4394 isVistaOr7 = 0;
4395 OSVERSIONINFO osvi = { 0 };
4396 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
4397 GetVersionEx(&osvi);
4398 if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion < 2)
4399 isVistaOr7 = 1;
4400 }
4401 if (!isVistaOr7)
4402 return;
4403 if (get_options()->ConstrainedSockets)
4404 return;
4405 ULONG isb = 0;
4406 DWORD bytesReturned = 0;
4407 if (!WSAIoctl(sock, SIO_IDEAL_SEND_BACKLOG_QUERY, NULL, 0,
4408 &isb, sizeof(isb), &bytesReturned, NULL, NULL)) {
4409 setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (const char*)&isb, sizeof(isb));
4410 }
4411#else /* !defined(_WIN32) */
4412 (void) sock;
4413#endif /* defined(_WIN32) */
4414}
4415
4416/** Try to flush more bytes onto <b>conn</b>->s.
4417 *
4418 * This function is called in connection_handle_write(), which gets
4419 * called from conn_write_callback() in main.c when libevent tells us
4420 * that <b>conn</b> wants to write.
4421 *
4422 * Update <b>conn</b>->timestamp_last_write_allowed to now, and call flush_buf
4423 * or flush_buf_tls appropriately. If it succeeds and there are no more
4424 * more bytes on <b>conn</b>->outbuf, then call connection_finished_flushing
4425 * on it too.
4426 *
4427 * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
4428 * limits. (Used for flushing messages to controller connections on fatal
4429 * errors.)
4430 *
4431 * Mark the connection and return -1 if you want to close it, else
4432 * return 0.
4433 */
4434static int
4436{
4437 int e;
4438 socklen_t len=(socklen_t)sizeof(e);
4439 int result;
4440 ssize_t max_to_write;
4441 time_t now = approx_time();
4442 size_t n_read = 0, n_written = 0;
4443 int dont_stop_writing = 0;
4444
4446
4447 if (conn->marked_for_close || !SOCKET_OK(conn->s))
4448 return 0; /* do nothing */
4449
4450 if (conn->in_flushed_some) {
4451 log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
4452 return 0;
4453 }
4454
4455 conn->timestamp_last_write_allowed = now;
4456
4458
4459 /* Sometimes, "writable" means "connected". */
4461 if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
4462 log_warn(LD_BUG, "getsockopt() syscall failed");
4463 if (conn->type == CONN_TYPE_OR) {
4464 or_connection_t *orconn = TO_OR_CONN(conn);
4466 } else {
4467 if (CONN_IS_EDGE(conn)) {
4469 }
4470 connection_mark_for_close(conn);
4471 }
4472 return -1;
4473 }
4474 if (e) {
4475 /* some sort of error, but maybe just inprogress still */
4476 if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
4477 log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
4478 tor_socket_strerror(e));
4479 if (CONN_IS_EDGE(conn))
4481 if (conn->type == CONN_TYPE_OR)
4484 tor_socket_strerror(e));
4485
4487 /*
4488 * This can bypass normal channel checking since we did
4489 * connection_or_notify_error() above.
4490 */
4491 connection_mark_for_close_internal(conn);
4492 return -1;
4493 } else {
4494 return 0; /* no change, see if next time is better */
4495 }
4496 }
4497 /* The connection is successful. */
4499 return -1;
4500 }
4501
4502 max_to_write = force ? (ssize_t)buf_datalen(conn->outbuf)
4503 : connection_bucket_write_limit(conn, now);
4504
4505 if (connection_speaks_cells(conn) &&
4507 or_connection_t *or_conn = TO_OR_CONN(conn);
4508 size_t initial_size;
4509 if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING) {
4511 if (connection_tls_continue_handshake(or_conn) < 0) {
4512 /* Don't flush; connection is dead. */
4514 END_OR_CONN_REASON_MISC,
4515 "TLS error in connection_tls_"
4516 "continue_handshake()");
4518 /*
4519 * This can bypass normal channel checking since we did
4520 * connection_or_notify_error() above.
4521 */
4522 connection_mark_for_close_internal(conn);
4523 return -1;
4524 }
4525 return 0;
4526 } else if (conn->state == OR_CONN_STATE_SERVER_VERSIONS_WAIT) {
4527 return connection_handle_read(conn);
4528 }
4529
4530 /* else open, or closing */
4531 initial_size = buf_datalen(conn->outbuf);
4532 result = buf_flush_to_tls(conn->outbuf, or_conn->tls,
4533 max_to_write);
4534
4535 if (result >= 0)
4537
4538 /* If we just flushed the last bytes, tell the channel on the
4539 * or_conn to check if it needs to geoip_change_dirreq_state() */
4540 /* XXXX move this to flushed_some or finished_flushing -NM */
4541 if (buf_datalen(conn->outbuf) == 0 && or_conn->chan)
4542 channel_notify_flushed(TLS_CHAN_TO_BASE(or_conn->chan));
4543
4544 switch (result) {
4546 case TOR_TLS_CLOSE:
4547 or_conn->tls_error = result;
4548 log_info(LD_NET, result != TOR_TLS_CLOSE ?
4549 "tls error. breaking.":"TLS connection closed on flush");
4550 /* Don't flush; connection is dead. */
4552 END_OR_CONN_REASON_MISC,
4553 result != TOR_TLS_CLOSE ?
4554 "TLS error in during flush" :
4555 "TLS closed during flush");
4557 /*
4558 * This can bypass normal channel checking since we did
4559 * connection_or_notify_error() above.
4560 */
4561 connection_mark_for_close_internal(conn);
4562 return -1;
4563 case TOR_TLS_WANTWRITE:
4564 log_debug(LD_NET,"wanted write.");
4565 /* we're already writing */
4566 dont_stop_writing = 1;
4567 break;
4568 case TOR_TLS_WANTREAD:
4569 /* Make sure to avoid a loop if the receive buckets are empty. */
4570 log_debug(LD_NET,"wanted read.");
4571 if (!connection_is_reading(conn)) {
4573 /* we'll start reading again when we get more tokens in our
4574 * read bucket; then we'll start writing again too.
4575 */
4576 }
4577 /* else no problem, we're already reading */
4578 return 0;
4579 /* case TOR_TLS_DONE:
4580 * for TOR_TLS_DONE, fall through to check if the flushlen
4581 * is empty, so we can stop writing.
4582 */
4583 }
4584
4585 tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
4586 log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
4587 result, (long)n_read, (long)n_written);
4588 or_conn->bytes_xmitted += result;
4589 or_conn->bytes_xmitted_by_tls += n_written;
4590 /* So we notice bytes were written even on error */
4591 /* XXXX This cast is safe since we can never write INT_MAX bytes in a
4592 * single set of TLS operations. But it looks kinda ugly. If we refactor
4593 * the *_buf_tls functions, we should make them return ssize_t or size_t
4594 * or something. */
4595 result = (int)(initial_size-buf_datalen(conn->outbuf));
4596 } else {
4597 CONN_LOG_PROTECT(conn,
4598 result = buf_flush_to_socket(conn->outbuf, conn->s,
4599 max_to_write));
4600 if (result < 0) {
4601 if (CONN_IS_EDGE(conn))
4603 if (conn->type == CONN_TYPE_AP) {
4604 /* writing failed; we couldn't send a SOCKS reply if we wanted to */
4606 }
4607
4608 /* The OR error is reported before immediate close cancels
4609 * attribution. */
4610 if (conn->type == CONN_TYPE_OR)
4612 connection_close_immediate(conn); /* Don't flush; connection is dead. */
4613 if (conn->type != CONN_TYPE_OR)
4614 connection_mark_for_close(conn);
4615 return -1;
4616 }
4618 n_written = (size_t) result;
4619 }
4620
4621 if (n_written && conn->type == CONN_TYPE_AP) {
4622 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
4623
4624 /* Check for overflow: */
4625 if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_written > n_written))
4626 edge_conn->n_written += (int)n_written;
4627 else
4628 edge_conn->n_written = UINT32_MAX;
4629 }
4630
4631 /* If CONN_BW events are enabled, update conn->n_written_conn_bw for
4632 * OR/DIR/EXIT connections, checking for overflow. */
4633 if (n_written && get_options()->TestingEnableConnBwEvent &&
4634 (conn->type == CONN_TYPE_OR ||
4635 conn->type == CONN_TYPE_DIR ||
4636 conn->type == CONN_TYPE_EXIT)) {
4637 if (PREDICT_LIKELY(UINT32_MAX - conn->n_written_conn_bw > n_written))
4638 conn->n_written_conn_bw += (int)n_written;
4639 else
4640 conn->n_written_conn_bw = UINT32_MAX;
4641 }
4642
4643 connection_buckets_decrement(conn, approx_time(), n_read, n_written);
4644
4645 if (result > 0) {
4646 /* If we wrote any bytes from our buffer, then call the appropriate
4647 * functions. */
4648 if (connection_flushed_some(conn) < 0) {
4649 if (connection_speaks_cells(conn)) {
4651 END_OR_CONN_REASON_MISC,
4652 "Got error back from "
4653 "connection_flushed_some()");
4654 }
4655
4656 /*
4657 * This can bypass normal channel checking since we did
4658 * connection_or_notify_error() above.
4659 */
4660 connection_mark_for_close_internal(conn);
4661 }
4662 }
4663
4664 if (!connection_wants_to_flush(conn) &&
4665 !dont_stop_writing) { /* it's done flushing */
4666 if (connection_finished_flushing(conn) < 0) {
4667 /* already marked */
4668 goto err;
4669 }
4670 goto done;
4671 }
4672
4673 /* Call even if result is 0, since the global write bucket may
4674 * have reached 0 on a different conn, and this connection needs to
4675 * know to stop writing. */
4677 if (n_read > 0 && connection_is_reading(conn))
4679
4680 done:
4681 /* If this is an edge connection with congestion control, check to see
4682 * if it is time to send an xon */
4683 if (conn_uses_flow_control(conn)) {
4684 flow_control_decide_xon(TO_EDGE_CONN(conn), n_written);
4685 }
4686
4687 return 0;
4688
4689 err:
4690 return -1;
4691}
4692
4693/* DOCDOC connection_handle_write */
4694int
4695connection_handle_write(connection_t *conn, int force)
4696{
4697 int res;
4698 update_current_time(time(NULL));
4699 /* connection_handle_write_impl() might call connection_handle_read()
4700 * if we're in the middle of a v2 handshake, in which case it needs this
4701 * flag set. */
4703 res = connection_handle_write_impl(conn, force);
4705 return res;
4706}
4707
4708/**
4709 * Try to flush data that's waiting for a write on <b>conn</b>. Return
4710 * -1 on failure, 0 on success.
4711 *
4712 * Don't use this function for regular writing; the buffers
4713 * system should be good enough at scheduling writes there. Instead, this
4714 * function is for cases when we're about to exit or something and we want
4715 * to report it right away.
4716 */
4717int
4719{
4720 return connection_handle_write(conn, 1);
4721}
4722
4723/** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4724 *
4725 * Return true iff it is okay to queue bytes on <b>conn</b>'s outbuf for
4726 * writing.
4727 */
4728static int
4730{
4731 /* if it's marked for close, only allow write if we mean to flush it */
4732 if (conn->marked_for_close && !conn->hold_open_until_flushed)
4733 return 0;
4734
4735 return 1;
4736}
4737
4738/** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4739 *
4740 * Called when an attempt to add bytes on <b>conn</b>'s outbuf has failed;
4741 * mark the connection and warn as appropriate.
4742 */
4743static void
4745{
4746 if (CONN_IS_EDGE(conn)) {
4747 /* if it failed, it means we have our package/delivery windows set
4748 wrong compared to our max outbuf size. close the whole circuit. */
4749 log_warn(LD_NET,
4750 "write_to_buf failed. Closing circuit (fd %d).", (int)conn->s);
4751 circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
4752 END_CIRC_REASON_INTERNAL);
4753 } else if (conn->type == CONN_TYPE_OR) {
4754 or_connection_t *orconn = TO_OR_CONN(conn);
4755 log_warn(LD_NET,
4756 "write_to_buf failed on an orconn; notifying of error "
4757 "(fd %d)", (int)(conn->s));
4758 /* Attribution exception: Tor cannot queue its own output. This is a
4759 * local queue-limit/invariant failure, not a failed establishment result.
4760 * Like OOS eviction, it is a distinct disposal decision with a single
4761 * cancellation site; opaque TLS/protocol errors are deliberately not
4762 * given per-cause exceptions. Cancellation here prevents the shared error
4763 * close from blaming the guard. */
4764 assert_connection_ok(conn, 0);
4765 if (orconn->chan)
4766 channel_note_establishment_cancelled(TLS_CHAN_TO_BASE(orconn->chan));
4768 } else {
4769 log_warn(LD_NET,
4770 "write_to_buf failed. Closing connection (fd %d).",
4771 (int)conn->s);
4772 connection_mark_for_close(conn);
4773 }
4774}
4775
4776/** Helper for connection_write_to_buf_impl and connection_write_buf_to_buf:
4777 *
4778 * Called when an attempt to add bytes on <b>conn</b>'s outbuf has succeeded:
4779 * start writing if appropriate.
4780 */
4781static void
4783{
4784 /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
4785 * state, we don't want to try to write it right away, since
4786 * conn->write_event won't be set yet. Otherwise, write data from
4787 * this conn as the socket is available. */
4788 if (conn->write_event) {
4790 }
4791}
4792
4793/** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
4794 * outbuf, and ask it to start writing.
4795 *
4796 * If <b>zlib</b> is nonzero, this is a directory connection that should get
4797 * its contents compressed or decompressed as they're written. If zlib is
4798 * negative, this is the last data to be compressed, and the connection's zlib
4799 * state should be flushed.
4800 */
4801MOCK_IMPL(void,
4802connection_write_to_buf_impl_,(const char *string, size_t len,
4803 connection_t *conn, int zlib))
4804{
4805 /* XXXX This function really needs to return -1 on failure. */
4806 int r;
4807 if (!len && !(zlib<0))
4808 return;
4809
4810 if (!connection_may_write_to_buf(conn))
4811 return;
4812
4813 if (zlib) {
4814 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
4815 int done = zlib < 0;
4817 dir_conn->compress_state,
4818 string, len, done));
4819 } else {
4820 CONN_LOG_PROTECT(conn, r = buf_add(conn->outbuf, string, len));
4821 }
4822 if (r < 0) {
4824 return;
4825 }
4827}
4828
4829/**
4830 * Write a <b>string</b> (of size <b>len</b> to directory connection
4831 * <b>dir_conn</b>. Apply compression if connection is configured to use
4832 * it and finalize it if <b>done</b> is true.
4833 */
4834void
4835connection_dir_buf_add(const char *string, size_t len,
4836 dir_connection_t *dir_conn, int done)
4837{
4838 if (dir_conn->compress_state != NULL) {
4839 connection_buf_add_compress(string, len, dir_conn, done);
4840 return;
4841 }
4842
4843 connection_buf_add(string, len, TO_CONN(dir_conn));
4844}
4845
4846void
4847connection_buf_add_compress(const char *string, size_t len,
4848 dir_connection_t *conn, int done)
4849{
4850 connection_write_to_buf_impl_(string, len, TO_CONN(conn), done ? -1 : 1);
4851}
4852
4853/**
4854 * Add all bytes from <b>buf</b> to <b>conn</b>'s outbuf, draining them
4855 * from <b>buf</b>. (If the connection is marked and will soon be closed,
4856 * nothing is drained.)
4857 */
4858void
4860{
4861 tor_assert(conn);
4862 tor_assert(buf);
4863 size_t len = buf_datalen(buf);
4864 if (len == 0)
4865 return;
4866
4867 if (!connection_may_write_to_buf(conn))
4868 return;
4869
4870 buf_move_all(conn->outbuf, buf);
4872}
4873
4874#define CONN_GET_ALL_TEMPLATE(var, test) \
4875 STMT_BEGIN \
4876 smartlist_t *conns = get_connection_array(); \
4877 smartlist_t *ret_conns = smartlist_new(); \
4878 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, var) { \
4879 if (var && (test) && !var->marked_for_close) \
4880 smartlist_add(ret_conns, var); \
4881 } SMARTLIST_FOREACH_END(var); \
4882 return ret_conns; \
4883 STMT_END
4884
4885/* Return a list of connections that aren't close and matches the given type
4886 * and state. The returned list can be empty and must be freed using
4887 * smartlist_free(). The caller does NOT have ownership of the objects in the
4888 * list so it must not free them nor reference them as they can disappear. */
4890connection_list_by_type_state(int type, int state)
4891{
4892 CONN_GET_ALL_TEMPLATE(conn, (conn->type == type && conn->state == state));
4893}
4894
4895/* Return a list of connections that aren't close and matches the given type
4896 * and purpose. The returned list can be empty and must be freed using
4897 * smartlist_free(). The caller does NOT have ownership of the objects in the
4898 * list so it must not free them nor reference them as they can disappear. */
4900connection_list_by_type_purpose(int type, int purpose)
4901{
4902 CONN_GET_ALL_TEMPLATE(conn,
4903 (conn->type == type && conn->purpose == purpose));
4904}
4905
4906/** Return a connection_t * from get_connection_array() that satisfies test on
4907 * var, and that is not marked for close. */
4908#define CONN_GET_TEMPLATE(var, test) \
4909 STMT_BEGIN \
4910 smartlist_t *conns = get_connection_array(); \
4911 SMARTLIST_FOREACH(conns, connection_t *, var, \
4912 { \
4913 if (var && (test) && !var->marked_for_close) \
4914 return var; \
4915 }); \
4916 return NULL; \
4917 STMT_END
4918
4919/** Return a connection with given type, address, port, and purpose;
4920 * or NULL if no such connection exists (or if all such connections are marked
4921 * for close). */
4924 const tor_addr_t *addr, uint16_t port,
4925 int purpose))
4926{
4927 CONN_GET_TEMPLATE(conn,
4928 (conn->type == type &&
4929 tor_addr_eq(&conn->addr, addr) &&
4930 conn->port == port &&
4931 conn->purpose == purpose));
4932}
4933
4934/** Return the stream with id <b>id</b> if it is not already marked for
4935 * close.
4936 */
4939{
4940 CONN_GET_TEMPLATE(conn, conn->global_identifier == id);
4941}
4942
4943/** Return a connection of type <b>type</b> that is not marked for close.
4944 */
4947{
4948 CONN_GET_TEMPLATE(conn, conn->type == type);
4949}
4950
4951/** Return a connection of type <b>type</b> that is in state <b>state</b>,
4952 * and that is not marked for close.
4953 */
4956{
4957 CONN_GET_TEMPLATE(conn, conn->type == type && conn->state == state);
4958}
4959
4960/**
4961 * Return a connection of type <b>type</b> that is not an internally linked
4962 * connection, and is not marked for close.
4963 **/
4966{
4967 CONN_GET_TEMPLATE(conn, conn->type == type && !conn->linked);
4968}
4969
4970/** Return a new smartlist of dir_connection_t * from get_connection_array()
4971 * that satisfy conn_test on connection_t *conn_var, and dirconn_test on
4972 * dir_connection_t *dirconn_var. conn_var must be of CONN_TYPE_DIR and not
4973 * marked for close to be included in the list. */
4974#define DIR_CONN_LIST_TEMPLATE(conn_var, conn_test, \
4975 dirconn_var, dirconn_test) \
4976 STMT_BEGIN \
4977 smartlist_t *conns = get_connection_array(); \
4978 smartlist_t *dir_conns = smartlist_new(); \
4979 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn_var) { \
4980 if (conn_var && (conn_test) \
4981 && conn_var->type == CONN_TYPE_DIR \
4982 && !conn_var->marked_for_close) { \
4983 dir_connection_t *dirconn_var = TO_DIR_CONN(conn_var); \
4984 if (dirconn_var && (dirconn_test)) { \
4985 smartlist_add(dir_conns, dirconn_var); \
4986 } \
4987 } \
4988 } SMARTLIST_FOREACH_END(conn_var); \
4989 return dir_conns; \
4990 STMT_END
4991
4992/** Return a list of directory connections that are fetching the item
4993 * described by <b>purpose</b>/<b>resource</b>. If there are none,
4994 * return an empty list. This list must be freed using smartlist_free,
4995 * but the pointers in it must not be freed.
4996 * Note that this list should not be cached, as the pointers in it can be
4997 * freed if their connections close. */
5000 int purpose,
5001 const char *resource)
5002{
5004 conn->purpose == purpose,
5005 dirconn,
5006 0 == strcmp_opt(resource,
5007 dirconn->requested_resource));
5008}
5009
5010/** Return a list of directory connections that are fetching the item
5011 * described by <b>purpose</b>/<b>resource</b>/<b>state</b>. If there are
5012 * none, return an empty list. This list must be freed using smartlist_free,
5013 * but the pointers in it must not be freed.
5014 * Note that this list should not be cached, as the pointers in it can be
5015 * freed if their connections close. */
5018 int purpose,
5019 const char *resource,
5020 int state)
5021{
5023 conn->purpose == purpose && conn->state == state,
5024 dirconn,
5025 0 == strcmp_opt(resource,
5026 dirconn->requested_resource));
5027}
5028
5029#undef DIR_CONN_LIST_TEMPLATE
5030
5031/** Return an arbitrary active OR connection that isn't <b>this_conn</b>.
5032 *
5033 * We use this to guess if we should tell the controller that we
5034 * didn't manage to connect to any of our bridges. */
5035static connection_t *
5037{
5038 CONN_GET_TEMPLATE(conn,
5039 conn != TO_CONN(this_conn) && conn->type == CONN_TYPE_OR);
5040}
5041
5042/** Return 1 if there are any active OR connections apart from
5043 * <b>this_conn</b>.
5044 *
5045 * We use this to guess if we should tell the controller that we
5046 * didn't manage to connect to any of our bridges. */
5047int
5049{
5051 if (conn != NULL) {
5052 log_debug(LD_DIR, "%s: Found an OR connection: %s",
5053 __func__, connection_describe(conn));
5054 return 1;
5055 }
5056
5057 return 0;
5058}
5059
5060#undef CONN_GET_TEMPLATE
5061
5062/** Return 1 if <b>conn</b> is a listener conn, else return 0. */
5063int
5065{
5066 if (conn->type == CONN_TYPE_OR_LISTENER ||
5068 conn->type == CONN_TYPE_AP_LISTENER ||
5073 conn->type == CONN_TYPE_DIR_LISTENER ||
5076 return 1;
5077 return 0;
5078}
5079
5080/** Return 1 if <b>conn</b> is in state "open" and is not marked
5081 * for close, else return 0.
5082 */
5083int
5085{
5086 tor_assert(conn);
5087
5088 if (conn->marked_for_close)
5089 return 0;
5090
5091 if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
5092 (conn->type == CONN_TYPE_EXT_OR) ||
5093 (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
5094 (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
5095 (conn->type == CONN_TYPE_CONTROL &&
5097 return 1;
5098
5099 return 0;
5100}
5101
5102/** Return 1 if conn is in 'connecting' state, else return 0. */
5103int
5105{
5106 tor_assert(conn);
5107
5108 if (conn->marked_for_close)
5109 return 0;
5110 switch (conn->type)
5111 {
5112 case CONN_TYPE_OR:
5113 return conn->state == OR_CONN_STATE_CONNECTING;
5114 case CONN_TYPE_EXIT:
5115 return conn->state == EXIT_CONN_STATE_CONNECTING;
5116 case CONN_TYPE_DIR:
5117 return conn->state == DIR_CONN_STATE_CONNECTING;
5118 }
5119
5120 return 0;
5121}
5122
5123/** Allocates a base64'ed authenticator for use in http or https
5124 * auth, based on the input string <b>authenticator</b>. Returns it
5125 * if success, else returns NULL. */
5126char *
5127alloc_http_authenticator(const char *authenticator)
5128{
5129 /* an authenticator in Basic authentication
5130 * is just the string "username:password" */
5131 const size_t authenticator_length = strlen(authenticator);
5132 const size_t base64_authenticator_length =
5133 base64_encode_size(authenticator_length, 0) + 1;
5134 char *base64_authenticator = tor_malloc(base64_authenticator_length);
5135 if (base64_encode(base64_authenticator, base64_authenticator_length,
5136 authenticator, authenticator_length, 0) < 0) {
5137 tor_free(base64_authenticator); /* free and set to null */
5138 }
5139 return base64_authenticator;
5140}
5141
5142/** Given a socket handle, check whether the local address (sockname) of the
5143 * socket is one that we've connected from before. If so, double-check
5144 * whether our address has changed and we need to generate keys. If we do,
5145 * call init_keys().
5146 */
5147static void
5149{
5150 tor_addr_t out_addr, iface_addr;
5151 tor_addr_t **last_interface_ip_ptr;
5152 sa_family_t family;
5153
5154 if (!outgoing_addrs)
5156
5157 if (tor_addr_from_getsockname(&out_addr, sock) < 0) {
5158 int e = tor_socket_errno(sock);
5159 log_warn(LD_NET, "getsockname() to check for address change failed: %s",
5160 tor_socket_strerror(e));
5161 return;
5162 }
5163 family = tor_addr_family(&out_addr);
5164
5165 if (family == AF_INET)
5166 last_interface_ip_ptr = &last_interface_ipv4;
5167 else if (family == AF_INET6)
5168 last_interface_ip_ptr = &last_interface_ipv6;
5169 else
5170 return;
5171
5172 if (! *last_interface_ip_ptr) {
5173 tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
5174 if (get_interface_address6(LOG_INFO, family, a)==0) {
5175 *last_interface_ip_ptr = a;
5176 } else {
5177 tor_free(a);
5178 }
5179 }
5180
5181 /* If we've used this address previously, we're okay. */
5183 if (tor_addr_eq(a_ptr, &out_addr))
5184 return;
5185 );
5186
5187 /* Uh-oh. We haven't connected from this address before. Has the interface
5188 * address changed? */
5189 if (get_interface_address6(LOG_INFO, family, &iface_addr)<0)
5190 return;
5191
5192 if (tor_addr_eq(&iface_addr, *last_interface_ip_ptr)) {
5193 /* Nope, it hasn't changed. Add this address to the list. */
5194 smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
5195 } else {
5196 /* The interface changed. We're a client, so we need to regenerate our
5197 * keys. First, reset the state. */
5198 log_notice(LD_NET, "Our IP address has changed. Rotating keys...");
5199 tor_addr_copy(*last_interface_ip_ptr, &iface_addr);
5202 smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
5203 /* We'll need to resolve ourselves again. */
5204 resolved_addr_reset_last(AF_INET);
5205 /* Okay, now change our keys. */
5207 }
5208}
5209
5210/** Some systems have limited system buffers for recv and xmit on
5211 * sockets allocated in a virtual server or similar environment. For a Tor
5212 * server this can produce the "Error creating network socket: No buffer
5213 * space available" error once all available TCP buffer space is consumed.
5214 * This method will attempt to constrain the buffers allocated for the socket
5215 * to the desired size to stay below system TCP buffer limits.
5216 */
5217static void
5219{
5220 void *sz = (void*)&size;
5221 socklen_t sz_sz = (socklen_t) sizeof(size);
5222 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
5223 int e = tor_socket_errno(sock);
5224 log_warn(LD_NET, "setsockopt() to constrain send "
5225 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
5226 }
5227 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
5228 int e = tor_socket_errno(sock);
5229 log_warn(LD_NET, "setsockopt() to constrain recv "
5230 "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
5231 }
5232}
5233
5234/** Process new bytes that have arrived on conn->inbuf.
5235 *
5236 * This function just passes conn to the connection-specific
5237 * connection_*_process_inbuf() function. It also passes in
5238 * package_partial if wanted.
5239 */
5240int
5241connection_process_inbuf(connection_t *conn, int package_partial)
5242{
5243 tor_assert(conn);
5244
5245 switch (conn->type) {
5246 case CONN_TYPE_OR:
5248 case CONN_TYPE_EXT_OR:
5250 case CONN_TYPE_EXIT:
5251 case CONN_TYPE_AP:
5253 package_partial);
5254 case CONN_TYPE_DIR:
5256 case CONN_TYPE_CONTROL:
5258 case CONN_TYPE_METRICS:
5260 default:
5261 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5263 return -1;
5264 }
5265}
5266
5267/** Called whenever we've written data on a connection. */
5268static int
5270{
5271 int r = 0;
5273 conn->in_flushed_some = 1;
5274 if (conn->type == CONN_TYPE_DIR &&
5276 r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
5277 } else if (conn->type == CONN_TYPE_OR) {
5279 } else if (CONN_IS_EDGE(conn)) {
5281 }
5282 conn->in_flushed_some = 0;
5283 return r;
5284}
5285
5286/** We just finished flushing bytes to the appropriately low network layer,
5287 * and there are no more bytes remaining in conn->outbuf or
5288 * conn->tls to be flushed.
5289 *
5290 * This function just passes conn to the connection-specific
5291 * connection_*_finished_flushing() function.
5292 */
5293static int
5295{
5296 tor_assert(conn);
5297
5298 /* If the connection is closed, don't try to do anything more here. */
5299 if (CONN_IS_CLOSED(conn))
5300 return 0;
5301
5302// log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
5303
5305
5306 switch (conn->type) {
5307 case CONN_TYPE_OR:
5309 case CONN_TYPE_EXT_OR:
5311 case CONN_TYPE_AP:
5312 case CONN_TYPE_EXIT:
5314 case CONN_TYPE_DIR:
5316 case CONN_TYPE_CONTROL:
5318 case CONN_TYPE_METRICS:
5320 default:
5321 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5323 return -1;
5324 }
5325}
5326
5327/** Called when our attempt to connect() to a server has just succeeded.
5328 *
5329 * This function checks if the interface address has changed (clients only),
5330 * and then passes conn to the connection-specific
5331 * connection_*_finished_connecting() function.
5332 */
5333static int
5335{
5336 tor_assert(conn);
5337
5338 if (!server_mode(get_options())) {
5339 /* See whether getsockname() says our address changed. We need to do this
5340 * now that the connection has finished, because getsockname() on Windows
5341 * won't work until then. */
5343 }
5344
5345 switch (conn->type)
5346 {
5347 case CONN_TYPE_OR:
5349 case CONN_TYPE_EXIT:
5351 case CONN_TYPE_DIR:
5353 default:
5354 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5356 return -1;
5357 }
5358}
5359
5360/** Callback: invoked when a connection reaches an EOF event. */
5361static int
5363{
5364 switch (conn->type) {
5365 case CONN_TYPE_OR:
5366 case CONN_TYPE_EXT_OR:
5368 case CONN_TYPE_AP:
5369 case CONN_TYPE_EXIT:
5371 case CONN_TYPE_DIR:
5373 case CONN_TYPE_CONTROL:
5375 case CONN_TYPE_METRICS:
5376 return metrics_connection_reached_eof(conn);
5377 default:
5378 log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
5380 return -1;
5381 }
5382}
5383
5384/** Comparator for the two-orconn case in OOS victim sort */
5385static int
5387{
5388 int a_circs, b_circs;
5389 /* Fewer circuits == higher priority for OOS kill, sort earlier */
5390
5391 a_circs = connection_or_get_num_circuits(a);
5392 b_circs = connection_or_get_num_circuits(b);
5393
5394 if (a_circs < b_circs) return 1;
5395 else if (a_circs > b_circs) return -1;
5396 else return 0;
5397}
5398
5399/** Sort comparator for OOS victims; better targets sort before worse
5400 * ones. */
5401static int
5402oos_victim_comparator(const void **a_v, const void **b_v)
5403{
5404 connection_t *a = NULL, *b = NULL;
5405
5406 /* Get connection pointers out */
5407
5408 a = (connection_t *)(*a_v);
5409 b = (connection_t *)(*b_v);
5410
5411 tor_assert(a != NULL);
5412 tor_assert(b != NULL);
5413
5414 /*
5415 * We always prefer orconns as victims currently; we won't even see
5416 * these non-orconn cases, but if we do, sort them after orconns.
5417 */
5418 if (a->type == CONN_TYPE_OR && b->type == CONN_TYPE_OR) {
5420 } else {
5421 /*
5422 * One isn't an orconn; if one is, it goes first. We currently have no
5423 * opinions about cases where neither is an orconn.
5424 */
5425 if (a->type == CONN_TYPE_OR) return -1;
5426 else if (b->type == CONN_TYPE_OR) return 1;
5427 else return 0;
5428 }
5429}
5430
5431/** Pick n victim connections for the OOS handler and return them in a
5432 * smartlist.
5433 */
5436{
5437 smartlist_t *eligible = NULL, *victims = NULL;
5438 smartlist_t *conns;
5439 int conn_counts_by_type[CONN_TYPE_MAX_ + 1], i;
5440
5441 /*
5442 * Big damn assumption (someone improve this someday!):
5443 *
5444 * Socket exhaustion normally happens on high-volume relays, and so
5445 * most of the connections involved are orconns. We should pick victims
5446 * by assembling a list of all orconns, and sorting them in order of
5447 * how much 'damage' by some metric we'd be doing by dropping them.
5448 *
5449 * If we move on from orconns, we should probably think about incoming
5450 * directory connections next, or exit connections. Things we should
5451 * probably never kill are controller connections and listeners.
5452 *
5453 * This function will count how many connections of different types
5454 * exist and log it for purposes of gathering data on typical OOS
5455 * situations to guide future improvements.
5456 */
5457
5458 /* First, get the connection array */
5459 conns = get_connection_array();
5460 /*
5461 * Iterate it and pick out eligible connection types, and log some stats
5462 * along the way.
5463 */
5464 eligible = smartlist_new();
5465 memset(conn_counts_by_type, 0, sizeof(conn_counts_by_type));
5467 /* Bump the counter */
5468 tor_assert(c->type <= CONN_TYPE_MAX_);
5469 ++(conn_counts_by_type[c->type]);
5470
5471 /* Skip anything without a socket we can free */
5472 if (!(SOCKET_OK(c->s))) {
5473 continue;
5474 }
5475
5476 /* Skip anything we would count as moribund */
5477 if (connection_is_moribund(c)) {
5478 continue;
5479 }
5480
5481 switch (c->type) {
5482 case CONN_TYPE_OR:
5483 /* We've got an orconn, it's eligible to be OOSed */
5484 smartlist_add(eligible, c);
5485 break;
5486 default:
5487 /* We don't know what to do with it, ignore it */
5488 break;
5489 }
5490 } SMARTLIST_FOREACH_END(c);
5491
5492 /* Log some stats */
5493 if (smartlist_len(conns) > 0) {
5494 /* At least one counter must be non-zero */
5495 log_info(LD_NET, "Some stats on conn types seen during OOS follow");
5496 for (i = CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
5497 /* Did we see any? */
5498 if (conn_counts_by_type[i] > 0) {
5499 log_info(LD_NET, "%s: %d conns",
5501 conn_counts_by_type[i]);
5502 }
5503 }
5504 log_info(LD_NET, "Done with OOS conn type stats");
5505 }
5506
5507 /* Did we find more eligible targets than we want to kill? */
5508 if (smartlist_len(eligible) > n) {
5509 /* Sort the list in order of target preference */
5511 /* Pick first n as victims */
5512 victims = smartlist_new();
5513 for (i = 0; i < n; ++i) {
5514 smartlist_add(victims, smartlist_get(eligible, i));
5515 }
5516 /* Free the original list */
5517 smartlist_free(eligible);
5518 } else {
5519 /* No, we can just call them all victims */
5520 victims = eligible;
5521 }
5522
5523 return victims;
5524}
5525
5526/** Kill a list of connections for the OOS handler. */
5527MOCK_IMPL(STATIC void,
5529{
5530 if (!conns) return;
5531
5533 /* Make sure the channel layer gets told about orconns */
5534 if (c->type == CONN_TYPE_OR) {
5535 /* Attribution exception: socket pressure elsewhere can make Tor evict
5536 * a healthy opening connection. OOS and output-queue disposal have
5537 * explicit local decision points. Cancellation here exempts OOS eviction
5538 * without an error-code taxonomy for TLS, proxy, or protocol
5539 * failures. */
5541 if (TO_OR_CONN(c)->chan)
5543 TLS_CHAN_TO_BASE(TO_OR_CONN(c)->chan));
5545 } else {
5546 connection_mark_for_close(c);
5547 }
5548 } SMARTLIST_FOREACH_END(c);
5549
5550 log_notice(LD_NET,
5551 "OOS handler marked %d connections",
5552 smartlist_len(conns));
5553}
5554
5555/** Check if a connection is on the way out so the OOS handler doesn't try
5556 * to kill more than it needs. */
5557int
5559{
5560 if (conn != NULL &&
5561 (conn->conn_array_index < 0 ||
5562 conn->marked_for_close)) {
5563 return 1;
5564 } else {
5565 return 0;
5566 }
5567}
5568
5569/** Out-of-Sockets handler; n_socks is the current number of open
5570 * sockets, and failed is non-zero if a socket exhaustion related
5571 * error immediately preceded this call. This is where to do
5572 * circuit-killing heuristics as needed.
5573 */
5574void
5575connection_check_oos(int n_socks, int failed)
5576{
5577 int target_n_socks = 0, moribund_socks, socks_to_kill;
5578 smartlist_t *conns;
5579
5580 /* Early exit: is OOS checking disabled? */
5581 if (get_options()->DisableOOSCheck) {
5582 return;
5583 }
5584
5585 /* Sanity-check args */
5586 tor_assert(n_socks >= 0);
5587
5588 /*
5589 * Make some log noise; keep it at debug level since this gets a chance
5590 * to run on every connection attempt.
5591 */
5592 log_debug(LD_NET,
5593 "Running the OOS handler (%d open sockets, %s)",
5594 n_socks, (failed != 0) ? "exhaustion seen" : "no exhaustion");
5595
5596 /*
5597 * Check if we're really handling an OOS condition, and if so decide how
5598 * many sockets we want to get down to. Be sure we check if the threshold
5599 * is distinct from zero first; it's possible for this to be called a few
5600 * times before we've finished reading the config.
5601 */
5602 if (n_socks >= get_options()->ConnLimit_high_thresh &&
5603 get_options()->ConnLimit_high_thresh != 0 &&
5604 get_options()->ConnLimit_ != 0) {
5605 /* Try to get down to the low threshold */
5606 target_n_socks = get_options()->ConnLimit_low_thresh;
5607 log_notice(LD_NET,
5608 "Current number of sockets %d is greater than configured "
5609 "limit %d; OOS handler trying to get down to %d",
5610 n_socks, get_options()->ConnLimit_high_thresh,
5611 target_n_socks);
5612 } else if (failed) {
5613 /*
5614 * If we're not at the limit but we hit a socket exhaustion error, try to
5615 * drop some (but not as aggressively as ConnLimit_low_threshold, which is
5616 * 3/4 of ConnLimit_)
5617 */
5618 target_n_socks = (n_socks * 9) / 10;
5619 log_notice(LD_NET,
5620 "We saw socket exhaustion at %d open sockets; OOS handler "
5621 "trying to get down to %d",
5622 n_socks, target_n_socks);
5623 }
5624
5625 if (target_n_socks > 0) {
5626 /*
5627 * It's an OOS!
5628 *
5629 * Count moribund sockets; it's be important that anything we decide
5630 * to get rid of here but don't immediately close get counted as moribund
5631 * on subsequent invocations so we don't try to kill too many things if
5632 * connection_check_oos() gets called multiple times.
5633 */
5634 moribund_socks = connection_count_moribund();
5635
5636 if (moribund_socks < n_socks - target_n_socks) {
5637 socks_to_kill = n_socks - target_n_socks - moribund_socks;
5638
5639 conns = pick_oos_victims(socks_to_kill);
5640 if (conns) {
5642 log_notice(LD_NET,
5643 "OOS handler killed %d conns", smartlist_len(conns));
5644 smartlist_free(conns);
5645 } else {
5646 log_notice(LD_NET, "OOS handler failed to pick any victim conns");
5647 }
5648 } else {
5649 log_notice(LD_NET,
5650 "Not killing any sockets for OOS because there are %d "
5651 "already moribund, and we only want to eliminate %d",
5652 moribund_socks, n_socks - target_n_socks);
5653 }
5654 }
5655}
5656
5657/** Log how many bytes are used by buffers of different kinds and sizes. */
5658void
5660{
5661 uint64_t used_by_type[CONN_TYPE_MAX_+1];
5662 uint64_t alloc_by_type[CONN_TYPE_MAX_+1];
5663 int n_conns_by_type[CONN_TYPE_MAX_+1];
5664 uint64_t total_alloc = 0;
5665 uint64_t total_used = 0;
5666 int i;
5668
5669 memset(used_by_type, 0, sizeof(used_by_type));
5670 memset(alloc_by_type, 0, sizeof(alloc_by_type));
5671 memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
5672
5674 int tp = c->type;
5675 ++n_conns_by_type[tp];
5676 if (c->inbuf) {
5677 used_by_type[tp] += buf_datalen(c->inbuf);
5678 alloc_by_type[tp] += buf_allocation(c->inbuf);
5679 }
5680 if (c->outbuf) {
5681 used_by_type[tp] += buf_datalen(c->outbuf);
5682 alloc_by_type[tp] += buf_allocation(c->outbuf);
5683 }
5684 } SMARTLIST_FOREACH_END(c);
5685 for (i=0; i <= CONN_TYPE_MAX_; ++i) {
5686 total_used += used_by_type[i];
5687 total_alloc += alloc_by_type[i];
5688 }
5689
5690 tor_log(severity, LD_GENERAL,
5691 "In buffers for %d connections: %"PRIu64" used/%"PRIu64" allocated",
5692 smartlist_len(conns),
5693 (total_used), (total_alloc));
5694 for (i=CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
5695 if (!n_conns_by_type[i])
5696 continue;
5697 tor_log(severity, LD_GENERAL,
5698 " For %d %s connections: %"PRIu64" used/%"PRIu64" allocated",
5699 n_conns_by_type[i], conn_type_to_string(i),
5700 (used_by_type[i]), (alloc_by_type[i]));
5701 }
5702}
5703
5704/** Verify that connection <b>conn</b> has all of its invariants
5705 * correct. Trigger an assert if anything is invalid.
5706 */
5707void
5709{
5710 (void) now; /* XXXX unused. */
5711 tor_assert(conn);
5712 tor_assert(conn->type >= CONN_TYPE_MIN_);
5713 tor_assert(conn->type <= CONN_TYPE_MAX_);
5714
5715 switch (conn->type) {
5716 case CONN_TYPE_OR:
5717 case CONN_TYPE_EXT_OR:
5718 tor_assert(conn->magic == OR_CONNECTION_MAGIC);
5719 break;
5720 case CONN_TYPE_AP:
5721 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
5722 break;
5723 case CONN_TYPE_EXIT:
5724 tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
5725 break;
5726 case CONN_TYPE_DIR:
5727 tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
5728 break;
5729 case CONN_TYPE_CONTROL:
5730 tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
5731 break;
5732 CASE_ANY_LISTENER_TYPE:
5733 tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
5734 break;
5735 default:
5736 tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
5737 break;
5738 }
5739
5740 if (conn->linked_conn) {
5741 tor_assert(conn->linked_conn->linked_conn == conn);
5742 tor_assert(conn->linked);
5743 }
5744 if (conn->linked)
5745 tor_assert(!SOCKET_OK(conn->s));
5746
5747 if (conn->hold_open_until_flushed)
5749
5750 /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
5751 * marked_for_close. */
5752
5753 /* buffers */
5754 if (conn->inbuf)
5755 buf_assert_ok(conn->inbuf);
5756 if (conn->outbuf)
5757 buf_assert_ok(conn->outbuf);
5758
5759 if (conn->type == CONN_TYPE_OR) {
5760 or_connection_t *or_conn = TO_OR_CONN(conn);
5761 if (conn->state == OR_CONN_STATE_OPEN) {
5762 /* tor_assert(conn->bandwidth > 0); */
5763 /* the above isn't necessarily true: if we just did a TLS
5764 * handshake but we didn't recognize the other peer, or it
5765 * gave a bad cert/etc, then we won't have assigned bandwidth,
5766 * yet it will be open. -RD
5767 */
5768// tor_assert(conn->read_bucket >= 0);
5769 }
5770// tor_assert(conn->addr && conn->port);
5771 tor_assert(conn->address);
5773 tor_assert(or_conn->tls);
5774 }
5775
5776 if (CONN_IS_EDGE(conn)) {
5777 /* XXX unchecked: package window, deliver window. */
5778 if (conn->type == CONN_TYPE_AP) {
5779 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
5780 if (entry_conn->chosen_exit_optional || entry_conn->chosen_exit_retries)
5781 tor_assert(entry_conn->chosen_exit_name);
5782
5783 tor_assert(entry_conn->socks_request);
5784 if (conn->state == AP_CONN_STATE_OPEN) {
5786 if (!conn->marked_for_close) {
5787 tor_assert(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
5788 cpath_assert_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
5789 }
5790 }
5791 }
5792 if (conn->type == CONN_TYPE_EXIT) {
5794 conn->purpose == EXIT_PURPOSE_RESOLVE);
5795 }
5796 } else if (conn->type == CONN_TYPE_DIR) {
5797 } else {
5798 /* Purpose is only used for dir and exit types currently */
5799 tor_assert(!conn->purpose);
5800 }
5801
5802 switch (conn->type)
5803 {
5804 CASE_ANY_LISTENER_TYPE:
5806 break;
5807 case CONN_TYPE_OR:
5808 tor_assert(conn->state >= OR_CONN_STATE_MIN_);
5809 tor_assert(conn->state <= OR_CONN_STATE_MAX_);
5810 break;
5811 case CONN_TYPE_EXT_OR:
5813 tor_assert(conn->state <= EXT_OR_CONN_STATE_MAX_);
5814 break;
5815 case CONN_TYPE_EXIT:
5816 tor_assert(conn->state >= EXIT_CONN_STATE_MIN_);
5817 tor_assert(conn->state <= EXIT_CONN_STATE_MAX_);
5818 tor_assert(conn->purpose >= EXIT_PURPOSE_MIN_);
5819 tor_assert(conn->purpose <= EXIT_PURPOSE_MAX_);
5820 break;
5821 case CONN_TYPE_AP:
5822 tor_assert(conn->state >= AP_CONN_STATE_MIN_);
5823 tor_assert(conn->state <= AP_CONN_STATE_MAX_);
5824 tor_assert(TO_ENTRY_CONN(conn)->socks_request);
5825 break;
5826 case CONN_TYPE_DIR:
5827 tor_assert(conn->state >= DIR_CONN_STATE_MIN_);
5828 tor_assert(conn->state <= DIR_CONN_STATE_MAX_);
5829 tor_assert(conn->purpose >= DIR_PURPOSE_MIN_);
5830 tor_assert(conn->purpose <= DIR_PURPOSE_MAX_);
5831 break;
5832 case CONN_TYPE_CONTROL:
5833 tor_assert(conn->state >= CONTROL_CONN_STATE_MIN_);
5834 tor_assert(conn->state <= CONTROL_CONN_STATE_MAX_);
5835 break;
5836 case CONN_TYPE_METRICS:
5837 /* No state. */
5838 break;
5839 default:
5840 tor_assert(0);
5841 }
5842}
5843
5844/** Fills <b>addr</b> and <b>port</b> with the details of the global
5845 * proxy server we are using. Store a 1 to the int pointed to by
5846 * <b>is_put_out</b> if the connection is using a pluggable
5847 * transport; store 0 otherwise. <b>conn</b> contains the connection
5848 * we are using the proxy for.
5849 *
5850 * Return 0 on success, -1 on failure.
5851 */
5852int
5853get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type,
5854 int *is_pt_out, const connection_t *conn)
5855{
5856 const or_options_t *options = get_options();
5857
5858 *is_pt_out = 0;
5859 /* Client Transport Plugins can use another proxy, but that should be hidden
5860 * from the rest of tor (as the plugin is responsible for dealing with the
5861 * proxy), check it first, then check the rest of the proxy types to allow
5862 * the config to have unused ClientTransportPlugin entries.
5863 */
5864 if (options->ClientTransportPlugin) {
5865 const transport_t *transport = NULL;
5866 int r;
5867 r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
5868 if (r<0)
5869 return -1;
5870 if (transport) { /* transport found */
5871 tor_addr_copy(addr, &transport->addr);
5872 *port = transport->port;
5873 *proxy_type = transport->socks_version;
5874 *is_pt_out = 1;
5875 return 0;
5876 }
5877
5878 /* Unused ClientTransportPlugin. */
5879 }
5880
5881 if (options->HTTPSProxy) {
5882 tor_addr_copy(addr, &options->HTTPSProxyAddr);
5883 *port = options->HTTPSProxyPort;
5884 *proxy_type = PROXY_CONNECT;
5885 return 0;
5886 } else if (options->Socks4Proxy) {
5887 tor_addr_copy(addr, &options->Socks4ProxyAddr);
5888 *port = options->Socks4ProxyPort;
5889 *proxy_type = PROXY_SOCKS4;
5890 return 0;
5891 } else if (options->Socks5Proxy) {
5892 tor_addr_copy(addr, &options->Socks5ProxyAddr);
5893 *port = options->Socks5ProxyPort;
5894 *proxy_type = PROXY_SOCKS5;
5895 return 0;
5896 } else if (options->TCPProxy) {
5897 tor_addr_copy(addr, &options->TCPProxyAddr);
5898 *port = options->TCPProxyPort;
5899 /* The only supported protocol in TCPProxy is haproxy. */
5901 *proxy_type = PROXY_HAPROXY;
5902 return 0;
5903 }
5904
5906 *port = 0;
5907 *proxy_type = PROXY_NONE;
5908 return 0;
5909}
5910
5911/** Log a failed connection to a proxy server.
5912 * <b>conn</b> is the connection we use the proxy server for. */
5913void
5915{
5916 tor_addr_t proxy_addr;
5917 uint16_t proxy_port;
5918 int proxy_type, is_pt;
5919
5920 if (get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, &is_pt,
5921 conn) != 0)
5922 return; /* if we have no proxy set up, leave this function. */
5923
5924 (void)is_pt;
5925 log_warn(LD_NET,
5926 "The connection to the %s proxy server at %s just failed. "
5927 "Make sure that the proxy server is up and running.",
5928 proxy_type_to_string(proxy_type),
5929 fmt_addrport(&proxy_addr, proxy_port));
5930}
5931
5932/** Return string representation of <b>proxy_type</b>. */
5933static const char *
5935{
5936 switch (proxy_type) {
5937 case PROXY_CONNECT: return "HTTP";
5938 case PROXY_SOCKS4: return "SOCKS4";
5939 case PROXY_SOCKS5: return "SOCKS5";
5940 case PROXY_HAPROXY: return "HAPROXY";
5941 case PROXY_PLUGGABLE: return "pluggable transports SOCKS";
5942 case PROXY_NONE: return "NULL";
5943 default: tor_assert(0);
5944 }
5945 return NULL; /*Unreached*/
5946}
5947
5948/** Call connection_free_minimal() on every connection in our array, and
5949 * release all storage held by connection.c.
5950 *
5951 * Don't do the checks in connection_free(), because they will
5952 * fail.
5953 */
5954void
5956{
5958
5959 /* We don't want to log any messages to controllers. */
5960 SMARTLIST_FOREACH(conns, connection_t *, conn,
5961 if (conn->type == CONN_TYPE_CONTROL)
5962 TO_CONTROL_CONN(conn)->event_mask = 0);
5963
5965
5966 /* Unlink everything from the identity map. */
5968
5969 /* Clear out our list of broken connections */
5971
5972 SMARTLIST_FOREACH(conns, connection_t *, conn,
5974
5975 if (outgoing_addrs) {
5977 smartlist_free(outgoing_addrs);
5978 outgoing_addrs = NULL;
5979 }
5980
5982 tor_free(last_interface_ipv6);
5984
5985 mainloop_event_free(reenable_blocked_connections_ev);
5987 memset(&reenable_blocked_connections_delay, 0, sizeof(struct timeval));
5988}
5989
5990/** Log a warning, and possibly emit a control event, that <b>received</b> came
5991 * at a skewed time. <b>trusted</b> indicates that the <b>source</b> was one
5992 * that we had more faith in and therefore the warning level should have higher
5993 * severity.
5994 */
5995MOCK_IMPL(void,
5996clock_skew_warning, (const connection_t *conn, long apparent_skew, int trusted,
5997 log_domain_mask_t domain, const char *received,
5998 const char *source))
5999{
6000 char dbuf[64];
6001 char *ext_source = NULL, *warn = NULL;
6002 format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
6003 if (conn)
6004 tor_asprintf(&ext_source, "%s:%s:%d", source,
6005 fmt_and_decorate_addr(&conn->addr), conn->port);
6006 else
6007 ext_source = tor_strdup(source);
6008 log_fn(trusted ? LOG_WARN : LOG_INFO, domain,
6009 "Received %s with skewed time (%s): "
6010 "It seems that our clock is %s by %s, or that theirs is %s%s. "
6011 "Tor requires an accurate clock to work: please check your time, "
6012 "timezone, and date settings.", received, ext_source,
6013 apparent_skew > 0 ? "ahead" : "behind", dbuf,
6014 apparent_skew > 0 ? "behind" : "ahead",
6015 (!conn || trusted) ? "" : ", or they are sending us the wrong time");
6016 if (trusted) {
6017 control_event_general_status(LOG_WARN, "CLOCK_SKEW SKEW=%ld SOURCE=%s",
6018 apparent_skew, ext_source);
6019 tor_asprintf(&warn, "Clock skew %ld in %s from %s", apparent_skew,
6020 received, source);
6021 control_event_bootstrap_problem(warn, "CLOCK_SKEW", conn, 1);
6022 }
6023 tor_free(warn);
6024 tor_free(ext_source);
6025}
socklen_t tor_addr_to_sockaddr(const tor_addr_t *a, uint16_t port, struct sockaddr *sa_out, socklen_t len)
Definition address.c:113
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition address.c:933
void tor_addr_make_unspec(tor_addr_t *a)
Definition address.c:225
tor_addr_port_t * tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
Definition address.c:2100
int tor_addr_is_loopback(const tor_addr_t *addr)
Definition address.c:805
int tor_addr_is_null(const tor_addr_t *addr)
Definition address.c:780
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition address.c:1164
int get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
Definition address.c:1723
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition address.c:1199
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition address.c:328
int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out)
Definition address.c:165
Headers for address.h.
#define fmt_and_decorate_addr(a)
Definition address.h:245
static uint32_t tor_addr_to_ipv4n(const tor_addr_t *a)
Definition address.h:154
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition address.h:189
#define tor_addr_to_in6_addr8(x)
Definition address.h:137
#define fmt_addr(a)
Definition address.h:241
#define TOR_ADDR_BUF_LEN
Definition address.h:226
#define tor_addr_eq(a, b)
Definition address.h:282
time_t approx_time(void)
Definition approx_time.c:32
Header file for directory authority mode.
Header for backtrace.c.
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition binascii.c:215
size_t base64_encode_size(size_t srclen, int flags)
Definition binascii.c:166
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition binascii.c:478
int get_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port, const transport_t **transport)
Definition bridges.c:665
const smartlist_t * get_socks_args_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
Definition bridges.c:695
Header file for circuitbuild.c.
buf_t * buf_new(void)
Definition buffers.c:365
size_t buf_move_all(buf_t *buf_out, buf_t *buf_in)
Definition buffers.c:691
void buf_clear(buf_t *buf)
Definition buffers.c:381
int buf_add(buf_t *buf, const char *string, size_t string_len)
Definition buffers.c:527
size_t buf_allocation(const buf_t *buf)
Definition buffers.c:401
size_t buf_datalen(const buf_t *buf)
Definition buffers.c:394
void buf_assert_ok(buf_t *buf)
Definition buffers.c:910
int buf_get_line(buf_t *buf, char *data_out, size_t *data_len)
Definition buffers.c:874
size_t buf_slack(const buf_t *buf)
Definition buffers.c:414
int buf_get_bytes(buf_t *buf, char *string, size_t string_len)
Definition buffers.c:637
Header file for buffers.c.
#define BUF_MAX_LEN
Definition buffers.h:33
int buf_flush_to_socket(buf_t *buf, tor_socket_t s, size_t sz)
int buf_read_from_socket(buf_t *buf, tor_socket_t s, size_t at_most, int *reached_eof, int *socket_error)
Header file for buffers_net.c.
int buf_read_from_tls(buf_t *buf, tor_tls_t *tls, size_t at_most)
Definition buffers_tls.c:67
int buf_flush_to_tls(buf_t *buf, tor_tls_t *tls, size_t flushlen)
Header for buffers_tls.c.
void bwhist_note_dir_bytes_written(uint64_t num_bytes, time_t when)
Definition bwhist.c:195
void bwhist_note_bytes_read(uint64_t num_bytes, time_t when, bool ipv6)
Definition bwhist.c:183
void bwhist_note_dir_bytes_read(uint64_t num_bytes, time_t when)
Definition bwhist.c:204
void bwhist_note_bytes_written(uint64_t num_bytes, time_t when, bool ipv6)
Definition bwhist.c:164
Header for feature/stats/bwhist.c.
void channel_close_for_error(channel_t *chan)
Definition channel.c:1257
void channel_notify_flushed(channel_t *chan)
Definition channel.c:1858
void channel_note_establishment_cancelled(channel_t *chan)
Definition channel.c:1290
Header file for channel.c.
Header file for channeltls.c.
Header file for circuitbuild.c.
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Header file for circuitlist.c.
Header file for circuituse.c.
#define ARRAY_LENGTH(x)
int mainloop_event_schedule(mainloop_event_t *event, const struct timeval *tv)
mainloop_event_t * mainloop_event_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
Header for compat_libevent.c.
uint32_t monotime_coarse_get_stamp(void)
Headers for compress.c.
int buf_add_compress(struct buf_t *buf, struct tor_compress_state_t *state, const char *data, size_t data_len, int done)
const smartlist_t * get_configured_ports(void)
Definition config.c:6736
const char * escaped_safe_str_client(const char *address)
Definition config.c:1149
const or_options_t * get_options(void)
Definition config.c:949
Header file for config.c.
bool conn_uses_flow_control(connection_t *conn)
void flow_control_decide_xon(edge_connection_t *stream, size_t n_written)
APIs for stream flow control on congestion controlled circuits.
void connection_mark_all_noncontrol_listeners(void)
edge_connection_t * edge_connection_new(int type, int socket_family)
Definition connection.c:620
smartlist_t * connection_dir_list_by_purpose_and_resource(int purpose, const char *resource)
static void client_check_address_changed(tor_socket_t sock)
int connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
connection_t * connection_get_by_type_nonlinked(int type)
void clock_skew_warning(const connection_t *conn, long apparent_skew, int trusted, log_domain_mask_t domain, const char *received, const char *source)
connection_t * connection_new(int type, int socket_family)
Definition connection.c:662
void connection_link_connections(connection_t *conn_a, connection_t *conn_b)
Definition connection.c:751
static mainloop_event_t * reenable_blocked_connections_ev
int connection_fetch_from_buf_http(connection_t *conn, char **headers_out, size_t max_headerlen, char **body_out, size_t *body_used, size_t max_bodylen, int force_complete)
static int connection_read_https_proxy_response(connection_t *conn)
int connection_outbuf_too_full(connection_t *conn)
listener_connection_t * listener_connection_new(int type, int socket_family)
Definition connection.c:647
bool connection_dir_is_global_write_low(const connection_t *conn, size_t attempt)
static int connection_reached_eof(connection_t *conn)
int connection_is_listener(connection_t *conn)
void connection_buf_add_buf(connection_t *conn, buf_t *buf)
static int connection_handle_listener_read(connection_t *conn, int new_type)
static int connection_flushed_some(connection_t *conn)
int get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type, int *is_pt_out, const connection_t *conn)
static int connection_is_rate_limited(const connection_t *conn)
int connection_buf_get_line(connection_t *conn, char *data, size_t *data_len)
int connection_wants_to_flush(connection_t *conn)
static smartlist_t * outgoing_addrs
Definition connection.c:210
STATIC smartlist_t * pick_oos_victims(int n)
static connection_t * connection_get_another_active_or_conn(const or_connection_t *this_conn)
void connection_mark_for_close_(connection_t *conn, int line, const char *file)
int connection_proxy_connect(connection_t *conn, int type)
int connection_is_moribund(connection_t *conn)
static void connection_write_to_buf_failed(connection_t *conn)
void connection_consider_empty_write_buckets(connection_t *conn)
static time_t last_recorded_accounting_at
static void record_num_bytes_transferred_impl(connection_t *conn, time_t now, size_t num_read, size_t num_written)
static void connection_write_to_buf_commit(connection_t *conn)
void connection_close_immediate(connection_t *conn)
static tor_addr_t * last_interface_ipv4
Definition connection.c:205
static int retry_listener_ports(smartlist_t *old_conns, const smartlist_t *ports, smartlist_t *new_conns, smartlist_t *replacements, int control_listeners_only)
static int conn_get_proxy_type(const connection_t *conn)
void connection_dump_buffer_mem_stats(int severity)
char * alloc_http_authenticator(const char *authenticator)
#define CONN_GET_TEMPLATE(var, test)
void connection_bucket_init(void)
static ssize_t connection_bucket_get_share(int base, int priority, ssize_t global_bucket_val, ssize_t conn_bucket)
#define DIR_CONN_LIST_TEMPLATE(conn_var, conn_test, dirconn_var, dirconn_test)
void connection_read_bw_exhausted(connection_t *conn, bool is_global_bw)
static int listen_limit
const char * conn_type_to_string(int type)
Definition connection.c:267
static int connection_https_proxy_connect(connection_t *conn)
static int connection_finished_connecting(connection_t *conn)
connection_t * connection_get_by_type_addr_port_purpose(int type, const tor_addr_t *addr, uint16_t port, int purpose)
static int connection_may_write_to_buf(connection_t *conn)
static int connection_haproxy_proxy_connect(connection_t *conn)
int connection_flush(connection_t *conn)
void assert_connection_ok(connection_t *conn, time_t now)
connection_t * connection_get_by_type(int type)
int connection_read_proxy_handshake(connection_t *conn)
static int connection_finished_flushing(connection_t *conn)
int connection_process_inbuf(connection_t *conn, int package_partial)
static void reenable_blocked_connection_init(const or_options_t *options)
ssize_t connection_bucket_write_limit(connection_t *conn, time_t now)
static void reenable_blocked_connections_cb(mainloop_event_t *ev, void *arg)
static void connection_init(time_t now, connection_t *conn, int type, int socket_family)
Definition connection.c:703
int retry_all_listeners(smartlist_t *new_conns, int close_all_noncontrol)
const tor_addr_t * conn_get_outbound_address(sa_family_t family, const or_options_t *options, unsigned int conn_type)
static void connection_send_socks5_connect(connection_t *conn)
const listener_connection_t * CONST_TO_LISTENER_CONN(const connection_t *c)
Definition connection.c:246
static void set_constrained_socket_buffers(tor_socket_t sock, int size)
static void update_send_buffer_size(tor_socket_t sock)
void connection_write_to_buf_impl_(const char *string, size_t len, connection_t *conn, int zlib)
void connection_mark_for_close_internal_(connection_t *conn, int line, const char *file)
int connection_state_is_open(connection_t *conn)
static void connection_buckets_decrement(connection_t *conn, time_t now, size_t num_read, size_t num_written)
const char * connection_describe_peer(const connection_t *conn)
Definition connection.c:523
static connection_t * connection_listener_new_for_port(const port_cfg_t *port, int *defer, int *addr_in_use)
static struct timeval reenable_blocked_connections_delay
static connection_t * connection_listener_new(const struct sockaddr *listensockaddr, socklen_t listensocklen, int type, const char *address, const port_cfg_t *portcfg, int *addr_in_use)
STATIC void connection_free_minimal(connection_t *conn)
Definition connection.c:783
void connection_bucket_adjust(const or_options_t *options)
int any_other_active_or_conns(const or_connection_t *this_conn)
static const char * connection_describe_peer_internal(const connection_t *conn, bool include_preposition)
Definition connection.c:398
entry_connection_t * entry_connection_new(int type, int socket_family)
Definition connection.c:596
void connection_consider_empty_read_buckets(connection_t *conn)
static int connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
static int oos_victim_comparator_for_orconns(or_connection_t *a, or_connection_t *b)
or_connection_t * or_connection_new(int type, int socket_family)
Definition connection.c:571
int conn_listener_type_supports_af_unix(int type)
Definition connection.c:765
static void socket_failed_from_tcp_port_exhaustion(void)
static uint32_t last_refilled_global_buckets_ts
void connection_free_all(void)
static time_t write_buckets_last_empty_at
static ssize_t connection_bucket_read_limit(connection_t *conn, time_t now)
smartlist_t * connection_dir_list_by_purpose_resource_and_state(int purpose, const char *resource, int state)
static int oos_victim_comparator(const void **a_v, const void **b_v)
static int connection_fetch_from_buf_socks_client(connection_t *conn, int state, char **reason)
static int connection_handle_write_impl(connection_t *conn, int force)
int connection_init_accepted_conn(connection_t *conn, const listener_connection_t *listener)
static void socket_failed_from_fd_exhaustion(void)
static int connection_handle_read_impl(connection_t *conn)
const char * connection_describe(const connection_t *conn)
Definition connection.c:538
connection_t * connection_get_by_type_state(int type, int state)
STATIC int connection_connect_sockaddr(connection_t *conn, const struct sockaddr *sa, socklen_t sa_len, const struct sockaddr *bindaddr, socklen_t bindaddr_len, int *socket_error)
void connection_mark_all_noncontrol_connections(void)
dir_connection_t * dir_connection_new(int socket_family)
Definition connection.c:556
void log_failed_proxy_connection(connection_t *conn)
void connection_write_bw_exhausted(connection_t *conn, bool is_global_bw)
static const char * connection_proxy_state_to_string(int state)
void connection_about_to_close_connection(connection_t *conn)
STATIC void kill_conn_list_for_oos(smartlist_t *conns)
#define CONN_IS_CLOSED(c)
static int reenable_blocked_connections_is_scheduled
static const char * proxy_type_to_string(int proxy_type)
void connection_free_(connection_t *conn)
Definition connection.c:965
listener_connection_t * TO_LISTENER_CONN(connection_t *c)
Definition connection.c:233
STATIC int connection_buf_read_from_socket(connection_t *conn, ssize_t *max_to_read, int *socket_error)
static void reenable_blocked_connection_schedule(void)
static int connection_socks4_proxy_connect(connection_t *conn)
int connection_state_is_connecting(connection_t *conn)
control_connection_t * control_connection_new(int socket_family)
Definition connection.c:635
static int connection_socks5_proxy_connect(connection_t *conn)
static int make_socket_reuseable(tor_socket_t sock)
void connection_dir_buf_add(const char *string, size_t len, dir_connection_t *dir_conn, int done)
#define CLIENT_IDLE_TIME_FOR_PRIORITY
static int check_sockaddr_family_match(sa_family_t got, connection_t *listener)
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
void connection_expire_held_open(void)
const char * conn_state_to_string(int type, int state)
Definition connection.c:301
void connection_check_oos(int n_socks, int failed)
static void connection_bucket_refill_single(connection_t *conn, uint32_t now_ts)
connection_t * connection_get_by_global_id(uint64_t id)
static int check_sockaddr(const struct sockaddr *sa, int len, int level)
Header file for connection.c.
#define CONN_TYPE_METRICS
Definition connection.h:79
#define CONN_TYPE_OR
Definition connection.h:44
#define CONN_TYPE_AP_HTTP_CONNECT_LISTENER
Definition connection.h:75
#define CONN_TYPE_DIR_LISTENER
Definition connection.h:53
#define CONN_TYPE_OR_LISTENER
Definition connection.h:41
#define CONN_TYPE_METRICS_LISTENER
Definition connection.h:77
#define CONN_TYPE_CONTROL_LISTENER
Definition connection.h:58
#define CONN_TYPE_CONTROL
Definition connection.h:60
#define CONN_TYPE_EXT_OR
Definition connection.h:71
#define CONN_TYPE_EXT_OR_LISTENER
Definition connection.h:73
#define CONN_LOG_PROTECT(conn, stmt)
Definition connection.h:368
#define MAX_SOCKS5_AUTH_SIZE_TOTAL
Definition connection.h:215
#define CONN_TYPE_AP
Definition connection.h:51
#define CONN_TYPE_DIR
Definition connection.h:55
#define MAX_SOCKS5_AUTH_FIELD_SIZE
Definition connection.h:211
#define CONN_TYPE_AP_NATD_LISTENER
Definition connection.h:66
#define LISTENER_STATE_READY
Definition connection.h:108
#define CONN_TYPE_AP_LISTENER
Definition connection.h:48
#define CONN_TYPE_AP_DNS_LISTENER
Definition connection.h:68
#define CONN_TYPE_EXIT
Definition connection.h:46
#define CONN_TYPE_AP_TRANS_LISTENER
Definition connection.h:63
const edge_connection_t * CONST_TO_EDGE_CONN(const connection_t *c)
int connection_ap_process_transparent(entry_connection_t *conn)
int connection_edge_finished_connecting(edge_connection_t *edge_conn)
int connection_edge_finished_flushing(edge_connection_t *conn)
void connection_exit_about_to_close(edge_connection_t *edge_conn)
int connection_edge_flushed_some(edge_connection_t *conn)
int connection_edge_reached_eof(edge_connection_t *conn)
int connection_edge_end_errno(edge_connection_t *conn)
void connection_ap_about_to_close(entry_connection_t *entry_conn)
entry_connection_t * TO_ENTRY_CONN(connection_t *c)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
int connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
Header file for connection_edge.c.
#define AP_CONN_STATE_HTTP_CONNECT_WAIT
#define EXIT_CONN_STATE_CONNECTING
#define AP_CONN_STATE_CONTROLLER_WAIT
#define EXIT_CONN_STATE_OPEN
#define AP_CONN_STATE_SOCKS_WAIT
#define EXIT_CONN_STATE_RESOLVEFAILED
#define AP_CONN_STATE_CONNECT_WAIT
#define AP_CONN_STATE_OPEN
#define EXIT_PURPOSE_CONNECT
#define AP_CONN_STATE_RESOLVE_WAIT
#define AP_CONN_STATE_CIRCUIT_WAIT
#define EXIT_CONN_STATE_RESOLVING
#define AP_CONN_STATE_NATD_WAIT
#define AP_CONN_STATE_RENDDESC_WAIT
#define EXIT_PURPOSE_RESOLVE
void connection_or_event_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
or_connection_t * TO_OR_CONN(connection_t *c)
int connection_or_reached_eof(or_connection_t *conn)
int connection_tls_continue_handshake(or_connection_t *conn)
void connection_or_notify_error(or_connection_t *conn, int reason, const char *msg)
int connection_or_process_inbuf(or_connection_t *conn)
void connection_or_note_establishment_failure(or_connection_t *conn)
void connection_or_clear_identity(or_connection_t *conn)
time_t connection_or_client_used(or_connection_t *conn)
int connection_or_finished_flushing(or_connection_t *conn)
void clear_broken_connection_map(int stop_recording)
int connection_tls_start_handshake(or_connection_t *conn, int receiving)
int connection_or_get_num_circuits(or_connection_t *conn)
int connection_or_flushed_some(or_connection_t *conn)
const struct ed25519_public_key_t * connection_or_get_alleged_ed25519_id(const or_connection_t *conn)
void connection_or_close_for_error(or_connection_t *orconn, int flush)
const or_connection_t * CONST_TO_OR_CONN(const connection_t *c)
int connection_or_finished_connecting(or_connection_t *or_conn)
void connection_or_about_to_close(or_connection_t *or_conn)
void connection_or_clear_identity_map(void)
void connection_or_close_normally(or_connection_t *orconn, int flush)
Header file for connection_or.c.
#define CONN_IS_EDGE(x)
#define DIR_CONN_IS_SERVER(conn)
void conn_stats_note_or_conn_bytes(uint64_t conn_id, size_t num_read, size_t num_written, time_t when, bool is_ipv6)
Definition connstats.c:185
Header for feature/stats/connstats.c.
control_connection_t * TO_CONTROL_CONN(connection_t *c)
Definition control.c:71
int connection_control_reached_eof(control_connection_t *conn)
Definition control.c:209
void connection_control_closed(control_connection_t *conn)
Definition control.c:231
int connection_control_finished_flushing(control_connection_t *conn)
Definition control.c:201
int connection_control_process_inbuf(control_connection_t *conn)
Definition control.c:420
Header file for control.c.
#define LOG_FN_CONN(conn, args)
Definition control.h:33
#define CONTROL_CONN_STATE_OPEN
Definition control.h:20
#define CONTROL_CONN_STATE_NEEDAUTH
Definition control.h:23
void control_event_bootstrap_problem(const char *warn, const char *reason, const connection_t *conn, int dowarn)
Controller connection structure.
int control_event_general_status(int severity, const char *format,...)
void control_update_global_event_mask(void)
Header file for control_events.c.
void cpath_assert_layer_ok(const crypt_path_t *cp)
Definition crypt_path.c:107
Header file for crypt_path.c.
#define HEX_DIGEST_LEN
void ed25519_public_to_base64(char *output, const ed25519_public_key_t *pkey)
Header for crypto_format.c.
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition crypto_util.c:55
Common functions for cryptographic routines.
#define tor_str_wipe_and_free(str)
Definition crypto_util.h:28
Compile-time assertions: CTASSERT(expression).
#define CTASSERT(x)
Definition ctassert.h:44
#define DIGEST_LEN
int check_private_dir(const char *dirname, cpd_check_t check, const char *effective_user)
Definition dir.c:71
unsigned int cpd_check_t
Definition dir.h:20
Client/server directory connection structure.
Header for feature/dirauth/dirauth_config.c.
int connection_dir_reached_eof(dir_connection_t *conn)
Definition dirclient.c:2834
int connection_dir_finished_flushing(dir_connection_t *conn)
Definition directory.c:547
int connection_dir_finished_connecting(dir_connection_t *conn)
Definition directory.c:593
int parse_http_response(const char *headers, int *code, time_t *date, compress_method_t *compression, char **reason)
Definition directory.c:393
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition directory.c:89
void connection_dir_about_to_close(dir_connection_t *dir_conn)
Definition directory.c:518
int connection_dir_process_inbuf(dir_connection_t *conn)
Definition directory.c:476
Header file for directory.c.
#define DIR_CONN_STATE_CONNECTING
Definition directory.h:20
#define DIR_CONN_STATE_CLIENT_FINISHED
Definition directory.h:26
#define DIR_CONN_STATE_CLIENT_READING
Definition directory.h:24
#define DIR_CONN_STATE_SERVER_WRITING
Definition directory.h:30
#define DIR_CONN_STATE_SERVER_COMMAND_WAIT
Definition directory.h:28
#define DIR_PURPOSE_SERVER
Definition directory.h:60
#define DIR_CONN_STATE_CLIENT_SENDING
Definition directory.h:22
Header file for dirserv.c.
Header file for dns.c.
void dnsserv_configure_listener(connection_t *conn)
Definition dnsserv.c:405
Header file for dnsserv.c.
Entry connection structure.
#define ENTRY_TO_EDGE_CONN(c)
void entry_guard_cancel(circuit_guard_state_t **guard_state_p)
Header file for circuitbuild.c.
char * esc_for_log(const char *s)
Definition escape.c:30
const char * escaped(const char *s)
Definition escape.c:126
int connection_ext_or_process_inbuf(or_connection_t *or_conn)
Definition ext_orport.c:547
int connection_ext_or_start_auth(or_connection_t *or_conn)
Definition ext_orport.c:643
int connection_ext_or_finished_flushing(or_connection_t *conn)
Definition ext_orport.c:631
Header for ext_orport.c.
#define EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH
Definition ext_orport.h:24
#define EXT_OR_CONN_STATE_OPEN
Definition ext_orport.h:28
#define EXT_OR_CONN_STATE_MIN_
Definition ext_orport.h:17
#define EXT_OR_CONN_STATE_FLUSHING
Definition ext_orport.h:31
#define EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE
Definition ext_orport.h:22
#define EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE
Definition ext_orport.h:20
Header file for geoip.c.
void accounting_add_bytes(size_t n_read, size_t n_written, int seconds)
Definition hibernate.c:331
int accounting_is_enabled(const or_options_t *options)
Definition hibernate.c:305
Header file for hibernate.c.
Header file containing common data for the whole HS subsystem.
Header file containing circuit and connection identifier data for the whole HS subsystem.
Header for feature/hs/hs_metrics.c.
#define hs_metrics_app_read_bytes(i, port, n)
Definition hs_metrics.h:52
uint16_t sa_family_t
Definition inaddr_st.h:77
Listener connection structure.
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition log.c:591
#define log_fn(severity, domain, args,...)
Definition log.h:283
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition log.h:288
#define LD_APP
Definition log.h:78
#define LD_PROTOCOL
Definition log.h:72
#define LD_CHANNEL
Definition log.h:105
#define LD_DIRSERV
Definition log.h:90
#define LOG_DEBUG
Definition log.h:42
#define LD_OR
Definition log.h:92
#define LOG_ERR
Definition log.h:56
#define LD_FS
Definition log.h:70
#define LD_BUG
Definition log.h:86
#define LD_NET
Definition log.h:66
#define LD_GENERAL
Definition log.h:62
#define LD_DIR
Definition log.h:88
#define LOG_NOTICE
Definition log.h:50
#define LD_CONFIG
Definition log.h:68
#define LD_CONTROL
Definition log.h:80
#define LOG_WARN
Definition log.h:53
#define LOG_INFO
Definition log.h:45
uint64_t log_domain_mask_t
#define bool_neq(a, b)
Definition logic.h:18
void stats_increment_bytes_read_and_written(uint64_t r, uint64_t w)
Definition mainloop.c:476
void connection_stop_reading(connection_t *conn)
Definition mainloop.c:614
void connection_stop_reading_from_linked_conn(connection_t *conn)
Definition mainloop.c:841
int connection_in_array(connection_t *conn)
Definition mainloop.c:435
void ip_address_changed(int on_client_conn)
Definition mainloop.c:2331
void connection_unregister_events(connection_t *conn)
Definition mainloop.c:276
void add_connection_to_closeable_list(connection_t *conn)
Definition mainloop.c:417
int connection_is_on_closeable_list(connection_t *conn)
Definition mainloop.c:428
void connection_start_reading(connection_t *conn)
Definition mainloop.c:636
void update_current_time(time_t now)
Definition mainloop.c:2239
int connection_is_writing(connection_t *conn)
Definition mainloop.c:676
int connection_is_reading(const connection_t *conn)
Definition mainloop.c:501
void connection_start_writing(connection_t *conn)
Definition mainloop.c:709
smartlist_t * get_connection_array(void)
Definition mainloop.c:444
int connection_count_moribund(void)
Definition mainloop.c:875
void connection_stop_writing(connection_t *conn)
Definition mainloop.c:686
unsigned get_signewnym_epoch(void)
Definition mainloop.c:1363
Header file for mainloop.c.
#define tor_free(p)
Definition malloc.h:56
int metrics_connection_process_inbuf(connection_t *conn)
Definition metrics.c:100
int metrics_connection_reached_eof(connection_t *conn)
Definition metrics.c:252
int metrics_connection_finished_flushing(connection_t *conn)
Definition metrics.c:264
Header for feature/metrics/metrics.c.
int net_is_completely_disabled(void)
Definition netstatus.c:34
void note_user_activity(time_t now)
Definition netstatus.c:63
Header for netstatus.c.
#define SOCKET_OK(s)
Definition nettypes.h:39
#define TOR_INVALID_SOCKET
Definition nettypes.h:41
#define tor_socket_t
Definition nettypes.h:36
int nodelist_probably_contains_address(const tor_addr_t *addr)
Definition nodelist.c:548
Header file for nodelist.c.
Master header file for Tor-specific functionality.
#define CELL_PAYLOAD_SIZE
Definition or.h:529
#define CFG_AUTO_PORT
Definition or.h:994
#define TO_CONN(c)
Definition or.h:709
#define MAX_HEADERS_SIZE
Definition or.h:122
#define DOWNCAST(to, ptr)
Definition or.h:109
#define RELAY_PAYLOAD_SIZE_MAX
Definition or.h:576
#define ENTRY_TO_CONN(c)
Definition or.h:712
#define SESSION_GROUP_FIRST_AUTO
Definition or.h:987
OR connection structure.
@ TCP_PROXY_PROTOCOL_HAPROXY
@ OUTBOUND_ADDR_OR
@ OUTBOUND_ADDR_EXIT
@ OUTBOUND_ADDR_ANY
#define OR_CONN_STATE_SERVER_VERSIONS_WAIT
#define OR_CONN_STATE_CONNECTING
#define OR_CONN_STATE_PROXY_HANDSHAKING
#define OR_CONN_STATE_TLS_HANDSHAKING
#define OR_CONN_STATE_OR_HANDSHAKING_V3
#define OR_CONN_STATE_OPEN
int get_parent_directory(char *fname)
Definition path.c:196
int reachable_addr_prefer_ipv6_dirport(const or_options_t *options)
Definition policies.c:512
int reachable_addr_prefer_ipv6_orport(const or_options_t *options)
Definition policies.c:490
int reachable_addr_use_ipv6(const or_options_t *options)
Definition policies.c:451
int dir_policy_permits_address(const tor_addr_t *addr)
Definition policies.c:1054
int socks_policy_permits_address(const tor_addr_t *addr)
Definition policies.c:1063
Header file for policies.c.
Listener port configuration structure.
int tor_asprintf(char **strp, const char *fmt,...)
Definition printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
int fetch_from_buf_http(buf_t *buf, char **headers_out, size_t max_headerlen, char **body_out, size_t *body_used, size_t max_bodylen, int force_complete)
Definition proto_http.c:50
Header for proto_http.c.
socks_request_t * socks_request_new(void)
Definition proto_socks.c:92
int fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
Header for proto_socks.c.
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition ratelim.c:42
int errno_to_orconn_end_reason(int e)
Definition reasons.c:295
Header file for reasons.c.
Header file for relay.c.
Header file for rendcommon.c.
void rep_hist_note_exit_bytes(uint16_t port, size_t num_written, size_t num_read)
Definition rephist.c:1623
void rep_hist_note_conn_closed(bool from_listener, unsigned int type, int af)
Definition rephist.c:1733
void rep_hist_note_conn_rejected(unsigned int type, int af)
Definition rephist.c:1758
void rep_hist_note_conn_opened(bool from_listener, unsigned int type, int af)
Definition rephist.c:1710
void rep_hist_note_overload(overload_type_t overload)
Definition rephist.c:541
void rep_hist_note_tcp_exhaustion(void)
Definition rephist.c:578
Header file for rephist.c.
void resolved_addr_reset_last(int family)
Header file for resolve_addr.c.
uint16_t routerconf_find_or_port(const or_options_t *options, sa_family_t family)
Definition router.c:1518
void mark_my_descriptor_dirty(const char *reason)
Definition router.c:2601
uint16_t routerconf_find_dir_port(const or_options_t *options, uint16_t dirport)
Definition router.c:1623
Router descriptor structure.
Header file for routerlist.c.
Header file for routermode.c.
Header file for sandbox.c.
#define sandbox_intern_string(s)
Definition sandbox.h:112
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition smartlist.c:334
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
void smartlist_remove(smartlist_t *sl, const void *element)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
#define SMARTLIST_DEL_CURRENT(sl, var)
tor_socket_t tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len)
Definition socket.c:366
int tor_close_socket(tor_socket_t s)
Definition socket.c:217
tor_socket_t tor_connect_socket(tor_socket_t sock, const struct sockaddr *address, socklen_t address_len)
Definition socket.c:251
int get_n_open_sockets(void)
Definition socket.c:440
void tor_release_socket_ownership(tor_socket_t s)
Definition socket.c:348
int tor_addr_from_getsockname(struct tor_addr_t *addr_out, tor_socket_t sock)
Definition socket.c:544
tor_socket_t tor_open_socket_nonblocking(int domain, int type, int protocol)
Definition socket.c:259
Client request structure.
#define SOCKS_COMMAND_CONNECT
void note_connection(bool inbound, const connection_t *conn)
Definition status.c:135
Header for status.c.
uint64_t global_identifier
Definition channel.h:198
time_t timestamp_last_read_allowed
unsigned int proxy_state
struct buf_t * inbuf
unsigned int in_connection_handle_write
struct event * write_event
uint32_t n_read_conn_bw
unsigned int inbuf_reached_eof
struct connection_t * linked_conn
unsigned int hold_open_until_flushed
unsigned int reading_from_linked_conn
unsigned int type
struct buf_t * outbuf
unsigned int from_listener
uint32_t magic
uint64_t global_identifier
unsigned int read_blocked_on_bw
unsigned int linked
uint16_t marked_for_close
const char * marked_for_close_file
uint32_t n_written_conn_bw
unsigned int linked_conn_is_closed
unsigned int in_flushed_some
unsigned int purpose
tor_socket_t s
unsigned int always_rate_limit_as_remote
time_t timestamp_created
unsigned int active_on_link
unsigned int write_blocked_on_bw
struct event * read_event
time_t timestamp_last_write_allowed
tor_addr_t addr
smartlist_t * ephemeral_onion_services
struct tor_compress_state_t * compress_state
struct circuit_guard_state_t * guard_state
token_bucket_rw_t bucket
unsigned int is_transparent_ap
socks_request_t * socks_request
unsigned int chosen_exit_optional
unsigned int chosen_exit_retries
struct buf_t * pending_optimistic_data
unsigned int socks_prefer_no_auth
unsigned int extended_socks5_codes
ed25519_public_key_t identity_pk
Definition hs_ident.h:112
uint16_t orig_virtual_port
Definition hs_ident.h:117
token_bucket_rw_t bucket
channel_tls_t * chan
char identity_digest[DIGEST_LEN]
or_handshake_state_t * handshake_state
tor_addr_port_t canonical_orport
struct tor_tls_t * tls
tor_addr_t Socks4ProxyAddr
uint64_t RelayBandwidthBurst
int ClientPreferIPv6DirPort
tor_addr_t HTTPSProxyAddr
uint16_t Socks4ProxyPort
tor_addr_t TCPProxyAddr
tcp_proxy_protocol_t TCPProxyProtocol
struct config_line_t * ClientTransportPlugin
uint64_t BandwidthRate
uint64_t ConstrainedSockSize
int TokenBucketRefillInterval
int ClientPreferIPv6ORPort
char * Socks5ProxyUsername
char * Socks5ProxyPassword
int CountPrivateBandwidth
tor_addr_t Socks5ProxyAddr
uint64_t RelayBandwidthRate
tor_addr_t OutboundBindAddresses[OUTBOUND_ADDR_MAX][2]
uint16_t TCPProxyPort
uint16_t Socks5ProxyPort
enum or_options_t::@2 TransProxyType_parsed
char * HTTPSProxyAuthenticator
uint16_t HTTPSProxyPort
uint64_t BandwidthBurst
char unix_addr[FLEXIBLE_ARRAY_MEMBER]
Definition port_cfg_st.h:38
uint8_t type
Definition port_cfg_st.h:23
unsigned is_unix_addr
Definition port_cfg_st.h:24
entry_port_cfg_t entry_cfg
Definition port_cfg_st.h:32
tor_addr_t addr
Definition port_cfg_st.h:20
unsigned int has_finished
unsigned int socks_prefer_no_auth
unsigned int socks_use_extended_errors
int socks_version
Definition transports.h:19
uint16_t port
Definition transports.h:26
tor_addr_t addr
Definition transports.h:24
#define STATIC
Definition testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
int format_time_interval(char *out, size_t out_len, long interval)
Definition time_fmt.c:512
int token_bucket_rw_dec(token_bucket_rw_t *bucket, ssize_t n_read, ssize_t n_written)
int token_bucket_rw_refill(token_bucket_rw_t *bucket, uint32_t now_ts_stamp)
void token_bucket_rw_adjust(token_bucket_rw_t *bucket, uint32_t rate, uint32_t burst)
void token_bucket_rw_init(token_bucket_rw_t *bucket, uint32_t rate, uint32_t burst, uint32_t now_ts_stamp)
const char * tor_tls_err_to_string(int err)
Definition tortls.c:142
Headers for tortls.c.
void tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
Definition tortls_nss.c:616
#define CASE_TOR_TLS_ERROR_ANY
Definition tortls.h:62
#define CASE_TOR_TLS_ERROR_ANY_NONIO
Definition tortls.h:53
int tor_tls_get_pending_bytes(tor_tls_t *tls)
Definition tortls_nss.c:596
void tor_tls_release_socket(tor_tls_t *tls)
Definition tortls_nss.c:449
char * pt_get_socks_args_for_proxy_addrport(const tor_addr_t *addr, uint16_t port)
Headers for transports.c.
const struct passwd * tor_getpwnam(const char *username)
Definition userdb.c:70
#define tor_assert_nonfatal_unreached()
Definition util_bug.h:177
#define tor_assert(expr)
Definition util_bug.h:103
#define tor_fragile_assert()
Definition util_bug.h:278
#define IF_BUG_ONCE(cond)
Definition util_bug.h:254
int strcmp_opt(const char *s1, const char *s2)
int fast_mem_is_zero(const char *mem, size_t len)
Definition util_string.c:76
int tor_digest_is_zero(const char *digest)
Definition util_string.c:98
#define ED25519_BASE64_LEN