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