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