Tor  0.4.5.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 connction,
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 preceeds member,
582  * > 0 if member preceeds 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 &&
1212  log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
1213  "The purpose on the circuit was %s; it was in state %s, "
1214  "path_state %s.",
1217  CIRCUIT_IS_ORIGIN(circ) ?
1218  pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
1219  "none");
1220  }
1221  log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
1222  "We tried for %d seconds to connect to '%s' using exit %s."
1223  " Retrying on a new circuit.",
1224  seconds_idle,
1225  safe_str_client(entry_conn->socks_request->address),
1226  conn->cpath_layer ?
1228  "*unnamed*");
1229  /* send an end down the circuit */
1230  connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1231  /* un-mark it as ending, since we're going to reuse it */
1232  conn->edge_has_sent_end = 0;
1233  conn->end_reason = 0;
1234  /* make us not try this circuit again, but allow
1235  * current streams on it to survive if they can */
1237 
1238  /* give our stream another 'cutoff' seconds to try */
1239  conn->base_.timestamp_last_read_allowed += cutoff;
1240  if (entry_conn->num_socks_retries < 250) /* avoid overflow */
1241  entry_conn->num_socks_retries++;
1242  /* move it back into 'pending' state, and try to attach. */
1243  if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
1244  END_STREAM_REASON_TIMEOUT)<0) {
1245  if (!base_conn->marked_for_close)
1246  connection_mark_unattached_ap(entry_conn,
1248  }
1249  } SMARTLIST_FOREACH_END(base_conn);
1250 }
1251 
1252 /**
1253  * As connection_ap_attach_pending, but first scans the entire connection
1254  * array to see if any elements are missing.
1255  */
1256 void
1258 {
1259  entry_connection_t *entry_conn;
1260  smartlist_t *conns = get_connection_array();
1261 
1262  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1264 
1265  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1266  if (conn->marked_for_close ||
1267  conn->type != CONN_TYPE_AP ||
1268  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1269  continue;
1270 
1271  entry_conn = TO_ENTRY_CONN(conn);
1272  tor_assert(entry_conn);
1273  if (! smartlist_contains(pending_entry_connections, entry_conn)) {
1274  log_warn(LD_BUG, "Found a connection %p that was supposed to be "
1275  "in pending_entry_connections, but wasn't. No worries; "
1276  "adding it.",
1278  untried_pending_connections = 1;
1279  connection_ap_mark_as_pending_circuit(entry_conn);
1280  }
1281 
1282  } SMARTLIST_FOREACH_END(conn);
1283 
1285 }
1286 
1287 #ifdef DEBUGGING_17659
1288 #define UNMARK() do { \
1289  entry_conn->marked_pending_circ_line = 0; \
1290  entry_conn->marked_pending_circ_file = 0; \
1291  } while (0)
1292 #else /* !defined(DEBUGGING_17659) */
1293 #define UNMARK() do { } while (0)
1294 #endif /* defined(DEBUGGING_17659) */
1295 
1296 /** Tell any AP streams that are listed as waiting for a new circuit to try
1297  * again. If there is an available circuit for a stream, attach it. Otherwise,
1298  * launch a new circuit.
1299  *
1300  * If <b>retry</b> is false, only check the list if it contains at least one
1301  * streams that we have not yet tried to attach to a circuit.
1302  */
1303 void
1305 {
1306  if (PREDICT_UNLIKELY(!pending_entry_connections)) {
1307  return;
1308  }
1309 
1310  if (untried_pending_connections == 0 && !retry)
1311  return;
1312 
1313  /* Don't allow any modifications to list while we are iterating over
1314  * it. We'll put streams back on this list if we can't attach them
1315  * immediately. */
1318 
1319  SMARTLIST_FOREACH_BEGIN(pending,
1320  entry_connection_t *, entry_conn) {
1321  connection_t *conn = ENTRY_TO_CONN(entry_conn);
1322  tor_assert(conn && entry_conn);
1323  if (conn->marked_for_close) {
1324  UNMARK();
1325  continue;
1326  }
1327  if (conn->magic != ENTRY_CONNECTION_MAGIC) {
1328  log_warn(LD_BUG, "%p has impossible magic value %u.",
1329  entry_conn, (unsigned)conn->magic);
1330  UNMARK();
1331  continue;
1332  }
1333  if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
1334  log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
1335  "is %s. Why is it on pending_entry_connections?",
1336  entry_conn,
1337  conn_state_to_string(conn->type, conn->state));
1338  UNMARK();
1339  continue;
1340  }
1341 
1342  /* Okay, we're through the sanity checks. Try to handle this stream. */
1343  if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
1344  if (!conn->marked_for_close)
1345  connection_mark_unattached_ap(entry_conn,
1347  }
1348 
1349  if (! conn->marked_for_close &&
1350  conn->type == CONN_TYPE_AP &&
1351  conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1352  /* Is it still waiting for a circuit? If so, we didn't attach it,
1353  * so it's still pending. Put it back on the list.
1354  */
1355  if (!smartlist_contains(pending_entry_connections, entry_conn)) {
1357  continue;
1358  }
1359  }
1360 
1361  /* If we got here, then we either closed the connection, or
1362  * we attached it. */
1363  UNMARK();
1364  } SMARTLIST_FOREACH_END(entry_conn);
1365 
1366  smartlist_free(pending);
1367  untried_pending_connections = 0;
1368 }
1369 
1370 static void
1371 attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
1372 {
1373  (void)ev;
1374  (void)arg;
1376 }
1377 
1378 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
1379  *
1380  * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
1381  * should not already be pending a circuit. The circuit will get
1382  * launched or the connection will get attached the next time we
1383  * call connection_ap_attach_pending().
1384  */
1385 void
1387  const char *fname, int lineno)
1388 {
1389  connection_t *conn = ENTRY_TO_CONN(entry_conn);
1391  tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
1392  if (conn->marked_for_close)
1393  return;
1394 
1395  if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
1397  }
1398  if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
1400  attach_pending_entry_connections_cb, NULL);
1401  }
1402  if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
1403  entry_conn))) {
1404  log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
1405  "(Called from %s:%d.)",
1406  entry_conn, fname, lineno);
1407 #ifdef DEBUGGING_17659
1408  const char *f2 = entry_conn->marked_pending_circ_file;
1409  log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
1410  f2 ? f2 : "<NULL>",
1411  entry_conn->marked_pending_circ_line);
1412 #endif /* defined(DEBUGGING_17659) */
1413  log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
1414  return;
1415  }
1416 
1417 #ifdef DEBUGGING_17659
1418  entry_conn->marked_pending_circ_line = (uint16_t) lineno;
1419  entry_conn->marked_pending_circ_file = fname;
1420 #endif
1421 
1422  untried_pending_connections = 1;
1424 
1426 }
1427 
1428 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
1429 void
1431 {
1432  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1433  return;
1434  UNMARK();
1436 }
1437 
1438 /** Mark <b>entry_conn</b> as waiting for a rendezvous descriptor. This
1439  * function will remove the entry connection from the waiting for a circuit
1440  * list (pending_entry_connections).
1441  *
1442  * This pattern is used across the code base because a connection in state
1443  * AP_CONN_STATE_RENDDESC_WAIT must not be in the pending list. */
1444 void
1446 {
1447  tor_assert(entry_conn);
1448 
1450  ENTRY_TO_CONN(entry_conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
1451 }
1452 
1453 /* DOCDOC */
1454 void
1455 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
1456  const char *where)
1457 {
1460  log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
1461  entry_conn, where);
1463  }
1464 }
1465 
1466 /** Tell any AP streams that are waiting for a one-hop tunnel to
1467  * <b>failed_digest</b> that they are going to fail. */
1468 /* XXXX We should get rid of this function, and instead attach
1469  * one-hop streams to circ->p_streams so they get marked in
1470  * circuit_mark_for_close like normal p_streams. */
1471 void
1472 connection_ap_fail_onehop(const char *failed_digest,
1473  cpath_build_state_t *build_state)
1474 {
1475  entry_connection_t *entry_conn;
1476  char digest[DIGEST_LEN];
1477  smartlist_t *conns = get_connection_array();
1478  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1479  if (conn->marked_for_close ||
1480  conn->type != CONN_TYPE_AP ||
1481  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1482  continue;
1483  entry_conn = TO_ENTRY_CONN(conn);
1484  if (!entry_conn->want_onehop)
1485  continue;
1486  if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
1487  tor_memneq(digest, failed_digest, DIGEST_LEN))
1488  continue;
1489  if (tor_digest_is_zero(digest)) {
1490  /* we don't know the digest; have to compare addr:port */
1491  tor_addr_t addr;
1492  if (!build_state || !build_state->chosen_exit ||
1493  !entry_conn->socks_request) {
1494  continue;
1495  }
1496  if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
1497  !extend_info_has_orport(build_state->chosen_exit, &addr,
1498  entry_conn->socks_request->port))
1499  continue;
1500  }
1501  log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
1502  "just failed.", entry_conn->chosen_exit_name,
1503  entry_conn->socks_request->address);
1504  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1505  } SMARTLIST_FOREACH_END(conn);
1506 }
1507 
1508 /** A circuit failed to finish on its last hop <b>info</b>. If there
1509  * are any streams waiting with this exit node in mind, but they
1510  * don't absolutely require it, make them give up on it.
1511  */
1512 void
1514 {
1515  entry_connection_t *entry_conn;
1516  const node_t *r1, *r2;
1517 
1518  smartlist_t *conns = get_connection_array();
1519  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1520  if (conn->marked_for_close ||
1521  conn->type != CONN_TYPE_AP ||
1522  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1523  continue;
1524  entry_conn = TO_ENTRY_CONN(conn);
1525  if (!entry_conn->chosen_exit_optional &&
1526  !entry_conn->chosen_exit_retries)
1527  continue;
1528  r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
1529  NNF_NO_WARN_UNNAMED);
1530  r2 = node_get_by_id(info->identity_digest);
1531  if (!r1 || !r2 || r1 != r2)
1532  continue;
1533  tor_assert(entry_conn->socks_request);
1534  if (entry_conn->chosen_exit_optional) {
1535  log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
1536  safe_str_client(entry_conn->chosen_exit_name),
1538  entry_conn->chosen_exit_optional = 0;
1539  tor_free(entry_conn->chosen_exit_name); /* clears it */
1540  /* if this port is dangerous, warn or reject it now that we don't
1541  * think it'll be using an enclave. */
1542  consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1543  }
1544  if (entry_conn->chosen_exit_retries) {
1545  if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
1547  tor_free(entry_conn->chosen_exit_name); /* clears it */
1548  /* if this port is dangerous, warn or reject it now that we don't
1549  * think it'll be using an enclave. */
1550  consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1551  }
1552  }
1553  } SMARTLIST_FOREACH_END(conn);
1554 }
1555 
1556 /** Set the connection state to CONTROLLER_WAIT and send an control port event.
1557  */
1558 void
1560 {
1561  CONNECTION_AP_EXPECT_NONPENDING(conn);
1563  control_event_stream_status(conn, STREAM_EVENT_CONTROLLER_WAIT, 0);
1564 }
1565 
1566 /** The AP connection <b>conn</b> has just failed while attaching or
1567  * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1568  * might work. Detach the circuit, and either reattach it, launch a
1569  * new circuit, tell the controller, or give up as appropriate.
1570  *
1571  * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1572  */
1573 int
1575  origin_circuit_t *circ,
1576  int reason)
1577 {
1578  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
1579  ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
1580 
1581  /* Roll back path bias use state so that we probe the circuit
1582  * if nothing else succeeds on it */
1584 
1585  if (conn->pending_optimistic_data) {
1586  buf_set_to_copy(&conn->sending_optimistic_data,
1587  conn->pending_optimistic_data);
1588  }
1589 
1590  if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
1591  /* If we're attaching streams ourself, or if this connection is
1592  * a tunneled directory connection, then just attach it. */
1595  connection_ap_mark_as_pending_circuit(conn);
1596  } else {
1599  }
1600  return 0;
1601 }
1602 
1603 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1604  * reject depending on our config options. */
1605 static int
1607 {
1608  const or_options_t *options = get_options();
1609  int reject = smartlist_contains_int_as_string(
1610  options->RejectPlaintextPorts, port);
1611 
1613  log_warn(LD_APP, "Application request to port %d: this port is "
1614  "commonly used for unencrypted protocols. Please make sure "
1615  "you don't send anything you would mind the rest of the "
1616  "Internet reading!%s", port, reject ? " Closing." : "");
1617  control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1618  port, reject ? "REJECT" : "WARN");
1619  }
1620 
1621  if (reject) {
1622  log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1623  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1624  return -1;
1625  }
1626 
1627  return 0;
1628 }
1629 
1630 /** Parse the given hostname in address. Returns true if the parsing was
1631  * successful and type_out contains the type of the hostname. Else, false is
1632  * returned which means it was not recognized and type_out is set to
1633  * BAD_HOSTNAME.
1634  *
1635  * The possible recognized forms are (where true is returned):
1636  *
1637  * If address is of the form "y.onion" with a well-formed handle y:
1638  * Put a NUL after y, lower-case it, and return ONION_V2_HOSTNAME or
1639  * ONION_V3_HOSTNAME depending on the HS version.
1640  *
1641  * If address is of the form "x.y.onion" with a well-formed handle x:
1642  * Drop "x.", put a NUL after y, lower-case it, and return
1643  * ONION_V2_HOSTNAME or ONION_V3_HOSTNAME depending on the HS version.
1644  *
1645  * If address is of the form "y.onion" with a badly-formed handle y:
1646  * Return BAD_HOSTNAME and log a message.
1647  *
1648  * If address is of the form "y.exit":
1649  * Put a NUL after y and return EXIT_HOSTNAME.
1650  *
1651  * Otherwise:
1652  * Return NORMAL_HOSTNAME and change nothing.
1653  */
1654 STATIC bool
1655 parse_extended_hostname(char *address, hostname_type_t *type_out)
1656 {
1657  char *s;
1658  char *q;
1659  char query[HS_SERVICE_ADDR_LEN_BASE32+1];
1660 
1661  s = strrchr(address,'.');
1662  if (!s) {
1663  *type_out = NORMAL_HOSTNAME; /* no dot, thus normal */
1664  goto success;
1665  }
1666  if (!strcmp(s+1,"exit")) {
1667  *s = 0; /* NUL-terminate it */
1668  *type_out = EXIT_HOSTNAME; /* .exit */
1669  goto success;
1670  }
1671  if (strcmp(s+1,"onion")) {
1672  *type_out = NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1673  goto success;
1674  }
1675 
1676  /* so it is .onion */
1677  *s = 0; /* NUL-terminate it */
1678  /* locate a 'sub-domain' component, in order to remove it */
1679  q = strrchr(address, '.');
1680  if (q == address) {
1681  *type_out = BAD_HOSTNAME;
1682  goto failed; /* reject sub-domain, as DNS does */
1683  }
1684  q = (NULL == q) ? address : q + 1;
1685  if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
1687  *type_out = BAD_HOSTNAME;
1688  goto failed;
1689  }
1690  if (q != address) {
1691  memmove(address, q, strlen(q) + 1 /* also get \0 */);
1692  }
1693  /* v2 onion address check. */
1694  if (strlen(query) == REND_SERVICE_ID_LEN_BASE32) {
1695  *type_out = ONION_V2_HOSTNAME;
1696  if (rend_valid_v2_service_id(query)) {
1697  goto success;
1698  }
1699  goto failed;
1700  }
1701 
1702  /* v3 onion address check. */
1703  if (strlen(query) == HS_SERVICE_ADDR_LEN_BASE32) {
1704  *type_out = ONION_V3_HOSTNAME;
1705  if (hs_address_is_valid(query)) {
1706  goto success;
1707  }
1708  goto failed;
1709  }
1710 
1711  /* Reaching this point, nothing was recognized. */
1712  *type_out = BAD_HOSTNAME;
1713  goto failed;
1714 
1715  success:
1716  return true;
1717  failed:
1718  /* otherwise, return to previous state and return 0 */
1719  *s = '.';
1720  const bool is_onion = (*type_out == ONION_V2_HOSTNAME) ||
1721  (*type_out == ONION_V3_HOSTNAME);
1722  log_warn(LD_APP, "Invalid %shostname %s; rejecting",
1723  is_onion ? "onion " : "",
1724  safe_str_client(address));
1725  if (*type_out == ONION_V3_HOSTNAME) {
1726  *type_out = BAD_HOSTNAME;
1727  }
1728  return false;
1729 }
1730 
1731 /** How many times do we try connecting with an exit configured via
1732  * TrackHostExits before concluding that it won't work any more and trying a
1733  * different one? */
1734 #define TRACKHOSTEXITS_RETRIES 5
1735 
1736 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1737  * asked us to leave streams unattached. Return 0 in that case.
1738  *
1739  * See connection_ap_handshake_rewrite_and_attach()'s
1740  * documentation for arguments and return value.
1741  */
1742 MOCK_IMPL(int,
1744  origin_circuit_t *circ,
1745  crypt_path_t *cpath))
1746 {
1747  const or_options_t *options = get_options();
1748 
1749  if (options->LeaveStreamsUnattached) {
1751  return 0;
1752  }
1753  return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1754 }
1755 
1756 /* Try to perform any map-based rewriting of the target address in
1757  * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1758  * conn->socks_request.address as appropriate.
1759  */
1760 STATIC void
1761 connection_ap_handshake_rewrite(entry_connection_t *conn,
1762  rewrite_result_t *out)
1763 {
1764  socks_request_t *socks = conn->socks_request;
1765  const or_options_t *options = get_options();
1766  tor_addr_t addr_tmp;
1767 
1768  /* Initialize all the fields of 'out' to reasonable defaults */
1769  out->automap = 0;
1770  out->exit_source = ADDRMAPSRC_NONE;
1771  out->map_expires = TIME_MAX;
1772  out->end_reason = 0;
1773  out->should_close = 0;
1774  out->orig_address[0] = 0;
1775 
1776  /* We convert all incoming addresses to lowercase. */
1777  tor_strlower(socks->address);
1778  /* Remember the original address. */
1779  strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
1780  log_debug(LD_APP,"Client asked for %s:%d",
1781  safe_str_client(socks->address),
1782  socks->port);
1783 
1784  /* Check for whether this is a .exit address. By default, those are
1785  * disallowed when they're coming straight from the client, but you're
1786  * allowed to have them in MapAddress commands and so forth. */
1787  if (!strcmpend(socks->address, ".exit")) {
1788  static ratelim_t exit_warning_limit = RATELIM_INIT(60*15);
1789  log_fn_ratelim(&exit_warning_limit, LOG_WARN, LD_APP,
1790  "The \".exit\" notation is disabled in Tor due to "
1791  "security risks.");
1792  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1793  escaped(socks->address));
1794  out->end_reason = END_STREAM_REASON_TORPROTOCOL;
1795  out->should_close = 1;
1796  return;
1797  }
1798 
1799  /* Remember the original address so we can tell the user about what
1800  * they actually said, not just what it turned into. */
1801  /* XXX yes, this is the same as out->orig_address above. One is
1802  * in the output, and one is in the connection. */
1803  if (! conn->original_dest_address) {
1804  /* Is the 'if' necessary here? XXXX */
1805  conn->original_dest_address = tor_strdup(conn->socks_request->address);
1806  }
1807 
1808  /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1809  * these only for non-reverse lookups, since they don't exist for those.
1810  * We also need to do this before we consider automapping, since we might
1811  * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1812  * we'd need to automap it. */
1813  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
1814  const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
1815  if (addressmap_rewrite(socks->address, sizeof(socks->address),
1816  rewrite_flags, &out->map_expires, &out->exit_source)) {
1817  control_event_stream_status(conn, STREAM_EVENT_REMAP,
1819  }
1820  }
1821 
1822  /* Now see if we need to create or return an existing Hostname->IP
1823  * automapping. Automapping happens when we're asked to resolve a
1824  * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1825  * suffix listed in AutomapHostsSuffixes. It's a handy feature
1826  * that lets you have Tor assign e.g. IPv6 addresses for .onion
1827  * names, and return them safely from DNSPort.
1828  */
1829  if (socks->command == SOCKS_COMMAND_RESOLVE &&
1830  tor_addr_parse(&addr_tmp, socks->address)<0 &&
1831  options->AutomapHostsOnResolve) {
1832  /* Check the suffix... */
1833  out->automap = addressmap_address_should_automap(socks->address, options);
1834  if (out->automap) {
1835  /* If we get here, then we should apply an automapping for this. */
1836  const char *new_addr;
1837  /* We return an IPv4 address by default, or an IPv6 address if we
1838  * are allowed to do so. */
1839  int addr_type = RESOLVED_TYPE_IPV4;
1840  if (conn->socks_request->socks_version != 4) {
1841  if (!conn->entry_cfg.ipv4_traffic ||
1842  (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
1843  conn->entry_cfg.prefer_ipv6_virtaddr)
1844  addr_type = RESOLVED_TYPE_IPV6;
1845  }
1846  /* Okay, register the target address as automapped, and find the new
1847  * address we're supposed to give as a resolve answer. (Return a cached
1848  * value if we've looked up this address before.
1849  */
1851  addr_type, tor_strdup(socks->address));
1852  if (! new_addr) {
1853  log_warn(LD_APP, "Unable to automap address %s",
1854  escaped_safe_str(socks->address));
1855  out->end_reason = END_STREAM_REASON_INTERNAL;
1856  out->should_close = 1;
1857  return;
1858  }
1859  log_info(LD_APP, "Automapping %s to %s",
1861  safe_str_client(new_addr));
1862  strlcpy(socks->address, new_addr, sizeof(socks->address));
1863  }
1864  }
1865 
1866  /* Now handle reverse lookups, if they're in the cache. This doesn't
1867  * happen too often, since client-side DNS caching is off by default,
1868  * and very deprecated. */
1869  if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1870  unsigned rewrite_flags = 0;
1871  if (conn->entry_cfg.use_cached_ipv4_answers)
1872  rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1873  if (conn->entry_cfg.use_cached_ipv6_answers)
1874  rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1875 
1876  if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1877  rewrite_flags, &out->map_expires)) {
1878  char *result = tor_strdup(socks->address);
1879  /* remember _what_ is supposed to have been resolved. */
1880  tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1881  out->orig_address);
1882  connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1883  strlen(result), (uint8_t*)result,
1884  -1,
1885  out->map_expires);
1886  tor_free(result);
1887  out->end_reason = END_STREAM_REASON_DONE |
1889  out->should_close = 1;
1890  return;
1891  }
1892 
1893  /* Hang on, did we find an answer saying that this is a reverse lookup for
1894  * an internal address? If so, we should reject it if we're configured to
1895  * do so. */
1896  if (options->ClientDNSRejectInternalAddresses) {
1897  /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1898  tor_addr_t addr;
1899  int ok;
1901  &addr, socks->address, AF_UNSPEC, 1);
1902  if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1903  connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1904  0, NULL, -1, TIME_MAX);
1905  out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
1907  out->should_close = 1;
1908  return;
1909  }
1910  }
1911  }
1912 
1913  /* If we didn't automap it before, then this is still the address that
1914  * came straight from the user, mapped according to any
1915  * MapAddress/MAPADDRESS commands. Now apply other mappings,
1916  * including previously registered Automap entries (IP back to
1917  * hostname), TrackHostExits entries, and client-side DNS cache
1918  * entries (if they're turned on).
1919  */
1920  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
1921  !out->automap) {
1922  unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
1923  addressmap_entry_source_t exit_source2;
1924  if (conn->entry_cfg.use_cached_ipv4_answers)
1925  rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1926  if (conn->entry_cfg.use_cached_ipv6_answers)
1927  rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1928  if (addressmap_rewrite(socks->address, sizeof(socks->address),
1929  rewrite_flags, &out->map_expires, &exit_source2)) {
1930  control_event_stream_status(conn, STREAM_EVENT_REMAP,
1932  }
1933  if (out->exit_source == ADDRMAPSRC_NONE) {
1934  /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1935  * the original source of a .exit. */
1936  out->exit_source = exit_source2;
1937  }
1938  }
1939 
1940  /* Check to see whether we're about to use an address in the virtual
1941  * range without actually having gotten it from an Automap. */
1942  if (!out->automap && address_is_in_virtual_range(socks->address)) {
1943  /* This address was probably handed out by
1944  * client_dns_get_unmapped_address, but the mapping was discarded for some
1945  * reason. Or the user typed in a virtual address range manually. We
1946  * *don't* want to send the address through Tor; that's likely to fail,
1947  * and may leak information.
1948  */
1949  log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1950  safe_str_client(socks->address));
1951  out->end_reason = END_STREAM_REASON_INTERNAL;
1952  out->should_close = 1;
1953  return;
1954  }
1955 }
1956 
1957 /** We just received a SOCKS request in <b>conn</b> to an onion address of type
1958  * <b>addresstype</b>. Start connecting to the onion service. */
1959 static int
1961  socks_request_t *socks,
1962  origin_circuit_t *circ,
1963  hostname_type_t addresstype)
1964 {
1965  time_t now = approx_time();
1966  connection_t *base_conn = ENTRY_TO_CONN(conn);
1967 
1968  /* If .onion address requests are disabled, refuse the request */
1969  if (!conn->entry_cfg.onion_traffic) {
1970  log_warn(LD_APP, "Onion address %s requested from a port with .onion "
1971  "disabled", safe_str_client(socks->address));
1972  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1973  return -1;
1974  }
1975 
1976  /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
1977  * for hidden service addresses. */
1978  if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1979  /* if it's a resolve request, fail it right now, rather than
1980  * building all the circuits and then realizing it won't work. */
1981  log_warn(LD_APP,
1982  "Resolve requests to hidden services not allowed. Failing.");
1983  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1984  0,NULL,-1,TIME_MAX);
1985  connection_mark_unattached_ap(conn,
1988  return -1;
1989  }
1990 
1991  /* If we were passed a circuit, then we need to fail. .onion addresses
1992  * only work when we launch our own circuits for now. */
1993  if (circ) {
1994  log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1995  "supported for .onion addresses currently. Failing.");
1996  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1997  return -1;
1998  }
1999 
2000  /* Interface: Regardless of HS version after the block below we should have
2001  set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
2002  const char *onion_address = NULL;
2003  int rend_cache_lookup_result = -ENOENT;
2004  int descriptor_is_usable = 0;
2005 
2006  if (addresstype == ONION_V2_HOSTNAME) { /* it's a v2 hidden service */
2007  rend_cache_entry_t *entry = NULL;
2008  /* Look up if we have client authorization configured for this hidden
2009  * service. If we do, associate it with the rend_data. */
2010  rend_service_authorization_t *client_auth =
2012 
2013  const uint8_t *cookie = NULL;
2014  rend_auth_type_t auth_type = REND_NO_AUTH;
2015  if (client_auth) {
2016  log_info(LD_REND, "Using previously configured client authorization "
2017  "for hidden service request.");
2018  auth_type = client_auth->auth_type;
2019  cookie = client_auth->descriptor_cookie;
2020  }
2021 
2022  /* Fill in the rend_data field so we can start doing a connection to
2023  * a hidden service. */
2024  rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
2025  rend_data_client_create(socks->address, NULL, (char *) cookie,
2026  auth_type);
2027  if (rend_data == NULL) {
2028  return -1;
2029  }
2030  onion_address = rend_data_get_address(rend_data);
2031  log_info(LD_REND,"Got a hidden service request for ID '%s'",
2032  safe_str_client(onion_address));
2033 
2034  rend_cache_lookup_result = rend_cache_lookup_entry(onion_address,-1,
2035  &entry);
2036  if (!rend_cache_lookup_result && entry) {
2037  descriptor_is_usable = rend_client_any_intro_points_usable(entry);
2038  }
2039  } else { /* it's a v3 hidden service */
2040  tor_assert(addresstype == ONION_V3_HOSTNAME);
2041  const hs_descriptor_t *cached_desc = NULL;
2042  int retval;
2043  /* Create HS conn identifier with HS pubkey */
2044  hs_ident_edge_conn_t *hs_conn_ident =
2045  tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
2046 
2047  retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
2048  NULL, NULL);
2049  if (retval < 0) {
2050  log_warn(LD_GENERAL, "failed to parse hs address");
2051  tor_free(hs_conn_ident);
2052  return -1;
2053  }
2054  ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
2055 
2056  onion_address = socks->address;
2057 
2058  /* Check the v3 desc cache */
2059  cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
2060  if (cached_desc) {
2061  rend_cache_lookup_result = 0;
2062  descriptor_is_usable =
2064  cached_desc);
2065  log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
2066  (descriptor_is_usable) ? "usable" : "unusable",
2067  safe_str_client(onion_address),
2068  (descriptor_is_usable) ? "Not fetching." : "Refecting.");
2069  } else {
2070  rend_cache_lookup_result = -ENOENT;
2071  }
2072  }
2073 
2074  /* Lookup the given onion address. If invalid, stop right now.
2075  * Otherwise, we might have it in the cache or not. */
2076  unsigned int refetch_desc = 0;
2077  if (rend_cache_lookup_result < 0) {
2078  switch (-rend_cache_lookup_result) {
2079  case EINVAL:
2080  /* We should already have rejected this address! */
2081  log_warn(LD_BUG,"Invalid service name '%s'",
2082  safe_str_client(onion_address));
2083  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2084  return -1;
2085  case ENOENT:
2086  /* We didn't have this; we should look it up. */
2087  log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
2088  safe_str_client(onion_address));
2089  refetch_desc = 1;
2090  break;
2091  default:
2092  log_warn(LD_BUG, "Unknown cache lookup error %d",
2093  rend_cache_lookup_result);
2094  return -1;
2095  }
2096  }
2097 
2098  /* Help predict that we'll want to do hidden service circuits in the
2099  * future. We're not sure if it will need a stable circuit yet, but
2100  * we know we'll need *something*. */
2101  rep_hist_note_used_internal(now, 0, 1);
2102 
2103  /* Now we have a descriptor but is it usable or not? If not, refetch.
2104  * Also, a fetch could have been requested if the onion address was not
2105  * found in the cache previously. */
2106  if (refetch_desc || !descriptor_is_usable) {
2107  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2109  base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
2110  if (addresstype == ONION_V2_HOSTNAME) {
2111  tor_assert(edge_conn->rend_data);
2113  /* Whatever the result of the refetch, we don't go further. */
2114  return 0;
2115  } else {
2116  tor_assert(addresstype == ONION_V3_HOSTNAME);
2117  tor_assert(edge_conn->hs_ident);
2118  /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
2119  * went and act accordingly. */
2120  int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2121  switch (ret) {
2123  /* Keeping the connection in descriptor wait state is fine because
2124  * once we get enough dirinfo or a new live consensus, the HS client
2125  * subsystem is notified and every connection in that state will
2126  * trigger a fetch for the service key. */
2130  return 0;
2131  case HS_CLIENT_FETCH_ERROR:
2134  /* Can't proceed further and better close the SOCKS request. */
2135  return -1;
2136  }
2137  }
2138  }
2139 
2140  /* We have the descriptor! So launch a connection to the HS. */
2141  log_info(LD_REND, "Descriptor is here. Great.");
2142 
2143  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2144  /* We'll try to attach it at the next event loop, or whenever
2145  * we call connection_ap_attach_pending() */
2146  connection_ap_mark_as_pending_circuit(conn);
2147  return 0;
2148 }
2149 
2150 /** Connection <b>conn</b> just finished its socks handshake, or the
2151  * controller asked us to take care of it. If <b>circ</b> is defined,
2152  * then that's where we'll want to attach it. Otherwise we have to
2153  * figure it out ourselves.
2154  *
2155  * First, parse whether it's a .exit address, remap it, and so on. Then
2156  * if it's for a general circuit, try to attach it to a circuit (or launch
2157  * one as needed), else if it's for a rendezvous circuit, fetch a
2158  * rendezvous descriptor first (or attach/launch a circuit if the
2159  * rendezvous descriptor is already here and fresh enough).
2160  *
2161  * The stream will exit from the hop
2162  * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2163  * <b>cpath</b> is NULL.
2164  */
2165 int
2167  origin_circuit_t *circ,
2168  crypt_path_t *cpath)
2169 {
2170  socks_request_t *socks = conn->socks_request;
2171  const or_options_t *options = get_options();
2172  connection_t *base_conn = ENTRY_TO_CONN(conn);
2173  time_t now = time(NULL);
2174  rewrite_result_t rr;
2175 
2176  /* First we'll do the rewrite part. Let's see if we get a reasonable
2177  * answer.
2178  */
2179  memset(&rr, 0, sizeof(rr));
2180  connection_ap_handshake_rewrite(conn,&rr);
2181 
2182  if (rr.should_close) {
2183  /* connection_ap_handshake_rewrite told us to close the connection:
2184  * either because it sent back an answer, or because it sent back an
2185  * error */
2186  connection_mark_unattached_ap(conn, rr.end_reason);
2187  if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
2188  return 0;
2189  else
2190  return -1;
2191  }
2192 
2193  const time_t map_expires = rr.map_expires;
2194  const int automap = rr.automap;
2195  const addressmap_entry_source_t exit_source = rr.exit_source;
2196 
2197  /* Now see whether the hostname is bogus. This could happen because of an
2198  * onion hostname whose format we don't recognize. */
2199  hostname_type_t addresstype;
2200  if (!parse_extended_hostname(socks->address, &addresstype)) {
2201  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2202  escaped(socks->address));
2203  if (addresstype == BAD_HOSTNAME) {
2204  conn->socks_request->socks_extended_error_code = SOCKS5_HS_BAD_ADDRESS;
2205  }
2206  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2207  return -1;
2208  }
2209 
2210  /* If this is a .exit hostname, strip off the .name.exit part, and
2211  * see whether we're willing to connect there, and and otherwise handle the
2212  * .exit address.
2213  *
2214  * We'll set chosen_exit_name and/or close the connection as appropriate.
2215  */
2216  if (addresstype == EXIT_HOSTNAME) {
2217  /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
2218  * not ExcludeExitNodes. */
2219  routerset_t *excludeset = options->StrictNodes ?
2220  options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
2221  const node_t *node = NULL;
2222 
2223  /* If this .exit was added by an AUTOMAP, then it came straight from
2224  * a user. That's not safe. */
2225  if (exit_source == ADDRMAPSRC_AUTOMAP) {
2226  /* Whoops; this one is stale. It must have gotten added earlier?
2227  * (Probably this is not possible, since AllowDotExit no longer
2228  * exists.) */
2229  log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
2230  safe_str_client(socks->address));
2231  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2232  escaped(socks->address));
2233  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2235  return -1;
2236  }
2237 
2238  /* Double-check to make sure there are no .exits coming from
2239  * impossible/weird sources. */
2240  if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
2241  /* It shouldn't be possible to get a .exit address from any of these
2242  * sources. */
2243  log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
2244  ".exit part. Refusing.",
2245  safe_str_client(socks->address));
2246  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2247  escaped(socks->address));
2248  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2249  return -1;
2250  }
2251 
2252  tor_assert(!automap);
2253 
2254  /* Now, find the character before the .(name) part.
2255  * (The ".exit" part got stripped off by "parse_extended_hostname").
2256  *
2257  * We're going to put the exit name into conn->chosen_exit_name, and
2258  * look up a node correspondingly. */
2259  char *s = strrchr(socks->address,'.');
2260  if (s) {
2261  /* The address was of the form "(stuff).(name).exit */
2262  if (s[1] != '\0') {
2263  /* Looks like a real .exit one. */
2264  conn->chosen_exit_name = tor_strdup(s+1);
2265  node = node_get_by_nickname(conn->chosen_exit_name, 0);
2266 
2267  if (exit_source == ADDRMAPSRC_TRACKEXIT) {
2268  /* We 5 tries before it expires the addressmap */
2270  }
2271  *s = 0;
2272  } else {
2273  /* Oops, the address was (stuff)..exit. That's not okay. */
2274  log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
2275  safe_str_client(socks->address));
2276  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2277  escaped(socks->address));
2278  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2279  return -1;
2280  }
2281  } else {
2282  /* It looks like they just asked for "foo.exit". That's a special
2283  * form that means (foo's address).foo.exit. */
2284 
2285  conn->chosen_exit_name = tor_strdup(socks->address);
2286  node = node_get_by_nickname(conn->chosen_exit_name, 0);
2287  if (node) {
2288  *socks->address = 0;
2289  node_get_address_string(node, socks->address, sizeof(socks->address));
2290  }
2291  }
2292 
2293  /* Now make sure that the chosen exit exists... */
2294  if (!node) {
2295  log_warn(LD_APP,
2296  "Unrecognized relay in exit address '%s.exit'. Refusing.",
2297  safe_str_client(socks->address));
2298  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2299  return -1;
2300  }
2301  /* ...and make sure that it isn't excluded. */
2302  if (routerset_contains_node(excludeset, node)) {
2303  log_warn(LD_APP,
2304  "Excluded relay in exit address '%s.exit'. Refusing.",
2305  safe_str_client(socks->address));
2306  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2307  return -1;
2308  }
2309  /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
2310  Bar is not listed in it? I say yes, but our revised manpage branch
2311  implies no. */
2312  }
2313 
2314  /* Now, we handle everything that isn't a .onion address. */
2315  if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {
2316  /* Not a hidden-service request. It's either a hostname or an IP,
2317  * possibly with a .exit that we stripped off. We're going to check
2318  * if we're allowed to connect/resolve there, and then launch the
2319  * appropriate request. */
2320 
2321  /* Check for funny characters in the address. */
2322  if (address_is_invalid_destination(socks->address, 1)) {
2323  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2324  escaped(socks->address));
2325  log_warn(LD_APP,
2326  "Destination '%s' seems to be an invalid hostname. Failing.",
2327  safe_str_client(socks->address));
2328  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2329  return -1;
2330  }
2331 
2332  /* socks->address is a non-onion hostname or IP address.
2333  * If we can't do any non-onion requests, refuse the connection.
2334  * If we have a hostname but can't do DNS, refuse the connection.
2335  * If we have an IP address, but we can't use that address family,
2336  * refuse the connection.
2337  *
2338  * If we can do DNS requests, and we can use at least one address family,
2339  * then we have to resolve the address first. Then we'll know if it
2340  * resolves to a usable address family. */
2341 
2342  /* First, check if all non-onion traffic is disabled */
2343  if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
2344  && !conn->entry_cfg.ipv6_traffic) {
2345  log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
2346  "or IP address %s because Port has OnionTrafficOnly set (or "
2347  "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
2348  safe_str_client(socks->address));
2349  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2350  return -1;
2351  }
2352 
2353  /* Then check if we have a hostname or IP address, and whether DNS or
2354  * the IP address family are permitted. Reject if not. */
2355  tor_addr_t dummy_addr;
2356  int socks_family = tor_addr_parse(&dummy_addr, socks->address);
2357  /* family will be -1 for a non-onion hostname that's not an IP */
2358  if (socks_family == -1) {
2359  if (!conn->entry_cfg.dns_request) {
2360  log_warn(LD_APP, "Refusing to connect to hostname %s "
2361  "because Port has NoDNSRequest set.",
2362  safe_str_client(socks->address));
2363  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2364  return -1;
2365  }
2366  } else if (socks_family == AF_INET) {
2367  if (!conn->entry_cfg.ipv4_traffic) {
2368  log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
2369  "Port has NoIPv4Traffic set.",
2370  safe_str_client(socks->address));
2371  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2372  return -1;
2373  }
2374  } else if (socks_family == AF_INET6) {
2375  if (!conn->entry_cfg.ipv6_traffic) {
2376  log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
2377  "Port has NoIPv6Traffic set.",
2378  safe_str_client(socks->address));
2379  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2380  return -1;
2381  }
2382  } else {
2383  tor_assert_nonfatal_unreached_once();
2384  }
2385 
2386  /* See if this is a hostname lookup that we can answer immediately.
2387  * (For example, an attempt to look up the IP address for an IP address.)
2388  */
2389  if (socks->command == SOCKS_COMMAND_RESOLVE) {
2390  tor_addr_t answer;
2391  /* Reply to resolves immediately if we can. */
2392  if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
2393  /* remember _what_ is supposed to have been resolved. */
2394  strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
2396  map_expires);
2397  connection_mark_unattached_ap(conn,
2398  END_STREAM_REASON_DONE |
2400  return 0;
2401  }
2402  tor_assert(!automap);
2403  rep_hist_note_used_resolve(now); /* help predict this next time */
2404  } else if (socks->command == SOCKS_COMMAND_CONNECT) {
2405  /* Now see if this is a connect request that we can reject immediately */
2406 
2407  tor_assert(!automap);
2408  /* Don't allow connections to port 0. */
2409  if (socks->port == 0) {
2410  log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
2411  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2412  return -1;
2413  }
2414  /* You can't make connections to internal addresses, by default.
2415  * Exceptions are begindir requests (where the address is meaningless),
2416  * or cases where you've hand-configured a particular exit, thereby
2417  * making the local address meaningful. */
2418  if (options->ClientRejectInternalAddresses &&
2419  !conn->use_begindir && !conn->chosen_exit_name && !circ) {
2420  /* If we reach this point then we don't want to allow internal
2421  * addresses. Check if we got one. */
2422  tor_addr_t addr;
2423  if (tor_addr_hostname_is_local(socks->address) ||
2424  (tor_addr_parse(&addr, socks->address) >= 0 &&
2425  tor_addr_is_internal(&addr, 0))) {
2426  /* If this is an explicit private address with no chosen exit node,
2427  * then we really don't want to try to connect to it. That's
2428  * probably an error. */
2429  if (conn->is_transparent_ap) {
2430 #define WARN_INTRVL_LOOP 300
2431  static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
2432  char *m;
2433  if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
2434  log_warn(LD_NET,
2435  "Rejecting request for anonymous connection to private "
2436  "address %s on a TransPort or NATDPort. Possible loop "
2437  "in your NAT rules?%s", safe_str_client(socks->address),
2438  m);
2439  tor_free(m);
2440  }
2441  } else {
2442 #define WARN_INTRVL_PRIV 300
2443  static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
2444  char *m;
2445  if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
2446  log_warn(LD_NET,
2447  "Rejecting SOCKS request for anonymous connection to "
2448  "private address %s.%s",
2449  safe_str_client(socks->address),m);
2450  tor_free(m);
2451  }
2452  }
2453  connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
2454  return -1;
2455  }
2456  } /* end "if we should check for internal addresses" */
2457 
2458  /* Okay. We're still doing a CONNECT, and it wasn't a private
2459  * address. Here we do special handling for literal IP addresses,
2460  * to see if we should reject this preemptively, and to set up
2461  * fields in conn->entry_cfg to tell the exit what AF we want. */
2462  {
2463  tor_addr_t addr;
2464  /* XXX Duplicate call to tor_addr_parse. */
2465  if (tor_addr_parse(&addr, socks->address) >= 0) {
2466  /* If we reach this point, it's an IPv4 or an IPv6 address. */
2467  sa_family_t family = tor_addr_family(&addr);
2468 
2469  if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
2470  (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
2471  /* You can't do an IPv4 address on a v6-only socks listener,
2472  * or vice versa. */
2473  log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
2474  "family that this listener does not support.");
2475  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2476  return -1;
2477  } else if (family == AF_INET6 && socks->socks_version == 4) {
2478  /* You can't make a socks4 request to an IPv6 address. Socks4
2479  * doesn't support that. */
2480  log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
2481  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2482  return -1;
2483  } else if (socks->socks_version == 4 &&
2484  !conn->entry_cfg.ipv4_traffic) {
2485  /* You can't do any kind of Socks4 request when IPv4 is forbidden.
2486  *
2487  * XXX raise this check outside the enclosing block? */
2488  log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
2489  "no IPv4 traffic supported.");
2490  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2491  return -1;
2492  } else if (family == AF_INET6) {
2493  /* Tell the exit: we won't accept any ipv4 connection to an IPv6
2494  * address. */
2495  conn->entry_cfg.ipv4_traffic = 0;
2496  } else if (family == AF_INET) {
2497  /* Tell the exit: we won't accept any ipv6 connection to an IPv4
2498  * address. */
2499  conn->entry_cfg.ipv6_traffic = 0;
2500  }
2501  }
2502  }
2503 
2504  /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
2505  if (socks->socks_version == 4)
2506  conn->entry_cfg.ipv6_traffic = 0;
2507 
2508  /* Still handling CONNECT. Now, check for exit enclaves. (Which we
2509  * don't do on BEGIN_DIR, or when there is a chosen exit.)
2510  *
2511  * TODO: Should we remove this? Exit enclaves are nutty and don't
2512  * work very well
2513  */
2514  if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
2515  /* see if we can find a suitable enclave exit */
2516  const node_t *r =
2518  if (r) {
2519  log_info(LD_APP,
2520  "Redirecting address %s to exit at enclave router %s",
2521  safe_str_client(socks->address), node_describe(r));
2522  /* use the hex digest, not nickname, in case there are two
2523  routers with this nickname */
2524  conn->chosen_exit_name =
2525  tor_strdup(hex_str(r->identity, DIGEST_LEN));
2526  conn->chosen_exit_optional = 1;
2527  }
2528  }
2529 
2530  /* Still handling CONNECT: warn or reject if it's using a dangerous
2531  * port. */
2532  if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
2533  if (consider_plaintext_ports(conn, socks->port) < 0)
2534  return -1;
2535 
2536  /* Remember the port so that we will predict that more requests
2537  there will happen in the future. */
2538  if (!conn->use_begindir) {
2539  /* help predict this next time */
2540  rep_hist_note_used_port(now, socks->port);
2541  }
2542  } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
2543  rep_hist_note_used_resolve(now); /* help predict this next time */
2544  /* no extra processing needed */
2545  } else {
2546  /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2548  }
2549 
2550  /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2551  * address, and decided not to reject it for any number of reasons. Now
2552  * mark the connection as waiting for a circuit, and try to attach it!
2553  */
2554  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2555 
2556  /* If we were given a circuit to attach to, try to attach. Otherwise,
2557  * try to find a good one and attach to that. */
2558  int rv;
2559  if (circ) {
2560  rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
2561  } else {
2562  /* We'll try to attach it at the next event loop, or whenever
2563  * we call connection_ap_attach_pending() */
2564  connection_ap_mark_as_pending_circuit(conn);
2565  rv = 0;
2566  }
2567 
2568  /* If the above function returned 0 then we're waiting for a circuit.
2569  * if it returned 1, we're attached. Both are okay. But if it returned
2570  * -1, there was an error, so make sure the connection is marked, and
2571  * return -1. */
2572  if (rv < 0) {
2573  if (!base_conn->marked_for_close)
2574  connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2575  return -1;
2576  }
2577 
2578  return 0;
2579  } else {
2580  /* If we get here, it's a request for a .onion address! */
2581  tor_assert(addresstype == ONION_V2_HOSTNAME ||
2582  addresstype == ONION_V3_HOSTNAME);
2583  tor_assert(!automap);
2584  return connection_ap_handle_onion(conn, socks, circ, addresstype);
2585  }
2586 
2587  return 0; /* unreached but keeps the compiler happy */
2588 }
2589 
2590 #ifdef TRANS_PF
2591 static int pf_socket = -1;
2592 int
2593 get_pf_socket(void)
2594 {
2595  int pf;
2596  /* This should be opened before dropping privileges. */
2597  if (pf_socket >= 0)
2598  return pf_socket;
2599 
2600 #if defined(OpenBSD)
2601  /* only works on OpenBSD */
2602  pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
2603 #else
2604  /* works on NetBSD and FreeBSD */
2605  pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
2606 #endif /* defined(OpenBSD) */
2607 
2608  if (pf < 0) {
2609  log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
2610  return -1;
2611  }
2612 
2613  pf_socket = pf;
2614  return pf_socket;
2615 }
2616 #endif /* defined(TRANS_PF) */
2617 
2618 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2619  defined(TRANS_TPROXY)
2620 /** Try fill in the address of <b>req</b> from the socket configured
2621  * with <b>conn</b>. */
2622 static int
2623 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
2624 {
2625  struct sockaddr_storage orig_dst;
2626  socklen_t orig_dst_len = sizeof(orig_dst);
2627  tor_addr_t addr;
2628 
2629 #ifdef TRANS_TPROXY
2630  if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
2631  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2632  &orig_dst_len) < 0) {
2633  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2634  log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2635  return -1;
2636  }
2637  goto done;
2638  }
2639 #endif /* defined(TRANS_TPROXY) */
2640 
2641 #ifdef TRANS_NETFILTER
2642  int rv = -1;
2643  switch (ENTRY_TO_CONN(conn)->socket_family) {
2644 #ifdef TRANS_NETFILTER_IPV4
2645  case AF_INET:
2646  rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
2647  (struct sockaddr*)&orig_dst, &orig_dst_len);
2648  break;
2649 #endif /* defined(TRANS_NETFILTER_IPV4) */
2650 #ifdef TRANS_NETFILTER_IPV6
2651  case AF_INET6:
2652  rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
2653  (struct sockaddr*)&orig_dst, &orig_dst_len);
2654  break;
2655 #endif /* defined(TRANS_NETFILTER_IPV6) */
2656  default:
2657  log_warn(LD_BUG,
2658  "Received transparent data from an unsuported socket family %d",
2659  ENTRY_TO_CONN(conn)->socket_family);
2660  return -1;
2661  }
2662  if (rv < 0) {
2663  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2664  log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
2665  return -1;
2666  }
2667  goto done;
2668 #elif defined(TRANS_PF)
2669  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2670  &orig_dst_len) < 0) {
2671  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2672  log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2673  return -1;
2674  }
2675  goto done;
2676 #else
2677  (void)conn;
2678  (void)req;
2679  log_warn(LD_BUG, "Unable to determine destination from socket.");
2680  return -1;
2681 #endif /* defined(TRANS_NETFILTER) || ... */
2682 
2683  done:
2684  tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
2685  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2686 
2687  return 0;
2688 }
2689 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2690 
2691 #ifdef TRANS_PF
2692 static int
2693 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
2694 {
2695  struct sockaddr_storage proxy_addr;
2696  socklen_t proxy_addr_len = sizeof(proxy_addr);
2697  struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
2698  struct pfioc_natlook pnl;
2699  tor_addr_t addr;
2700  int pf = -1;
2701 
2702  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
2703  &proxy_addr_len) < 0) {
2704  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2705  log_warn(LD_NET, "getsockname() to determine transocks destination "
2706  "failed: %s", tor_socket_strerror(e));
2707  return -1;
2708  }
2709 
2710 #ifdef __FreeBSD__
2711  if (get_options()->TransProxyType_parsed == TPT_IPFW) {
2712  /* ipfw(8) is used and in this case getsockname returned the original
2713  destination */
2714  if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
2716  return -1;
2717  }
2718 
2719  tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
2720 
2721  return 0;
2722  }
2723 #endif /* defined(__FreeBSD__) */
2724 
2725  memset(&pnl, 0, sizeof(pnl));
2726  pnl.proto = IPPROTO_TCP;
2727  pnl.direction = PF_OUT;
2728  if (proxy_sa->sa_family == AF_INET) {
2729  struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
2730  pnl.af = AF_INET;
2731  pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
2732  pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2733  pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
2734  pnl.dport = sin->sin_port;
2735  } else if (proxy_sa->sa_family == AF_INET6) {
2736  struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
2737  pnl.af = AF_INET6;
2738  const struct in6_addr *dest_in6 =
2739  tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr);
2740  if (BUG(!dest_in6))
2741  return -1;
2742  memcpy(&pnl.saddr.v6, dest_in6, sizeof(struct in6_addr));
2743  pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2744  memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
2745  pnl.dport = sin6->sin6_port;
2746  } else {
2747  log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
2748  (int)proxy_sa->sa_family);
2749  return -1;
2750  }
2751 
2752  pf = get_pf_socket();
2753  if (pf<0)
2754  return -1;
2755 
2756  if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
2757  log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
2758  return -1;
2759  }
2760 
2761  if (pnl.af == AF_INET) {
2762  tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
2763  } else if (pnl.af == AF_INET6) {
2764  tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
2765  } else {
2767  return -1;
2768  }
2769 
2770  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2771  req->port = ntohs(pnl.rdport);
2772 
2773  return 0;
2774 }
2775 #endif /* defined(TRANS_PF) */
2776 
2777 /** Fetch the original destination address and port from a
2778  * system-specific interface and put them into a
2779  * socks_request_t as if they came from a socks request.
2780  *
2781  * Return -1 if an error prevents fetching the destination,
2782  * else return 0.
2783  */
2784 static int
2786  socks_request_t *req)
2787 {
2788 #ifdef TRANS_NETFILTER
2789  return destination_from_socket(conn, req);
2790 #elif defined(TRANS_PF)
2791  const or_options_t *options = get_options();
2792 
2793  if (options->TransProxyType_parsed == TPT_PF_DIVERT)
2794  return destination_from_socket(conn, req);
2795 
2796  if (options->TransProxyType_parsed == TPT_DEFAULT ||
2797  options->TransProxyType_parsed == TPT_IPFW)
2798  return destination_from_pf(conn, req);
2799 
2800  (void)conn;
2801  (void)req;
2802  log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
2803  options->TransProxyType);
2804  return -1;
2805 #else
2806  (void)conn;
2807  (void)req;
2808  log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
2809  "transparent proxy method was configured.");
2810  return -1;
2811 #endif /* defined(TRANS_NETFILTER) || ... */
2812 }
2813 
2814 /** connection_edge_process_inbuf() found a conn in state
2815  * socks_wait. See if conn->inbuf has the right bytes to proceed with
2816  * the socks handshake.
2817  *
2818  * If the handshake is complete, send it to
2819  * connection_ap_handshake_rewrite_and_attach().
2820  *
2821  * Return -1 if an unexpected error with conn occurs (and mark it for close),
2822  * else return 0.
2823  */
2824 static int
2826 {
2827  socks_request_t *socks;
2828  int sockshere;
2829  const or_options_t *options = get_options();
2830  int had_reply = 0;
2831  connection_t *base_conn = ENTRY_TO_CONN(conn);
2832 
2833  tor_assert(conn);
2834  tor_assert(base_conn->type == CONN_TYPE_AP);
2835  tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
2836  tor_assert(conn->socks_request);
2837  socks = conn->socks_request;
2838 
2839  log_debug(LD_APP,"entered.");
2840 
2841  sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2842  options->TestSocks, options->SafeSocks);
2843 
2844  if (socks->replylen) {
2845  had_reply = 1;
2846  connection_buf_add((const char*)socks->reply, socks->replylen,
2847  base_conn);
2848  socks->replylen = 0;
2849  if (sockshere == -1) {
2850  /* An invalid request just got a reply, no additional
2851  * one is necessary. */
2852  socks->has_finished = 1;
2853  }
2854  }
2855 
2856  if (sockshere == 0) {
2857  log_debug(LD_APP,"socks handshake not all here yet.");
2858  return 0;
2859  } else if (sockshere == -1) {
2860  if (!had_reply) {
2861  log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2864  }
2865  connection_mark_unattached_ap(conn,
2868  return -1;
2869  } /* else socks handshake is done, continue processing */
2870 
2871  if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2872  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2873  else
2874  control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2875 
2876  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2877 }
2878 
2879 /** connection_init_accepted_conn() found a new trans AP conn.
2880  * Get the original destination and send it to
2881  * connection_ap_handshake_rewrite_and_attach().
2882  *
2883  * Return -1 if an unexpected error with conn (and it should be marked
2884  * for close), else return 0.
2885  */
2886 int
2888 {
2889  socks_request_t *socks;
2890 
2891  tor_assert(conn);
2892  tor_assert(conn->socks_request);
2893  socks = conn->socks_request;
2894 
2895  /* pretend that a socks handshake completed so we don't try to
2896  * send a socks reply down a transparent conn */
2897  socks->command = SOCKS_COMMAND_CONNECT;
2898  socks->has_finished = 1;
2899 
2900  log_debug(LD_APP,"entered.");
2901 
2902  if (connection_ap_get_original_destination(conn, socks) < 0) {
2903  log_warn(LD_APP,"Fetching original destination failed. Closing.");
2904  connection_mark_unattached_ap(conn,
2906  return -1;
2907  }
2908  /* we have the original destination */
2909 
2910  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2911 
2912  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2913 }
2914 
2915 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2916  * conn->inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2917  * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2918  * form of the original destination.
2919  *
2920  * If the original destination is complete, send it to
2921  * connection_ap_handshake_rewrite_and_attach().
2922  *
2923  * Return -1 if an unexpected error with conn (and it should be marked
2924  * for close), else return 0.
2925  */
2926 static int
2928 {
2929  char tmp_buf[36], *tbuf, *daddr;
2930  size_t tlen = 30;
2931  int err, port_ok;
2932  socks_request_t *socks;
2933 
2934  tor_assert(conn);
2936  tor_assert(conn->socks_request);
2937  socks = conn->socks_request;
2938 
2939  log_debug(LD_APP,"entered.");
2940 
2941  /* look for LF-terminated "[DEST ip_addr port]"
2942  * where ip_addr is a dotted-quad and port is in string form */
2943  err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2944  if (err == 0)
2945  return 0;
2946  if (err < 0) {
2947  log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2948  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2949  return -1;
2950  }
2951 
2952  if (strcmpstart(tmp_buf, "[DEST ")) {
2953  log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2954  "said: %s",
2955  escaped(tmp_buf));
2956  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2957  return -1;
2958  }
2959 
2960  daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2961  if (!(tbuf = strchr(tbuf, ' '))) {
2962  log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2963  "said: %s",
2964  escaped(tmp_buf));
2965  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2966  return -1;
2967  }
2968  *tbuf++ = '\0';
2969 
2970  /* pretend that a socks handshake completed so we don't try to
2971  * send a socks reply down a natd conn */
2972  strlcpy(socks->address, daddr, sizeof(socks->address));
2973  socks->port = (uint16_t)
2974  tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2975  if (!port_ok) {
2976  log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2977  "of range.", escaped(tbuf));
2978  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2979  return -1;
2980  }
2981 
2982  socks->command = SOCKS_COMMAND_CONNECT;
2983  socks->has_finished = 1;
2984 
2985  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2986 
2988 
2989  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2990 }
2991 
2992 static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
2993  "HTTP/1.0 405 Method Not Allowed\r\n"
2994  "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
2995  "<html>\n"
2996  "<head>\n"
2997  "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
2998  "</head>\n"
2999  "<body>\n"
3000  "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
3001  "<p>\n"
3002  "It appears you have configured your web browser to use this Tor port as\n"
3003  "an HTTP proxy.\n"
3004  "</p><p>\n"
3005  "This is not correct: This port is configured as a CONNECT tunnel, not\n"
3006  "an HTTP proxy. Please configure your client accordingly. You can also\n"
3007  "use HTTPS; then the client should automatically use HTTP CONNECT."
3008  "</p>\n"
3009  "<p>\n"
3010  "See <a href=\"https://www.torproject.org/documentation.html\">"
3011  "https://www.torproject.org/documentation.html</a> for more "
3012  "information.\n"
3013  "</p>\n"
3014  "</body>\n"
3015  "</html>\n";
3016 
3017 /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
3018  * but we have not yet received a full HTTP CONNECT request. Try to parse an
3019  * HTTP CONNECT request from the connection's inbuf. On success, set up the
3020  * connection's socks_request field and try to attach the connection. On
3021  * failure, send an HTTP reply, and mark the connection.
3022  */
3023 STATIC int
3025 {
3026  if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
3027  return -1;
3028 
3029  char *headers = NULL, *body = NULL;
3030  char *command = NULL, *addrport = NULL;
3031  char *addr = NULL;
3032  size_t bodylen = 0;
3033 
3034  const char *errmsg = NULL;
3035  int rv = 0;
3036 
3037  const int http_status =
3038  fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
3039  &body, &bodylen, 1024, 0);
3040  if (http_status < 0) {
3041  /* Bad http status */
3042  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3043  goto err;
3044  } else if (http_status == 0) {
3045  /* no HTTP request yet. */
3046  goto done;
3047  }
3048 
3049  const int cmd_status = parse_http_command(headers, &command, &addrport);
3050  if (cmd_status < 0) {
3051  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3052  goto err;
3053  }
3055  tor_assert(addrport);
3056  if (strcasecmp(command, "connect")) {
3057  errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
3058  goto err;
3059  }
3060 
3061  tor_assert(conn->socks_request);
3062  socks_request_t *socks = conn->socks_request;
3063  uint16_t port;
3064  if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
3065  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3066  goto err;
3067  }
3068  if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
3069  errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
3070  goto err;
3071  }
3072 
3073  /* Abuse the 'username' and 'password' fields here. They are already an
3074  * abuse. */
3075  {
3076  char *authorization = http_get_header(headers, "Proxy-Authorization: ");
3077  if (authorization) {
3078  socks->username = authorization; // steal reference
3079  socks->usernamelen = strlen(authorization);
3080  }
3081  char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
3082  if (isolation) {
3083  socks->password = isolation; // steal reference
3084  socks->passwordlen = strlen(isolation);
3085  }
3086  }
3087 
3088  socks->command = SOCKS_COMMAND_CONNECT;
3090  strlcpy(socks->address, addr, sizeof(socks->address));
3091  socks->port = port;
3092 
3093  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3094 
3095  rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
3096 
3097  // XXXX send a "100 Continue" message?
3098 
3099  goto done;
3100 
3101  err:
3102  if (BUG(errmsg == NULL))
3103  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3104  log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
3105  connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
3106  /* Mark it as "has_finished" so that we don't try to send an extra socks
3107  * reply. */
3108  conn->socks_request->has_finished = 1;
3109  connection_mark_unattached_ap(conn,
3112 
3113  done:
3114  tor_free(headers);
3115  tor_free(body);
3116  tor_free(command);
3117  tor_free(addrport);
3118  tor_free(addr);
3119  return rv;
3120 }
3121 
3122 /** Iterate over the two bytes of stream_id until we get one that is not
3123  * already in use; return it. Return 0 if can't get a unique stream_id.
3124  */
3125 streamid_t
3127 {
3128  edge_connection_t *tmpconn;
3129  streamid_t test_stream_id;
3130  uint32_t attempts=0;
3131 
3132  again:
3133  test_stream_id = circ->next_stream_id++;
3134  if (++attempts > 1<<16) {
3135  /* Make sure we don't loop forever if all stream_id's are used. */
3136  log_warn(LD_APP,"No unused stream IDs. Failing.");
3137  return 0;
3138  }
3139  if (test_stream_id == 0)
3140  goto again;
3141  for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
3142  if (tmpconn->stream_id == test_stream_id)
3143  goto again;
3144 
3146  test_stream_id))
3147  goto again;
3148 
3149  return test_stream_id;
3150 }
3151 
3152 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
3153  * an exit that supports optimistic data. */
3154 static int
3156 {
3157  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
3158  /* We can only send optimistic data if we're connected to an open
3159  general circuit. */
3160  if (edge_conn->on_circuit == NULL ||
3161  edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
3162  (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
3166  return 0;
3167 
3168  return conn->may_use_optimistic_data;
3169 }
3170 
3171 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
3172  * RELAY_BEGIN cell for <b>ap_conn</b>. */
3173 static uint32_t
3175 {
3176  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3177  const node_t *exitnode = NULL;
3178  const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
3179  uint32_t flags = 0;
3180 
3181  /* No flags for begindir */
3182  if (ap_conn->use_begindir)
3183  return 0;
3184 
3185  /* No flags for hidden services. */
3186  if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
3187  return 0;
3188 
3189  /* If only IPv4 is supported, no flags */
3190  if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
3191  return 0;
3192 
3193  if (! cpath_layer ||
3194  ! cpath_layer->extend_info)
3195  return 0;
3196 
3197  if (!ap_conn->entry_cfg.ipv4_traffic)
3198  flags |= BEGIN_FLAG_IPV4_NOT_OK;
3199 
3200  exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
3201 
3202  if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
3203  tor_addr_t a;
3204  tor_addr_make_null(&a, AF_INET6);
3206  exitnode)
3207  != ADDR_POLICY_REJECTED) {
3208  /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
3209  * no point. */
3210  flags |= BEGIN_FLAG_IPV6_OK;
3211  }
3212  }
3213 
3214  if (flags == BEGIN_FLAG_IPV6_OK) {
3215  /* When IPv4 and IPv6 are both allowed, consider whether to say we
3216  * prefer IPv6. Otherwise there's no point in declaring a preference */
3217  if (ap_conn->entry_cfg.prefer_ipv6)
3218  flags |= BEGIN_FLAG_IPV6_PREFERRED;
3219  }
3220 
3221  if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
3222  log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
3223  "am telling it to fulfil with neither IPv4 nor IPv6. That's "
3224  "not going to work. Did you perhaps ask for an IPv6 address "
3225  "on an IPv4Only port, or vice versa?");
3226  }
3227 
3228  return flags;
3229 }
3230 
3231 /** Write a relay begin cell, using destaddr and destport from ap_conn's
3232  * socks_request field, and send it down circ.
3233  *
3234  * If ap_conn is broken, mark it for close and return -1. Else return 0.
3235  */
3236 MOCK_IMPL(int,
3238 {
3239  char payload[CELL_PAYLOAD_SIZE];
3240  int payload_len;
3241  int begin_type;
3242  const or_options_t *options = get_options();
3243  origin_circuit_t *circ;
3244  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3245  connection_t *base_conn = TO_CONN(edge_conn);
3246  tor_assert(edge_conn->on_circuit);
3247  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3248 
3249  tor_assert(base_conn->type == CONN_TYPE_AP);
3251  tor_assert(ap_conn->socks_request);
3252  tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
3253 
3254  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3255  if (edge_conn->stream_id==0) {
3256  /* XXXX+ Instead of closing this stream, we should make it get
3257  * retried on another circuit. */
3258  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3259 
3260  /* Mark this circuit "unusable for new streams". */
3262  return -1;
3263  }
3264 
3265  /* Set up begin cell flags. */
3266  edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
3267 
3268  tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
3269  (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
3270  ap_conn->socks_request->address : "",
3271  ap_conn->socks_request->port);
3272  payload_len = (int)strlen(payload)+1;
3273  if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
3274  set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
3275  payload_len += 4;
3276  }
3277 
3278  log_info(LD_APP,
3279  "Sending relay cell %d on circ %u to begin stream %d.",
3280  (int)ap_conn->use_begindir,
3281  (unsigned)circ->base_.n_circ_id,
3282  edge_conn->stream_id);
3283 
3284  begin_type = ap_conn->use_begindir ?
3285  RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
3286 
3287  /* Check that circuits are anonymised, based on their type. */
3288  if (begin_type == RELAY_COMMAND_BEGIN) {
3289  /* This connection is a standard OR connection.
3290  * Make sure its path length is anonymous, or that we're in a
3291  * non-anonymous mode. */
3292  assert_circ_anonymity_ok(circ, options);
3293  } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
3294  /* This connection is a begindir directory connection.
3295  * Look at the linked directory connection to access the directory purpose.
3296  * If a BEGINDIR connection is ever not linked, that's a bug. */
3297  if (BUG(!base_conn->linked)) {
3298  return -1;
3299  }
3300  connection_t *linked_dir_conn_base = base_conn->linked_conn;
3301  /* If the linked connection has been unlinked by other code, we can't send
3302  * a begin cell on it. */
3303  if (!linked_dir_conn_base) {
3304  return -1;
3305  }
3306  /* Sensitive directory connections must have an anonymous path length.
3307  * Otherwise, directory connections are typically one-hop.
3308  * This matches the earlier check for directory connection path anonymity
3309  * in directory_initiate_request(). */
3310  if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
3311  TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
3312  TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
3313  assert_circ_anonymity_ok(circ, options);
3314  }
3315  } else {
3316  /* This code was written for the two connection types BEGIN and BEGIN_DIR
3317  */
3318  tor_assert_unreached();
3319  }
3320 
3321  if (connection_edge_send_command(edge_conn, begin_type,
3322  begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
3323  begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
3324  return -1; /* circuit is closed, don't continue */
3325 
3326  edge_conn->package_window = STREAMWINDOW_START;
3327  edge_conn->deliver_window = STREAMWINDOW_START;
3328  base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
3329  log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
3330  ", n_circ_id %u",
3331  base_conn->s, (unsigned)circ->base_.n_circ_id);
3332  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
3333 
3334  /* If there's queued-up data, send it now */
3335  if ((connection_get_inbuf_len(base_conn) ||
3336  ap_conn->sending_optimistic_data) &&
3338  log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
3339  (long)connection_get_inbuf_len(base_conn),
3340  ap_conn->sending_optimistic_data ?
3341  (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
3342  if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
3343  connection_mark_for_close(base_conn);
3344  }
3345  }
3346 
3347  return 0;
3348 }
3349 
3350 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
3351  * socks_request field, and send it down circ.
3352  *
3353  * If ap_conn is broken, mark it for close and return -1. Else return 0.
3354  */
3355 int
3357 {
3358  int payload_len, command;
3359  const char *string_addr;
3360  char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
3361  origin_circuit_t *circ;
3362  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3363  connection_t *base_conn = TO_CONN(edge_conn);
3364  tor_assert(edge_conn->on_circuit);
3365  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3366 
3367  tor_assert(base_conn->type == CONN_TYPE_AP);
3369  tor_assert(ap_conn->socks_request);
3371 
3372  command = ap_conn->socks_request->command;
3373  tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
3374 
3375  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3376  if (edge_conn->stream_id==0) {
3377  /* XXXX+ Instead of closing this stream, we should make it get
3378  * retried on another circuit. */
3379  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3380 
3381  /* Mark this circuit "unusable for new streams". */
3383  return -1;
3384  }
3385 
3386  if (command == SOCKS_COMMAND_RESOLVE) {
3387  string_addr = ap_conn->socks_request->address;
3388  payload_len = (int)strlen(string_addr)+1;
3389  } else {
3390  /* command == SOCKS_COMMAND_RESOLVE_PTR */
3391  const char *a = ap_conn->socks_request->address;
3392  tor_addr_t addr;
3393  int r;
3394 
3395  /* We're doing a reverse lookup. The input could be an IP address, or
3396  * could be an .in-addr.arpa or .ip6.arpa address */
3397  r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
3398  if (r <= 0) {
3399  log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
3400  safe_str_client(a));
3401  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3402  return -1;
3403  }
3404 
3405  r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
3406  if (r < 0) {
3407  log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
3408  safe_str_client(a));
3409  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3410  return -1;
3411  }
3412 
3413  string_addr = inaddr_buf;
3414  payload_len = (int)strlen(inaddr_buf)+1;
3415  tor_assert(payload_len <= (int)sizeof(inaddr_buf));
3416  }
3417 
3418  log_debug(LD_APP,
3419  "Sending relay cell to begin stream %d.", edge_conn->stream_id);
3420 
3421  if (connection_edge_send_command(edge_conn,
3422  RELAY_COMMAND_RESOLVE,
3423  string_addr, payload_len) < 0)
3424  return -1; /* circuit is closed, don't continue */
3425 
3426  if (!base_conn->address) {
3427  /* This might be unnecessary. XXXX */
3428  base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
3429  }
3430  base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
3431  log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
3432  ", n_circ_id %u",
3433  base_conn->s, (unsigned)circ->base_.n_circ_id);
3434  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
3435  return 0;
3436 }
3437 
3438 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
3439  * new linked connection pair, and attach one side to the conn, connection_add
3440  * it, initialize it to circuit_wait, and call
3441  * connection_ap_handshake_attach_circuit(conn) on it.
3442  *
3443  * Return the newly created end of the linked connection pair, or -1 if error.
3444  */
3447  char *address, uint16_t port,
3448  const char *digest,
3449  int session_group, int isolation_flags,
3450  int use_begindir, int want_onehop)
3451 {
3452  entry_connection_t *conn;
3453  connection_t *base_conn;
3454 
3455  log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
3456  want_onehop ? "direct" : "anonymized",
3457  safe_str_client(address), port);
3458 
3460  base_conn = ENTRY_TO_CONN(conn);
3461  base_conn->linked = 1; /* so that we can add it safely below. */
3462 
3463  /* populate conn->socks_request */
3464 
3465  /* leave version at zero, so the socks_reply is empty */
3466  conn->socks_request->socks_version = 0;
3467  conn->socks_request->has_finished = 0; /* waiting for 'connected' */
3468  strlcpy(conn->socks_request->address, address,
3469  sizeof(conn->socks_request->address));
3470  conn->socks_request->port = port;
3472  conn->want_onehop = want_onehop;
3473  conn->use_begindir = use_begindir;
3474  if (use_begindir) {
3475  conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
3476  conn->chosen_exit_name[0] = '$';
3477  tor_assert(digest);
3479  digest, DIGEST_LEN);
3480  }
3481 
3482  /* Populate isolation fields. */
3484  conn->original_dest_address = tor_strdup(address);
3485  conn->entry_cfg.session_group = session_group;
3486  conn->entry_cfg.isolation_flags = isolation_flags;
3487 
3488  base_conn->address = tor_strdup("(Tor_internal)");
3489  tor_addr_make_unspec(&base_conn->addr);
3490  base_conn->port = 0;
3491 
3492  connection_link_connections(partner, base_conn);
3493 
3494  if (connection_add(base_conn) < 0) { /* no space, forget it */
3495  connection_free(base_conn);
3496  return NULL;
3497  }
3498 
3499  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
3500 
3501  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3502 
3503  /* attaching to a dirty circuit is fine */
3504  connection_ap_mark_as_pending_circuit(conn);
3505  log_info(LD_APP,"... application connection created and linked.");
3506  return conn;
3507 }
3508 
3509 /** Notify any interested controller connections about a new hostname resolve
3510  * or resolve error. Takes the same arguments as does
3511  * connection_ap_handshake_socks_resolved(). */
3512 static void
3514  int answer_type,
3515  size_t answer_len,
3516  const char *answer,
3517  int ttl,
3518  time_t expires)
3519 {
3520  expires = time(NULL) + ttl;
3521  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
3522  char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
3523  if (cp)
3525  cp, expires, NULL, 0);
3526  tor_free(cp);
3527  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3528  char *cp = tor_strndup(answer, answer_len);
3530  cp, expires, NULL, 0);
3531  tor_free(cp);
3532  } else {
3534  "<error>", time(NULL)+ttl,
3535  "error=yes", 0);
3536  }
3537 }
3538 
3539 /**
3540  * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
3541  * as the answer.
3542  */
3543 void
3545  const tor_addr_t *answer,
3546  int ttl,
3547  time_t expires)
3548 {
3549  if (tor_addr_family(answer) == AF_INET) {
3550  uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
3551  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
3552  (uint8_t*)&a,
3553  ttl, expires);
3554  } else if (tor_addr_family(answer) == AF_INET6) {
3555  const uint8_t *a = tor_addr_to_in6_addr8(answer);
3556  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
3557  a,
3558  ttl, expires);
3559  } else {
3560  log_warn(LD_BUG, "Got called with address of unexpected family %d",
3561  tor_addr_family(answer));
3563  RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
3564  }
3565 }
3566 
3567 /** Send an answer to an AP connection that has requested a DNS lookup via
3568  * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
3569  * for unreachable; the answer should be in the format specified in the socks
3570  * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
3571  * certain errors or for values that didn't come via DNS. <b>expires</b> is
3572  * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
3573  **/
3574 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
3575  * interface and those that use it less ugly. */
3576 MOCK_IMPL(void,
3578  int answer_type,
3579  size_t answer_len,
3580  const uint8_t *answer,
3581  int ttl,
3582  time_t expires))
3583 {
3584  char buf[384];
3585  size_t replylen;
3586 
3587  if (ttl >= 0) {
3588  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3589  tor_addr_t a;
3590  tor_addr_from_ipv4n(&a, get_uint32(answer));
3591  if (! tor_addr_is_null(&a)) {
3593  conn->socks_request->address, &a,
3594  conn->chosen_exit_name, ttl);
3595  }
3596  } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3597  tor_addr_t a;
3598  tor_addr_from_ipv6_bytes(&a, answer);
3599  if (! tor_addr_is_null(&a)) {
3601  conn->socks_request->address, &a,
3602  conn->chosen_exit_name, ttl);
3603  }
3604  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3605  char *cp = tor_strndup((char*)answer, answer_len);
3607  conn->socks_request->address,
3608  cp,
3609  conn->chosen_exit_name, ttl);
3610  tor_free(cp);
3611  }
3612  }
3613 
3614  if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
3615  if (conn->dns_server_request) {
3616  /* We had a request on our DNS port: answer it. */
3617  dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
3618  conn->socks_request->has_finished = 1;
3619  return;
3620  } else {
3621  /* This must be a request from the controller. Since answers to those
3622  * requests are not cached, they do not generate an ADDRMAP event on
3623  * their own. */
3624  tell_controller_about_resolved_result(conn, answer_type, answer_len,
3625  (char*)answer, ttl, expires);
3626  conn->socks_request->has_finished = 1;
3627  return;
3628  }
3629  /* We shouldn't need to free conn here; it gets marked by the caller. */
3630  }
3631 
3632  if (conn->socks_request->socks_version == 4) {
3633  buf[0] = 0x00; /* version */
3634  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3635  buf[1] = SOCKS4_GRANTED;
3636  set_uint16(buf+2, 0);
3637  memcpy(buf+4, answer, 4); /* address */
3638  replylen = SOCKS4_NETWORK_LEN;
3639  } else { /* "error" */
3640  buf[1] = SOCKS4_REJECT;
3641  memset(buf+2, 0, 6);
3642  replylen = SOCKS4_NETWORK_LEN;
3643  }
3644  } else if (conn->socks_request->socks_version == 5) {
3645  /* SOCKS5 */
3646  buf[0] = 0x05; /* version */
3647  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3648  buf[1] = SOCKS5_SUCCEEDED;
3649  buf[2] = 0; /* reserved */
3650  buf[3] = 0x01; /* IPv4 address type */
3651  memcpy(buf+4, answer, 4); /* address */
3652  set_uint16(buf+8, 0); /* port == 0. */
3653  replylen = 10;
3654  } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3655  buf[1] = SOCKS5_SUCCEEDED;
3656  buf[2] = 0; /* reserved */
3657  buf[3] = 0x04; /* IPv6 address type */
3658  memcpy(buf+4, answer, 16); /* address */
3659  set_uint16(buf+20, 0); /* port == 0. */
3660  replylen = 22;
3661  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3662  buf[1] = SOCKS5_SUCCEEDED;
3663  buf[2] = 0; /* reserved */
3664  buf[3] = 0x03; /* Domainname address type */
3665  buf[4] = (char)answer_len;
3666  memcpy(buf+5, answer, answer_len); /* address */
3667  set_uint16(buf+5+answer_len, 0); /* port == 0. */
3668  replylen = 5+answer_len+2;
3669  } else {
3670  buf[1] = SOCKS5_HOST_UNREACHABLE;
3671  memset(buf+2, 0, 8);
3672  replylen = 10;
3673  }
3674  } else {
3675  /* no socks version info; don't send anything back */
3676  return;
3677  }
3678  connection_ap_handshake_socks_reply(conn, buf, replylen,
3679  (answer_type == RESOLVED_TYPE_IPV4 ||
3680  answer_type == RESOLVED_TYPE_IPV6 ||
3681  answer_type == RESOLVED_TYPE_HOSTNAME) ?
3682  0 : END_STREAM_REASON_RESOLVEFAILED);
3683 }
3684 
3685 /** Send a socks reply to stream <b>conn</b>, using the appropriate
3686  * socks version, etc, and mark <b>conn</b> as completed with SOCKS
3687  * handshaking.
3688  *
3689  * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
3690  * and return, else reply based on <b>endreason</b> (one of
3691  * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
3692  * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
3693  */
3694 void
3696  size_t replylen, int endreason)
3697 {
3698  char buf[256];
3699  socks5_reply_status_t status;
3700 
3701  tor_assert(conn->socks_request); /* make sure it's an AP stream */
3702 
3705  status = conn->socks_request->socks_extended_error_code;
3706  } else {
3707  status = stream_end_reason_to_socks5_response(endreason);
3708  }
3709 
3710  if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3711  control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
3712  STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
3713  endreason);
3714  }
3715 
3716  /* Flag this stream's circuit as having completed a stream successfully
3717  * (for path bias) */
3718  if (status == SOCKS5_SUCCEEDED ||
3719  endreason == END_STREAM_REASON_RESOLVEFAILED ||
3720  endreason == END_STREAM_REASON_CONNECTREFUSED ||
3721  endreason == END_STREAM_REASON_CONNRESET ||
3722  endreason == END_STREAM_REASON_NOROUTE ||
3723  endreason == END_STREAM_REASON_RESOURCELIMIT) {
3724  if (!conn->edge_.on_circuit ||
3725  !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
3726  if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
3727  log_info(LD_BUG,
3728  "No origin circuit for successful SOCKS stream %"PRIu64
3729  ". Reason: %d",
3730  (ENTRY_TO_CONN(conn)->global_identifier),
3731  endreason);
3732  }
3733  /*
3734  * Else DNS remaps and failed hidden service lookups can send us
3735  * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3736  *
3737  * Perhaps we could make the test more precise; we can tell hidden
3738  * services by conn->edge_.renddata != NULL; anything analogous for
3739  * the DNS remap case?
3740  */
3741  } else {
3742  // XXX: Hrmm. It looks like optimistic data can't go through this
3743  // codepath, but someone should probably test it and make sure.
3744  // We don't want to mark optimistically opened streams as successful.
3746  }
3747  }
3748 
3749  if (conn->socks_request->has_finished) {
3750  log_warn(LD_BUG, "(Harmless.) duplicate calls to "
3751  "connection_ap_handshake_socks_reply.");
3752  return;
3753  }
3754  if (replylen) { /* we already have a reply in mind */
3755  connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
3756  conn->socks_request->has_finished = 1;
3757  return;
3758  }
3759  if (conn->socks_request->listener_type ==
3761  const char *response = end_reason_to_http_connect_response_line(endreason);
3762  if (!response) {
3763  response = "HTTP/1.0 400 Bad Request\r\n\r\n";
3764  }
3765  connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
3766  } else if (conn->socks_request->socks_version == 4) {
3767  memset(buf,0,SOCKS4_NETWORK_LEN);
3768  buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
3769  /* leave version, destport, destip zero */
3770  connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
3771  } else if (conn->socks_request->socks_version == 5) {
3772  size_t buf_len;
3773  memset(buf,0,sizeof(buf));
3774  if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
3775  buf[0] = 5; /* version 5 */
3776  buf[1] = (char)status;
3777  buf[2] = 0;
3778  buf[3] = 1; /* ipv4 addr */
3779  /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3780  buf_len = 10;
3781  } else { /* AF_INET6. */
3782  buf[0] = 5; /* version 5 */
3783  buf[1] = (char)status;
3784  buf[2] = 0;
3785  buf[3] = 4; /* ipv6 addr */
3786  /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3787  buf_len = 22;
3788  }
3789  connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
3790  }
3791  /* If socks_version isn't 4 or 5, don't send anything.
3792  * This can happen in the case of AP bridges. */
3793  conn->socks_request->has_finished = 1;
3794  return;
3795 }
3796 
3797 /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
3798  * place the result in <b>bcell</b>. On success return 0; on failure return
3799  * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
3800  * the client.
3801  *
3802  * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
3803  * we don't.
3804  **/
3805 STATIC int
3806 begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
3807  uint8_t *end_reason_out)
3808 {
3809  relay_header_t rh;
3810  const uint8_t *body, *nul;
3811 
3812  memset(bcell, 0, sizeof(*bcell));
3813  *end_reason_out = END_STREAM_REASON_MISC;
3814 
3815  relay_header_unpack(&rh, cell->payload);
3816  if (rh.length > RELAY_PAYLOAD_SIZE) {
3817  return -2; /*XXXX why not TORPROTOCOL? */
3818  }
3819 
3820  bcell->stream_id = rh.stream_id;
3821 
3822  if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3823  bcell->is_begindir = 1;
3824  return 0;
3825  } else if (rh.command != RELAY_COMMAND_BEGIN) {
3826  log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3827  *end_reason_out = END_STREAM_REASON_INTERNAL;
3828  return -1;
3829  }
3830 
3831  body = cell->payload + RELAY_HEADER_SIZE;
3832  nul = memchr(body, 0, rh.length);
3833  if (! nul) {
3834  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3835  "Relay begin cell has no \\0. Closing.");
3836  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3837  return -1;
3838  }
3839 
3840  if (tor_addr_port_split(LOG_PROTOCOL_WARN,
3841  (char*)(body),
3842  &bcell->address,&bcell->port)<0) {
3843  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3844  "Unable to parse addr:port in relay begin cell. Closing.");
3845  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3846  return -1;
3847  }
3848  if (bcell->port == 0) {
3849  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3850  "Missing port in relay begin cell. Closing.");
3851  tor_free(bcell->address);
3852  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3853  return -1;
3854  }
3855  if (body + rh.length >= nul + 4)
3856  bcell->flags = ntohl(get_uint32(nul+1));
3857 
3858  return 0;
3859 }
3860 
3861 /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
3862  * connection, attach it to the circ and connect it. Return 0 on success
3863  * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
3864  * where the caller should close the circuit. */
3865 static int
3867 {
3868  int ret;
3869  origin_circuit_t *origin_circ;
3870 
3871  assert_circuit_ok(circ);
3873  tor_assert(conn);
3874 
3875  log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
3876  "to the service destination.");
3877 
3878  origin_circ = TO_ORIGIN_CIRCUIT(circ);
3879  conn->base_.address = tor_strdup("(rendezvous)");
3880  conn->base_.state = EXIT_CONN_STATE_CONNECTING;
3881 
3882  /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
3883  * service. */
3884  if (origin_circ->rend_data) {
3885  conn->rend_data = rend_data_dup(origin_circ->rend_data);
3887  ret = rend_service_set_connection_addr_port(conn, origin_circ);
3888  } else if (origin_circ->hs_ident) {
3889  /* Setup the identifier to be the one for the circuit service. */
3890  conn->hs_ident =
3893  ret = hs_service_set_conn_addr_port(origin_circ, conn);
3894  } else {
3895  /* We should never get here if the circuit's purpose is rendezvous. */
3897  return -1;
3898  }
3899  if (ret < 0) {
3900  log_info(LD_REND, "Didn't find rendezvous service at %s",
3902  /* Send back reason DONE because we want to make hidden service port
3903  * scanning harder thus instead of returning that the exit policy
3904  * didn't match, which makes it obvious that the port is closed,
3905  * return DONE and kill the circuit. That way, a user (malicious or
3906  * not) needs one circuit per bad port unless it matches the policy of
3907  * the hidden service. */
3909  END_STREAM_REASON_DONE,
3910  origin_circ->cpath->prev);
3911  connection_free_(TO_CONN(conn));
3912 
3913  /* Drop the circuit here since it might be someone deliberately
3914  * scanning the hidden service ports. Note that this mitigates port
3915  * scanning by adding more work on the attacker side to successfully
3916  * scan but does not fully solve it. */
3917  if (ret < -1) {
3918  return END_CIRC_AT_ORIGIN;
3919  } else {
3920  return 0;
3921  }
3922  }
3923 
3924  /* Link the circuit and the connection crypt path. */
3925  conn->cpath_layer = origin_circ->cpath->prev;
3926 
3927  /* If this is the first stream on this circuit, tell circpad */
3928  if (!origin_circ->p_streams)
3930 
3931  /* Add it into the linked list of p_streams on this circuit */
3932  conn->next_stream = origin_circ->p_streams;
3933  origin_circ->p_streams = conn;
3934  conn->on_circuit = circ;
3935  assert_circuit_ok(circ);
3936 
3937  hs_inc_rdv_stream_counter(origin_circ);
3938 
3939  /* If it's an onion service connection, we might want to include the proxy
3940  * protocol header: */
3941  if (conn->hs_ident) {
3942  hs_circuit_id_protocol_t circuit_id_protocol =
3943  hs_service_exports_circuit_id(&conn->hs_ident->identity_pk);
3944  export_hs_client_circuit_id(conn, circuit_id_protocol);
3945  }
3946 
3947  /* Connect tor to the hidden service destination. */
3949 
3950  /* For path bias: This circuit was used successfully */
3951  pathbias_mark_use_success(origin_circ);
3952  return 0;
3953 }
3954 
3955 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
3956  * an exit hop for the circuit, or we are the origin and it is a
3957  * rendezvous begin.
3958  *
3959  * Launch a new exit connection and initialize things appropriately.
3960  *
3961  * If it's a rendezvous stream, call connection_exit_connect() on
3962  * it.
3963  *
3964  * For general streams, call dns_resolve() on it first, and only call
3965  * connection_exit_connect() if the dns answer is already known.
3966  *
3967  * Note that we don't call connection_add() on the new stream! We wait
3968  * for connection_exit_connect() to do that.
3969  *
3970  * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
3971  * Else return 0.
3972  */
3973 int
3975 {
3976  edge_connection_t *n_stream;
3977  relay_header_t rh;
3978  char *address = NULL;
3979  uint16_t port = 0;
3980  or_circuit_t *or_circ = NULL;
3981  origin_circuit_t *origin_circ = NULL;
3982  crypt_path_t *layer_hint = NULL;
3983  const or_options_t *options = get_options();
3984  begin_cell_t bcell;
3985  int rv;
3986  uint8_t end_reason=0;
3987 
3988  assert_circuit_ok(circ);
3989  if (!CIRCUIT_IS_ORIGIN(circ)) {
3990  or_circ = TO_OR_CIRCUIT(circ);
3991  } else {
3993  origin_circ = TO_ORIGIN_CIRCUIT(circ);
3994  layer_hint = origin_circ->cpath->prev;
3995  }
3996 
3997  relay_header_unpack(&rh, cell->payload);
3998  if (rh.length > RELAY_PAYLOAD_SIZE)
3999  return -END_CIRC_REASON_TORPROTOCOL;
4000 
4001  if (!server_mode(options) &&
4003  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
4004  "Relay begin cell at non-server. Closing.");
4006  END_STREAM_REASON_EXITPOLICY, NULL);
4007  return 0;
4008  }
4009 
4010  rv = begin_cell_parse(cell, &bcell, &end_reason);
4011  if (rv < -1) {
4012  return -END_CIRC_REASON_TORPROTOCOL;
4013  } else if (rv == -1) {
4014  tor_free(bcell.address);
4015  relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
4016  return 0;
4017  }
4018 
4019  if (! bcell.is_begindir) {
4020  /* Steal reference */
4021  tor_assert(bcell.address);
4022  address = bcell.address;
4023  port = bcell.port;
4024 
4025  if (or_circ && or_circ->p_chan) {
4026  const int client_chan = channel_is_client(or_circ->p_chan);
4027  if ((client_chan ||
4029  or_circ->p_chan->identity_digest) &&
4030  should_refuse_unknown_exits(options)))) {
4031  /* Don't let clients use us as a single-hop proxy. It attracts
4032  * attackers and users who'd be better off with, well, single-hop
4033  * proxies. */
4034  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
4035  "Attempt by %s to open a stream %s. Closing.",
4036  safe_str(channel_describe_peer(or_circ->p_chan)),
4037  client_chan ? "on first hop of circuit" :
4038  "from unknown relay");
4040  client_chan ?
4041  END_STREAM_REASON_TORPROTOCOL :
4042  END_STREAM_REASON_MISC,
4043  NULL);
4044  tor_free(address);
4045  return 0;
4046  }
4047  }
4048  } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
4049  if (!directory_permits_begindir_requests(options) ||
4050  circ->purpose != CIRCUIT_PURPOSE_OR) {
4052  END_STREAM_REASON_NOTDIRECTORY, layer_hint);
4053  return 0;
4054  }
4055  /* Make sure to get the 'real' address of the previous hop: the
4056  * caller might want to know whether the remote IP address has changed,
4057  * and we might already have corrected base_.addr[ess] for the relay's
4058  * canonical IP address. */
4059  tor_addr_t chan_addr;
4060  if (or_circ && or_circ->p_chan &&
4061  channel_get_addr_if_possible(or_circ->p_chan, &chan_addr)) {
4062  address = tor_addr_to_str_dup(&chan_addr);
4063  } else {
4064  address = tor_strdup("127.0.0.1");
4065  }
4066  port = 1; /* XXXX This value is never actually used anywhere, and there
4067  * isn't "really" a connection here. But we
4068  * need to set it to something nonzero. */
4069  } else {
4070  log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
4072  END_STREAM_REASON_INTERNAL, layer_hint);
4073  return 0;
4074  }
4075 
4076  if (! options->IPv6Exit) {
4077  /* I don't care if you prefer IPv6; I can't give you any. */
4078  bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
4079  /* If you don't want IPv4, I can't help. */
4080  if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
4081  tor_free(address);
4083  END_STREAM_REASON_EXITPOLICY, layer_hint);
4084  return 0;
4085  }
4086  }
4087 
4088  log_debug(LD_EXIT,"Creating new exit connection.");
4089  /* The 'AF_INET' here is temporary; we might need to change it later in
4090  * connection_exit_connect(). */
4091  n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
4092 
4093  /* Remember the tunneled request ID in the new edge connection, so that
4094  * we can measure download times. */
4095  n_stream->dirreq_id = circ->dirreq_id;
4096 
4097  n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
4098  n_stream->begincell_flags = bcell.flags;
4099  n_stream->stream_id = rh.stream_id;
4100  n_stream->base_.port = port;
4101  /* leave n_stream->s at -1, because it's not yet valid */
4102  n_stream->package_window = STREAMWINDOW_START;
4103  n_stream->deliver_window = STREAMWINDOW_START;
4104 
4105  if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
4106  int ret;
4107  tor_free(address);
4108  /* We handle this circuit and stream in this function for all supported
4109  * hidden service version. */
4110  ret = handle_hs_exit_conn(circ, n_stream);
4111 
4112  if (ret == 0) {
4113  /* This was a valid cell. Count it as delivered + overhead. */
4114  circuit_read_valid_data(origin_circ, rh.length);
4115  }
4116  return ret;
4117  }
4118  tor_strlower(address);
4119  n_stream->base_.address = address;
4120  n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4121  /* default to failed, change in dns_resolve if it turns out not to fail */
4122 
4123  /* If we're hibernating or shutting down, we refuse to open new streams. */
4124  if (we_are_hibernating()) {
4126  END_STREAM_REASON_HIBERNATING, NULL);
4127  connection_free_(TO_CONN(n_stream));
4128  return 0;
4129  }
4130 
4131  n_stream->on_circuit = circ;
4132 
4133  if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
4134  tor_addr_t tmp_addr;
4135  tor_assert(or_circ);
4136  if (or_circ->p_chan &&
4137  channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
4138  tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
4139  }
4140  return connection_exit_connect_dir(n_stream);
4141  }
4142 
4143  log_debug(LD_EXIT,"about to start the dns_resolve().");
4144 
4145  /* send it off to the gethostbyname farm */
4146  switch (dns_resolve(n_stream)) {
4147  case 1: /* resolve worked; now n_stream is attached to circ. */
4148  assert_circuit_ok(circ);
4149  log_debug(LD_EXIT,"about to call connection_exit_connect().");
4150  connection_exit_connect(n_stream);
4151  return 0;
4152  case -1: /* resolve failed */
4154  END_STREAM_REASON_RESOLVEFAILED, NULL);
4155  /* n_stream got freed. don't touch it. */
4156  break;
4157  case 0: /* resolve added to pending list */
4158  assert_circuit_ok(circ);
4159  break;
4160  }
4161  return 0;
4162 }
4163 
4164 /**
4165  * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
4166  * circuit <b>circ</b>;
4167  * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
4168  */
4169 int
4171 {
4172  edge_connection_t *dummy_conn;
4173  relay_header_t rh;
4174 
4176  relay_header_unpack(&rh, cell->payload);
4177  if (rh.length > RELAY_PAYLOAD_SIZE)
4178  return -1;
4179 
4180  /* This 'dummy_conn' only exists to remember the stream ID
4181  * associated with the resolve request; and to make the
4182  * implementation of dns.c more uniform. (We really only need to
4183  * remember the circuit, the stream ID, and the hostname to be
4184  * resolved; but if we didn't store them in a connection like this,
4185  * the housekeeping in dns.c would get way more complicated.)
4186  */
4187  dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
4188  dummy_conn->stream_id = rh.stream_id;
4189  dummy_conn->base_.address = tor_strndup(
4190  (char*)cell->payload+RELAY_HEADER_SIZE,
4191  rh.length);
4192  dummy_conn->base_.port = 0;
4193  dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4194  dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
4195 
4196  dummy_conn->on_circuit = TO_CIRCUIT(circ);
4197 
4198  /* send it off to the gethostbyname farm */
4199  switch (dns_resolve(dummy_conn)) {
4200  case -1: /* Impossible to resolve; a resolved cell was sent. */
4201  /* Connection freed; don't touch it. */
4202  return 0;
4203  case 1: /* The result was cached; a resolved cell was sent. */
4204  if (!dummy_conn->base_.marked_for_close)
4205  connection_free_(TO_CONN(dummy_conn));
4206  return 0;
4207  case 0: /* resolve added to pending list */
4209  break;
4210  }
4211  return 0;
4212 }
4213 
4214 /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
4215  * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
4216  */
4217 static int
4219  uint16_t port,
4220  const char **why_rejected)
4221 {
4222  if (router_compare_to_my_exit_policy(addr, port)) {
4223  *why_rejected = "";
4224  return 1;
4225  } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
4226  *why_rejected = " (IPv6 address without IPv6Exit configured)";
4227  return 1;
4228  }
4229  return 0;
4230 }
4231 
4232 /** Connect to conn's specified addr and port. If it worked, conn
4233  * has now been added to the connection_array.
4234  *
4235  * Send back a connected cell. Include the resolved IP of the destination
4236  * address, but <em>only</em> if it's a general exit stream. (Rendezvous
4237  * streams must not reveal what IP they connected to.)
4238  */
4239 void
4241 {
4242  const tor_addr_t *addr;
4243  uint16_t port;
4244  connection_t *conn = TO_CONN(edge_conn);
4245  int socket_error = 0, result;
4246  const char *why_failed_exit_policy = NULL;
4247 
4248  /* Apply exit policy to non-rendezvous connections. */
4249  if (! connection_edge_is_rendezvous_stream(edge_conn) &&
4250  my_exit_policy_rejects(&edge_conn->base_.addr,
4251  edge_conn->base_.port,
4252  &why_failed_exit_policy)) {
4253  if (BUG(!why_failed_exit_policy))
4254  why_failed_exit_policy = "";
4255  log_info(LD_EXIT,"%s failed exit policy%s. Closing.",
4256  connection_describe(conn),
4257  why_failed_exit_policy);
4258  connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
4259  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4260  connection_free(conn);
4261  return;
4262  }
4263 
4264 #ifdef HAVE_SYS_UN_H
4265  if (conn->socket_family != AF_UNIX) {
4266 #else
4267  {
4268 #endif /* defined(HAVE_SYS_UN_H) */
4269  addr = &conn->addr;
4270  port = conn->port;
4271 
4272  if (tor_addr_family(addr) == AF_INET6)
4273  conn->socket_family = AF_INET6;
4274 
4275  log_debug(LD_EXIT, "about to try connecting");
4276  result = connection_connect(conn, conn->address,
4277  addr, port, &socket_error);
4278 #ifdef HAVE_SYS_UN_H
4279  } else {
4280  /*
4281  * In the AF_UNIX case, we expect to have already had conn->port = 1,
4282  * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
4283  * case in connection_handle_listener_read()), and conn->address should
4284  * have the socket path to connect to.
4285  */
4286  tor_assert(conn->address && strlen(conn->address) > 0);
4287 
4288  log_debug(LD_EXIT, "about to try connecting");
4289  result = connection_connect_unix(conn, conn->address, &socket_error);
4290 #endif /* defined(HAVE_SYS_UN_H) */
4291  }
4292 
4293  switch (result) {
4294  case -1: {
4295  int reason = errno_to_stream_end_reason(socket_error);
4296  connection_edge_end(edge_conn, reason);
4297  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4298  connection_free(conn);
4299  return;
4300  }
4301  case 0:
4303 
4305  /* writable indicates finish;
4306  * readable/error indicates broken link in windows-land. */
4307  return;
4308  /* case 1: fall through */
4309  }
4310 
4311  conn->state = EXIT_CONN_STATE_OPEN;
4312  if (connection_get_outbuf_len(conn)) {
4313  /* in case there are any queued data cells, from e.g. optimistic data */
4315  } else {
4317  }
4318 
4319  /* also, deliver a 'connected' cell back through the circuit. */
4320  if (connection_edge_is_rendezvous_stream(edge_conn)) {
4321  /* don't send an address back! */
4322  connection_edge_send_command(edge_conn,
4323  RELAY_COMMAND_CONNECTED,
4324  NULL, 0);
4325  } else { /* normal stream */
4326  uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
4327  int connected_payload_len =
4328  connected_cell_format_payload(connected_payload, &conn->addr,
4329  edge_conn->address_ttl);
4330  if (connected_payload_len < 0) {
4331  connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
4332  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4333  connection_free(conn);
4334  return;
4335  }
4336 
4337  connection_edge_send_command(edge_conn,
4338  RELAY_COMMAND_CONNECTED,
4339  (char*)connected_payload,
4340  connected_payload_len);
4341  }
4342 }
4343 
4344 /** Given an exit conn that should attach to us as a directory server, open a
4345  * bridge connection with a linked connection pair, create a new directory
4346  * conn, and join them together. Return 0 on success (or if there was an
4347  * error we could send back an end cell for). Return -(some circuit end
4348  * reason) if the circuit needs to be torn down. Either connects
4349  * <b>exitconn</b>, frees it, or marks it, as appropriate.
4350  */
4351 static int
4353 {
4354  dir_connection_t *dirconn = NULL;
4355  or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
4356 
4357  log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
4358 
4359  exitconn->base_.state = EXIT_CONN_STATE_OPEN;
4360 
4361  dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
4362 
4363  tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
4364  dirconn->base_.port = 0;
4365  dirconn->base_.address = tor_strdup(exitconn->base_.address);
4366  dirconn->base_.type = CONN_TYPE_DIR;
4367  dirconn->base_.purpose = DIR_PURPOSE_SERVER;
4368  dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
4369 
4370  /* Note that the new dir conn belongs to the same tunneled request as
4371  * the edge conn, so that we can measure download times. */
4372  dirconn->dirreq_id = exitconn->dirreq_id;
4373 
4374  connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
4375 
4376  if (connection_add(TO_CONN(exitconn))<0) {
4377  connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4378  connection_free_(TO_CONN(exitconn));
4379  connection_free_(TO_CONN(dirconn));
4380  return 0;
4381  }
4382 
4383  /* link exitconn to circ, now that we know we can use it. */
4384  exitconn->next_stream = circ->n_streams;
4385  circ->n_streams = exitconn;
4386 
4387  if (connection_add(TO_CONN(dirconn))<0) {
4388  connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4390  connection_mark_for_close(TO_CONN(exitconn));
4391  connection_free_(TO_CONN(dirconn));
4392  return 0;
4393  }
4394 
4396  connection_start_reading(TO_CONN(exitconn));
4397 
4398  if (connection_edge_send_command(exitconn,
4399  RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
4400  connection_mark_for_close(TO_CONN(exitconn));
4401  connection_mark_for_close(TO_CONN(dirconn));
4402  return 0;
4403  }
4404 
4405  return 0;
4406 }
4407 
4408 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
4409  * it is a general stream.
4410  */
4411 int
4413 {
4414  tor_assert(conn);
4415  /* It should not be possible to set both of these structs */
4416  tor_assert_nonfatal(!(conn->rend_data && conn->hs_ident));
4417 
4418  if (conn->rend_data || conn->hs_ident) {
4419  return 1;
4420  }
4421  return 0;
4422 }
4423 
4424 /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
4425  * to exit from it, or 0 if it probably will not allow it.
4426  * (We might be uncertain if conn's destination address has not yet been
4427  * resolved.)
4428  */
4429 int
4431  const node_t *exit_node)
4432 {
4433  const or_options_t *options = get_options();
4434 
4435  tor_assert(conn);
4436  tor_assert(conn->socks_request);
4437  tor_assert(exit_node);
4438 
4439  /* If a particular exit node has been requested for the new connection,
4440  * make sure the exit node of the existing circuit matches exactly.
4441  */
4442  if (conn->chosen_exit_name) {
4443  const node_t *chosen_exit =
4445  if (!chosen_exit || tor_memneq(chosen_exit->identity,
4446  exit_node->identity, DIGEST_LEN)) {
4447  /* doesn't match */
4448 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
4449 // conn->chosen_exit_name, exit->nickname);
4450  return 0;
4451  }
4452  }
4453 
4454  if (conn->use_begindir) {
4455  /* Internal directory fetches do not count as exiting. */
4456  return 1;
4457  }
4458 
4460  tor_addr_t addr, *addrp = NULL;
4462  if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
4463  addrp = &addr;
4464  } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
4465  tor_addr_make_null(&addr, AF_INET6);
4466  addrp = &addr;
4467  } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
4468  tor_addr_make_null(&addr, AF_INET);
4469  addrp = &addr;
4470  }
4472  exit_node);
4473  if (r == ADDR_POLICY_REJECTED)
4474  return 0; /* We know the address, and the exit policy rejects it. */
4476  return 0; /* We don't know the addr, but the exit policy rejects most
4477  * addresses with this port. Since the user didn't ask for
4478  * this node, err on the side of caution. */
4479  } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
4480  /* Don't send DNS requests to non-exit servers by default. */
4481  if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
4482  return 0;
4483  }
4484  if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
4485  /* Not a suitable exit. Refuse it. */
4486  return 0;
4487  }
4488 
4489  return 1;
4490 }
4491 
4492 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
4493  * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
4494  * at <b>b</b>. */
4495 static int
4496 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
4497 {
4498  if (a == NULL) {
4499  return (b == NULL);
4500  } else if (b == NULL) {
4501  return 0;
4502  } else if (alen != blen) {
4503  return 0;
4504  } else {
4505  return tor_memeq(a, b, alen);
4506  }
4507 }
4508 
4509 /**
4510  * Return true iff none of the isolation flags and fields in <b>conn</b>
4511  * should prevent it from being attached to <b>circ</b>.
4512  */
4513 int
4515  const origin_circuit_t *circ)
4516 {
4517  const uint8_t iso = conn->entry_cfg.isolation_flags;
4518  const socks_request_t *sr = conn->socks_request;
4519 
4520  /* If circ has never been used for an isolated connection, we can
4521  * totally use it for this one. */
4522  if (!circ->isolation_values_set)
4523  return 1;
4524 
4525  /* If circ has been used for connections having more than one value
4526  * for some field f, it will have the corresponding bit set in
4527  * isolation_flags_mixed. If isolation_flags_mixed has any bits
4528  * in common with iso, then conn must be isolated from at least
4529  * one stream that has been attached to circ. */
4530  if ((iso & circ->isolation_flags_mixed) != 0) {
4531  /* For at least one field where conn is isolated, the circuit
4532  * already has mixed streams. */
4533  return 0;
4534  }
4535 
4536  if (! conn->original_dest_address) {
4537  log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
4538  "having set conn->original_dest_address");
4539  ((entry_connection_t*)conn)->original_dest_address =
4540  tor_strdup(conn->socks_request->address);
4541  }
4542 
4543  if ((iso & ISO_STREAM) &&
4545  ENTRY_TO_CONN(conn)->global_identifier))
4546  return 0;
4547 
4548  if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
4549  return 0;
4550  if ((iso & ISO_DESTADDR) &&
4551  strcasecmp(conn->original_dest_address, circ->dest_address))
4552  return 0;
4553  if ((iso & ISO_SOCKSAUTH) &&
4554  (! memeq_opt(sr->username, sr->usernamelen,
4555  circ->socks_username, circ->socks_username_len) ||
4556  ! memeq_opt(sr->password, sr->passwordlen,
4557  circ->socks_password, circ->socks_password_len)))
4558  return 0;
4559  if ((iso & ISO_CLIENTPROTO) &&
4560  (conn->socks_request->listener_type != circ->client_proto_type ||
4561  conn->socks_request->socks_version != circ->client_proto_socksver))
4562  return 0;
4563  if ((iso & ISO_CLIENTADDR) &&
4564  !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4565  return 0;
4566  if ((iso & ISO_SESSIONGRP) &&
4567  conn->entry_cfg.session_group != circ->session_group)
4568  return 0;
4569  if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
4570  return 0;
4571 
4572  return 1;
4573 }
4574 
4575 /**
4576  * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
4577  * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
4578  * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
4579  * a bitfield of isolation flags that we would have to set in
4580  * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
4581  * <b>circ</b> has had no streams attached to it.
4582  */
4583 int
4585  origin_circuit_t *circ,
4586  int dry_run)
4587 {
4588  const socks_request_t *sr = conn->socks_request;
4589  if (! conn->original_dest_address) {
4590  log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
4591  "having set conn->original_dest_address");
4592  ((entry_connection_t*)conn)->original_dest_address =
4593  tor_strdup(conn->socks_request->address);
4594  }
4595 
4596  if (!circ->isolation_values_set) {
4597  if (dry_run)
4598  return -1;
4600  ENTRY_TO_CONN(conn)->global_identifier;
4601  circ->dest_port = conn->socks_request->port;
4602  circ->dest_address = tor_strdup(conn->original_dest_address);
4603  circ->client_proto_type = conn->socks_request->listener_type;
4604  circ->client_proto_socksver = conn->socks_request->socks_version;
4605  tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
4606  circ->session_group = conn->entry_cfg.session_group;
4607  circ->nym_epoch = conn->nym_epoch;
4608  circ->socks_username = sr->username ?
4609  tor_memdup(sr->username, sr->usernamelen) : NULL;
4610  circ->socks_password = sr->password ?
4611  tor_memdup(sr->password, sr->passwordlen) : NULL;
4612  circ->socks_username_len = sr->usernamelen;
4613  circ->socks_password_len = sr->passwordlen;
4614 
4615  circ->isolation_values_set = 1;
4616  return 0;
4617  } else {
4618  uint8_t mixed = 0;
4619  if (conn->socks_request->port != circ->dest_port)
4620  mixed |= ISO_DESTPORT;
4621  if (strcasecmp(conn->original_dest_address, circ->dest_address))
4622  mixed |= ISO_DESTADDR;
4623  if (!memeq_opt(sr->username, sr->usernamelen,
4624  circ->socks_username, circ->socks_username_len) ||
4625  !memeq_opt(sr->password, sr->passwordlen,
4626  circ->socks_password, circ->socks_password_len))
4627  mixed |= ISO_SOCKSAUTH;
4628  if ((conn->socks_request->listener_type != circ->client_proto_type ||
4629  conn->socks_request->socks_version != circ->client_proto_socksver))
4630  mixed |= ISO_CLIENTPROTO;
4631  if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4632  mixed |= ISO_CLIENTADDR;
4633  if (conn->entry_cfg.session_group != circ->session_group)
4634  mixed |= ISO_SESSIONGRP;
4635  if (conn->nym_epoch != circ->nym_epoch)
4636  mixed |= ISO_NYM_EPOCH;
4637 
4638  if (dry_run)
4639  return mixed;
4640 
4641  if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
4642  log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
4643  "isolation flags.");
4644  }
4645  circ->isolation_flags_mixed |= mixed;
4646  return 0;
4647  }
4648 }
4649 
4650 /**
4651  * Clear the isolation settings on <b>circ</b>.
4652  *
4653  * This only works on an open circuit that has never had a stream attached to
4654  * it, and whose isolation settings are hypothetical. (We set hypothetical
4655  * isolation settings on circuits as we're launching them, so that we
4656  * know whether they can handle more streams or whether we need to launch
4657  * even more circuits. Once the circuit is open, if it turns out that
4658  * we no longer have any streams to attach to it, we clear the isolation flags
4659  * and data so that other streams can have a chance.)
4660  */
4661 void
4663 {
4664  if (circ->isolation_any_streams_attached) {
4665  log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
4666  return;
4667  }
4668  if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
4669  log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
4670  "circuit");
4671  return;
4672  }
4673 
4674  circ->isolation_values_set = 0;
4675  circ->isolation_flags_mixed = 0;
4677  circ->client_proto_type = 0;
4678  circ->client_proto_socksver = 0;
4679  circ->dest_port = 0;
4680  tor_addr_make_unspec(&circ->client_addr);
4681  tor_free(circ->dest_address);
4682  circ->session_group = -1;
4683  circ->nym_epoch = 0;
4684  if (circ->socks_username) {
4685  memwipe(circ->socks_username, 0x11, circ->socks_username_len);
4686  tor_free(circ->socks_username);
4687  }
4688  if (circ->socks_password) {
4689  memwipe(circ->socks_password, 0x05, circ->socks_password_len);
4690  tor_free(circ->socks_password);
4691  }
4692  circ->socks_username_len = circ->socks_password_len = 0;
4693 }
4694 
4695 /** Send an END and mark for close the given edge connection conn using the
4696  * given reason that has to be a stream reason.
4697  *
4698  * Note: We don't unattached the AP connection (if applicable) because we
4699  * don't want to flush the remaining data. This function aims at ending
4700  * everything quickly regardless of the connection state.
4701  *
4702  * This function can't fail and does nothing if conn is NULL. */
4703 void
4705 {
4706  if (!conn) {
4707  return;
4708  }
4709 
4710  connection_edge_end(conn, reason);
4711  connection_mark_for_close(TO_CONN(conn));
4712 }
4713 
4714 /** Free all storage held in module-scoped variables for connection_edge.c */
4715 void
4717 {
4718  untried_pending_connections = 0;
4719  smartlist_free(pending_entry_connections);
4721  mainloop_event_free(attach_pending_entry_connections_ev);
4722 }
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:3806
connection_edge_free_all
void connection_edge_free_all(void)
Definition: connection_edge.c:4716
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:3974
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:732
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:142
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:548
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:932
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:2882
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:4514
connection_ap_fail_onehop
void connection_ap_fail_onehop(const char *failed_digest, cpath_build_state_t *build_state)
Definition: connection_edge.c:1472
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:3896
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:3024
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:4430
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:3544
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:1513
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:122
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:1559
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:2767
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:2226
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:352
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:1651
conn_state_to_string
const char * conn_state_to_string(int type, int state)
Definition: connection.c:297
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:4218
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:259
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:1617
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:1462
HS_CIRCUIT_ID_PROTOCOL_HAPROXY
@ HS_CIRCUIT_ID_PROTOCOL_HAPROXY
Definition: hs_service.h:192
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:1004
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:3174
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:2031
or_options_t::LeaveStreamsUnattached
int LeaveStreamsUnattached
Definition: or_options_st.h:538
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:146
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:974
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:684
rend_data_dup
rend_data_t * rend_data_dup(const rend_data_t *data)
Definition: hs_common.c:387
extend_info_describe
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:202
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:3513
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:175
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:3695
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 subsytem.
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:3816
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:1120
crypto_util.h
Common functions for cryptographic routines.
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:1257
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:2804
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:1386
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:4704
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:3866
control_event_client_status
int control_event_client_status(int severity, const char *format,...)
Definition: control_events.c:1758
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:376
connection_ap_mark_as_waiting_for_renddesc
void connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
Definition: connection_edge.c:1445
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:4496
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:1960
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:372
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:515
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:171
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:1606
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:2927
connection_ap_handshake_send_resolve
int connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
Definition: connection_edge.c:3356
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:829
relay_header_unpack
void relay_header_unpack(relay_header_t *dest, const uint8_t *src)
Definition: relay.c:490
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:1304
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:187
should_refuse_unknown_exits
int should_refuse_unknown_exits(const or_options_t *options)
Definition: router.c:1342
connection_ap_handshake_attach_circuit
int connection_ap_handshake_attach_circuit(entry_connection_t *conn)
Definition: circuituse.c:2852
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:2825
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:589
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:1033
connection_exit_connect_dir
static int connection_exit_connect_dir(edge_connection_t *exitconn)
Definition: connection_edge.c:4352
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:2301
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:4584
command
tor_cmdline_mode_t command
Definition: config.c:2448
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:2166
get_unique_stream_id_by_circ
streamid_t get_unique_stream_id_by_circ(origin_circuit_t *circ)
Definition: connection_edge.c:3126
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:3237
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:608
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:680
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:2054
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:950
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:731
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:929
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:4662
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:4928
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:1574
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:4412
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:2145
connection_exit_begin_resolve
int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
Definition: connection_edge.c:4170
extend_info_st.h
Extend-info structure.
node_describe
const char * node_describe(const node_t *node)
Definition: describe.c:142
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:2367
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:824
hs_common.h
Header file containing common data for the whole HS subsytem.
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:530
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:393
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:404
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:3446
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:3191
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:494
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:4240
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:1857
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:786
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:529
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:1745
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:748
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:1430
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:3582
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:2857
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:1132
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:958
or_options_t::TestSocks
int TestSocks
Definition: or_options_st.h:565
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:3146
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:2824
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:2887
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 subsytem.
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:1655
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:1498
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:1066
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.
circuit_t::state
uint8_t state
Definition: circuit_st.h:110
mainloop_event_postloop_new
mainloop_event_t * mainloop_event_postloop_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
Definition: compat_libevent.c:410
tor_addr_port_split
int tor_addr_port_split(int severity, const char *addrport, char **address_out, uint16_t *