Tor  0.4.8.0-alpha-dev
connection_edge.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_edge.c
9  * \brief Handle edge streams.
10  *
11  * An edge_connection_t is a subtype of a connection_t, and represents two
12  * critical concepts in Tor: a stream, and an edge connection. From the Tor
13  * protocol's point of view, a stream is a bi-directional channel that is
14  * multiplexed on a single circuit. Each stream on a circuit is identified
15  * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
16  * Streams are created in response to client requests.
17  *
18  * An edge connection is one thing that can implement a stream: it is either a
19  * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
20  * exit connection.
21  *
22  * Not every instance of edge_connection_t truly represents an edge connection,
23  * however. (Sorry!) We also create edge_connection_t objects for streams that
24  * we will not be handling with TCP. The types of these streams are:
25  * <ul>
26  * <li>DNS lookup streams, created on the client side in response to
27  * a UDP DNS request received on a DNSPort, or a RESOLVE command
28  * on a controller.
29  * <li>DNS lookup streams, created on the exit side in response to
30  * a RELAY_RESOLVE cell from a client.
31  * <li>Tunneled directory streams, created on the directory cache side
32  * in response to a RELAY_BEGIN_DIR cell. These streams attach directly
33  * to a dir_connection_t object without ever using TCP.
34  * </ul>
35  *
36  * This module handles general-purpose functionality having to do with
37  * edge_connection_t. On the client side, it accepts various types of
38  * application requests on SocksPorts, TransPorts, and NATDPorts, and
39  * creates streams appropriately.
40  *
41  * This module is also responsible for implementing stream isolation:
42  * ensuring that streams that should not be linkable to one another are
43  * kept to different circuits.
44  *
45  * On the exit side, this module handles the various stream-creating
46  * type of RELAY cells by launching appropriate outgoing connections,
47  * DNS requests, or directory connection objects.
48  *
49  * And for all edge connections, this module is responsible for handling
50  * incoming and outdoing data as it arrives or leaves in the relay.c
51  * module. (Outgoing data will be packaged in
52  * connection_edge_process_inbuf() as it calls
53  * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
54  * cells is applied in connection_edge_process_relay_cell().)
55  **/
56 #define CONNECTION_EDGE_PRIVATE
57 
58 #include "core/or/or.h"
59 
60 #include "lib/err/backtrace.h"
61 
62 #include "app/config/config.h"
64 #include "core/mainloop/mainloop.h"
66 #include "core/or/channel.h"
67 #include "core/or/circuitbuild.h"
68 #include "core/or/circuitlist.h"
69 #include "core/or/circuituse.h"
70 #include "core/or/circuitpadding.h"
73 #include "core/or/circuitstats.h"
74 #include "core/or/connection_or.h"
75 #include "core/or/extendinfo.h"
76 #include "core/or/policies.h"
77 #include "core/or/reasons.h"
78 #include "core/or/relay.h"
79 #include "core/or/sendme.h"
80 #include "core/proto/proto_http.h"
81 #include "core/proto/proto_socks.h"
83 #include "feature/client/circpathbias.h"
84 #include "feature/client/dnsserv.h"
89 #include "feature/hs/hs_cache.h"
90 #include "feature/hs/hs_circuit.h"
91 #include "feature/hs/hs_client.h"
92 #include "feature/hs/hs_common.h"
98 #include "feature/relay/dns.h"
99 #include "feature/relay/router.h"
101 #include "feature/rend/rendcommon.h"
103 #include "feature/stats/rephist.h"
104 #include "lib/buf/buffers.h"
107 
108 #include "core/or/cell_st.h"
112 #include "core/or/extend_info_st.h"
114 #include "core/or/or_circuit_st.h"
116 #include "core/or/half_edge_st.h"
119 
120 #ifdef HAVE_LINUX_TYPES_H
121 #include <linux/types.h>
122 #endif
123 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
124 #include <linux/netfilter_ipv4.h>
125 #define TRANS_NETFILTER
126 #define TRANS_NETFILTER_IPV4
127 #endif
128 
129 #ifdef HAVE_LINUX_IF_H
130 #include <linux/if.h>
131 #endif
132 
133 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
134 #include <linux/netfilter_ipv6/ip6_tables.h>
135 #if defined(IP6T_SO_ORIGINAL_DST)
136 #define TRANS_NETFILTER
137 #define TRANS_NETFILTER_IPV6
138 #endif
139 #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
140 
141 #ifdef HAVE_FCNTL_H
142 #include <fcntl.h>
143 #endif
144 #ifdef HAVE_SYS_IOCTL_H
145 #include <sys/ioctl.h>
146 #endif
147 #ifdef HAVE_SYS_PARAM_H
148 #include <sys/param.h>
149 #endif
150 
151 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
152 #include <net/if.h>
153 #include <net/pfvar.h>
154 #define TRANS_PF
155 #endif
156 
157 #ifdef IP_TRANSPARENT
158 #define TRANS_TPROXY
159 #endif
160 
161 #define SOCKS4_GRANTED 90
162 #define SOCKS4_REJECT 91
163 
166 static int connection_exit_connect_dir(edge_connection_t *exitconn);
167 static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
169 static bool network_reentry_is_allowed(void);
170 
171 /**
172  * Cast a `connection_t *` to an `edge_connection_t *`.
173  *
174  * Exit with an assertion failure if the input is not an
175  * `edge_connection_t`.
176  **/
179 {
180  tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
181  c->magic == ENTRY_CONNECTION_MAGIC);
182  return DOWNCAST(edge_connection_t, c);
183 }
184 
185 /**
186  * Cast a `const connection_t *` to a `const edge_connection_t *`.
187  *
188  * Exit with an assertion failure if the input is not an
189  * `edge_connection_t`.
190  **/
191 const edge_connection_t *
193 {
194  return TO_EDGE_CONN((connection_t *)c);
195 }
196 
197 /**
198  * Cast a `connection_t *` to an `entry_connection_t *`.
199  *
200  * Exit with an assertion failure if the input is not an
201  * `entry_connection_t`.
202  **/
205 {
206  tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
207  return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
208 }
209 
210 /**
211  * Cast a `const connection_t *` to a `const entry_connection_t *`.
212  *
213  * Exit with an assertion failure if the input is not an
214  * `entry_connection_t`.
215  **/
216 const entry_connection_t *
218 {
219  return TO_ENTRY_CONN((connection_t*) c);
220 }
221 
222 /**
223  * Cast an `edge_connection_t *` to an `entry_connection_t *`.
224  *
225  * Exit with an assertion failure if the input is not an
226  * `entry_connection_t`.
227  **/
230 {
231  tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
232  return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
233 }
234 
235 /**
236  * Cast a `const edge_connection_t *` to a `const entry_connection_t *`.
237  *
238  * Exit with an assertion failure if the input is not an
239  * `entry_connection_t`.
240  **/
241 const entry_connection_t *
243 {
245 }
246 
247 /** An AP stream has failed/finished. If it hasn't already sent back
248  * a socks reply, send one now (based on endreason). Also set
249  * has_sent_end to 1, and mark the conn.
250  */
251 MOCK_IMPL(void,
253  int line, const char *file))
254 {
255  connection_t *base_conn = ENTRY_TO_CONN(conn);
256  tor_assert(base_conn->type == CONN_TYPE_AP);
257  ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
258 
259  if (base_conn->marked_for_close) {
260  /* This call will warn as appropriate. */
261  connection_mark_for_close_(base_conn, line, file);
262  return;
263  }
264 
265  if (!conn->socks_request->has_finished) {
267  log_warn(LD_BUG,
268  "stream (marked at %s:%d) sending two socks replies?",
269  file, line);
270 
271  if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
272  connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
273  else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
275  RESOLVED_TYPE_ERROR_TRANSIENT,
276  0, NULL, -1, -1);
277  else /* unknown or no handshake at all. send no response. */
278  conn->socks_request->has_finished = 1;
279  }
280 
281  connection_mark_and_flush_(base_conn, line, file);
282 
283  ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
284 }
285 
286 /** There was an EOF. Send an end and mark the connection for close.
287  */
288 int
290 {
291  if (connection_get_inbuf_len(TO_CONN(conn)) &&
293  /* it still has stuff to process. don't let it die yet. */
294  return 0;
295  }
296  log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
297  conn->base_.s);
298  if (!conn->base_.marked_for_close) {
299  /* only mark it if not already marked. it's possible to
300  * get the 'end' right around when the client hangs up on us. */
301  connection_edge_end(conn, END_STREAM_REASON_DONE);
302  if (conn->base_.type == CONN_TYPE_AP) {
303  /* eof, so don't send a socks reply back */
304  if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
306  }
307  connection_mark_for_close(TO_CONN(conn));
308  }
309  return 0;
310 }
311 
312 /** Handle new bytes on conn->inbuf based on state:
313  * - If it's waiting for socks info, try to read another step of the
314  * socks handshake out of conn->inbuf.
315  * - If it's waiting for the original destination, fetch it.
316  * - If it's open, then package more relay cells from the stream.
317  * - Else, leave the bytes on inbuf alone for now.
318  *
319  * Mark and return -1 if there was an unexpected error with the conn,
320  * else return 0.
321  */
322 int
324 {
325  tor_assert(conn);
326 
327  switch (conn->base_.state) {
330  /* already marked */
331  return -1;
332  }
333  return 0;
336  /* already marked */
337  return -1;
338  }
339  return 0;
342  return -1;
343  }
344  return 0;
345  case AP_CONN_STATE_OPEN:
346  if (! conn->base_.linked) {
348  }
349 
350  FALLTHROUGH;
352  if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
353  /* (We already sent an end cell if possible) */
354  connection_mark_for_close(TO_CONN(conn));
355  return -1;
356  }
357  return 0;
360  log_info(LD_EDGE,
361  "data from edge while in '%s' state. Sending it anyway. "
362  "package_partial=%d, buflen=%ld",
363  conn_state_to_string(conn->base_.type, conn->base_.state),
364  package_partial,
365  (long)connection_get_inbuf_len(TO_CONN(conn)));
366  if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
367  /* (We already sent an end cell if possible) */
368  connection_mark_for_close(TO_CONN(conn));
369  return -1;
370  }
371  return 0;
372  }
373  /* Fall through if the connection is on a circuit without optimistic
374  * data support. */
375  FALLTHROUGH;
381  log_info(LD_EDGE,
382  "data from edge while in '%s' state. Leaving it on buffer.",
383  conn_state_to_string(conn->base_.type, conn->base_.state));
384  return 0;
385  }
386  log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
388  connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
389  connection_mark_for_close(TO_CONN(conn));
390  return -1;
391 }
392 
393 /** This edge needs to be closed, because its circuit has closed.
394  * Mark it for close and return 0.
395  */
396 int
398 {
399  if (!conn->base_.marked_for_close) {
400  log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
401  (unsigned) circ_id);
402  if (conn->base_.type == CONN_TYPE_AP) {
403  entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
404  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
406  control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
407  END_STREAM_REASON_DESTROY);
409  } else {
410  /* closing the circuit, nothing to send an END to */
411  conn->edge_has_sent_end = 1;
412  conn->end_reason = END_STREAM_REASON_DESTROY;
414  connection_mark_and_flush(TO_CONN(conn));
415  }
416  }
417  conn->cpath_layer = NULL;
418  conn->on_circuit = NULL;
419  return 0;
420 }
421 
422 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
423  * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
424  * is not a client connection, set the relay end cell's reason for closing
425  * as <b>reason</b> */
426 static int
428  uint8_t reason, crypt_path_t *cpath_layer)
429 {
430  char payload[1];
431 
432  if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
433  /* Never send the server an informative reason code; it doesn't need to
434  * know why the client stream is failing. */
435  reason = END_STREAM_REASON_MISC;
436  }
437 
438  payload[0] = (char) reason;
439 
440  /* Note: we have to use relay_send_command_from_edge here, not
441  * connection_edge_end or connection_edge_send_command, since those require
442  * that we have a stream connected to a circuit, and we don't connect to a
443  * circuit until we have a pending/successful resolve. */
444  return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
445  payload, 1, cpath_layer);
446 }
447 
448 /* If the connection <b>conn</b> is attempting to connect to an external
449  * destination that is an hidden service and the reason is a connection
450  * refused or timeout, log it so the operator can take appropriate actions.
451  * The log statement is a rate limited warning. */
452 static void
453 warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
454 {
455  tor_assert(conn);
456 
457  if (conn->base_.type == CONN_TYPE_EXIT &&
459  (reason == END_STREAM_REASON_CONNECTREFUSED ||
460  reason == END_STREAM_REASON_TIMEOUT)) {
461 #define WARN_FAILED_HS_CONNECTION 300
462  static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
463  char *m;
464  if ((m = rate_limit_log(&warn_limit, approx_time()))) {
465  log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
468  tor_free(m);
469  }
470  }
471 }
472 
473 /** Given a TTL (in seconds) from a DNS response or from a relay, determine
474  * what TTL clients and relays should actually use for caching it. */
475 uint32_t
476 clip_dns_ttl(uint32_t ttl)
477 {
478  /* This logic is a defense against "DefectTor" DNS-based traffic
479  * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
480  * We only give two values: a "low" value and a "high" value.
481  */
482  if (ttl < MIN_DNS_TTL)
483  return MIN_DNS_TTL;
484  else
485  return MAX_DNS_TTL;
486 }
487 
488 /** Given a TTL (in seconds), determine what TTL an exit relay should use by
489  * first clipping as usual and then adding some randomness which is sampled
490  * uniformly at random from [-FUZZY_DNS_TTL, FUZZY_DNS_TTL]. This facilitates
491  * fuzzy TTLs, which makes it harder to infer when a website was visited via
492  * side-channels like DNS (see "Website Fingerprinting with Website Oracles").
493  *
494  * Note that this can't underflow because FUZZY_DNS_TTL < MIN_DNS_TTL.
495  */
496 uint32_t
497 clip_dns_fuzzy_ttl(uint32_t ttl)
498 {
499  return clip_dns_ttl(ttl) +
501 }
502 
503 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
504  * remember that we've done so. If this is not a client connection, set the
505  * relay end cell's reason for closing as <b>reason</b>.
506  *
507  * Return -1 if this function has already been called on this conn,
508  * else return 0.
509  */
510 int
512 {
513  char payload[RELAY_PAYLOAD_SIZE];
514  size_t payload_len=1;
515  circuit_t *circ;
516  uint8_t control_reason = reason;
517 
518  if (conn->edge_has_sent_end) {
519  log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
520  "on an already ended stream?", reason);
522  return -1;
523  }
524 
525  if (conn->base_.marked_for_close) {
526  log_warn(LD_BUG,
527  "called on conn that's already marked for close at %s:%d.",
528  conn->base_.marked_for_close_file, conn->base_.marked_for_close);
529  return 0;
530  }
531 
532  circ = circuit_get_by_edge_conn(conn);
533  if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
534  /* If this is a client circuit, don't send the server an informative
535  * reason code; it doesn't need to know why the client stream is
536  * failing. */
537  reason = END_STREAM_REASON_MISC;
538  }
539 
540  payload[0] = (char)reason;
541  if (reason == END_STREAM_REASON_EXITPOLICY &&
543  int addrlen;
544  if (tor_addr_family(&conn->base_.addr) == AF_INET) {
545  set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
546  addrlen = 4;
547  } else {
548  memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
549  addrlen = 16;
550  }
551  set_uint32(payload+1+addrlen, htonl(conn->address_ttl));
552  payload_len += 4+addrlen;
553  }
554 
555  if (circ && !circ->marked_for_close) {
556  log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
557  conn->base_.s);
558 
559  if (CIRCUIT_IS_ORIGIN(circ)) {
560  origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
561  connection_half_edge_add(conn, origin_circ);
562  }
563 
564  connection_edge_send_command(conn, RELAY_COMMAND_END,
565  payload, payload_len);
566  /* We'll log warn if the connection was an hidden service and couldn't be
567  * made because the service wasn't available. */
568  warn_if_hs_unreachable(conn, control_reason);
569  } else {
570  log_debug(LD_EDGE,"No circ to send end on conn "
571  "(fd "TOR_SOCKET_T_FORMAT").",
572  conn->base_.s);
573  }
574 
575  conn->edge_has_sent_end = 1;
576  conn->end_reason = control_reason;
577  return 0;
578 }
579 
580 /**
581  * Helper function for bsearch.
582  *
583  * As per smartlist_bsearch, return < 0 if key precedes member,
584  * > 0 if member precedes key, and 0 if they are equal.
585  *
586  * This is equivalent to subtraction of the values of key - member
587  * (why does no one ever say that explicitly?).
588  */
589 static int
590 connection_half_edge_compare_bsearch(const void *key, const void **member)
591 {
592  const half_edge_t *e2;
593  tor_assert(key);
594  tor_assert(member && *(half_edge_t**)member);
595  e2 = *(const half_edge_t **)member;
596 
597  return *(const streamid_t*)key - e2->stream_id;
598 }
599 
600 /** Total number of half_edge_t objects allocated */
601 static size_t n_half_conns_allocated = 0;
602 
603 /**
604  * Add a half-closed connection to the list, to watch for activity.
605  *
606  * These connections are removed from the list upon receiving an end
607  * cell.
608  */
609 STATIC void
611  origin_circuit_t *circ)
612 {
613  half_edge_t *half_conn = NULL;
614  int insert_at = 0;
615  int ignored;
616 
617  /* Double-check for re-insertion. This should not happen,
618  * but this check is cheap compared to the sort anyway */
620  conn->stream_id)) {
621  log_warn(LD_BUG, "Duplicate stream close for stream %d on circuit %d",
622  conn->stream_id, circ->global_identifier);
623  return;
624  }
625 
626  half_conn = tor_malloc_zero(sizeof(half_edge_t));
628 
629  if (!circ->half_streams) {
630  circ->half_streams = smartlist_new();
631  }
632 
633  half_conn->stream_id = conn->stream_id;
634 
635  // Is there a connected cell pending?
636  half_conn->connected_pending = conn->base_.state ==
638 
639  if (edge_uses_flow_control(conn)) {
640  /* If the edge uses the new congestion control flow control, we must use
641  * time-based limits on half-edge activity. */
642  uint64_t timeout_usec = (uint64_t)(get_circuit_build_timeout_ms()*1000);
643  half_conn->used_ccontrol = 1;
644 
645  /* If this is an onion service circuit, double the CBT as an approximate
646  * value for the other half of the circuit */
647  if (conn->hs_ident) {
648  timeout_usec *= 2;
649  }
650 
651  /* The stream should stop seeing any use after the larger of the circuit
652  * RTT and the overall circuit build timeout */
653  half_conn->end_ack_expected_usec = MAX(timeout_usec,
654  edge_get_max_rtt(conn)) +
656  } else {
657  // How many sendme's should I expect?
658  half_conn->sendmes_pending =
660 
661  /* Data should only arrive if we're not waiting on a resolved cell.
662  * It can arrive after waiting on connected, because of optimistic
663  * data. */
664  if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
665  // How many more data cells can arrive on this id?
666  half_conn->data_pending = conn->deliver_window;
667  }
668  }
669 
670  insert_at = smartlist_bsearch_idx(circ->half_streams, &half_conn->stream_id,
672  &ignored);
673  smartlist_insert(circ->half_streams, insert_at, half_conn);
674 }
675 
676 /** Release space held by <b>he</b> */
677 void
679 {
680  if (!he)
681  return;
683  tor_free(he);
684 }
685 
686 /** Return the number of bytes devoted to storing info on half-open streams. */
687 size_t
689 {
690  return n_half_conns_allocated * sizeof(half_edge_t);
691 }
692 
693 /**
694  * Find a stream_id_t in the list in O(lg(n)).
695  *
696  * Returns NULL if the list is empty or element is not found.
697  * Returns a pointer to the element if found.
698  */
701  streamid_t stream_id)
702 {
703  if (!half_conns)
704  return NULL;
705 
706  return smartlist_bsearch(half_conns, &stream_id,
708 }
709 
710 /**
711  * Check if this stream_id is in a half-closed state. If so,
712  * check if it still has data cells pending, and decrement that
713  * window if so.
714  *
715  * Return 1 if the data window was not empty.
716  * Return 0 otherwise.
717  */
718 int
720  streamid_t stream_id)
721 {
723  stream_id);
724 
725  if (!half)
726  return 0;
727 
728  if (half->used_ccontrol) {
730  return 0;
731  return 1;
732  }
733 
734  if (half->data_pending > 0) {
735  half->data_pending--;
736  return 1;
737  }
738 
739  return 0;
740 }
741 
742 /**
743  * Check if this stream_id is in a half-closed state. If so,
744  * check if it still has a connected cell pending, and decrement
745  * that window if so.
746  *
747  * Return 1 if the connected window was not empty.
748  * Return 0 otherwise.
749  */
750 int
752  streamid_t stream_id)
753 {
755  stream_id);
756 
757  if (!half)
758  return 0;
759 
760  if (half->connected_pending) {
761  half->connected_pending = 0;
762  return 1;
763  }
764 
765  return 0;
766 }
767 
768 /**
769  * Check if this stream_id is in a half-closed state. If so,
770  * check if it still has sendme cells pending, and decrement that
771  * window if so.
772  *
773  * Return 1 if the sendme window was not empty.
774  * Return 0 otherwise.
775  */
776 int
778  streamid_t stream_id)
779 {
781  stream_id);
782 
783  if (!half)
784  return 0;
785 
786  /* congestion control edges don't use sendmes */
787  if (half->used_ccontrol)
788  return 0;
789 
790  if (half->sendmes_pending > 0) {
791  half->sendmes_pending--;
792  return 1;
793  }
794 
795  return 0;
796 }
797 
798 /**
799  * Check if this stream_id is in a half-closed state. If so, remove
800  * it from the list. No other data should come after the END cell.
801  *
802  * Return 1 if stream_id was in half-closed state.
803  * Return 0 otherwise.
804  */
805 int
807  streamid_t stream_id)
808 {
809  half_edge_t *half;
810  int found, remove_idx;
811 
812  if (!half_conns)
813  return 0;
814 
815  remove_idx = smartlist_bsearch_idx(half_conns, &stream_id,
817  &found);
818  if (!found)
819  return 0;
820 
821  half = smartlist_get(half_conns, remove_idx);
822  smartlist_del_keeporder(half_conns, remove_idx);
823  half_edge_free(half);
824  return 1;
825 }
826 
827 /**
828  * Streams that were used to send a RESOLVE cell are closed
829  * when they get the RESOLVED, without an end. So treat
830  * a RESOLVED just like an end, and remove from the list.
831  */
832 int
834  streamid_t stream_id)
835 {
836  return connection_half_edge_is_valid_end(half_conns, stream_id);
837 }
838 
839 /** An error has just occurred on an operation on an edge connection
840  * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
841  * appropriate relay end cell to the other end of the connection's circuit.
842  **/
843 int
845 {
846  uint8_t reason;
847  tor_assert(conn);
848  reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
849  return connection_edge_end(conn, reason);
850 }
851 
852 /** We just wrote some data to <b>conn</b>; act appropriately.
853  *
854  * (That is, if it's open, consider sending a stream-level sendme cell if we
855  * have just flushed enough.)
856  */
857 int
859 {
860  switch (conn->base_.state) {
861  case AP_CONN_STATE_OPEN:
862  if (! conn->base_.linked) {
864  }
865 
866  FALLTHROUGH;
869  break;
870  }
871  return 0;
872 }
873 
874 /** Connection <b>conn</b> has finished writing and has no bytes left on
875  * its outbuf.
876  *
877  * If it's in state 'open', stop writing, consider responding with a
878  * sendme, and return.
879  * Otherwise, stop writing and return.
880  *
881  * If <b>conn</b> is broken, mark it for close and return -1, else
882  * return 0.
883  */
884 int
886 {
887  tor_assert(conn);
888 
889  switch (conn->base_.state) {
890  case AP_CONN_STATE_OPEN:
893  return 0;
902  return 0;
903  default:
904  log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
906  return -1;
907  }
908  return 0;
909 }
910 
911 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
912  * able to generate. */
913 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
914 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
915 
916 /** Set the buffer at <b>payload_out</b> -- which must have at least
917  * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
918  * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
919  * that the name resolution that led us to <b>addr</b> will be valid for
920  * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
921  * success. */
922 STATIC int
923 connected_cell_format_payload(uint8_t *payload_out,
924  const tor_addr_t *addr,
925  uint32_t ttl)
926 {
927  const sa_family_t family = tor_addr_family(addr);
928  int connected_payload_len;
929 
930  /* should be needless */
931  memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
932 
933  if (family == AF_INET) {
934  set_uint32(payload_out, tor_addr_to_ipv4n(addr));
935  connected_payload_len = 4;
936  } else if (family == AF_INET6) {
937  set_uint32(payload_out, 0);
938  set_uint8(payload_out + 4, 6);
939  memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
940  connected_payload_len = 21;
941  } else {
942  return -1;
943  }
944 
945  set_uint32(payload_out + connected_payload_len, htonl(ttl));
946  connected_payload_len += 4;
947 
948  tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
949 
950  return connected_payload_len;
951 }
952 
953 /* This is an onion service client connection: Export the client circuit ID
954  * according to the HAProxy proxy protocol. */
955 STATIC void
956 export_hs_client_circuit_id(edge_connection_t *edge_conn,
957  hs_circuit_id_protocol_t protocol)
958 {
959  /* We only support HAProxy right now. */
960  if (protocol != HS_CIRCUIT_ID_PROTOCOL_HAPROXY)
961  return;
962 
963  char *buf = NULL;
964  const char dst_ipv6[] = "::1";
965  /* See RFC4193 regarding fc00::/7 */
966  const char src_ipv6_prefix[] = "fc00:dead:beef:4dad:";
967  uint16_t dst_port = 0;
968  uint16_t src_port = 1; /* default value */
969  uint32_t gid = 0; /* default value */
970 
971  /* Generate a GID and source port for this client */
972  if (edge_conn->on_circuit != NULL) {
974  src_port = gid & 0x0000ffff;
975  }
976 
977  /* Grab the original dest port from the hs ident */
978  if (edge_conn->hs_ident) {
979  dst_port = edge_conn->hs_ident->orig_virtual_port;
980  }
981 
982  /* Build the string */
983  tor_asprintf(&buf, "PROXY TCP6 %s:%x:%x %s %d %d\r\n",
984  src_ipv6_prefix,
985  gid >> 16, gid & 0x0000ffff,
986  dst_ipv6, src_port, dst_port);
987 
988  connection_buf_add(buf, strlen(buf), TO_CONN(edge_conn));
989 
990  tor_free(buf);
991 }
992 
993 /** Connected handler for exit connections: start writing pending
994  * data, deliver 'CONNECTED' relay cells as appropriate, and check
995  * any pending data that may have been received. */
996 int
998 {
999  connection_t *conn;
1000 
1001  tor_assert(edge_conn);
1002  tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
1003  conn = TO_CONN(edge_conn);
1005 
1006  log_info(LD_EXIT,"%s established.",
1007  connection_describe(conn));
1008 
1010 
1011  conn->state = EXIT_CONN_STATE_OPEN;
1012 
1013  connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
1014  if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
1015  * cells */
1017  /* deliver a 'connected' relay cell back through the circuit. */
1018  if (connection_edge_is_rendezvous_stream(edge_conn)) {
1019  if (connection_edge_send_command(edge_conn,
1020  RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
1021  return 0; /* circuit is closed, don't continue */
1022  } else {
1023  uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
1024  int connected_payload_len =
1025  connected_cell_format_payload(connected_payload, &conn->addr,
1026  edge_conn->address_ttl);
1027  if (connected_payload_len < 0)
1028  return -1;
1029 
1030  if (connection_edge_send_command(edge_conn,
1031  RELAY_COMMAND_CONNECTED,
1032  (char*)connected_payload, connected_payload_len) < 0)
1033  return 0; /* circuit is closed, don't continue */
1034  }
1035  tor_assert(edge_conn->package_window > 0);
1036  /* in case the server has written anything */
1037  return connection_edge_process_inbuf(edge_conn, 1);
1038 }
1039 
1040 /** A list of all the entry_connection_t * objects that are not marked
1041  * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
1042  *
1043  * (Right now, we check in several places to make sure that this list is
1044  * correct. When it's incorrect, we'll fix it, and log a BUG message.)
1045  */
1047 
1048 static int untried_pending_connections = 0;
1049 
1050 /**
1051  * Mainloop event to tell us to scan for pending connections that can
1052  * be attached.
1053  */
1055 
1056 /** Common code to connection_(ap|exit)_about_to_close. */
1057 static void
1059 {
1060  if (!edge_conn->edge_has_sent_end) {
1061  connection_t *conn = TO_CONN(edge_conn);
1062  log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
1063  "hasn't sent end yet?",
1066  }
1067 }
1068 
1069 /** Called when we're about to finally unlink and free an AP (client)
1070  * connection: perform necessary accounting and cleanup */
1071 void
1073 {
1074  circuit_t *circ;
1075  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
1076  connection_t *conn = ENTRY_TO_CONN(entry_conn);
1077 
1078  connection_edge_about_to_close(edge_conn);
1079 
1080  if (entry_conn->socks_request->has_finished == 0) {
1081  /* since conn gets removed right after this function finishes,
1082  * there's no point trying to send back a reply at this point. */
1083  log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
1084  " back a socks reply.",
1086  }
1087  if (!edge_conn->end_reason) {
1088  log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
1089  " set end_reason.",
1091  }
1092  if (entry_conn->dns_server_request) {
1093  log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
1094  " replied to DNS request.",
1096  dnsserv_reject_request(entry_conn);
1097  }
1098 
1099  if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1101  }
1102 
1103 #if 1
1104  /* Check to make sure that this isn't in pending_entry_connections if it
1105  * didn't actually belong there. */
1106  if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
1107  connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
1108  "about_to_close");
1109  }
1110 #endif /* 1 */
1111 
1112  control_event_stream_bandwidth(edge_conn);
1113  control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
1114  edge_conn->end_reason);
1115  circ = circuit_get_by_edge_conn(edge_conn);
1116  if (circ)
1117  circuit_detach_stream(circ, edge_conn);
1118 }
1119 
1120 /** Called when we're about to finally unlink and free an exit
1121  * connection: perform necessary accounting and cleanup */
1122 void
1124 {
1125  circuit_t *circ;
1126  connection_t *conn = TO_CONN(edge_conn);
1127 
1128  connection_edge_about_to_close(edge_conn);
1129 
1130  circ = circuit_get_by_edge_conn(edge_conn);
1131  if (circ)
1132  circuit_detach_stream(circ, edge_conn);
1133  if (conn->state == EXIT_CONN_STATE_RESOLVING) {
1134  connection_dns_remove(edge_conn);
1135  }
1136 }
1137 
1138 /** Define a schedule for how long to wait between retrying
1139  * application connections. Rather than waiting a fixed amount of
1140  * time between each retry, we wait 10 seconds each for the first
1141  * two tries, and 15 seconds for each retry after
1142  * that. Hopefully this will improve the expected user experience. */
1143 static int
1145 {
1147  if (timeout) /* if our config options override the default, use them */
1148  return timeout;
1149  if (conn->num_socks_retries < 2) /* try 0 and try 1 */
1150  return 10;
1151  return 15;
1152 }
1153 
1154 /** Find all general-purpose AP streams waiting for a response that sent their
1155  * begin/resolve cell too long ago. Detach from their current circuit, and
1156  * mark their current circuit as unsuitable for new streams. Then call
1157  * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
1158  * available) or launch a new one.
1159  *
1160  * For rendezvous streams, simply give up after SocksTimeout seconds (with no
1161  * retry attempt).
1162  */
1163 void
1165 {
1166  edge_connection_t *conn;
1167  entry_connection_t *entry_conn;
1168  circuit_t *circ;
1169  time_t now = time(NULL);
1170  const or_options_t *options = get_options();
1171  int severity;
1172  int cutoff;
1173  int seconds_idle, seconds_since_born;
1174  smartlist_t *conns = get_connection_array();
1175 
1176  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1177  if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
1178  continue;
1179  entry_conn = TO_ENTRY_CONN(base_conn);
1180  conn = ENTRY_TO_EDGE_CONN(entry_conn);
1181  /* if it's an internal linked connection, don't yell its status. */
1182  severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
1183  ? LOG_INFO : LOG_NOTICE;
1184  seconds_idle = (int)( now - base_conn->timestamp_last_read_allowed );
1185  seconds_since_born = (int)( now - base_conn->timestamp_created );
1186 
1187  if (base_conn->state == AP_CONN_STATE_OPEN)
1188  continue;
1189 
1190  /* We already consider SocksTimeout in
1191  * connection_ap_handshake_attach_circuit(), but we need to consider
1192  * it here too because controllers that put streams in controller_wait
1193  * state never ask Tor to attach the circuit. */
1194  if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
1195  if (seconds_since_born >= options->SocksTimeout) {
1196  log_fn(severity, LD_APP,
1197  "Tried for %d seconds to get a connection to %s:%d. "
1198  "Giving up. (%s)",
1199  seconds_since_born,
1200  safe_str_client(entry_conn->socks_request->address),
1201  entry_conn->socks_request->port,
1202  conn_state_to_string(CONN_TYPE_AP, base_conn->state));
1203  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1204  }
1205  continue;
1206  }
1207 
1208  /* We're in state connect_wait or resolve_wait now -- waiting for a
1209  * reply to our relay cell. See if we want to retry/give up. */
1210 
1211  cutoff = compute_retry_timeout(entry_conn);
1212  if (seconds_idle < cutoff)
1213  continue;
1214  circ = circuit_get_by_edge_conn(conn);
1215  if (!circ) { /* it's vanished? */
1216  log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
1217  safe_str_client(entry_conn->socks_request->address));
1218  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1219  continue;
1220  }
1221  if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
1222  if (seconds_idle >= options->SocksTimeout) {
1223  log_fn(severity, LD_REND,
1224  "Rend stream is %d seconds late. Giving up on address"
1225  " '%s.onion'.",
1226  seconds_idle,
1227  safe_str_client(entry_conn->socks_request->address));
1228  /* Roll back path bias use state so that we probe the circuit
1229  * if nothing else succeeds on it */
1231 
1232  connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1233  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1234  }
1235  continue;
1236  }
1237 
1238  if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1244  log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
1245  "The purpose on the circuit was %s; it was in state %s, "
1246  "path_state %s.",
1249  CIRCUIT_IS_ORIGIN(circ) ?
1250  pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
1251  "none");
1252  }
1253  log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
1254  "We tried for %d seconds to connect to '%s' using exit %s."
1255  " Retrying on a new circuit.",
1256  seconds_idle,
1257  safe_str_client(entry_conn->socks_request->address),
1258  conn->cpath_layer ?
1260  "*unnamed*");
1261  /* send an end down the circuit */
1262  connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1263  /* un-mark it as ending, since we're going to reuse it */
1264  conn->edge_has_sent_end = 0;
1265  conn->end_reason = 0;
1266  /* make us not try this circuit again, but allow
1267  * current streams on it to survive if they can */
1269 
1270  /* give our stream another 'cutoff' seconds to try */
1271  conn->base_.timestamp_last_read_allowed += cutoff;
1272  if (entry_conn->num_socks_retries < 250) /* avoid overflow */
1273  entry_conn->num_socks_retries++;
1274  /* move it back into 'pending' state, and try to attach. */
1275  if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
1276  END_STREAM_REASON_TIMEOUT)<0) {
1277  if (!base_conn->marked_for_close)
1278  connection_mark_unattached_ap(entry_conn,
1280  }
1281  } SMARTLIST_FOREACH_END(base_conn);
1282 }
1283 
1284 /**
1285  * As connection_ap_attach_pending, but first scans the entire connection
1286  * array to see if any elements are missing.
1287  */
1288 void
1290 {
1291  entry_connection_t *entry_conn;
1292  smartlist_t *conns = get_connection_array();
1293 
1294  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1296 
1297  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1298  if (conn->marked_for_close ||
1299  conn->type != CONN_TYPE_AP ||
1300  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1301  continue;
1302 
1303  entry_conn = TO_ENTRY_CONN(conn);
1304  tor_assert(entry_conn);
1305  if (! smartlist_contains(pending_entry_connections, entry_conn)) {
1306  log_warn(LD_BUG, "Found a connection %p that was supposed to be "
1307  "in pending_entry_connections, but wasn't. No worries; "
1308  "adding it.",
1310  untried_pending_connections = 1;
1311  connection_ap_mark_as_pending_circuit(entry_conn);
1312  }
1313 
1314  } SMARTLIST_FOREACH_END(conn);
1315 
1317 }
1318 
1319 /** Tell any AP streams that are listed as waiting for a new circuit to try
1320  * again. If there is an available circuit for a stream, attach it. Otherwise,
1321  * launch a new circuit.
1322  *
1323  * If <b>retry</b> is false, only check the list if it contains at least one
1324  * streams that we have not yet tried to attach to a circuit.
1325  */
1326 void
1328 {
1329  if (PREDICT_UNLIKELY(!pending_entry_connections)) {
1330  return;
1331  }
1332 
1333  if (untried_pending_connections == 0 && !retry)
1334  return;
1335 
1336  /* Don't allow any modifications to list while we are iterating over
1337  * it. We'll put streams back on this list if we can't attach them
1338  * immediately. */
1341 
1342  SMARTLIST_FOREACH_BEGIN(pending,
1343  entry_connection_t *, entry_conn) {
1344  connection_t *conn = ENTRY_TO_CONN(entry_conn);
1345  tor_assert(conn && entry_conn);
1346  if (conn->marked_for_close) {
1347  continue;
1348  }
1349  if (conn->magic != ENTRY_CONNECTION_MAGIC) {
1350  log_warn(LD_BUG, "%p has impossible magic value %u.",
1351  entry_conn, (unsigned)conn->magic);
1352  continue;
1353  }
1354  if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
1355  /* The connection_ap_handshake_attach_circuit() call, for onion service,
1356  * can lead to more than one connections in the "pending" list to change
1357  * state and so it is OK to get here. Ignore it because this connection
1358  * won't be in pending_entry_connections list after this point. */
1359  continue;
1360  }
1361 
1362  /* Okay, we're through the sanity checks. Try to handle this stream. */
1363  if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
1364  if (!conn->marked_for_close)
1365  connection_mark_unattached_ap(entry_conn,
1367  }
1368 
1369  if (! conn->marked_for_close &&
1370  conn->type == CONN_TYPE_AP &&
1371  conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1372  /* Is it still waiting for a circuit? If so, we didn't attach it,
1373  * so it's still pending. Put it back on the list.
1374  */
1375  if (!smartlist_contains(pending_entry_connections, entry_conn)) {
1377  continue;
1378  }
1379  }
1380 
1381  /* If we got here, then we either closed the connection, or
1382  * we attached it. */
1383  } SMARTLIST_FOREACH_END(entry_conn);
1384 
1385  smartlist_free(pending);
1386  untried_pending_connections = 0;
1387 }
1388 
1389 static void
1390 attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
1391 {
1392  (void)ev;
1393  (void)arg;
1395 }
1396 
1397 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
1398  *
1399  * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
1400  * should not already be pending a circuit. The circuit will get
1401  * launched or the connection will get attached the next time we
1402  * call connection_ap_attach_pending().
1403  */
1404 void
1406  const char *fname, int lineno)
1407 {
1408  connection_t *conn = ENTRY_TO_CONN(entry_conn);
1410  tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
1411  if (conn->marked_for_close)
1412  return;
1413 
1414  if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
1416  }
1417  if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
1419  attach_pending_entry_connections_cb, NULL);
1420  }
1421  if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
1422  entry_conn))) {
1423  log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
1424  "(Called from %s:%d.)",
1425  entry_conn, fname, lineno);
1426 #ifdef DEBUGGING_17659
1427  const char *f2 = entry_conn->marked_pending_circ_file;
1428  log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
1429  f2 ? f2 : "<NULL>",
1430  entry_conn->marked_pending_circ_line);
1431 #endif /* defined(DEBUGGING_17659) */
1432  log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
1433  return;
1434  }
1435 
1436 #ifdef DEBUGGING_17659
1437  entry_conn->marked_pending_circ_line = (uint16_t) lineno;
1438  entry_conn->marked_pending_circ_file = fname;
1439 #endif
1440 
1441  untried_pending_connections = 1;
1443 
1445 }
1446 
1447 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
1448 void
1450 {
1451  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1452  return;
1454 }
1455 
1456 /** Mark <b>entry_conn</b> as waiting for a rendezvous descriptor. This
1457  * function will remove the entry connection from the waiting for a circuit
1458  * list (pending_entry_connections).
1459  *
1460  * This pattern is used across the code base because a connection in state
1461  * AP_CONN_STATE_RENDDESC_WAIT must not be in the pending list. */
1462 void
1464 {
1465  tor_assert(entry_conn);
1466 
1468  ENTRY_TO_CONN(entry_conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
1469 }
1470 
1471 /* DOCDOC */
1472 void
1473 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
1474  const char *where)
1475 {
1478  log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
1479  entry_conn, where);
1481  }
1482 }
1483 
1484 /** Tell any AP streams that are waiting for a one-hop tunnel to
1485  * <b>failed_digest</b> that they are going to fail. */
1486 /* XXXX We should get rid of this function, and instead attach
1487  * one-hop streams to circ->p_streams so they get marked in
1488  * circuit_mark_for_close like normal p_streams. */
1489 void
1490 connection_ap_fail_onehop(const char *failed_digest,
1491  cpath_build_state_t *build_state)
1492 {
1493  entry_connection_t *entry_conn;
1494  char digest[DIGEST_LEN];
1495  smartlist_t *conns = get_connection_array();
1496  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1497  if (conn->marked_for_close ||
1498  conn->type != CONN_TYPE_AP ||
1499  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1500  continue;
1501  entry_conn = TO_ENTRY_CONN(conn);
1502  if (!entry_conn->want_onehop)
1503  continue;
1504  if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
1505  tor_memneq(digest, failed_digest, DIGEST_LEN))
1506  continue;
1507  if (tor_digest_is_zero(digest)) {
1508  /* we don't know the digest; have to compare addr:port */
1509  tor_addr_t addr;
1510  if (!build_state || !build_state->chosen_exit ||
1511  !entry_conn->socks_request) {
1512  continue;
1513  }
1514  if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
1515  !extend_info_has_orport(build_state->chosen_exit, &addr,
1516  entry_conn->socks_request->port))
1517  continue;
1518  }
1519  log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
1520  "just failed.", entry_conn->chosen_exit_name,
1521  entry_conn->socks_request->address);
1522  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1523  } SMARTLIST_FOREACH_END(conn);
1524 }
1525 
1526 /** A circuit failed to finish on its last hop <b>info</b>. If there
1527  * are any streams waiting with this exit node in mind, but they
1528  * don't absolutely require it, make them give up on it.
1529  */
1530 void
1532 {
1533  entry_connection_t *entry_conn;
1534  const node_t *r1, *r2;
1535 
1536  smartlist_t *conns = get_connection_array();
1537  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1538  if (conn->marked_for_close ||
1539  conn->type != CONN_TYPE_AP ||
1540  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1541  continue;
1542  entry_conn = TO_ENTRY_CONN(conn);
1543  if (!entry_conn->chosen_exit_optional &&
1544  !entry_conn->chosen_exit_retries)
1545  continue;
1546  r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
1547  NNF_NO_WARN_UNNAMED);
1548  r2 = node_get_by_id(info->identity_digest);
1549  if (!r1 || !r2 || r1 != r2)
1550  continue;
1551  tor_assert(entry_conn->socks_request);
1552  if (entry_conn->chosen_exit_optional) {
1553  log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
1554  safe_str_client(entry_conn->chosen_exit_name),
1556  entry_conn->chosen_exit_optional = 0;
1557  tor_free(entry_conn->chosen_exit_name); /* clears it */
1558  /* if this port is dangerous, warn or reject it now that we don't
1559  * think it'll be using an enclave. */
1560  consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1561  }
1562  if (entry_conn->chosen_exit_retries) {
1563  if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
1565  tor_free(entry_conn->chosen_exit_name); /* clears it */
1566  /* if this port is dangerous, warn or reject it now that we don't
1567  * think it'll be using an enclave. */
1568  consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1569  }
1570  }
1571  } SMARTLIST_FOREACH_END(conn);
1572 }
1573 
1574 /** Set the connection state to CONTROLLER_WAIT and send an control port event.
1575  */
1576 void
1578 {
1579  CONNECTION_AP_EXPECT_NONPENDING(conn);
1581  control_event_stream_status(conn, STREAM_EVENT_CONTROLLER_WAIT, 0);
1582 }
1583 
1584 /** The AP connection <b>conn</b> has just failed while attaching or
1585  * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1586  * might work. Detach the circuit, and either reattach it, launch a
1587  * new circuit, tell the controller, or give up as appropriate.
1588  *
1589  * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1590  */
1591 int
1593  origin_circuit_t *circ,
1594  int reason)
1595 {
1596  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
1597  ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
1598 
1599  /* Roll back path bias use state so that we probe the circuit
1600  * if nothing else succeeds on it */
1602 
1603  if (conn->pending_optimistic_data) {
1604  buf_set_to_copy(&conn->sending_optimistic_data,
1605  conn->pending_optimistic_data);
1606  }
1607 
1608  if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
1609  /* If we're attaching streams ourself, or if this connection is
1610  * a tunneled directory connection, then just attach it. */
1613  connection_ap_mark_as_pending_circuit(conn);
1614  } else {
1617  }
1618  return 0;
1619 }
1620 
1621 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1622  * reject depending on our config options. */
1623 static int
1625 {
1626  const or_options_t *options = get_options();
1627  int reject = smartlist_contains_int_as_string(
1628  options->RejectPlaintextPorts, port);
1629 
1631  log_warn(LD_APP, "Application request to port %d: this port is "
1632  "commonly used for unencrypted protocols. Please make sure "
1633  "you don't send anything you would mind the rest of the "
1634  "Internet reading!%s", port, reject ? " Closing." : "");
1635  control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1636  port, reject ? "REJECT" : "WARN");
1637  }
1638 
1639  if (reject) {
1640  log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1641  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1642  return -1;
1643  }
1644 
1645  return 0;
1646 }
1647 
1648 /** Parse the given hostname in address. Returns true if the parsing was
1649  * successful and type_out contains the type of the hostname. Else, false is
1650  * returned which means it was not recognized and type_out is set to
1651  * BAD_HOSTNAME.
1652  *
1653  * The possible recognized forms are (where true is returned):
1654  *
1655  * If address is of the form "y.onion" with a well-formed handle y:
1656  * Put a NUL after y, lower-case it, and return ONION_V3_HOSTNAME
1657  * depending on the HS version.
1658  *
1659  * If address is of the form "x.y.onion" with a well-formed handle x:
1660  * Drop "x.", put a NUL after y, lower-case it, and return
1661  * ONION_V3_HOSTNAME depending on the HS version.
1662  *
1663  * If address is of the form "y.onion" with a badly-formed handle y:
1664  * Return BAD_HOSTNAME and log a message.
1665  *
1666  * If address is of the form "y.exit":
1667  * Put a NUL after y and return EXIT_HOSTNAME.
1668  *
1669  * Otherwise:
1670  * Return NORMAL_HOSTNAME and change nothing.
1671  */
1672 STATIC bool
1673 parse_extended_hostname(char *address, hostname_type_t *type_out)
1674 {
1675  char *s;
1676  char *q;
1677  char query[HS_SERVICE_ADDR_LEN_BASE32+1];
1678 
1679  s = strrchr(address,'.');
1680  if (!s) {
1681  *type_out = NORMAL_HOSTNAME; /* no dot, thus normal */
1682  goto success;
1683  }
1684  if (!strcmp(s+1,"exit")) {
1685  *s = 0; /* NUL-terminate it */
1686  *type_out = EXIT_HOSTNAME; /* .exit */
1687  goto success;
1688  }
1689  if (strcmp(s+1,"onion")) {
1690  *type_out = NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1691  goto success;
1692  }
1693 
1694  /* so it is .onion */
1695  *s = 0; /* NUL-terminate it */
1696  /* locate a 'sub-domain' component, in order to remove it */
1697  q = strrchr(address, '.');
1698  if (q == address) {
1699  *type_out = BAD_HOSTNAME;
1700  goto failed; /* reject sub-domain, as DNS does */
1701  }
1702  q = (NULL == q) ? address : q + 1;
1703  if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
1705  *type_out = BAD_HOSTNAME;
1706  goto failed;
1707  }
1708  if (q != address) {
1709  memmove(address, q, strlen(q) + 1 /* also get \0 */);
1710  }
1711 
1712  /* v3 onion address check. */
1713  if (strlen(query) == HS_SERVICE_ADDR_LEN_BASE32) {
1714  *type_out = ONION_V3_HOSTNAME;
1715  if (hs_address_is_valid(query)) {
1716  goto success;
1717  }
1718  goto failed;
1719  }
1720 
1721  /* Reaching this point, nothing was recognized. */
1722  *type_out = BAD_HOSTNAME;
1723  goto failed;
1724 
1725  success:
1726  return true;
1727  failed:
1728  /* otherwise, return to previous state and return 0 */
1729  *s = '.';
1730  const bool is_onion = (*type_out == ONION_V3_HOSTNAME);
1731  log_warn(LD_APP, "Invalid %shostname %s; rejecting",
1732  is_onion ? "onion " : "",
1733  safe_str_client(address));
1734  if (*type_out == ONION_V3_HOSTNAME) {
1735  *type_out = BAD_HOSTNAME;
1736  }
1737  return false;
1738 }
1739 
1740 /** How many times do we try connecting with an exit configured via
1741  * TrackHostExits before concluding that it won't work any more and trying a
1742  * different one? */
1743 #define TRACKHOSTEXITS_RETRIES 5
1744 
1745 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1746  * asked us to leave streams unattached. Return 0 in that case.
1747  *
1748  * See connection_ap_handshake_rewrite_and_attach()'s
1749  * documentation for arguments and return value.
1750  */
1751 MOCK_IMPL(int,
1753  origin_circuit_t *circ,
1754  crypt_path_t *cpath))
1755 {
1756  const or_options_t *options = get_options();
1757 
1758  if (options->LeaveStreamsUnattached) {
1760  return 0;
1761  }
1762  return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1763 }
1764 
1765 /* Try to perform any map-based rewriting of the target address in
1766  * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1767  * conn->socks_request.address as appropriate.
1768  */
1769 STATIC void
1770 connection_ap_handshake_rewrite(entry_connection_t *conn,
1771  rewrite_result_t *out)
1772 {
1773  socks_request_t *socks = conn->socks_request;
1774  const or_options_t *options = get_options();
1775  tor_addr_t addr_tmp;
1776 
1777  /* Initialize all the fields of 'out' to reasonable defaults */
1778  out->automap = 0;
1779  out->exit_source = ADDRMAPSRC_NONE;
1780  out->map_expires = TIME_MAX;
1781  out->end_reason = 0;
1782  out->should_close = 0;
1783  out->orig_address[0] = 0;
1784 
1785  /* We convert all incoming addresses to lowercase. */
1786  tor_strlower(socks->address);
1787  /* Remember the original address. */
1788  strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
1789  log_debug(LD_APP,"Client asked for %s:%d",
1790  safe_str_client(socks->address),
1791  socks->port);
1792 
1793  /* Check for whether this is a .exit address. By default, those are
1794  * disallowed when they're coming straight from the client, but you're
1795  * allowed to have them in MapAddress commands and so forth. */
1796  if (!strcmpend(socks->address, ".exit")) {
1797  static ratelim_t exit_warning_limit = RATELIM_INIT(60*15);
1798  log_fn_ratelim(&exit_warning_limit, LOG_WARN, LD_APP,
1799  "The \".exit\" notation is disabled in Tor due to "
1800  "security risks.");
1801  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1802  escaped(socks->address));
1803  out->end_reason = END_STREAM_REASON_TORPROTOCOL;
1804  out->should_close = 1;
1805  return;
1806  }
1807 
1808  /* Remember the original address so we can tell the user about what
1809  * they actually said, not just what it turned into. */
1810  /* XXX yes, this is the same as out->orig_address above. One is
1811  * in the output, and one is in the connection. */
1812  if (! conn->original_dest_address) {
1813  /* Is the 'if' necessary here? XXXX */
1814  conn->original_dest_address = tor_strdup(conn->socks_request->address);
1815  }
1816 
1817  /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1818  * these only for non-reverse lookups, since they don't exist for those.
1819  * We also need to do this before we consider automapping, since we might
1820  * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1821  * we'd need to automap it. */
1822  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
1823  const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
1824  if (addressmap_rewrite(socks->address, sizeof(socks->address),
1825  rewrite_flags, &out->map_expires, &out->exit_source)) {
1826  control_event_stream_status(conn, STREAM_EVENT_REMAP,
1828  }
1829  }
1830 
1831  /* Now see if we need to create or return an existing Hostname->IP
1832  * automapping. Automapping happens when we're asked to resolve a
1833  * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1834  * suffix listed in AutomapHostsSuffixes. It's a handy feature
1835  * that lets you have Tor assign e.g. IPv6 addresses for .onion
1836  * names, and return them safely from DNSPort.
1837  */
1838  if (socks->command == SOCKS_COMMAND_RESOLVE &&
1839  tor_addr_parse(&addr_tmp, socks->address)<0 &&
1840  options->AutomapHostsOnResolve) {
1841  /* Check the suffix... */
1842  out->automap = addressmap_address_should_automap(socks->address, options);
1843  if (out->automap) {
1844  /* If we get here, then we should apply an automapping for this. */
1845  const char *new_addr;
1846  /* We return an IPv4 address by default, or an IPv6 address if we
1847  * are allowed to do so. */
1848  int addr_type = RESOLVED_TYPE_IPV4;
1849  if (conn->socks_request->socks_version != 4) {
1850  if (!conn->entry_cfg.ipv4_traffic ||
1851  (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
1852  conn->entry_cfg.prefer_ipv6_virtaddr)
1853  addr_type = RESOLVED_TYPE_IPV6;
1854  }
1855  /* Okay, register the target address as automapped, and find the new
1856  * address we're supposed to give as a resolve answer. (Return a cached
1857  * value if we've looked up this address before.
1858  */
1860  addr_type, tor_strdup(socks->address));
1861  if (! new_addr) {
1862  log_warn(LD_APP, "Unable to automap address %s",
1863  escaped_safe_str(socks->address));
1864  out->end_reason = END_STREAM_REASON_INTERNAL;
1865  out->should_close = 1;
1866  return;
1867  }
1868  log_info(LD_APP, "Automapping %s to %s",
1870  safe_str_client(new_addr));
1871  strlcpy(socks->address, new_addr, sizeof(socks->address));
1872  }
1873  }
1874 
1875  /* Now handle reverse lookups, if they're in the cache. This doesn't
1876  * happen too often, since client-side DNS caching is off by default,
1877  * and very deprecated. */
1878  if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1879  unsigned rewrite_flags = 0;
1880  if (conn->entry_cfg.use_cached_ipv4_answers)
1881  rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1882  if (conn->entry_cfg.use_cached_ipv6_answers)
1883  rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1884 
1885  if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1886  rewrite_flags, &out->map_expires)) {
1887  char *result = tor_strdup(socks->address);
1888  /* remember _what_ is supposed to have been resolved. */
1889  tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1890  out->orig_address);
1891  connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1892  strlen(result), (uint8_t*)result,
1893  -1,
1894  out->map_expires);
1895  tor_free(result);
1896  out->end_reason = END_STREAM_REASON_DONE |
1898  out->should_close = 1;
1899  return;
1900  }
1901 
1902  /* Hang on, did we find an answer saying that this is a reverse lookup for
1903  * an internal address? If so, we should reject it if we're configured to
1904  * do so. */
1905  if (options->ClientDNSRejectInternalAddresses) {
1906  /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1907  tor_addr_t addr;
1908  int ok;
1910  &addr, socks->address, AF_UNSPEC, 1);
1911  if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1912  connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1913  0, NULL, -1, TIME_MAX);
1914  out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
1916  out->should_close = 1;
1917  return;
1918  }
1919  }
1920  }
1921 
1922  /* If we didn't automap it before, then this is still the address that
1923  * came straight from the user, mapped according to any
1924  * MapAddress/MAPADDRESS commands. Now apply other mappings,
1925  * including previously registered Automap entries (IP back to
1926  * hostname), TrackHostExits entries, and client-side DNS cache
1927  * entries (if they're turned on).
1928  */
1929  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
1930  !out->automap) {
1931  unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
1932  addressmap_entry_source_t exit_source2;
1933  if (conn->entry_cfg.use_cached_ipv4_answers)
1934  rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1935  if (conn->entry_cfg.use_cached_ipv6_answers)
1936  rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1937  if (addressmap_rewrite(socks->address, sizeof(socks->address),
1938  rewrite_flags, &out->map_expires, &exit_source2)) {
1939  control_event_stream_status(conn, STREAM_EVENT_REMAP,
1941  }
1942  if (out->exit_source == ADDRMAPSRC_NONE) {
1943  /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1944  * the original source of a .exit. */
1945  out->exit_source = exit_source2;
1946  }
1947  }
1948 
1949  /* Check to see whether we're about to use an address in the virtual
1950  * range without actually having gotten it from an Automap. */
1951  if (!out->automap && address_is_in_virtual_range(socks->address)) {
1952  /* This address was probably handed out by
1953  * client_dns_get_unmapped_address, but the mapping was discarded for some
1954  * reason. Or the user typed in a virtual address range manually. We
1955  * *don't* want to send the address through Tor; that's likely to fail,
1956  * and may leak information.
1957  */
1958  log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1959  safe_str_client(socks->address));
1960  out->end_reason = END_STREAM_REASON_INTERNAL;
1961  out->should_close = 1;
1962  return;
1963  }
1964 }
1965 
1966 /** We just received a SOCKS request in <b>conn</b> to a v3 onion. Start
1967  * connecting to the onion service. */
1968 static int
1970  socks_request_t *socks,
1971  origin_circuit_t *circ)
1972 {
1973  int retval;
1974  time_t now = approx_time();
1975  connection_t *base_conn = ENTRY_TO_CONN(conn);
1976 
1977  /* If .onion address requests are disabled, refuse the request */
1978  if (!conn->entry_cfg.onion_traffic) {
1979  log_warn(LD_APP, "Onion address %s requested from a port with .onion "
1980  "disabled", safe_str_client(socks->address));
1981  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1982  return -1;
1983  }
1984 
1985  /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
1986  * for hidden service addresses. */
1987  if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1988  /* if it's a resolve request, fail it right now, rather than
1989  * building all the circuits and then realizing it won't work. */
1990  log_warn(LD_APP,
1991  "Resolve requests to hidden services not allowed. Failing.");
1992  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1993  0,NULL,-1,TIME_MAX);
1994  connection_mark_unattached_ap(conn,
1997  return -1;
1998  }
1999 
2000  /* If we were passed a circuit, then we need to fail. .onion addresses
2001  * only work when we launch our own circuits for now. */
2002  if (circ) {
2003  log_warn(LD_CONTROL, "Attachstream to a circuit is not "
2004  "supported for .onion addresses currently. Failing.");
2005  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2006  return -1;
2007  }
2008 
2009  int descriptor_is_usable = 0;
2010 
2011  /* Create HS conn identifier with HS pubkey */
2012  hs_ident_edge_conn_t *hs_conn_ident =
2013  tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
2014 
2015  retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
2016  NULL, NULL);
2017  if (retval < 0) {
2018  log_warn(LD_GENERAL, "failed to parse hs address");
2019  tor_free(hs_conn_ident);
2020  return -1;
2021  }
2022  ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
2023 
2024  /* Check the v3 desc cache */
2025  const hs_descriptor_t *cached_desc = NULL;
2026  unsigned int refetch_desc = 0;
2027  cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
2028  if (cached_desc) {
2029  descriptor_is_usable =
2031  cached_desc);
2032  log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
2033  (descriptor_is_usable) ? "usable" : "unusable",
2034  safe_str_client(socks->address),
2035  (descriptor_is_usable) ? "Not fetching." : "Refetching.");
2036  } else {
2037  /* We couldn't find this descriptor; we should look it up. */
2038  log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
2039  safe_str_client(socks->address));
2040  refetch_desc = 1;
2041  }
2042 
2043  /* Help predict that we'll want to do hidden service circuits in the
2044  * future. We're not sure if it will need a stable circuit yet, but
2045  * we know we'll need *something*. */
2046  rep_hist_note_used_internal(now, 0, 1);
2047 
2048  /* Now we have a descriptor but is it usable or not? If not, refetch.
2049  * Also, a fetch could have been requested if the onion address was not
2050  * found in the cache previously. */
2051  if (refetch_desc || !descriptor_is_usable) {
2052  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2054  base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
2055  tor_assert(edge_conn->hs_ident);
2056  /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
2057  * went and act accordingly. */
2058  int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2059  switch (ret) {
2061  /* Keeping the connection in descriptor wait state is fine because
2062  * once we get enough dirinfo or a new live consensus, the HS client
2063  * subsystem is notified and every connection in that state will
2064  * trigger a fetch for the service key. */
2068  return 0;
2069  case HS_CLIENT_FETCH_ERROR:
2072  /* Can't proceed further and better close the SOCKS request. */
2073  return -1;
2074  }
2075  }
2076 
2077  /* We have the descriptor! So launch a connection to the HS. */
2078  log_info(LD_REND, "Descriptor is here. Great.");
2079 
2080  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2081  /* We'll try to attach it at the next event loop, or whenever
2082  * we call connection_ap_attach_pending() */
2083  connection_ap_mark_as_pending_circuit(conn);
2084  return 0;
2085 }
2086 
2087 /** Connection <b>conn</b> just finished its socks handshake, or the
2088  * controller asked us to take care of it. If <b>circ</b> is defined,
2089  * then that's where we'll want to attach it. Otherwise we have to
2090  * figure it out ourselves.
2091  *
2092  * First, parse whether it's a .exit address, remap it, and so on. Then
2093  * if it's for a general circuit, try to attach it to a circuit (or launch
2094  * one as needed), else if it's for a rendezvous circuit, fetch a
2095  * rendezvous descriptor first (or attach/launch a circuit if the
2096  * rendezvous descriptor is already here and fresh enough).
2097  *
2098  * The stream will exit from the hop
2099  * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2100  * <b>cpath</b> is NULL.
2101  */
2102 int
2104  origin_circuit_t *circ,
2105  crypt_path_t *cpath)
2106 {
2107  socks_request_t *socks = conn->socks_request;
2108  const or_options_t *options = get_options();
2109  connection_t *base_conn = ENTRY_TO_CONN(conn);
2110  time_t now = time(NULL);
2111  rewrite_result_t rr;
2112 
2113  /* First we'll do the rewrite part. Let's see if we get a reasonable
2114  * answer.
2115  */
2116  memset(&rr, 0, sizeof(rr));
2117  connection_ap_handshake_rewrite(conn,&rr);
2118 
2119  if (rr.should_close) {
2120  /* connection_ap_handshake_rewrite told us to close the connection:
2121  * either because it sent back an answer, or because it sent back an
2122  * error */
2123  connection_mark_unattached_ap(conn, rr.end_reason);
2124  if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
2125  return 0;
2126  else
2127  return -1;
2128  }
2129 
2130  const time_t map_expires = rr.map_expires;
2131  const int automap = rr.automap;
2132  const addressmap_entry_source_t exit_source = rr.exit_source;
2133 
2134  /* Now see whether the hostname is bogus. This could happen because of an
2135  * onion hostname whose format we don't recognize. */
2136  hostname_type_t addresstype;
2137  if (!parse_extended_hostname(socks->address, &addresstype)) {
2138  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2139  escaped(socks->address));
2140  if (addresstype == BAD_HOSTNAME) {
2141  conn->socks_request->socks_extended_error_code = SOCKS5_HS_BAD_ADDRESS;
2142  }
2143  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2144  return -1;
2145  }
2146 
2147  /* If this is a .exit hostname, strip off the .name.exit part, and
2148  * see whether we're willing to connect there, and otherwise handle the
2149  * .exit address.
2150  *
2151  * We'll set chosen_exit_name and/or close the connection as appropriate.
2152  */
2153  if (addresstype == EXIT_HOSTNAME) {
2154  /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
2155  * not ExcludeExitNodes. */
2156  routerset_t *excludeset = options->StrictNodes ?
2157  options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
2158  const node_t *node = NULL;
2159 
2160  /* If this .exit was added by an AUTOMAP, then it came straight from
2161  * a user. That's not safe. */
2162  if (exit_source == ADDRMAPSRC_AUTOMAP) {
2163  /* Whoops; this one is stale. It must have gotten added earlier?
2164  * (Probably this is not possible, since AllowDotExit no longer
2165  * exists.) */
2166  log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
2167  safe_str_client(socks->address));
2168  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2169  escaped(socks->address));
2170  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2172  return -1;
2173  }
2174 
2175  /* Double-check to make sure there are no .exits coming from
2176  * impossible/weird sources. */
2177  if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
2178  /* It shouldn't be possible to get a .exit address from any of these
2179  * sources. */
2180  log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
2181  ".exit part. Refusing.",
2182  safe_str_client(socks->address));
2183  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2184  escaped(socks->address));
2185  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2186  return -1;
2187  }
2188 
2189  tor_assert(!automap);
2190 
2191  /* Now, find the character before the .(name) part.
2192  * (The ".exit" part got stripped off by "parse_extended_hostname").
2193  *
2194  * We're going to put the exit name into conn->chosen_exit_name, and
2195  * look up a node correspondingly. */
2196  char *s = strrchr(socks->address,'.');
2197  if (s) {
2198  /* The address was of the form "(stuff).(name).exit */
2199  if (s[1] != '\0') {
2200  /* Looks like a real .exit one. */
2201  conn->chosen_exit_name = tor_strdup(s+1);
2202  node = node_get_by_nickname(conn->chosen_exit_name, 0);
2203 
2204  if (exit_source == ADDRMAPSRC_TRACKEXIT) {
2205  /* We 5 tries before it expires the addressmap */
2207  }
2208  *s = 0;
2209  } else {
2210  /* Oops, the address was (stuff)..exit. That's not okay. */
2211  log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
2212  safe_str_client(socks->address));
2213  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2214  escaped(socks->address));
2215  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2216  return -1;
2217  }
2218  } else {
2219  /* It looks like they just asked for "foo.exit". That's a special
2220  * form that means (foo's address).foo.exit. */
2221 
2222  conn->chosen_exit_name = tor_strdup(socks->address);
2223  node = node_get_by_nickname(conn->chosen_exit_name, 0);
2224  if (node) {
2225  *socks->address = 0;
2226  node_get_address_string(node, socks->address, sizeof(socks->address));
2227  }
2228  }
2229 
2230  /* Now make sure that the chosen exit exists... */
2231  if (!node) {
2232  log_warn(LD_APP,
2233  "Unrecognized relay in exit address '%s.exit'. Refusing.",
2234  safe_str_client(socks->address));
2235  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2236  return -1;
2237  }
2238  /* ...and make sure that it isn't excluded. */
2239  if (routerset_contains_node(excludeset, node)) {
2240  log_warn(LD_APP,
2241  "Excluded relay in exit address '%s.exit'. Refusing.",
2242  safe_str_client(socks->address));
2243  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2244  return -1;
2245  }
2246  /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
2247  Bar is not listed in it? I say yes, but our revised manpage branch
2248  implies no. */
2249  }
2250 
2251  /* Now, we handle everything that isn't a .onion address. */
2252  if (addresstype != ONION_V3_HOSTNAME) {
2253  /* Not a hidden-service request. It's either a hostname or an IP,
2254  * possibly with a .exit that we stripped off. We're going to check
2255  * if we're allowed to connect/resolve there, and then launch the
2256  * appropriate request. */
2257 
2258  /* Check for funny characters in the address. */
2259  if (address_is_invalid_destination(socks->address, 1)) {
2260  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2261  escaped(socks->address));
2262  log_warn(LD_APP,
2263  "Destination '%s' seems to be an invalid hostname. Failing.",
2264  safe_str_client(socks->address));
2265  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2266  return -1;
2267  }
2268 
2269  /* socks->address is a non-onion hostname or IP address.
2270  * If we can't do any non-onion requests, refuse the connection.
2271  * If we have a hostname but can't do DNS, refuse the connection.
2272  * If we have an IP address, but we can't use that address family,
2273  * refuse the connection.
2274  *
2275  * If we can do DNS requests, and we can use at least one address family,
2276  * then we have to resolve the address first. Then we'll know if it
2277  * resolves to a usable address family. */
2278 
2279  /* First, check if all non-onion traffic is disabled */
2280  if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
2281  && !conn->entry_cfg.ipv6_traffic) {
2282  log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
2283  "or IP address %s because Port has OnionTrafficOnly set (or "
2284  "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
2285  safe_str_client(socks->address));
2286  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2287  return -1;
2288  }
2289 
2290  /* Then check if we have a hostname or IP address, and whether DNS or
2291  * the IP address family are permitted. Reject if not. */
2292  tor_addr_t dummy_addr;
2293  int socks_family = tor_addr_parse(&dummy_addr, socks->address);
2294  /* family will be -1 for a non-onion hostname that's not an IP */
2295  if (socks_family == -1) {
2296  if (!conn->entry_cfg.dns_request) {
2297  log_warn(LD_APP, "Refusing to connect to hostname %s "
2298  "because Port has NoDNSRequest set.",
2299  safe_str_client(socks->address));
2300  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2301  return -1;
2302  }
2303  } else if (socks_family == AF_INET) {
2304  if (!conn->entry_cfg.ipv4_traffic) {
2305  log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
2306  "Port has NoIPv4Traffic set.",
2307  safe_str_client(socks->address));
2308  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2309  return -1;
2310  }
2311  } else if (socks_family == AF_INET6) {
2312  if (!conn->entry_cfg.ipv6_traffic) {
2313  log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
2314  "Port has NoIPv6Traffic set.",
2315  safe_str_client(socks->address));
2316  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2317  return -1;
2318  }
2319  } else {
2320  tor_assert_nonfatal_unreached_once();
2321  }
2322 
2323  /* See if this is a hostname lookup that we can answer immediately.
2324  * (For example, an attempt to look up the IP address for an IP address.)
2325  */
2326  if (socks->command == SOCKS_COMMAND_RESOLVE) {
2327  tor_addr_t answer;
2328  /* Reply to resolves immediately if we can. */
2329  if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
2330  /* remember _what_ is supposed to have been resolved. */
2331  strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
2333  map_expires);
2334  connection_mark_unattached_ap(conn,
2335  END_STREAM_REASON_DONE |
2337  return 0;
2338  }
2339  tor_assert(!automap);
2340  rep_hist_note_used_resolve(now); /* help predict this next time */
2341  } else if (socks->command == SOCKS_COMMAND_CONNECT) {
2342  /* Now see if this is a connect request that we can reject immediately */
2343 
2344  tor_assert(!automap);
2345  /* Don't allow connections to port 0. */
2346  if (socks->port == 0) {
2347  log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
2348  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2349  return -1;
2350  }
2351  /* You can't make connections to internal addresses, by default.
2352  * Exceptions are begindir requests (where the address is meaningless),
2353  * or cases where you've hand-configured a particular exit, thereby
2354  * making the local address meaningful. */
2355  if (options->ClientRejectInternalAddresses &&
2356  !conn->use_begindir && !conn->chosen_exit_name && !circ) {
2357  /* If we reach this point then we don't want to allow internal
2358  * addresses. Check if we got one. */
2359  tor_addr_t addr;
2360  if (tor_addr_hostname_is_local(socks->address) ||
2361  (tor_addr_parse(&addr, socks->address) >= 0 &&
2362  tor_addr_is_internal(&addr, 0))) {
2363  /* If this is an explicit private address with no chosen exit node,
2364  * then we really don't want to try to connect to it. That's
2365  * probably an error. */
2366  if (conn->is_transparent_ap) {
2367 #define WARN_INTRVL_LOOP 300
2368  static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
2369  char *m;
2370  if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
2371  log_warn(LD_NET,
2372  "Rejecting request for anonymous connection to private "
2373  "address %s on a TransPort or NATDPort. Possible loop "
2374  "in your NAT rules?%s", safe_str_client(socks->address),
2375  m);
2376  tor_free(m);
2377  }
2378  } else {
2379 #define WARN_INTRVL_PRIV 300
2380  static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
2381  char *m;
2382  if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
2383  log_warn(LD_NET,
2384  "Rejecting SOCKS request for anonymous connection to "
2385  "private address %s.%s",
2386  safe_str_client(socks->address),m);
2387  tor_free(m);
2388  }
2389  }
2390  connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
2391  return -1;
2392  }
2393  } /* end "if we should check for internal addresses" */
2394 
2395  /* Okay. We're still doing a CONNECT, and it wasn't a private
2396  * address. Here we do special handling for literal IP addresses,
2397  * to see if we should reject this preemptively, and to set up
2398  * fields in conn->entry_cfg to tell the exit what AF we want. */
2399  {
2400  tor_addr_t addr;
2401  /* XXX Duplicate call to tor_addr_parse. */
2402  if (tor_addr_parse(&addr, socks->address) >= 0) {
2403  /* If we reach this point, it's an IPv4 or an IPv6 address. */
2404  sa_family_t family = tor_addr_family(&addr);
2405 
2406  if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
2407  (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
2408  /* You can't do an IPv4 address on a v6-only socks listener,
2409  * or vice versa. */
2410  log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
2411  "family that this listener does not support.");
2412  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2413  return -1;
2414  } else if (family == AF_INET6 && socks->socks_version == 4) {
2415  /* You can't make a socks4 request to an IPv6 address. Socks4
2416  * doesn't support that. */
2417  log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
2418  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2419  return -1;
2420  } else if (socks->socks_version == 4 &&
2421  !conn->entry_cfg.ipv4_traffic) {
2422  /* You can't do any kind of Socks4 request when IPv4 is forbidden.
2423  *
2424  * XXX raise this check outside the enclosing block? */
2425  log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
2426  "no IPv4 traffic supported.");
2427  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2428  return -1;
2429  } else if (family == AF_INET6) {
2430  /* Tell the exit: we won't accept any ipv4 connection to an IPv6
2431  * address. */
2432  conn->entry_cfg.ipv4_traffic = 0;
2433  } else if (family == AF_INET) {
2434  /* Tell the exit: we won't accept any ipv6 connection to an IPv4
2435  * address. */
2436  conn->entry_cfg.ipv6_traffic = 0;
2437  }
2438 
2439  /* Next, yet another check: we know it's a direct IP address. Is it
2440  * the IP address of a known relay and its ORPort, or of a directory
2441  * authority and its OR or Dir Port? If so, and if a consensus param
2442  * says to, then exit relays will refuse this request (see ticket
2443  * 2667 for details). Let's just refuse it locally right now, to
2444  * save time and network load but also to give the user a more
2445  * useful log message. */
2446  if (!network_reentry_is_allowed() &&
2447  nodelist_reentry_contains(&addr, socks->port)) {
2448  log_warn(LD_APP, "Not attempting connection to %s:%d because "
2449  "the network would reject it. Are you trying to send "
2450  "Tor traffic over Tor? This traffic can be harmful to "
2451  "the Tor network. If you really need it, try using "
2452  "a bridge as a workaround.",
2453  safe_str_client(socks->address), socks->port);
2454  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2455  return -1;
2456  }
2457  }
2458  }
2459 
2460  /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
2461  if (socks->socks_version == 4)
2462  conn->entry_cfg.ipv6_traffic = 0;
2463 
2464  /* Still handling CONNECT. Now, check for exit enclaves. (Which we
2465  * don't do on BEGIN_DIR, or when there is a chosen exit.)
2466  *
2467  * TODO: Should we remove this? Exit enclaves are nutty and don't
2468  * work very well
2469  */
2470  if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
2471  /* see if we can find a suitable enclave exit */
2472  const node_t *r =
2474  if (r) {
2475  log_info(LD_APP,
2476  "Redirecting address %s to exit at enclave router %s",
2477  safe_str_client(socks->address), node_describe(r));
2478  /* use the hex digest, not nickname, in case there are two
2479  routers with this nickname */
2480  conn->chosen_exit_name =
2481  tor_strdup(hex_str(r->identity, DIGEST_LEN));
2482  conn->chosen_exit_optional = 1;
2483  }
2484  }
2485 
2486  /* Still handling CONNECT: warn or reject if it's using a dangerous
2487  * port. */
2488  if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
2489  if (consider_plaintext_ports(conn, socks->port) < 0)
2490  return -1;
2491 
2492  /* Remember the port so that we will predict that more requests
2493  there will happen in the future. */
2494  if (!conn->use_begindir) {
2495  /* help predict this next time */
2496  rep_hist_note_used_port(now, socks->port);
2497  }
2498  } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
2499  rep_hist_note_used_resolve(now); /* help predict this next time */
2500  /* no extra processing needed */
2501  } else {
2502  /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2504  }
2505 
2506  /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2507  * address, and decided not to reject it for any number of reasons. Now
2508  * mark the connection as waiting for a circuit, and try to attach it!
2509  */
2510  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2511 
2512  /* If we were given a circuit to attach to, try to attach. Otherwise,
2513  * try to find a good one and attach to that. */
2514  int rv;
2515  if (circ) {
2516  rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
2517  } else {
2518  /* We'll try to attach it at the next event loop, or whenever
2519  * we call connection_ap_attach_pending() */
2520  connection_ap_mark_as_pending_circuit(conn);
2521  rv = 0;
2522  }
2523 
2524  /* If the above function returned 0 then we're waiting for a circuit.
2525  * if it returned 1, we're attached. Both are okay. But if it returned
2526  * -1, there was an error, so make sure the connection is marked, and
2527  * return -1. */
2528  if (rv < 0) {
2529  if (!base_conn->marked_for_close)
2530  connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2531  return -1;
2532  }
2533 
2534  return 0;
2535  } else {
2536  /* If we get here, it's a request for a .onion address! */
2537  tor_assert(addresstype == ONION_V3_HOSTNAME);
2538  tor_assert(!automap);
2539  return connection_ap_handle_onion(conn, socks, circ);
2540  }
2541 
2542  return 0; /* unreached but keeps the compiler happy */
2543 }
2544 
2545 #ifdef TRANS_PF
2546 static int pf_socket = -1;
2547 int
2548 get_pf_socket(void)
2549 {
2550  int pf;
2551  /* This should be opened before dropping privileges. */
2552  if (pf_socket >= 0)
2553  return pf_socket;
2554 
2555 #if defined(OpenBSD)
2556  /* only works on OpenBSD */
2557  pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
2558 #else
2559  /* works on NetBSD and FreeBSD */
2560  pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
2561 #endif /* defined(OpenBSD) */
2562 
2563  if (pf < 0) {
2564  log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
2565  return -1;
2566  }
2567 
2568  pf_socket = pf;
2569  return pf_socket;
2570 }
2571 #endif /* defined(TRANS_PF) */
2572 
2573 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2574  defined(TRANS_TPROXY)
2575 /** Try fill in the address of <b>req</b> from the socket configured
2576  * with <b>conn</b>. */
2577 static int
2578 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
2579 {
2580  struct sockaddr_storage orig_dst;
2581  socklen_t orig_dst_len = sizeof(orig_dst);
2582  tor_addr_t addr;
2583 
2584 #ifdef TRANS_TPROXY
2585  if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
2586  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2587  &orig_dst_len) < 0) {
2588  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2589  log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2590  return -1;
2591  }
2592  goto done;
2593  }
2594 #endif /* defined(TRANS_TPROXY) */
2595 
2596 #ifdef TRANS_NETFILTER
2597  int rv = -1;
2598  switch (ENTRY_TO_CONN(conn)->socket_family) {
2599 #ifdef TRANS_NETFILTER_IPV4
2600  case AF_INET:
2601  rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
2602  (struct sockaddr*)&orig_dst, &orig_dst_len);
2603  break;
2604 #endif /* defined(TRANS_NETFILTER_IPV4) */
2605 #ifdef TRANS_NETFILTER_IPV6
2606  case AF_INET6:
2607  rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
2608  (struct sockaddr*)&orig_dst, &orig_dst_len);
2609  break;
2610 #endif /* defined(TRANS_NETFILTER_IPV6) */
2611  default:
2612  log_warn(LD_BUG, "Received transparent data from an unsupported "
2613  "socket family %d",
2614  ENTRY_TO_CONN(conn)->socket_family);
2615  return -1;
2616  }
2617  if (rv < 0) {
2618  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2619  log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
2620  return -1;
2621  }
2622  goto done;
2623 #elif defined(TRANS_PF)
2624  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2625  &orig_dst_len) < 0) {
2626  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2627  log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2628  return -1;
2629  }
2630  goto done;
2631 #else
2632  (void)conn;
2633  (void)req;
2634  log_warn(LD_BUG, "Unable to determine destination from socket.");
2635  return -1;
2636 #endif /* defined(TRANS_NETFILTER) || ... */
2637 
2638  done:
2639  tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
2640  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2641 
2642  return 0;
2643 }
2644 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2645 
2646 #ifdef TRANS_PF
2647 static int
2648 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
2649 {
2650  struct sockaddr_storage proxy_addr;
2651  socklen_t proxy_addr_len = sizeof(proxy_addr);
2652  struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
2653  struct pfioc_natlook pnl;
2654  tor_addr_t addr;
2655  int pf = -1;
2656 
2657  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
2658  &proxy_addr_len) < 0) {
2659  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2660  log_warn(LD_NET, "getsockname() to determine transocks destination "
2661  "failed: %s", tor_socket_strerror(e));
2662  return -1;
2663  }
2664 
2665 #ifdef __FreeBSD__
2666  if (get_options()->TransProxyType_parsed == TPT_IPFW) {
2667  /* ipfw(8) is used and in this case getsockname returned the original
2668  destination */
2669  if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
2671  return -1;
2672  }
2673 
2674  tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
2675 
2676  return 0;
2677  }
2678 #endif /* defined(__FreeBSD__) */
2679 
2680  memset(&pnl, 0, sizeof(pnl));
2681  pnl.proto = IPPROTO_TCP;
2682  pnl.direction = PF_OUT;
2683  if (proxy_sa->sa_family == AF_INET) {
2684  struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
2685  pnl.af = AF_INET;
2686  pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
2687  pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2688  pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
2689  pnl.dport = sin->sin_port;
2690  } else if (proxy_sa->sa_family == AF_INET6) {
2691  struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
2692  pnl.af = AF_INET6;
2693  const struct in6_addr *dest_in6 =
2694  tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr);
2695  if (BUG(!dest_in6))
2696  return -1;
2697  memcpy(&pnl.saddr.v6, dest_in6, sizeof(struct in6_addr));
2698  pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2699  memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
2700  pnl.dport = sin6->sin6_port;
2701  } else {
2702  log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
2703  (int)proxy_sa->sa_family);
2704  return -1;
2705  }
2706 
2707  pf = get_pf_socket();
2708  if (pf<0)
2709  return -1;
2710 
2711  if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
2712  log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
2713  return -1;
2714  }
2715 
2716  if (pnl.af == AF_INET) {
2717  tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
2718  } else if (pnl.af == AF_INET6) {
2719  tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
2720  } else {
2722  return -1;
2723  }
2724 
2725  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2726  req->port = ntohs(pnl.rdport);
2727 
2728  return 0;
2729 }
2730 #endif /* defined(TRANS_PF) */
2731 
2732 /** Fetch the original destination address and port from a
2733  * system-specific interface and put them into a
2734  * socks_request_t as if they came from a socks request.
2735  *
2736  * Return -1 if an error prevents fetching the destination,
2737  * else return 0.
2738  */
2739 static int
2741  socks_request_t *req)
2742 {
2743 #ifdef TRANS_NETFILTER
2744  return destination_from_socket(conn, req);
2745 #elif defined(TRANS_PF)
2746  const or_options_t *options = get_options();
2747 
2748  if (options->TransProxyType_parsed == TPT_PF_DIVERT)
2749  return destination_from_socket(conn, req);
2750 
2751  if (options->TransProxyType_parsed == TPT_DEFAULT ||
2752  options->TransProxyType_parsed == TPT_IPFW)
2753  return destination_from_pf(conn, req);
2754 
2755  (void)conn;
2756  (void)req;
2757  log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
2758  options->TransProxyType);
2759  return -1;
2760 #else
2761  (void)conn;
2762  (void)req;
2763  log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
2764  "transparent proxy method was configured.");
2765  return -1;
2766 #endif /* defined(TRANS_NETFILTER) || ... */
2767 }
2768 
2769 /** connection_edge_process_inbuf() found a conn in state
2770  * socks_wait. See if conn->inbuf has the right bytes to proceed with
2771  * the socks handshake.
2772  *
2773  * If the handshake is complete, send it to
2774  * connection_ap_handshake_rewrite_and_attach().
2775  *
2776  * Return -1 if an unexpected error with conn occurs (and mark it for close),
2777  * else return 0.
2778  */
2779 static int
2781 {
2782  socks_request_t *socks;
2783  int sockshere;
2784  const or_options_t *options = get_options();
2785  int had_reply = 0;
2786  connection_t *base_conn = ENTRY_TO_CONN(conn);
2787 
2788  tor_assert(conn);
2789  tor_assert(base_conn->type == CONN_TYPE_AP);
2790  tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
2791  tor_assert(conn->socks_request);
2792  socks = conn->socks_request;
2793 
2794  log_debug(LD_APP,"entered.");
2795 
2796  sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2797  options->TestSocks, options->SafeSocks);
2798 
2799  if (socks->replylen) {
2800  had_reply = 1;
2801  connection_buf_add((const char*)socks->reply, socks->replylen,
2802  base_conn);
2803  socks->replylen = 0;
2804  if (sockshere == -1) {
2805  /* An invalid request just got a reply, no additional
2806  * one is necessary. */
2807  socks->has_finished = 1;
2808  }
2809  }
2810 
2811  if (sockshere == 0) {
2812  log_debug(LD_APP,"socks handshake not all here yet.");
2813  return 0;
2814  } else if (sockshere == -1) {
2815  if (!had_reply) {
2816  log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2819  }
2820  connection_mark_unattached_ap(conn,
2823  return -1;
2824  } /* else socks handshake is done, continue processing */
2825 
2826  if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2827  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2828  else
2829  control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2830 
2831  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2832 }
2833 
2834 /** connection_init_accepted_conn() found a new trans AP conn.
2835  * Get the original destination and send it to
2836  * connection_ap_handshake_rewrite_and_attach().
2837  *
2838  * Return -1 if an unexpected error with conn (and it should be marked
2839  * for close), else return 0.
2840  */
2841 int
2843 {
2844  socks_request_t *socks;
2845 
2846  tor_assert(conn);
2847  tor_assert(conn->socks_request);
2848  socks = conn->socks_request;
2849 
2850  /* pretend that a socks handshake completed so we don't try to
2851  * send a socks reply down a transparent conn */
2852  socks->command = SOCKS_COMMAND_CONNECT;
2853  socks->has_finished = 1;
2854 
2855  log_debug(LD_APP,"entered.");
2856 
2857  if (connection_ap_get_original_destination(conn, socks) < 0) {
2858  log_warn(LD_APP,"Fetching original destination failed. Closing.");
2859  connection_mark_unattached_ap(conn,
2861  return -1;
2862  }
2863  /* we have the original destination */
2864 
2865  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2866 
2867  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2868 }
2869 
2870 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2871  * conn->inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2872  * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2873  * form of the original destination.
2874  *
2875  * If the original destination is complete, send it to
2876  * connection_ap_handshake_rewrite_and_attach().
2877  *
2878  * Return -1 if an unexpected error with conn (and it should be marked
2879  * for close), else return 0.
2880  */
2881 static int
2883 {
2884  char tmp_buf[36], *tbuf, *daddr;
2885  size_t tlen = 30;
2886  int err, port_ok;
2887  socks_request_t *socks;
2888 
2889  tor_assert(conn);
2891  tor_assert(conn->socks_request);
2892  socks = conn->socks_request;
2893 
2894  log_debug(LD_APP,"entered.");
2895 
2896  /* look for LF-terminated "[DEST ip_addr port]"
2897  * where ip_addr is a dotted-quad and port is in string form */
2898  err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2899  if (err == 0)
2900  return 0;
2901  if (err < 0) {
2902  log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2903  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2904  return -1;
2905  }
2906 
2907  if (strcmpstart(tmp_buf, "[DEST ")) {
2908  log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2909  "said: %s",
2910  escaped(tmp_buf));
2911  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2912  return -1;
2913  }
2914 
2915  daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2916  if (!(tbuf = strchr(tbuf, ' '))) {
2917  log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2918  "said: %s",
2919  escaped(tmp_buf));
2920  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2921  return -1;
2922  }
2923  *tbuf++ = '\0';
2924 
2925  /* pretend that a socks handshake completed so we don't try to
2926  * send a socks reply down a natd conn */
2927  strlcpy(socks->address, daddr, sizeof(socks->address));
2928  socks->port = (uint16_t)
2929  tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2930  if (!port_ok) {
2931  log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2932  "of range.", escaped(tbuf));
2933  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2934  return -1;
2935  }
2936 
2937  socks->command = SOCKS_COMMAND_CONNECT;
2938  socks->has_finished = 1;
2939 
2940  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2941 
2943 
2944  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2945 }
2946 
2947 static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
2948  "HTTP/1.0 405 Method Not Allowed\r\n"
2949  "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
2950  "<html>\n"
2951  "<head>\n"
2952  "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
2953  "</head>\n"
2954  "<body>\n"
2955  "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
2956  "<p>\n"
2957  "It appears you have configured your web browser to use this Tor port as\n"
2958  "an HTTP proxy.\n"
2959  "</p><p>\n"
2960  "This is not correct: This port is configured as a CONNECT tunnel, not\n"
2961  "an HTTP proxy. Please configure your client accordingly. You can also\n"
2962  "use HTTPS; then the client should automatically use HTTP CONNECT."
2963  "</p>\n"
2964  "<p>\n"
2965  "See <a href=\"https://www.torproject.org/documentation.html\">"
2966  "https://www.torproject.org/documentation.html</a> for more "
2967  "information.\n"
2968  "</p>\n"
2969  "</body>\n"
2970  "</html>\n";
2971 
2972 /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
2973  * but we have not yet received a full HTTP CONNECT request. Try to parse an
2974  * HTTP CONNECT request from the connection's inbuf. On success, set up the
2975  * connection's socks_request field and try to attach the connection. On
2976  * failure, send an HTTP reply, and mark the connection.
2977  */
2978 STATIC int
2980 {
2981  if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
2982  return -1;
2983 
2984  char *headers = NULL, *body = NULL;
2985  char *command = NULL, *addrport = NULL;
2986  char *addr = NULL;
2987  size_t bodylen = 0;
2988 
2989  const char *errmsg = NULL;
2990  int rv = 0;
2991 
2992  const int http_status =
2993  fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
2994  &body, &bodylen, 1024, 0);
2995  if (http_status < 0) {
2996  /* Bad http status */
2997  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2998  goto err;
2999  } else if (http_status == 0) {
3000  /* no HTTP request yet. */
3001  goto done;
3002  }
3003 
3004  const int cmd_status = parse_http_command(headers, &command, &addrport);
3005  if (cmd_status < 0) {
3006  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3007  goto err;
3008  }
3010  tor_assert(addrport);
3011  if (strcasecmp(command, "connect")) {
3012  errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
3013  goto err;
3014  }
3015 
3016  tor_assert(conn->socks_request);
3017  socks_request_t *socks = conn->socks_request;
3018  uint16_t port;
3019  if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
3020  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3021  goto err;
3022  }
3023  if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
3024  errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
3025  goto err;
3026  }
3027 
3028  /* Abuse the 'username' and 'password' fields here. They are already an
3029  * abuse. */
3030  {
3031  char *authorization = http_get_header(headers, "Proxy-Authorization: ");
3032  if (authorization) {
3033  socks->username = authorization; // steal reference
3034  socks->usernamelen = strlen(authorization);
3035  }
3036  char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
3037  if (isolation) {
3038  socks->password = isolation; // steal reference
3039  socks->passwordlen = strlen(isolation);
3040  }
3041  }
3042 
3043  socks->command = SOCKS_COMMAND_CONNECT;
3045  strlcpy(socks->address, addr, sizeof(socks->address));
3046  socks->port = port;
3047 
3048  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3049 
3050  rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
3051 
3052  // XXXX send a "100 Continue" message?
3053 
3054  goto done;
3055 
3056  err:
3057  if (BUG(errmsg == NULL))
3058  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3059  log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
3060  connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
3061  /* Mark it as "has_finished" so that we don't try to send an extra socks
3062  * reply. */
3063  conn->socks_request->has_finished = 1;
3064  connection_mark_unattached_ap(conn,
3067 
3068  done:
3069  tor_free(headers);
3070  tor_free(body);
3071  tor_free(command);
3072  tor_free(addrport);
3073  tor_free(addr);
3074  return rv;
3075 }
3076 
3077 /** Iterate over the two bytes of stream_id until we get one that is not
3078  * already in use; return it. Return 0 if can't get a unique stream_id.
3079  */
3080 streamid_t
3082 {
3083  edge_connection_t *tmpconn;
3084  streamid_t test_stream_id;
3085  uint32_t attempts=0;
3086 
3087  again:
3088  test_stream_id = circ->next_stream_id++;
3089  if (++attempts > 1<<16) {
3090  /* Make sure we don't loop forever if all stream_id's are used. */
3091  log_warn(LD_APP,"No unused stream IDs. Failing.");
3092  return 0;
3093  }
3094  if (test_stream_id == 0)
3095  goto again;
3096  for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
3097  if (tmpconn->stream_id == test_stream_id)
3098  goto again;
3099 
3101  test_stream_id))
3102  goto again;
3103 
3104  return test_stream_id;
3105 }
3106 
3107 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
3108  * an exit that supports optimistic data. */
3109 static int
3111 {
3112  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
3113  /* We can only send optimistic data if we're connected to an open
3114  general circuit. */
3115  if (edge_conn->on_circuit == NULL ||
3116  edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
3117  (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
3121  return 0;
3122 
3123  return conn->may_use_optimistic_data;
3124 }
3125 
3126 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
3127  * RELAY_BEGIN cell for <b>ap_conn</b>. */
3128 static uint32_t
3130 {
3131  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3132  const node_t *exitnode = NULL;
3133  const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
3134  uint32_t flags = 0;
3135 
3136  /* No flags for begindir */
3137  if (ap_conn->use_begindir)
3138  return 0;
3139 
3140  /* No flags for hidden services. */
3141  if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
3142  return 0;
3143 
3144  /* If only IPv4 is supported, no flags */
3145  if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
3146  return 0;
3147 
3148  if (! cpath_layer ||
3149  ! cpath_layer->extend_info)
3150  return 0;
3151 
3152  if (!ap_conn->entry_cfg.ipv4_traffic)
3153  flags |= BEGIN_FLAG_IPV4_NOT_OK;
3154 
3155  exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
3156 
3157  if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
3158  tor_addr_t a;
3159  tor_addr_make_null(&a, AF_INET6);
3161  exitnode)
3162  != ADDR_POLICY_REJECTED) {
3163  /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
3164  * no point. */
3165  flags |= BEGIN_FLAG_IPV6_OK;
3166  }
3167  }
3168 
3169  if (flags == BEGIN_FLAG_IPV6_OK) {
3170  /* When IPv4 and IPv6 are both allowed, consider whether to say we
3171  * prefer IPv6. Otherwise there's no point in declaring a preference */
3172  if (ap_conn->entry_cfg.prefer_ipv6)
3173  flags |= BEGIN_FLAG_IPV6_PREFERRED;
3174  }
3175 
3176  if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
3177  log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
3178  "am telling it to fulfil with neither IPv4 nor IPv6. That's "
3179  "not going to work. Did you perhaps ask for an IPv6 address "
3180  "on an IPv4Only port, or vice versa?");
3181  }
3182 
3183  return flags;
3184 }
3185 
3186 /** Write a relay begin cell, using destaddr and destport from ap_conn's
3187  * socks_request field, and send it down circ.
3188  *
3189  * If ap_conn is broken, mark it for close and return -1. Else return 0.
3190  */
3191 MOCK_IMPL(int,
3193 {
3194  char payload[CELL_PAYLOAD_SIZE];
3195  int payload_len;
3196  int begin_type;
3197  const or_options_t *options = get_options();
3198  origin_circuit_t *circ;
3199  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3200  connection_t *base_conn = TO_CONN(edge_conn);
3201  tor_assert(edge_conn->on_circuit);
3202  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3203 
3204  tor_assert(base_conn->type == CONN_TYPE_AP);
3206  tor_assert(ap_conn->socks_request);
3207  tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
3208 
3209  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3210  if (edge_conn->stream_id==0) {
3211  /* XXXX+ Instead of closing this stream, we should make it get
3212  * retried on another circuit. */
3213  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3214 
3215  /* Mark this circuit "unusable for new streams". */
3217  return -1;
3218  }
3219 
3220  /* Set up begin cell flags. */
3221  edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
3222 
3223  tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
3224  (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
3225  circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) ?
3226  ap_conn->socks_request->address : "",
3227  ap_conn->socks_request->port);
3228  payload_len = (int)strlen(payload)+1;
3229  if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
3230  set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
3231  payload_len += 4;
3232  }
3233 
3234  log_info(LD_APP,
3235  "Sending relay cell %d on circ %u to begin stream %d.",
3236  (int)ap_conn->use_begindir,
3237  (unsigned)circ->base_.n_circ_id,
3238  edge_conn->stream_id);
3239 
3240  begin_type = ap_conn->use_begindir ?
3241  RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
3242 
3243  /* Check that circuits are anonymised, based on their type. */
3244  if (begin_type == RELAY_COMMAND_BEGIN) {
3245  /* This connection is a standard OR connection.
3246  * Make sure its path length is anonymous, or that we're in a
3247  * non-anonymous mode. */
3248  assert_circ_anonymity_ok(circ, options);
3249  } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
3250  /* This connection is a begindir directory connection.
3251  * Look at the linked directory connection to access the directory purpose.
3252  * If a BEGINDIR connection is ever not linked, that's a bug. */
3253  if (BUG(!base_conn->linked)) {
3254  return -1;
3255  }
3256  connection_t *linked_dir_conn_base = base_conn->linked_conn;
3257  /* If the linked connection has been unlinked by other code, we can't send
3258  * a begin cell on it. */
3259  if (!linked_dir_conn_base) {
3260  return -1;
3261  }
3262  /* Sensitive directory connections must have an anonymous path length.
3263  * Otherwise, directory connections are typically one-hop.
3264  * This matches the earlier check for directory connection path anonymity
3265  * in directory_initiate_request(). */
3266  if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
3267  TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
3268  TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
3269  assert_circ_anonymity_ok(circ, options);
3270  }
3271  } else {
3272  /* This code was written for the two connection types BEGIN and BEGIN_DIR
3273  */
3274  tor_assert_unreached();
3275  }
3276 
3277  if (connection_edge_send_command(edge_conn, begin_type,
3278  begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
3279  begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
3280  return -1; /* circuit is closed, don't continue */
3281 
3282  edge_conn->package_window = STREAMWINDOW_START;
3283  edge_conn->deliver_window = STREAMWINDOW_START;
3284  base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
3285  log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
3286  ", n_circ_id %u",
3287  base_conn->s, (unsigned)circ->base_.n_circ_id);
3288  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
3289 
3290  /* If there's queued-up data, send it now */
3291  if ((connection_get_inbuf_len(base_conn) ||
3292  ap_conn->sending_optimistic_data) &&
3294  log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
3295  (long)connection_get_inbuf_len(base_conn),
3296  ap_conn->sending_optimistic_data ?
3297  (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
3298  if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
3299  connection_mark_for_close(base_conn);
3300  }
3301  }
3302 
3303  return 0;
3304 }
3305 
3306 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
3307  * socks_request field, and send it down circ.
3308  *
3309  * If ap_conn is broken, mark it for close and return -1. Else return 0.
3310  */
3311 int
3313 {
3314  int payload_len, command;
3315  const char *string_addr;
3316  char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
3317  origin_circuit_t *circ;
3318  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3319  connection_t *base_conn = TO_CONN(edge_conn);
3320  tor_assert(edge_conn->on_circuit);
3321  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3322 
3323  tor_assert(base_conn->type == CONN_TYPE_AP);
3325  tor_assert(ap_conn->socks_request);
3327 
3328  command = ap_conn->socks_request->command;
3329  tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
3330 
3331  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3332  if (edge_conn->stream_id==0) {
3333  /* XXXX+ Instead of closing this stream, we should make it get
3334  * retried on another circuit. */
3335  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3336 
3337  /* Mark this circuit "unusable for new streams". */
3339  return -1;
3340  }
3341 
3342  if (command == SOCKS_COMMAND_RESOLVE) {
3343  string_addr = ap_conn->socks_request->address;
3344  payload_len = (int)strlen(string_addr)+1;
3345  } else {
3346  /* command == SOCKS_COMMAND_RESOLVE_PTR */
3347  const char *a = ap_conn->socks_request->address;
3348  tor_addr_t addr;
3349  int r;
3350 
3351  /* We're doing a reverse lookup. The input could be an IP address, or
3352  * could be an .in-addr.arpa or .ip6.arpa address */
3353  r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
3354  if (r <= 0) {
3355  log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
3356  safe_str_client(a));
3357  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3358  return -1;
3359  }
3360 
3361  r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
3362  if (r < 0) {
3363  log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
3364  safe_str_client(a));
3365  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3366  return -1;
3367  }
3368 
3369  string_addr = inaddr_buf;
3370  payload_len = (int)strlen(inaddr_buf)+1;
3371  tor_assert(payload_len <= (int)sizeof(inaddr_buf));
3372  }
3373 
3374  log_debug(LD_APP,
3375  "Sending relay cell to begin stream %d.", edge_conn->stream_id);
3376 
3377  if (connection_edge_send_command(edge_conn,
3378  RELAY_COMMAND_RESOLVE,
3379  string_addr, payload_len) < 0)
3380  return -1; /* circuit is closed, don't continue */
3381 
3382  if (!base_conn->address) {
3383  /* This might be unnecessary. XXXX */
3384  base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
3385  }
3386  base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
3387  log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
3388  ", n_circ_id %u",
3389  base_conn->s, (unsigned)circ->base_.n_circ_id);
3390  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
3391  return 0;
3392 }
3393 
3394 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
3395  * new linked connection pair, and attach one side to the conn, connection_add
3396  * it, initialize it to circuit_wait, and call
3397  * connection_ap_handshake_attach_circuit(conn) on it.
3398  *
3399  * Return the newly created end of the linked connection pair, or -1 if error.
3400  */
3403  char *address, uint16_t port,
3404  const char *digest,
3405  int session_group, int isolation_flags,
3406  int use_begindir, int want_onehop)
3407 {
3408  entry_connection_t *conn;
3409  connection_t *base_conn;
3410 
3411  log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
3412  want_onehop ? "direct" : "anonymized",
3413  safe_str_client(address), port);
3414 
3416  base_conn = ENTRY_TO_CONN(conn);
3417  base_conn->linked = 1; /* so that we can add it safely below. */
3418 
3419  /* populate conn->socks_request */
3420 
3421  /* leave version at zero, so the socks_reply is empty */
3422  conn->socks_request->socks_version = 0;
3423  conn->socks_request->has_finished = 0; /* waiting for 'connected' */
3424  strlcpy(conn->socks_request->address, address,
3425  sizeof(conn->socks_request->address));
3426  conn->socks_request->port = port;
3428  conn->want_onehop = want_onehop;
3429  conn->use_begindir = use_begindir;
3430  if (use_begindir) {
3431  conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
3432  conn->chosen_exit_name[0] = '$';
3433  tor_assert(digest);
3435  digest, DIGEST_LEN);
3436  }
3437 
3438  /* Populate isolation fields. */
3440  conn->original_dest_address = tor_strdup(address);
3441  conn->entry_cfg.session_group = session_group;
3442  conn->entry_cfg.isolation_flags = isolation_flags;
3443 
3444  base_conn->address = tor_strdup("(Tor_internal)");
3445  tor_addr_make_unspec(&base_conn->addr);
3446  base_conn->port = 0;
3447 
3448  connection_link_connections(partner, base_conn);
3449 
3450  if (connection_add(base_conn) < 0) { /* no space, forget it */
3451  connection_free(base_conn);
3452  return NULL;
3453  }
3454 
3455  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
3456 
3457  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3458 
3459  /* attaching to a dirty circuit is fine */
3460  connection_ap_mark_as_pending_circuit(conn);
3461  log_info(LD_APP,"... application connection created and linked.");
3462  return conn;
3463 }
3464 
3465 /** Notify any interested controller connections about a new hostname resolve
3466  * or resolve error. Takes the same arguments as does
3467  * connection_ap_handshake_socks_resolved(). */
3468 static void
3470  int answer_type,
3471  size_t answer_len,
3472  const char *answer,
3473  int ttl,
3474  time_t expires)
3475 {
3476  uint64_t stream_id = 0;
3477 
3478  if (BUG(!conn)) {
3479  return;
3480  }
3481 
3482  stream_id = ENTRY_TO_CONN(conn)->global_identifier;
3483 
3484  expires = time(NULL) + ttl;
3485  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
3486  char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
3487  if (cp)
3489  cp, expires, NULL, 0, stream_id);
3490  tor_free(cp);
3491  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3492  char *cp = tor_strndup(answer, answer_len);
3494  cp, expires, NULL, 0, stream_id);
3495  tor_free(cp);
3496  } else {
3498  "<error>", time(NULL)+ttl,
3499  "error=yes", 0, stream_id);
3500  }
3501 }
3502 
3503 /**
3504  * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
3505  * as the answer.
3506  */
3507 void
3509  const tor_addr_t *answer,
3510  int ttl,
3511  time_t expires)
3512 {
3513  if (tor_addr_family(answer) == AF_INET) {
3514  uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
3515  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
3516  (uint8_t*)&a,
3517  ttl, expires);
3518  } else if (tor_addr_family(answer) == AF_INET6) {
3519  const uint8_t *a = tor_addr_to_in6_addr8(answer);
3520  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
3521  a,
3522  ttl, expires);
3523  } else {
3524  log_warn(LD_BUG, "Got called with address of unexpected family %d",
3525  tor_addr_family(answer));
3527  RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
3528  }
3529 }
3530 
3531 /** Send an answer to an AP connection that has requested a DNS lookup via
3532  * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
3533  * for unreachable; the answer should be in the format specified in the socks
3534  * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
3535  * certain errors or for values that didn't come via DNS. <b>expires</b> is
3536  * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
3537  **/
3538 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
3539  * interface and those that use it less ugly. */
3540 MOCK_IMPL(void,
3542  int answer_type,
3543  size_t answer_len,
3544  const uint8_t *answer,
3545  int ttl,
3546  time_t expires))
3547 {
3548  char buf[384];
3549  size_t replylen;
3550 
3551  if (ttl >= 0) {
3552  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3553  tor_addr_t a;
3554  tor_addr_from_ipv4n(&a, get_uint32(answer));
3555  if (! tor_addr_is_null(&a)) {
3557  conn->socks_request->address, &a,
3558  conn->chosen_exit_name, ttl);
3559  }
3560  } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3561  tor_addr_t a;
3562  tor_addr_from_ipv6_bytes(&a, answer);
3563  if (! tor_addr_is_null(&a)) {
3565  conn->socks_request->address, &a,
3566  conn->chosen_exit_name, ttl);
3567  }
3568  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3569  char *cp = tor_strndup((char*)answer, answer_len);
3571  conn->socks_request->address,
3572  cp,
3573  conn->chosen_exit_name, ttl);
3574  tor_free(cp);
3575  }
3576  }
3577 
3578  if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
3579  if (conn->dns_server_request) {
3580  /* We had a request on our DNS port: answer it. */
3581  dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
3582  conn->socks_request->has_finished = 1;
3583  return;
3584  } else {
3585  /* This must be a request from the controller. Since answers to those
3586  * requests are not cached, they do not generate an ADDRMAP event on
3587  * their own. */
3588  tell_controller_about_resolved_result(conn, answer_type, answer_len,
3589  (char*)answer, ttl, expires);
3590  conn->socks_request->has_finished = 1;
3591  return;
3592  }
3593  /* We shouldn't need to free conn here; it gets marked by the caller. */
3594  }
3595 
3596  if (conn->socks_request->socks_version == 4) {
3597  buf[0] = 0x00; /* version */
3598  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3599  buf[1] = SOCKS4_GRANTED;
3600  set_uint16(buf+2, 0);
3601  memcpy(buf+4, answer, 4); /* address */
3602  replylen = SOCKS4_NETWORK_LEN;
3603  } else { /* "error" */
3604  buf[1] = SOCKS4_REJECT;
3605  memset(buf+2, 0, 6);
3606  replylen = SOCKS4_NETWORK_LEN;
3607  }
3608  } else if (conn->socks_request->socks_version == 5) {
3609  /* SOCKS5 */
3610  buf[0] = 0x05; /* version */
3611  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3612  buf[1] = SOCKS5_SUCCEEDED;
3613  buf[2] = 0; /* reserved */
3614  buf[3] = 0x01; /* IPv4 address type */
3615  memcpy(buf+4, answer, 4); /* address */
3616  set_uint16(buf+8, 0); /* port == 0. */
3617  replylen = 10;
3618  } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3619  buf[1] = SOCKS5_SUCCEEDED;
3620  buf[2] = 0; /* reserved */
3621  buf[3] = 0x04; /* IPv6 address type */
3622  memcpy(buf+4, answer, 16); /* address */
3623  set_uint16(buf+20, 0); /* port == 0. */
3624  replylen = 22;
3625  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3626  buf[1] = SOCKS5_SUCCEEDED;
3627  buf[2] = 0; /* reserved */
3628  buf[3] = 0x03; /* Domainname address type */
3629  buf[4] = (char)answer_len;
3630  memcpy(buf+5, answer, answer_len); /* address */
3631  set_uint16(buf+5+answer_len, 0); /* port == 0. */
3632  replylen = 5+answer_len+2;
3633  } else {
3634  buf[1] = SOCKS5_HOST_UNREACHABLE;
3635  memset(buf+2, 0, 8);
3636  replylen = 10;
3637  }
3638  } else {
3639  /* no socks version info; don't send anything back */
3640  return;
3641  }
3642  connection_ap_handshake_socks_reply(conn, buf, replylen,
3643  (answer_type == RESOLVED_TYPE_IPV4 ||
3644  answer_type == RESOLVED_TYPE_IPV6 ||
3645  answer_type == RESOLVED_TYPE_HOSTNAME) ?
3646  0 : END_STREAM_REASON_RESOLVEFAILED);
3647 }
3648 
3649 /** Send a socks reply to stream <b>conn</b>, using the appropriate
3650  * socks version, etc, and mark <b>conn</b> as completed with SOCKS
3651  * handshaking.
3652  *
3653  * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
3654  * and return, else reply based on <b>endreason</b> (one of
3655  * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
3656  * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
3657  */
3658 void
3660  size_t replylen, int endreason)
3661 {
3662  char buf[256];
3663  socks5_reply_status_t status;
3664 
3665  tor_assert(conn->socks_request); /* make sure it's an AP stream */
3666 
3669  status = conn->socks_request->socks_extended_error_code;
3670  } else {
3671  status = stream_end_reason_to_socks5_response(endreason);
3672  }
3673 
3674  if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3675  control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
3676  STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
3677  endreason);
3678  }
3679 
3680  /* Flag this stream's circuit as having completed a stream successfully
3681  * (for path bias) */
3682  if (status == SOCKS5_SUCCEEDED ||
3683  endreason == END_STREAM_REASON_RESOLVEFAILED ||
3684  endreason == END_STREAM_REASON_CONNECTREFUSED ||
3685  endreason == END_STREAM_REASON_CONNRESET ||
3686  endreason == END_STREAM_REASON_NOROUTE ||
3687  endreason == END_STREAM_REASON_RESOURCELIMIT) {
3688  if (!conn->edge_.on_circuit ||
3689  !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
3690  if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
3691  log_info(LD_BUG,
3692  "No origin circuit for successful SOCKS stream %"PRIu64
3693  ". Reason: %d",
3694  (ENTRY_TO_CONN(conn)->global_identifier),
3695  endreason);
3696  }
3697  /*
3698  * Else DNS remaps and failed hidden service lookups can send us
3699  * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3700  *
3701  * Perhaps we could make the test more precise; we can tell hidden
3702  * services by conn->edge_.renddata != NULL; anything analogous for
3703  * the DNS remap case?
3704  */
3705  } else {
3706  // XXX: Hrmm. It looks like optimistic data can't go through this
3707  // codepath, but someone should probably test it and make sure.
3708  // We don't want to mark optimistically opened streams as successful.
3710  }
3711  }
3712 
3713  if (conn->socks_request->has_finished) {
3714  log_warn(LD_BUG, "(Harmless.) duplicate calls to "
3715  "connection_ap_handshake_socks_reply.");
3716  return;
3717  }
3718  if (replylen) { /* we already have a reply in mind */
3719  connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
3720  conn->socks_request->has_finished = 1;
3721  return;
3722  }
3723  if (conn->socks_request->listener_type ==
3725  const char *response = end_reason_to_http_connect_response_line(endreason);
3726  if (!response) {
3727  response = "HTTP/1.0 400 Bad Request\r\n\r\n";
3728  }
3729  connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
3730  } else if (conn->socks_request->socks_version == 4) {
3731  memset(buf,0,SOCKS4_NETWORK_LEN);
3732  buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
3733  /* leave version, destport, destip zero */
3734  connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
3735  } else if (conn->socks_request->socks_version == 5) {
3736  size_t buf_len;
3737  memset(buf,0,sizeof(buf));
3738  if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
3739  buf[0] = 5; /* version 5 */
3740  buf[1] = (char)status;
3741  buf[2] = 0;
3742  buf[3] = 1; /* ipv4 addr */
3743  /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3744  buf_len = 10;
3745  } else { /* AF_INET6. */
3746  buf[0] = 5; /* version 5 */
3747  buf[1] = (char)status;
3748  buf[2] = 0;
3749  buf[3] = 4; /* ipv6 addr */
3750  /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3751  buf_len = 22;
3752  }
3753  connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
3754  }
3755  /* If socks_version isn't 4 or 5, don't send anything.
3756  * This can happen in the case of AP bridges. */
3757  conn->socks_request->has_finished = 1;
3758  return;
3759 }
3760 
3761 /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
3762  * place the result in <b>bcell</b>. On success return 0; on failure return
3763  * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
3764  * the client.
3765  *
3766  * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
3767  * we don't.
3768  **/
3769 STATIC int
3770 begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
3771  uint8_t *end_reason_out)
3772 {
3773  relay_header_t rh;
3774  const uint8_t *body, *nul;
3775 
3776  memset(bcell, 0, sizeof(*bcell));
3777  *end_reason_out = END_STREAM_REASON_MISC;
3778 
3779  relay_header_unpack(&rh, cell->payload);
3780  if (rh.length > RELAY_PAYLOAD_SIZE) {
3781  return -2; /*XXXX why not TORPROTOCOL? */
3782  }
3783 
3784  bcell->stream_id = rh.stream_id;
3785 
3786  if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3787  bcell->is_begindir = 1;
3788  return 0;
3789  } else if (rh.command != RELAY_COMMAND_BEGIN) {
3790  log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3791  *end_reason_out = END_STREAM_REASON_INTERNAL;
3792  return -1;
3793  }
3794 
3795  body = cell->payload + RELAY_HEADER_SIZE;
3796  nul = memchr(body, 0, rh.length);
3797  if (! nul) {
3798  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3799  "Relay begin cell has no \\0. Closing.");
3800  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3801  return -1;
3802  }
3803 
3804  if (tor_addr_port_split(LOG_PROTOCOL_WARN,
3805  (char*)(body),
3806  &bcell->address,&bcell->port)<0) {
3807  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3808  "Unable to parse addr:port in relay begin cell. Closing.");
3809  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3810  return -1;
3811  }
3812  if (bcell->port == 0) {
3813  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3814  "Missing port in relay begin cell. Closing.");
3815  tor_free(bcell->address);
3816  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3817  return -1;
3818  }
3819  if (body + rh.length >= nul + 4)
3820  bcell->flags = ntohl(get_uint32(nul+1));
3821 
3822  return 0;
3823 }
3824 
3825 /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
3826  * connection, attach it to the circ and connect it. Return 0 on success
3827  * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
3828  * where the caller should close the circuit. */
3829 static int
3831 {
3832  int ret;
3833  origin_circuit_t *origin_circ;
3834 
3835  assert_circuit_ok(circ);
3837  tor_assert(conn);
3838 
3839  log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
3840  "to the service destination.");
3841 
3842  origin_circ = TO_ORIGIN_CIRCUIT(circ);
3843  conn->base_.address = tor_strdup("(rendezvous)");
3844  conn->base_.state = EXIT_CONN_STATE_CONNECTING;
3845 
3846  if (origin_circ->hs_ident) {
3847  /* Setup the identifier to be the one for the circuit service. */
3848  conn->hs_ident =
3851  ret = hs_service_set_conn_addr_port(origin_circ, conn);
3852  } else {
3853  /* We should never get here if the circuit's purpose is rendezvous. */
3855  return -1;
3856  }
3857  if (ret < 0) {
3858  log_info(LD_REND, "Didn't find rendezvous service at %s",
3860  /* Send back reason DONE because we want to make hidden service port
3861  * scanning harder thus instead of returning that the exit policy
3862  * didn't match, which makes it obvious that the port is closed,
3863  * return DONE and kill the circuit. That way, a user (malicious or
3864  * not) needs one circuit per bad port unless it matches the policy of
3865  * the hidden service. */
3867  END_STREAM_REASON_DONE,
3868  origin_circ->cpath->prev);
3869  connection_free_(TO_CONN(conn));
3870 
3871  /* Drop the circuit here since it might be someone deliberately
3872  * scanning the hidden service ports. Note that this mitigates port
3873  * scanning by adding more work on the attacker side to successfully
3874  * scan but does not fully solve it. */
3875  if (ret < -1) {
3876  return END_CIRC_AT_ORIGIN;
3877  } else {
3878  return 0;
3879  }
3880  }
3881 
3882  /* Link the circuit and the connection crypt path. */
3883  conn->cpath_layer = origin_circ->cpath->prev;
3884 
3885  /* If this is the first stream on this circuit, tell circpad */
3886  if (!origin_circ->p_streams)
3888 
3889  /* Add it into the linked list of p_streams on this circuit */
3890  conn->next_stream = origin_circ->p_streams;
3891  origin_circ->p_streams = conn;
3892  conn->on_circuit = circ;
3893  assert_circuit_ok(circ);
3894 
3895  hs_inc_rdv_stream_counter(origin_circ);
3896 
3897  /* If it's an onion service connection, we might want to include the proxy
3898  * protocol header: */
3899  if (conn->hs_ident) {
3900  hs_circuit_id_protocol_t circuit_id_protocol =
3901  hs_service_exports_circuit_id(&conn->hs_ident->identity_pk);
3902  export_hs_client_circuit_id(conn, circuit_id_protocol);
3903  }
3904 
3905  /* Connect tor to the hidden service destination. */
3907 
3908  /* For path bias: This circuit was used successfully */
3909  pathbias_mark_use_success(origin_circ);
3910  return 0;
3911 }
3912 
3913 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
3914  * an exit hop for the circuit, or we are the origin and it is a
3915  * rendezvous begin.
3916  *
3917  * Launch a new exit connection and initialize things appropriately.
3918  *
3919  * If it's a rendezvous stream, call connection_exit_connect() on
3920  * it.
3921  *
3922  * For general streams, call dns_resolve() on it first, and only call
3923  * connection_exit_connect() if the dns answer is already known.
3924  *
3925  * Note that we don't call connection_add() on the new stream! We wait
3926  * for connection_exit_connect() to do that.
3927  *
3928  * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
3929  * Else return 0.
3930  */
3931 int
3933 {
3934  edge_connection_t *n_stream;
3935  relay_header_t rh;
3936  char *address = NULL;
3937  uint16_t port = 0;
3938  or_circuit_t *or_circ = NULL;
3939  origin_circuit_t *origin_circ = NULL;
3940  crypt_path_t *layer_hint = NULL;
3941  const or_options_t *options = get_options();
3942  begin_cell_t bcell;
3943  int rv;
3944  uint8_t end_reason=0;
3945 
3946  assert_circuit_ok(circ);
3947  if (!CIRCUIT_IS_ORIGIN(circ)) {
3948  or_circ = TO_OR_CIRCUIT(circ);
3949  } else {
3951  origin_circ = TO_ORIGIN_CIRCUIT(circ);
3952  layer_hint = origin_circ->cpath->prev;
3953  }
3954 
3955  relay_header_unpack(&rh, cell->payload);
3956  if (rh.length > RELAY_PAYLOAD_SIZE)
3957  return -END_CIRC_REASON_TORPROTOCOL;
3958 
3959  if (!server_mode(options) &&
3961  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3962  "Relay begin cell at non-server. Closing.");
3964  END_STREAM_REASON_EXITPOLICY, NULL);
3965  return 0;
3966  }
3967 
3968  rv = begin_cell_parse(cell, &bcell, &end_reason);
3969  if (rv < -1) {
3970  return -END_CIRC_REASON_TORPROTOCOL;
3971  } else if (rv == -1) {
3972  tor_free(bcell.address);
3973  relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
3974  return 0;
3975  }
3976 
3977  if (! bcell.is_begindir) {
3978  /* Steal reference */
3979  tor_assert(bcell.address);
3980  address = bcell.address;
3981  port = bcell.port;
3982 
3983  if (or_circ && or_circ->p_chan) {
3984  const int client_chan = channel_is_client(or_circ->p_chan);
3985  if ((client_chan ||
3987  or_circ->p_chan->identity_digest) &&
3988  should_refuse_unknown_exits(options)))) {
3989  /* Don't let clients use us as a single-hop proxy. It attracts
3990  * attackers and users who'd be better off with, well, single-hop
3991  * proxies. */
3992  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3993  "Attempt by %s to open a stream %s. Closing.",
3994  safe_str(channel_describe_peer(or_circ->p_chan)),
3995  client_chan ? "on first hop of circuit" :
3996  "from unknown relay");
3998  client_chan ?
3999  END_STREAM_REASON_TORPROTOCOL :
4000  END_STREAM_REASON_MISC,
4001  NULL);
4002  tor_free(address);
4003  return 0;
4004  }
4005  }
4006  } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
4007  if (!directory_permits_begindir_requests(options) ||
4008  circ->purpose != CIRCUIT_PURPOSE_OR) {
4010  END_STREAM_REASON_NOTDIRECTORY, layer_hint);
4011  return 0;
4012  }
4013  /* Make sure to get the 'real' address of the previous hop: the
4014  * caller might want to know whether the remote IP address has changed,
4015  * and we might already have corrected base_.addr[ess] for the relay's
4016  * canonical IP address. */
4017  tor_addr_t chan_addr;
4018  if (or_circ && or_circ->p_chan &&
4019  channel_get_addr_if_possible(or_circ->p_chan, &chan_addr)) {
4020  address = tor_addr_to_str_dup(&chan_addr);
4021  } else {
4022  address = tor_strdup("127.0.0.1");
4023  }
4024  port = 1; /* XXXX This value is never actually used anywhere, and there
4025  * isn't "really" a connection here. But we
4026  * need to set it to something nonzero. */
4027  } else {
4028  log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
4030  END_STREAM_REASON_INTERNAL, layer_hint);
4031  return 0;
4032  }
4033 
4034  if (! options->IPv6Exit) {
4035  /* I don't care if you prefer IPv6; I can't give you any. */
4036  bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
4037  /* If you don't want IPv4, I can't help. */
4038  if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
4039  tor_free(address);
4041  END_STREAM_REASON_EXITPOLICY, layer_hint);
4042  return 0;
4043  }
4044  }
4045 
4046  log_debug(LD_EXIT,"Creating new exit connection.");
4047  /* The 'AF_INET' here is temporary; we might need to change it later in
4048  * connection_exit_connect(). */
4049  n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
4050 
4051  /* Remember the tunneled request ID in the new edge connection, so that
4052  * we can measure download times. */
4053  n_stream->dirreq_id = circ->dirreq_id;
4054 
4055  n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
4056  n_stream->begincell_flags = bcell.flags;
4057  n_stream->stream_id = rh.stream_id;
4058  n_stream->base_.port = port;
4059  /* leave n_stream->s at -1, because it's not yet valid */
4060  n_stream->package_window = STREAMWINDOW_START;
4061  n_stream->deliver_window = STREAMWINDOW_START;
4062 
4063  if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
4064  int ret;
4065  tor_free(address);
4066  /* We handle this circuit and stream in this function for all supported
4067  * hidden service version. */
4068  ret = handle_hs_exit_conn(circ, n_stream);
4069 
4070  if (ret == 0) {
4071  /* This was a valid cell. Count it as delivered + overhead. */
4072  circuit_read_valid_data(origin_circ, rh.length);
4073  }
4074  return ret;
4075  }
4076  tor_strlower(address);
4077  n_stream->base_.address = address;
4078  n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4079  /* default to failed, change in dns_resolve if it turns out not to fail */
4080 
4081  /* If we're hibernating or shutting down, we refuse to open new streams. */
4082  if (we_are_hibernating()) {
4084  END_STREAM_REASON_HIBERNATING, NULL);
4085  connection_free_(TO_CONN(n_stream));
4086  return 0;
4087  }
4088 
4089  n_stream->on_circuit = circ;
4090 
4091  if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
4092  tor_addr_t tmp_addr;
4093  tor_assert(or_circ);
4094  if (or_circ->p_chan &&
4095  channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
4096  tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
4097  }
4098  return connection_exit_connect_dir(n_stream);
4099  }
4100 
4101  log_debug(LD_EXIT,"about to start the dns_resolve().");
4102 
4103  /* send it off to the gethostbyname farm */
4104  switch (dns_resolve(n_stream)) {
4105  case 1: /* resolve worked; now n_stream is attached to circ. */
4106  assert_circuit_ok(circ);
4107  log_debug(LD_EXIT,"about to call connection_exit_connect().");
4108  connection_exit_connect(n_stream);
4109  return 0;
4110  case -1: /* resolve failed */
4112  END_STREAM_REASON_RESOLVEFAILED, NULL);
4113  /* n_stream got freed. don't touch it. */
4114  break;
4115  case 0: /* resolve added to pending list */
4116  assert_circuit_ok(circ);
4117  break;
4118  }
4119  return 0;
4120 }
4121 
4122 /**
4123  * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
4124  * circuit <b>circ</b>;
4125  * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
4126  */
4127 int
4129 {
4130  edge_connection_t *dummy_conn;
4131  relay_header_t rh;
4132 
4134  relay_header_unpack(&rh, cell->payload);
4135  if (rh.length > RELAY_PAYLOAD_SIZE)
4136  return -1;
4137 
4138  /* Note the RESOLVE stream as seen. */
4139  rep_hist_note_exit_stream(RELAY_COMMAND_RESOLVE);
4140 
4141  /* This 'dummy_conn' only exists to remember the stream ID
4142  * associated with the resolve request; and to make the
4143  * implementation of dns.c more uniform. (We really only need to
4144  * remember the circuit, the stream ID, and the hostname to be
4145  * resolved; but if we didn't store them in a connection like this,
4146  * the housekeeping in dns.c would get way more complicated.)
4147  */
4148  dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
4149  dummy_conn->stream_id = rh.stream_id;
4150  dummy_conn->base_.address = tor_strndup(
4151  (char*)cell->payload+RELAY_HEADER_SIZE,
4152  rh.length);
4153  dummy_conn->base_.port = 0;
4154  dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4155  dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
4156 
4157  dummy_conn->on_circuit = TO_CIRCUIT(circ);
4158 
4159  /* send it off to the gethostbyname farm */
4160  switch (dns_resolve(dummy_conn)) {
4161  case -1: /* Impossible to resolve; a resolved cell was sent. */
4162  /* Connection freed; don't touch it. */
4163  return 0;
4164  case 1: /* The result was cached; a resolved cell was sent. */
4165  if (!dummy_conn->base_.marked_for_close)
4166  connection_free_(TO_CONN(dummy_conn));
4167  return 0;
4168  case 0: /* resolve added to pending list */
4170  break;
4171  }
4172  return 0;
4173 }
4174 
4175 /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
4176  * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
4177  */
4178 static int
4180  uint16_t port,
4181  const char **why_rejected)
4182 {
4183  if (router_compare_to_my_exit_policy(addr, port)) {
4184  *why_rejected = "";
4185  return 1;
4186  } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
4187  *why_rejected = " (IPv6 address without IPv6Exit configured)";
4188  return 1;
4189  }
4190  return 0;
4191 }
4192 
4193 /** Return true iff the consensus allows network reentry. The default value is
4194  * false if the parameter is not found. */
4195 static bool
4197 {
4198  /* Default is false, re-entry is not allowed. */
4199  return !!networkstatus_get_param(NULL, "allow-network-reentry", 0, 0, 1);
4200 }
4201 
4202 /** Connect to conn's specified addr and port. If it worked, conn
4203  * has now been added to the connection_array.
4204  *
4205  * Send back a connected cell. Include the resolved IP of the destination
4206  * address, but <em>only</em> if it's a general exit stream. (Rendezvous
4207  * streams must not reveal what IP they connected to.)
4208  */
4209 void
4211 {
4212  const tor_addr_t *addr;
4213  uint16_t port;
4214  connection_t *conn = TO_CONN(edge_conn);
4215  int socket_error = 0, result;
4216  const char *why_failed_exit_policy = NULL;
4217 
4218  /* Apply exit policy to non-rendezvous connections. */
4219  if (! connection_edge_is_rendezvous_stream(edge_conn) &&
4220  my_exit_policy_rejects(&edge_conn->base_.addr,
4221  edge_conn->base_.port,
4222  &why_failed_exit_policy)) {
4223  if (BUG(!why_failed_exit_policy))
4224  why_failed_exit_policy = "";
4225  log_info(LD_EXIT,"%s failed exit policy%s. Closing.",
4226  connection_describe(conn),
4227  why_failed_exit_policy);
4229  connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
4230  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4231  connection_free(conn);
4232  return;
4233  }
4234 
4235  /* Next, check for attempts to connect back into the Tor network. We don't
4236  * want to allow these for the same reason we don't want to allow
4237  * infinite-length circuits (see "A Practical Congestion Attack on Tor Using
4238  * Long Paths", Usenix Security 2009). See also ticket 2667.
4239  *
4240  * Skip this if the network reentry is allowed (known from the consensus).
4241  *
4242  * The TORPROTOCOL reason is used instead of EXITPOLICY so client do NOT
4243  * attempt to retry connecting onto another circuit that will also fail
4244  * bringing considerable more load on the network if so.
4245  *
4246  * Since the address+port set here is a bloomfilter, in very rare cases, the
4247  * check will create a false positive meaning that the destination could
4248  * actually be legit and thus being denied exit. However, sending back a
4249  * reason that makes the client retry results in much worst consequences in
4250  * case of an attack so this is a small price to pay. */
4251  if (!connection_edge_is_rendezvous_stream(edge_conn) &&
4253  nodelist_reentry_contains(&conn->addr, conn->port)) {
4254  log_info(LD_EXIT, "%s tried to connect back to a known relay address. "
4255  "Closing.", connection_describe(conn));
4257  connection_edge_end(edge_conn, END_STREAM_REASON_CONNECTREFUSED);
4258  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4259  connection_free(conn);
4260  return;
4261  }
4262 
4263  /* Note the BEGIN stream as seen. We do this after the Exit policy check in
4264  * order to only account for valid streams. */
4265  rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN);
4266 
4267 #ifdef HAVE_SYS_UN_H
4268  if (conn->socket_family != AF_UNIX) {
4269 #else
4270  {
4271 #endif /* defined(HAVE_SYS_UN_H) */
4272  addr = &conn->addr;
4273  port = conn->port;
4274 
4275  if (tor_addr_family(addr) == AF_INET6)
4276  conn->socket_family = AF_INET6;
4277 
4278  log_debug(LD_EXIT, "about to try connecting");
4279  result = connection_connect(conn, conn->address,
4280  addr, port, &socket_error);
4281 #ifdef HAVE_SYS_UN_H
4282  } else {
4283  /*
4284  * In the AF_UNIX case, we expect to have already had conn->port = 1,
4285  * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
4286  * case in connection_handle_listener_read()), and conn->address should
4287  * have the socket path to connect to.
4288  */
4289  tor_assert(conn->address && strlen(conn->address) > 0);
4290 
4291  log_debug(LD_EXIT, "about to try connecting");
4292  result = connection_connect_unix(conn, conn->address, &socket_error);
4293 #endif /* defined(HAVE_SYS_UN_H) */
4294  }
4295 
4296  switch (result) {
4297  case -1: {
4298  int reason = errno_to_stream_end_reason(socket_error);
4299  connection_edge_end(edge_conn, reason);
4300  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4301  connection_free(conn);
4302  return;
4303  }
4304  case 0:
4306 
4308  /* writable indicates finish;
4309  * readable/error indicates broken link in windows-land. */
4310  return;
4311  /* case 1: fall through */
4312  }
4313 
4314  conn->state = EXIT_CONN_STATE_OPEN;
4315  if (connection_get_outbuf_len(conn)) {
4316  /* in case there are any queued data cells, from e.g. optimistic data */
4318  } else {
4320  }
4321 
4322  /* also, deliver a 'connected' cell back through the circuit. */
4323  if (connection_edge_is_rendezvous_stream(edge_conn)) {
4324  /* don't send an address back! */
4325  connection_edge_send_command(edge_conn,
4326  RELAY_COMMAND_CONNECTED,
4327  NULL, 0);
4328  } else { /* normal stream */
4329  uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
4330  int connected_payload_len =
4331  connected_cell_format_payload(connected_payload, &conn->addr,
4332  edge_conn->address_ttl);
4333  if (connected_payload_len < 0) {
4334  connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
4335  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4336  connection_free(conn);
4337  return;
4338  }
4339 
4340  connection_edge_send_command(edge_conn,
4341  RELAY_COMMAND_CONNECTED,
4342  (char*)connected_payload,
4343  connected_payload_len);
4344  }
4345 }
4346 
4347 /** Given an exit conn that should attach to us as a directory server, open a
4348  * bridge connection with a linked connection pair, create a new directory
4349  * conn, and join them together. Return 0 on success (or if there was an
4350  * error we could send back an end cell for). Return -(some circuit end
4351  * reason) if the circuit needs to be torn down. Either connects
4352  * <b>exitconn</b>, frees it, or marks it, as appropriate.
4353  */
4354 static int
4356 {
4357  dir_connection_t *dirconn = NULL;
4358  or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
4359 
4360  log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
4361 
4362  /* Note the BEGIN_DIR stream as seen. */
4363  rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN_DIR);
4364 
4365  exitconn->base_.state = EXIT_CONN_STATE_OPEN;
4366 
4367  dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
4368 
4369  tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
4370  dirconn->base_.port = 0;
4371  dirconn->base_.address = tor_strdup(exitconn->base_.address);
4372  dirconn->base_.type = CONN_TYPE_DIR;
4373  dirconn->base_.purpose = DIR_PURPOSE_SERVER;
4374  dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
4375 
4376  /* Note that the new dir conn belongs to the same tunneled request as
4377  * the edge conn, so that we can measure download times. */
4378  dirconn->dirreq_id = exitconn->dirreq_id;
4379 
4380  connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
4381 
4382  if (connection_add(TO_CONN(exitconn))<0) {
4383  connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4384  connection_free_(TO_CONN(exitconn));
4385  connection_free_(TO_CONN(dirconn));
4386  return 0;
4387  }
4388 
4389  /* link exitconn to circ, now that we know we can use it. */
4390  exitconn->next_stream = circ->n_streams;
4391  circ->n_streams = exitconn;
4392 
4393  if (connection_add(TO_CONN(dirconn))<0) {
4394  connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4396  connection_mark_for_close(TO_CONN(exitconn));
4397  connection_free_(TO_CONN(dirconn));
4398  return 0;
4399  }
4400 
4402  connection_start_reading(TO_CONN(exitconn));
4403 
4404  if (connection_edge_send_command(exitconn,
4405  RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
4406  connection_mark_for_close(TO_CONN(exitconn));
4407  connection_mark_for_close(TO_CONN(dirconn));
4408  return 0;
4409  }
4410 
4411  return 0;
4412 }
4413 
4414 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
4415  * it is a general stream.
4416  */
4417 int
4419 {
4420  tor_assert(conn);
4421 
4422  if (conn->hs_ident) {
4423  return 1;
4424  }
4425  return 0;
4426 }
4427 
4428 /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
4429  * to exit from it, or 0 if it probably will not allow it.
4430  * (We might be uncertain if conn's destination address has not yet been
4431  * resolved.)
4432  */
4433 int
4435  const node_t *exit_node)
4436 {
4437  const or_options_t *options = get_options();
4438 
4439  tor_assert(conn);
4440  tor_assert(conn->socks_request);
4441  tor_assert(exit_node);
4442 
4443  /* If a particular exit node has been requested for the new connection,
4444  * make sure the exit node of the existing circuit matches exactly.
4445  */
4446  if (conn->chosen_exit_name) {
4447  const node_t *chosen_exit =
4449  if (!chosen_exit || tor_memneq(chosen_exit->identity,
4450  exit_node->identity, DIGEST_LEN)) {
4451  /* doesn't match */
4452 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
4453 // conn->chosen_exit_name, exit->nickname);
4454  return 0;
4455  }
4456  }
4457 
4458  if (conn->use_begindir) {
4459  /* Internal directory fetches do not count as exiting. */
4460  return 1;
4461  }
4462 
4464  tor_addr_t addr, *addrp = NULL;
4466  if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
4467  addrp = &addr;
4468  } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
4469  tor_addr_make_null(&addr, AF_INET6);
4470  addrp = &addr;
4471  } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
4472  tor_addr_make_null(&addr, AF_INET);
4473  addrp = &addr;
4474  }
4476  exit_node);
4477  if (r == ADDR_POLICY_REJECTED)
4478  return 0; /* We know the address, and the exit policy rejects it. */
4480  return 0; /* We don't know the addr, but the exit policy rejects most
4481  * addresses with this port. Since the user didn't ask for
4482  * this node, err on the side of caution. */
4483  } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
4484  /* Don't send DNS requests to non-exit servers by default. */
4485  if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
4486  return 0;
4487  }
4488  if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
4489  /* Not a suitable exit. Refuse it. */
4490  return 0;
4491  }
4492 
4493  return 1;
4494 }
4495 
4496 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
4497  * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
4498  * at <b>b</b>. */
4499 static int
4500 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
4501 {
4502  if (a == NULL) {
4503  return (b == NULL);
4504  } else if (b == NULL) {
4505  return 0;
4506  } else if (alen != blen) {
4507  return 0;
4508  } else {
4509  return tor_memeq(a, b, alen);
4510  }
4511 }
4512 
4513 /**
4514  * Return true iff none of the isolation flags and fields in <b>conn</b>
4515  * should prevent it from being attached to <b>circ</b>.
4516  */
4517 int
4519  const origin_circuit_t *circ)
4520 {
4521  const uint8_t iso = conn->entry_cfg.isolation_flags;
4522  const socks_request_t *sr = conn->socks_request;
4523 
4524  /* If circ has never been used for an isolated connection, we can
4525  * totally use it for this one. */
4526  if (!circ->isolation_values_set)
4527  return 1;
4528 
4529  /* If circ has been used for connections having more than one value
4530  * for some field f, it will have the corresponding bit set in
4531  * isolation_flags_mixed. If isolation_flags_mixed has any bits
4532  * in common with iso, then conn must be isolated from at least
4533  * one stream that has been attached to circ. */
4534  if ((iso & circ->isolation_flags_mixed) != 0) {
4535  /* For at least one field where conn is isolated, the circuit
4536  * already has mixed streams. */
4537  return 0;
4538  }
4539 
4540  if (! conn->original_dest_address) {
4541  log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
4542  "having set conn->original_dest_address");
4543  ((entry_connection_t*)conn)->original_dest_address =
4544  tor_strdup(conn->socks_request->address);
4545  }
4546 
4547  if ((iso & ISO_STREAM) &&
4549  ENTRY_TO_CONN(conn)->global_identifier))
4550  return 0;
4551 
4552  if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
4553  return 0;
4554  if ((iso & ISO_DESTADDR) &&
4555  strcasecmp(conn->original_dest_address, circ->dest_address))
4556  return 0;
4557  if ((iso & ISO_SOCKSAUTH) &&
4558  (! memeq_opt(sr->username, sr->usernamelen,
4559  circ->socks_username, circ->socks_username_len) ||
4560  ! memeq_opt(sr->password, sr->passwordlen,
4561  circ->socks_password, circ->socks_password_len)))
4562  return 0;
4563  if ((iso & ISO_CLIENTPROTO) &&
4564  (conn->socks_request->listener_type != circ->client_proto_type ||
4565  conn->socks_request->socks_version != circ->client_proto_socksver))
4566  return 0;
4567  if ((iso & ISO_CLIENTADDR) &&
4568  !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4569  return 0;
4570  if ((iso & ISO_SESSIONGRP) &&
4571  conn->entry_cfg.session_group != circ->session_group)
4572  return 0;
4573  if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
4574  return 0;
4575 
4576  return 1;
4577 }
4578 
4579 /**
4580  * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
4581  * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
4582  * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
4583  * a bitfield of isolation flags that we would have to set in
4584  * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
4585  * <b>circ</b> has had no streams attached to it.
4586  */
4587 int
4589  origin_circuit_t *circ,
4590  int dry_run)
4591 {
4592  const socks_request_t *sr = conn->socks_request;
4593  if (! conn->original_dest_address) {
4594  log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
4595  "having set conn->original_dest_address");
4596  ((entry_connection_t*)conn)->original_dest_address =
4597  tor_strdup(conn->socks_request->address);
4598  }
4599 
4600  if (!circ->isolation_values_set) {
4601  if (dry_run)
4602  return -1;
4604  ENTRY_TO_CONN(conn)->global_identifier;
4605  circ->dest_port = conn->socks_request->port;
4606  circ->dest_address = tor_strdup(conn->original_dest_address);
4607  circ->client_proto_type = conn->socks_request->listener_type;
4608  circ->client_proto_socksver = conn->socks_request->socks_version;
4609  tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
4610  circ->session_group = conn->entry_cfg.session_group;
4611  circ->nym_epoch = conn->nym_epoch;
4612  circ->socks_username = sr->username ?
4613  tor_memdup(sr->username, sr->usernamelen) : NULL;
4614  circ->socks_password = sr->password ?
4615  tor_memdup(sr->password, sr->passwordlen) : NULL;
4616  circ->socks_username_len = sr->usernamelen;
4617  circ->socks_password_len = sr->passwordlen;
4618 
4619  circ->isolation_values_set = 1;
4620  return 0;
4621  } else {
4622  uint8_t mixed = 0;
4623  if (conn->socks_request->port != circ->dest_port)
4624  mixed |= ISO_DESTPORT;
4625  if (strcasecmp(conn->original_dest_address, circ->dest_address))
4626  mixed |= ISO_DESTADDR;
4627  if (!memeq_opt(sr->username, sr->usernamelen,
4628  circ->socks_username, circ->socks_username_len) ||
4629  !memeq_opt(sr->password, sr->passwordlen,
4630  circ->socks_password, circ->socks_password_len))
4631  mixed |= ISO_SOCKSAUTH;
4632  if ((conn->socks_request->listener_type != circ->client_proto_type ||
4633  conn->socks_request->socks_version != circ->client_proto_socksver))
4634  mixed |= ISO_CLIENTPROTO;
4635  if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4636  mixed |= ISO_CLIENTADDR;
4637  if (conn->entry_cfg.session_group != circ->session_group)
4638  mixed |= ISO_SESSIONGRP;
4639  if (conn->nym_epoch != circ->nym_epoch)
4640  mixed |= ISO_NYM_EPOCH;
4641 
4642  if (dry_run)
4643  return mixed;
4644 
4645  if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
4646  log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
4647  "isolation flags.");
4648  }
4649  circ->isolation_flags_mixed |= mixed;
4650  return 0;
4651  }
4652 }
4653 
4654 /**
4655  * Clear the isolation settings on <b>circ</b>.
4656  *
4657  * This only works on an open circuit that has never had a stream attached to
4658  * it, and whose isolation settings are hypothetical. (We set hypothetical
4659  * isolation settings on circuits as we're launching them, so that we
4660  * know whether they can handle more streams or whether we need to launch
4661  * even more circuits. Once the circuit is open, if it turns out that
4662  * we no longer have any streams to attach to it, we clear the isolation flags
4663  * and data so that other streams can have a chance.)
4664  */
4665 void
4667 {
4668  if (circ->isolation_any_streams_attached) {
4669  log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
4670  return;
4671  }
4672  if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
4673  log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
4674  "circuit");
4675  return;
4676  }
4677 
4678  circ->isolation_values_set = 0;
4679  circ->isolation_flags_mixed = 0;
4681  circ->client_proto_type = 0;
4682  circ->client_proto_socksver = 0;
4683  circ->dest_port = 0;
4684  tor_addr_make_unspec(&circ->client_addr);
4685  tor_free(circ->dest_address);
4686  circ->session_group = -1;
4687  circ->nym_epoch = 0;
4688  if (circ->socks_username) {
4689  memwipe(circ->socks_username, 0x11, circ->socks_username_len);
4690  tor_free(circ->socks_username);
4691  }
4692  if (circ->socks_password) {
4693  memwipe(circ->socks_password, 0x05, circ->socks_password_len);
4694  tor_free(circ->socks_password);
4695  }
4696  circ->socks_username_len = circ->socks_password_len = 0;
4697 }
4698 
4699 /** Send an END and mark for close the given edge connection conn using the
4700  * given reason that has to be a stream reason.
4701  *
4702  * Note: We don't unattached the AP connection (if applicable) because we
4703  * don't want to flush the remaining data. This function aims at ending
4704  * everything quickly regardless of the connection state.
4705  *
4706  * This function can't fail and does nothing if conn is NULL. */
4707 void
4709 {
4710  if (!conn) {
4711  return;
4712  }
4713 
4714  connection_edge_end(conn, reason);
4715  connection_mark_for_close(TO_CONN(conn));
4716 }
4717 
4718 /** Free all storage held in module-scoped variables for connection_edge.c */
4719 void
4721 {
4722  untried_pending_connections = 0;
4723  smartlist_free(pending_entry_connections);
4725  mainloop_event_free(attach_pending_entry_connections_ev);
4726 }
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:889
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
int tor_addr_hostname_is_local(const char *name)
Definition: address.c:2090
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1349
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition: address.c:235
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1164
int tor_addr_port_split(int severity, const char *addrport, char **address_out, uint16_t *port_out)
Definition: address.c:1916
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:780
int tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, int family, int accept_regular)
Definition: address.c:380
char * tor_dup_ip(uint32_t addr)
Definition: address.c:2047
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:911
int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out)
Definition: address.c:165
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const uint8_t *ipv6_bytes)
Definition: address.c:900
int tor_addr_to_PTR_name(char *out, size_t outlen, const tor_addr_t *addr)
Definition: address.c:470
static uint32_t tor_addr_to_ipv4n(const tor_addr_t *a)
Definition: address.h:152
#define REVERSE_LOOKUP_NAME_BUF_LEN
Definition: address.h:296
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:187
static const struct in6_addr * tor_addr_to_in6(const tor_addr_t *a)
Definition: address.h:117
#define tor_addr_to_in6_addr8(x)
Definition: address.h:135
#define tor_addr_eq(a, b)
Definition: address.h:280
void client_dns_set_reverse_addressmap(entry_connection_t *for_conn, const char *address, const char *v, const char *exitname, int ttl)
Definition: addressmap.c:767
void clear_trackexithost_mappings(const char *exitname)
Definition: addressmap.c:174
int address_is_in_virtual_range(const char *address)
Definition: addressmap.c:860
void client_dns_set_addressmap(entry_connection_t *for_conn, const char *address, const tor_addr_t *val, const char *exitname, int ttl)
Definition: addressmap.c:728
int addressmap_rewrite(char *address, size_t maxlen, unsigned flags, time_t *expires_out, addressmap_entry_source_t *exit_source_out)
Definition: addressmap.c:383
int addressmap_address_should_automap(const char *address, const or_options_t *options)
Definition: addressmap.c:249
const char * addressmap_register_virtual_address(int type, char *new_address)
Definition: addressmap.c:1000
int addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags, time_t *expires_out)
Definition: addressmap.c:503
Header for addressmap.c.
time_t approx_time(void)
Definition: approx_time.c:32
Header for backtrace.c.
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
size_t buf_datalen(const buf_t *buf)
Definition: buffers.c:394
int buf_set_to_copy(buf_t **output, const buf_t *input)
Definition: buffers.c:898
Header file for buffers.c.
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:78
static void set_uint32(void *cp, uint32_t v)
Definition: bytes.h:87
static void set_uint8(void *cp, uint8_t v)
Definition: bytes.h:31
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:54
Fixed-size cell structure.
int channel_is_client(const channel_t *chan)
Definition: channel.c:2915
int channel_get_addr_if_possible(const channel_t *chan, tor_addr_t *addr_out)
Definition: channel.c:2857
const char * channel_describe_peer(channel_t *chan)
Definition: channel.c:2837
Header file for channel.c.
void pathbias_mark_use_rollback(origin_circuit_t *circ)
Definition: circpathbias.c:711
void pathbias_mark_use_success(origin_circuit_t *circ)
Definition: circpathbias.c:672
const char * pathbias_state_to_string(path_state_t state)
Definition: circpathbias.c:265
Header file for circuitbuild.c.
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1584
const char * circuit_purpose_to_string(uint8_t purpose)
Definition: circuitlist.c:914
void assert_circuit_ok(const circuit_t *c)
Definition: circuitlist.c:2764
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:177
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:165
const char * circuit_state_to_string(int state)
Definition: circuitlist.c:773
Header file for circuitlist.c.
#define CIRCUIT_PURPOSE_IS_CLIENT(p)
Definition: circuitlist.h:143
#define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
Definition: circuitlist.h:93
#define CIRCUIT_PURPOSE_PATH_BIAS_TESTING
Definition: circuitlist.h:123
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:32
#define CIRCUIT_PURPOSE_C_REND_JOINED
Definition: circuitlist.h:88
#define CIRCUIT_PURPOSE_CONTROLLER
Definition: circuitlist.h:121
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:147
#define CIRCUIT_PURPOSE_OR
Definition: circuitlist.h:39
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:110
#define CIRCUIT_PURPOSE_S_HSDIR_POST
Definition: circuitlist.h:112
#define CIRCUIT_PURPOSE_C_HSDIR_GET
Definition: circuitlist.h:90
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:70
void circpad_machine_event_circ_has_streams(origin_circuit_t *circ)
Header file for circuitpadding.c.
double get_circuit_build_timeout_ms(void)
Definition: circuitstats.c:101
Header file for circuitstats.c.
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1330
void circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
Definition: circuituse.c:3119
int connection_ap_handshake_attach_circuit(entry_connection_t *conn)
Definition: circuituse.c:2780
int connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: circuituse.c:2698
void mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
Definition: circuituse.c:3074
Header file for circuituse.c.
#define MAX(a, b)
Definition: cmp.h:22
#define SUBTYPE_P(p, subtype, basemember)
mainloop_event_t * mainloop_event_postloop_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
void mainloop_event_activate(mainloop_event_t *event)
Header for compat_libevent.c.
uint64_t monotime_absolute_usec(void)
Definition: compat_time.c:804
const or_options_t * get_options(void)
Definition: config.c:926
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1117
tor_cmdline_mode_t command
Definition: config.c:2449
const char * escaped_safe_str(const char *address)
Definition: config.c:1129
Header file for config.c.
uint64_t edge_get_max_rtt(const edge_connection_t *stream)
bool edge_uses_flow_control(const edge_connection_t *stream)
APIs for stream flow control on congestion controlled circuits.
const char * conn_state_to_string(int type, int state)
Definition: connection.c:305
void connection_link_connections(connection_t *conn_a, connection_t *conn_b)
Definition: connection.c:759
dir_connection_t * dir_connection_new(int socket_family)
Definition: connection.c:564
int connection_buf_get_line(connection_t *conn, char *data, size_t *data_len)
Definition: connection.c:4318
void connection_mark_for_close_(connection_t *conn, int line, const char *file)
Definition: connection.c:1089
edge_connection_t * edge_connection_new(int type, int socket_family)
Definition: connection.c:628
void connection_close_immediate(connection_t *conn)
Definition: connection.c:1056
const char * connection_describe(const connection_t *conn)
Definition: connection.c:546
int connection_state_is_open(connection_t *conn)
Definition: connection.c:5045
const char * connection_describe_peer(const connection_t *conn)
Definition: connection.c:531
entry_connection_t * entry_connection_new(int type, int socket_family)
Definition: connection.c:604
void connection_free_(connection_t *conn)
Definition: connection.c:973
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
Definition: connection.c:2447
Header file for connection.c.
#define CONN_TYPE_AP_HTTP_CONNECT_LISTENER
Definition: connection.h:75
#define CONN_TYPE_DIR_LISTENER
Definition: connection.h:53
#define CONN_TYPE_AP
Definition: connection.h:51
#define connection_mark_and_flush_(c, line, file)
Definition: connection.h:179
#define CONN_TYPE_DIR
Definition: connection.h:55
#define CONN_TYPE_EXIT
Definition: connection.h:46
int connection_edge_compatible_with_circuit(const entry_connection_t *conn, const origin_circuit_t *circ)
int connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
int connection_half_edge_is_valid_data(const smartlist_t *half_conns, streamid_t stream_id)
void connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
void connection_mark_unattached_ap_(entry_connection_t *conn, int endreason, int line, const char *file)
static uint32_t connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
void connection_edge_free_all(void)
void connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
static int connection_half_edge_compare_bsearch(const void *key, const void **member)
static size_t n_half_conns_allocated
int connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
uint32_t clip_dns_fuzzy_ttl(uint32_t ttl)
static int connection_ap_supports_optimistic_data(const entry_connection_t *)
STATIC int connection_ap_process_http_connect(entry_connection_t *conn)
entry_connection_t * connection_ap_make_link(connection_t *partner, char *address, uint16_t port, const char *digest, int session_group, int isolation_flags, int use_begindir, int want_onehop)
#define MAX_CONNECTED_CELL_PAYLOAD_LEN
void connection_ap_expire_beginning(void)
void connection_ap_fail_onehop(const char *failed_digest, cpath_build_state_t *build_state)
static void connection_edge_about_to_close(edge_connection_t *edge_conn)
int connection_ap_detach_retriable(entry_connection_t *conn, origin_circuit_t *circ, int reason)
STATIC int connected_cell_format_payload(uint8_t *payload_out, const tor_addr_t *addr, uint32_t ttl)
void connection_ap_rescan_and_attach_pending(void)
int connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
static int connection_ap_process_natd(entry_connection_t *conn)
const entry_connection_t * CONST_TO_ENTRY_CONN(const connection_t *c)
static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
void connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply, size_t replylen, int endreason)
static smartlist_t * pending_entry_connections
int connection_half_edge_is_valid_end(smartlist_t *half_conns, streamid_t stream_id)
void connection_exit_connect(edge_connection_t *edge_conn)
uint32_t clip_dns_ttl(uint32_t ttl)
static bool network_reentry_is_allowed(void)
int connection_ap_process_transparent(entry_connection_t *conn)
void connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn, const char *fname, int lineno)
#define TRACKHOSTEXITS_RETRIES
static mainloop_event_t * attach_pending_entry_connections_ev
void connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
int connection_edge_finished_connecting(edge_connection_t *edge_conn)
int connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
static int connection_exit_connect_dir(edge_connection_t *exitconn)
int connection_edge_finished_flushing(edge_connection_t *conn)
static int my_exit_policy_rejects(const tor_addr_t *addr, uint16_t port, const char **why_rejected)
void circuit_clear_isolation(origin_circuit_t *circ)
int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
void connection_exit_about_to_close(edge_connection_t *edge_conn)
static int connection_ap_get_original_destination(entry_connection_t *conn, socks_request_t *req)
STATIC bool parse_extended_hostname(char *address, hostname_type_t *type_out)
int connection_half_edge_is_valid_connected(const smartlist_t *half_conns, streamid_t stream_id)
entry_connection_t * EDGE_TO_ENTRY_CONN(edge_connection_t *c)
int connection_edge_flushed_some(edge_connection_t *conn)
int connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
void connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn, const tor_addr_t *answer, int ttl, time_t expires)
int connection_edge_update_circuit_isolation(const entry_connection_t *conn, origin_circuit_t *circ, int dry_run)
int connection_edge_reached_eof(edge_connection_t *conn)
static void tell_controller_about_resolved_result(entry_connection_t *conn, int answer_type, size_t answer_len, const char *answer, int ttl, time_t expires)
int connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit_node)
int connection_half_edge_is_valid_resolved(smartlist_t *half_conns, streamid_t stream_id)
int connection_edge_end_errno(edge_connection_t *conn)
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
void connection_ap_attach_pending(int retry)
size_t half_streams_get_total_allocation(void)
int connection_half_edge_is_valid_sendme(const smartlist_t *half_conns, streamid_t stream_id)
int connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
static int connection_ap_handle_onion(entry_connection_t *conn, socks_request_t *socks, origin_circuit_t *circ)
STATIC int begin_cell_parse(const cell_t *cell, begin_cell_t *bcell, uint8_t *end_reason_out)
void connection_ap_about_to_close(entry_connection_t *entry_conn)
static int relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ, uint8_t reason, crypt_path_t *cpath_layer)
const entry_connection_t * CONST_EDGE_TO_ENTRY_CONN(const edge_connection_t *c)
STATIC void connection_half_edge_add(const edge_connection_t *conn, origin_circuit_t *circ)
static int handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
const edge_connection_t * CONST_TO_EDGE_CONN(const connection_t *c)
void connection_ap_handshake_socks_resolved(entry_connection_t *conn, int answer_type, size_t answer_len, const uint8_t *answer, int ttl, time_t expires)
entry_connection_t * TO_ENTRY_CONN(connection_t *c)
STATIC half_edge_t * connection_half_edge_find_stream_id(const smartlist_t *half_conns, streamid_t stream_id)
static int memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
int connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
void connection_entry_set_controller_wait(entry_connection_t *conn)
streamid_t get_unique_stream_id_by_circ(origin_circuit_t *circ)
void half_edge_free_(half_edge_t *he)
void circuit_discard_optional_exit_enclaves(extend_info_t *info)
static int connection_ap_handshake_process_socks(entry_connection_t *conn)
int connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
static int compute_retry_timeout(entry_connection_t *conn)
Header file for connection_edge.c.
#define AP_CONN_STATE_HTTP_CONNECT_WAIT
#define EXIT_CONN_STATE_CONNECTING
#define AP_CONN_STATE_CONTROLLER_WAIT
#define EXIT_CONN_STATE_OPEN
#define AP_CONN_STATE_SOCKS_WAIT
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1082
#define BEGIN_FLAG_IPV6_PREFERRED
#define EXIT_CONN_STATE_RESOLVEFAILED
#define AP_CONN_STATE_IS_UNATTACHED(s)
#define AP_CONN_STATE_CONNECT_WAIT
hostname_type_t
#define AP_CONN_STATE_OPEN
#define EXIT_PURPOSE_CONNECT
#define AP_CONN_STATE_RESOLVE_WAIT
#define BEGIN_FLAG_IPV4_NOT_OK
#define FUZZY_DNS_TTL
#define AP_CONN_STATE_CIRCUIT_WAIT
#define EXIT_CONN_STATE_RESOLVING
#define MIN_DNS_TTL
#define AP_CONN_STATE_NATD_WAIT
#define AP_CONN_STATE_RENDDESC_WAIT
#define BEGIN_FLAG_IPV6_OK
#define EXIT_PURPOSE_RESOLVE
#define MAX_DNS_TTL
int connection_or_digest_is_known_relay(const char *id_digest)
Header file for connection_or.c.
int control_event_stream_bandwidth(edge_connection_t *edge_conn)
int control_event_client_status(int severity, const char *format,...)
int control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp, int reason_code)
int control_event_address_mapped(const char *from, const char *to, time_t expires, const char *error, const int cached, uint64_t stream_id)
Header file for control_events.c.
#define REMAP_STREAM_SOURCE_CACHE
Circuit-build-stse structure.
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
Common functions for using (pseudo-)random number generators.
unsigned crypto_rand_uint(unsigned limit)
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
Common functions for cryptographic routines.
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:224
const char * node_describe(const node_t *node)
Definition: describe.c:160
Header file for describe.c.
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
#define DIGEST_LEN
Definition: digest_sizes.h:20
Client/server directory connection structure.
int purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose, const char *resource)
Definition: directory.c:113
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition: directory.c:88
char * http_get_header(const char *headers, const char *which)
Definition: directory.c:325
int parse_http_command(const char *headers, char **command_out, char **url_out)
Definition: directory.c:271
Header file for directory.c.
#define DIR_CONN_STATE_SERVER_COMMAND_WAIT
Definition: directory.h:28
#define DIR_PURPOSE_SERVER
Definition: directory.h:60
int directory_permits_begindir_requests(const or_options_t *options)
Definition: dirserv.c:110
Header file for dirserv.c.
void connection_dns_remove(edge_connection_t *conn)
Definition: dns.c:984
int dns_resolve(edge_connection_t *exitconn)
Definition: dns.c:625
Header file for dns.c.
void dnsserv_reject_request(entry_connection_t *conn)
Definition: dnsserv.c:292
void dnsserv_resolved(entry_connection_t *conn, int answer_type, size_t answer_len, const char *answer, int ttl)
Definition: dnsserv.c:342
Header file for dnsserv.c.
Entry connection structure.
#define ENTRY_TO_EDGE_CONN(c)
const char * escaped(const char *s)
Definition: escape.c:126
Extend-info structure.
bool extend_info_has_orport(const extend_info_t *ei, const tor_addr_t *addr, uint16_t port)
Definition: extendinfo.c:265
Header for core/or/extendinfo.c.
int tor_open_cloexec(const char *path, int flags, unsigned mode)
Definition: files.c:54
Half-open connection structure.
int we_are_hibernating(void)
Definition: hibernate.c:937
Header file for hibernate.c.
const hs_descriptor_t * hs_cache_lookup_as_client(const ed25519_public_key_t *key)
Definition: hs_cache.c:843
Header file for hs_cache.c.
Header file containing circuit data for the whole HS subsystem.
int hs_client_any_intro_points_usable(const ed25519_public_key_t *service_pk, const hs_descriptor_t *desc)
Definition: hs_client.c:2089
int hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
Definition: hs_client.c:2112
Header file containing client data for the HS subsystem.
@ HS_CLIENT_FETCH_PENDING
Definition: hs_client.h:33
@ HS_CLIENT_FETCH_MISSING_INFO
Definition: hs_client.h:31
@ HS_CLIENT_FETCH_NO_HSDIRS
Definition: hs_client.h:27
@ HS_CLIENT_FETCH_HAVE_DESC
Definition: hs_client.h:25
@ HS_CLIENT_FETCH_NOT_ALLOWED
Definition: hs_client.h:29
@ HS_CLIENT_FETCH_ERROR
Definition: hs_client.h:21
@ HS_CLIENT_FETCH_LAUNCHED
Definition: hs_client.h:23
int hs_parse_address(const char *address, ed25519_public_key_t *key_out, uint8_t *checksum_out, uint8_t *version_out)
Definition: hs_common.c:840
int hs_address_is_valid(const char *address)
Definition: hs_common.c:856
void hs_inc_rdv_stream_counter(origin_circuit_t *circ)
Definition: hs_common.c:1737
Header file containing common data for the whole HS subsystem.
#define HS_SERVICE_ADDR_LEN_BASE32
Definition: hs_common.h:80
hs_ident_edge_conn_t * hs_ident_edge_conn_new(const ed25519_public_key_t *identity_pk)
Definition: hs_ident.c:84
hs_circuit_id_protocol_t hs_service_exports_circuit_id(const ed25519_public_key_t *pk)
Definition: hs_service.c:4059
int hs_service_set_conn_addr_port(const origin_circuit_t *circ, edge_connection_t *conn)
Definition: hs_service.c:3979
hs_circuit_id_protocol_t
Definition: hs_service.h:194
@ HS_CIRCUIT_ID_PROTOCOL_HAPROXY
Definition: hs_service.h:199
uint16_t sa_family_t
Definition: inaddr_st.h:77
#define log_fn(severity, domain, args,...)
Definition: log.h:283
#define LD_REND
Definition: log.h:84
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:288
#define LD_EDGE
Definition: log.h:94
#define LD_APP
Definition: log.h:78
#define LD_PROTOCOL
Definition: log.h:72
#define LD_BUG
Definition: log.h:86
#define LD_NET
Definition: log.h:66
#define LD_GENERAL
Definition: log.h:62
#define LOG_NOTICE
Definition: log.h:50
#define LD_CONTROL
Definition: log.h:80
#define LOG_WARN
Definition: log.h:53
#define LOG_INFO
Definition: log.h:45
void connection_watch_events(connection_t *conn, watchable_events_t events)
Definition: mainloop.c:485
void connection_start_reading(connection_t *conn)
Definition: mainloop.c:623
void connection_start_writing(connection_t *conn)
Definition: mainloop.c:686
smartlist_t * get_connection_array(void)
Definition: mainloop.c:443
Header file for mainloop.c.
@ WRITE_EVENT
Definition: mainloop.h:38
@ READ_EVENT
Definition: mainloop.h:37
#define tor_free(p)
Definition: malloc.h:56
void note_user_activity(time_t now)
Definition: netstatus.c:63
Header for netstatus.c.
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
Header file for networkstatus.c.
Node information structure.
void node_get_address_string(const node_t *node, char *buf, size_t len)
Definition: nodelist.c:1698
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1085
const node_t * router_find_exact_exit_enclave(const char *address, uint16_t port)
Definition: nodelist.c:2307
bool nodelist_reentry_contains(const tor_addr_t *addr, uint16_t port)
Definition: nodelist.c:562
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:226
int node_exit_policy_rejects_all(const node_t *node)
Definition: nodelist.c:1579
Header file for nodelist.c.
Master header file for Tor-specific functionality.
#define CELL_PAYLOAD_SIZE
Definition: or.h:456
addressmap_entry_source_t
Definition: or.h:906
@ ADDRMAPSRC_TRACKEXIT
Definition: or.h:917
@ ADDRMAPSRC_AUTOMAP
Definition: or.h:911
@ ADDRMAPSRC_NONE
Definition: or.h:925
@ ADDRMAPSRC_DNS
Definition: or.h:920
#define STREAMWINDOW_INCREMENT
Definition: or.h:395
#define STREAMWINDOW_START
Definition: or.h:392
#define END_STREAM_REASON_SOCKSPROTOCOL
Definition: or.h:260
#define END_STREAM_REASON_INVALID_NATD_DEST
Definition: or.h:266
#define END_STREAM_REASON_HTTPPROTOCOL
Definition: or.h:273
#define END_STREAM_REASON_CANT_ATTACH
Definition: or.h:254
#define END_STREAM_REASON_PRIVATE_ADDR
Definition: or.h:269
#define ISO_STREAM
Definition: or.h:859
uint32_t circid_t
Definition: or.h:488
#define ISO_CLIENTPROTO
Definition: or.h:851
#define ISO_DESTADDR
Definition: or.h:847
#define ISO_SESSIONGRP
Definition: or.h:855
uint16_t streamid_t
Definition: or.h:490
#define END_STREAM_REASON_CANT_FETCH_ORIG_DEST
Definition: or.h:263
#define TO_CIRCUIT(x)
Definition: or.h:836
#define RELAY_PAYLOAD_SIZE
Definition: or.h:485
#define ISO_SOCKSAUTH
Definition: or.h:849
#define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
Definition: or.h:287
#define ISO_DESTPORT
Definition: or.h:845
#define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
Definition: or.h:283
#define TO_CONN(c)
Definition: or.h:603
#define ISO_NYM_EPOCH
Definition: or.h:857
#define ISO_CLIENTADDR
Definition: or.h:853
#define RELAY_HEADER_SIZE
Definition: or.h:483
#define DOWNCAST(to, ptr)
Definition: or.h:109
#define END_STREAM_REASON_MASK
Definition: or.h:276
#define SOCKS4_NETWORK_LEN
Definition: or.h:443
#define END_CIRC_AT_ORIGIN
Definition: or.h:309
#define ENTRY_TO_CONN(c)
Definition: or.h:606
Origin circuit structure.
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:59
addr_policy_result_t compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port, const node_t *node)
Definition: policies.c:2907
Header file for policies.c.
addr_policy_result_t
Definition: policies.h:38
@ ADDR_POLICY_PROBABLY_REJECTED
Definition: policies.h:48
@ ADDR_POLICY_REJECTED
Definition: policies.h:42
void rep_hist_note_used_port(time_t now, uint16_t port)
void rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
void rep_hist_note_used_resolve(time_t now)
Header file for predict_ports.c.
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
int fetch_from_buf_http(buf_t *buf, char **headers_out, size_t max_headerlen, char **body_out, size_t *body_used, size_t max_bodylen, int force_complete)
Definition: proto_http.c:50
Header for proto_http.c.
int fetch_from_buf_socks(buf_t *buf, socks_request_t *req, int log_sockstype, int safe_socks)
Definition: proto_socks.c:829
Header for proto_socks.c.
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:42
const char * stream_end_reason_to_string(int reason)
Definition: reasons.c:64
socks5_reply_status_t stream_end_reason_to_socks5_response(int reason)
Definition: reasons.c:100
const char * end_reason_to_http_connect_response_line(int endreason)
Definition: reasons.c:461
uint8_t errno_to_stream_end_reason(int e)
Definition: reasons.c:177
Header file for reasons.c.
void relay_header_unpack(relay_header_t *dest, const uint8_t *src)
Definition: relay.c:496
int connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial, int *max_cells)
Definition: relay.c:2219
int connection_edge_send_command(edge_connection_t *fromconn, uint8_t relay_command, const char *payload, size_t payload_len)
Definition: relay.c:737
Header file for relay.c.
Header file for rendcommon.c.
void rep_hist_note_exit_stream(unsigned int cmd)
Definition: rephist.c:1653
void rep_hist_note_exit_stream_opened(uint16_t port)
Definition: rephist.c:1634
void rep_hist_note_conn_rejected(unsigned int type, int af)
Definition: rephist.c:1755
Header file for rephist.c.
int router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
Definition: router.c:1692
int should_refuse_unknown_exits(const or_options_t *options)
Definition: router.c:1380
Header file for router.c.
int hexdigest_to_digest(const char *hexdigest, char *digest)
Definition: routerlist.c:747
Header file for routerlist.c.
int server_mode(const or_options_t *options)
Definition: routermode.c:34
Header file for routermode.c.
int routerset_contains_node(const routerset_t *set, const node_t *node)
Definition: routerset.c:353
Header file for routerset.c.
void sendme_connection_edge_consider_sending(edge_connection_t *conn)
Definition: sendme.c:373
Header file for sendme.c.
void * smartlist_bsearch(const smartlist_t *sl, const void *key, int(*compare)(const void *key, const void **member))
Definition: smartlist.c:411
int smartlist_contains_int_as_string(const smartlist_t *sl, int num)
Definition: smartlist.c:147
int smartlist_bsearch_idx(const smartlist_t *sl, const void *key, int(*compare)(const void *key, const void **member), int *found_out)
Definition: smartlist.c:428
void smartlist_insert(smartlist_t *sl, int idx, void *val)
smartlist_t * smartlist_new(void)
int smartlist_contains(const smartlist_t *sl, const void *element)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_remove(smartlist_t *sl, const void *element)
void smartlist_del_keeporder(smartlist_t *sl, int idx)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
socks5_reply_status_t
Definition: socks5_status.h:20
Client request structure.
#define SOCKS_COMMAND_RESOLVE_PTR
#define SOCKS_COMMAND_CONNECT
#define SOCKS_COMMAND_RESOLVE
Definition: cell_st.h:17
uint8_t payload[CELL_PAYLOAD_SIZE]
Definition: cell_st.h:21
char identity_digest[DIGEST_LEN]
Definition: channel.h:378
uint8_t state
Definition: circuit_st.h:111
uint64_t dirreq_id
Definition: circuit_st.h:205
uint16_t marked_for_close
Definition: circuit_st.h:190
uint8_t purpose
Definition: circuit_st.h:112
circid_t n_circ_id
Definition: circuit_st.h:79
time_t timestamp_last_read_allowed
uint8_t state
Definition: connection_st.h:49
struct buf_t * inbuf
struct connection_t * linked_conn
unsigned int type
Definition: connection_st.h:50
uint32_t magic
Definition: connection_st.h:46
unsigned int linked
Definition: connection_st.h:78
uint16_t marked_for_close
uint16_t port
const char * marked_for_close_file
unsigned int purpose
Definition: connection_st.h:51
tor_socket_t s
tor_addr_t addr
extend_info_t * chosen_exit
struct crypt_path_t * prev
Definition: crypt_path_st.h:80
extend_info_t * extend_info
Definition: crypt_path_st.h:66
struct crypt_path_t * cpath_layer
struct edge_connection_t * next_stream
unsigned int edge_has_sent_end
struct circuit_t * on_circuit
unsigned int is_transparent_ap
socks_request_t * socks_request
struct evdns_server_request * dns_server_request
unsigned int chosen_exit_optional
unsigned int chosen_exit_retries
unsigned int may_use_optimistic_data
struct buf_t * pending_optimistic_data
unsigned int use_cached_ipv4_answers
unsigned int prefer_ipv6_virtaddr
char identity_digest[DIGEST_LEN]
int used_ccontrol
Definition: half_edge_st.h:44
uint64_t end_ack_expected_usec
Definition: half_edge_st.h:39
streamid_t stream_id
Definition: half_edge_st.h:24
int connected_pending
Definition: half_edge_st.h:47
int sendmes_pending
Definition: half_edge_st.h:28
int data_pending
Definition: half_edge_st.h:32
ed25519_public_key_t identity_pk
Definition: hs_ident.h:45
ed25519_public_key_t identity_pk
Definition: hs_ident.h:106
uint16_t orig_virtual_port
Definition: hs_ident.h:111
Definition: node_st.h:34
char identity[DIGEST_LEN]
Definition: node_st.h:46
channel_t * p_chan
Definition: or_circuit_st.h:37
edge_connection_t * n_streams
Definition: or_circuit_st.h:39
struct routerset_t * ExcludeExitNodes
struct smartlist_t * RejectPlaintextPorts
struct routerset_t * ExcludeExitNodesUnion_
struct smartlist_t * WarnPlaintextPorts
char * TransProxyType
int LeaveStreamsUnattached
int ClientRejectInternalAddresses
enum or_options_t::@2 TransProxyType_parsed
int AutomapHostsOnResolve
int CircuitStreamTimeout
int ClientDNSRejectInternalAddresses
uint64_t associated_isolated_stream_global_id
struct hs_ident_circuit_t * hs_ident
edge_connection_t * p_streams
unsigned int isolation_values_set