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