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