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