Bug 29085: Refactor non-padding accounting out of token removal.
[tor.git] / src / core / or / connection_edge.c
blob8ed40345606a1a40eacbf610eeaad0d4213f4f60
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 */
7 /**
8 * \file connection_edge.c
9 * \brief Handle edge streams.
11 * An edge_connection_t is a subtype of a connection_t, and represents two
12 * critical concepts in Tor: a stream, and an edge connection. From the Tor
13 * protocol's point of view, a stream is a bi-directional channel that is
14 * multiplexed on a single circuit. Each stream on a circuit is identified
15 * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
16 * Streams are created in response to client requests.
18 * An edge connection is one thing that can implement a stream: it is either a
19 * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
20 * exit connection.
22 * Not every instance of edge_connection_t truly represents an edge connction,
23 * however. (Sorry!) We also create edge_connection_t objects for streams that
24 * we will not be handling with TCP. The types of these streams are:
25 * <ul>
26 * <li>DNS lookup streams, created on the client side in response to
27 * a UDP DNS request received on a DNSPort, or a RESOLVE command
28 * on a controller.
29 * <li>DNS lookup streams, created on the exit side in response to
30 * a RELAY_RESOLVE cell from a client.
31 * <li>Tunneled directory streams, created on the directory cache side
32 * in response to a RELAY_BEGIN_DIR cell. These streams attach directly
33 * to a dir_connection_t object without ever using TCP.
34 * </ul>
36 * This module handles general-purpose functionality having to do with
37 * edge_connection_t. On the client side, it accepts various types of
38 * application requests on SocksPorts, TransPorts, and NATDPorts, and
39 * creates streams appropriately.
41 * This module is also responsible for implementing stream isolation:
42 * ensuring that streams that should not be linkable to one another are
43 * kept to different circuits.
45 * On the exit side, this module handles the various stream-creating
46 * type of RELAY cells by launching appropriate outgoing connections,
47 * DNS requests, or directory connection objects.
49 * And for all edge connections, this module is responsible for handling
50 * incoming and outdoing data as it arrives or leaves in the relay.c
51 * module. (Outgoing data will be packaged in
52 * connection_edge_process_inbuf() as it calls
53 * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
54 * cells is applied in connection_edge_process_relay_cell().)
55 **/
56 #define CONNECTION_EDGE_PRIVATE
58 #include "core/or/or.h"
60 #include "lib/err/backtrace.h"
62 #include "app/config/config.h"
63 #include "core/mainloop/connection.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"
71 #include "core/or/connection_edge.h"
72 #include "core/or/connection_or.h"
73 #include "core/or/policies.h"
74 #include "core/or/reasons.h"
75 #include "core/or/relay.h"
76 #include "core/or/sendme.h"
77 #include "core/proto/proto_http.h"
78 #include "core/proto/proto_socks.h"
79 #include "feature/client/addressmap.h"
80 #include "feature/client/circpathbias.h"
81 #include "feature/client/dnsserv.h"
82 #include "feature/control/control_events.h"
83 #include "feature/dircache/dirserv.h"
84 #include "feature/dircommon/directory.h"
85 #include "feature/hibernate/hibernate.h"
86 #include "feature/hs/hs_cache.h"
87 #include "feature/hs/hs_circuit.h"
88 #include "feature/hs/hs_client.h"
89 #include "feature/hs/hs_common.h"
90 #include "feature/nodelist/describe.h"
91 #include "feature/nodelist/networkstatus.h"
92 #include "feature/nodelist/nodelist.h"
93 #include "feature/nodelist/routerlist.h"
94 #include "feature/nodelist/routerset.h"
95 #include "feature/relay/dns.h"
96 #include "feature/relay/router.h"
97 #include "feature/relay/routermode.h"
98 #include "feature/rend/rendclient.h"
99 #include "feature/rend/rendcommon.h"
100 #include "feature/rend/rendservice.h"
101 #include "feature/stats/predict_ports.h"
102 #include "feature/stats/rephist.h"
103 #include "lib/buf/buffers.h"
104 #include "lib/crypt_ops/crypto_util.h"
106 #include "core/or/cell_st.h"
107 #include "core/or/cpath_build_state_st.h"
108 #include "feature/dircommon/dir_connection_st.h"
109 #include "core/or/entry_connection_st.h"
110 #include "core/or/extend_info_st.h"
111 #include "feature/nodelist/node_st.h"
112 #include "core/or/or_circuit_st.h"
113 #include "core/or/origin_circuit_st.h"
114 #include "core/or/half_edge_st.h"
115 #include "core/or/socks_request_st.h"
116 #include "lib/evloop/compat_libevent.h"
118 #ifdef HAVE_LINUX_TYPES_H
119 #include <linux/types.h>
120 #endif
121 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
122 #include <linux/netfilter_ipv4.h>
123 #define TRANS_NETFILTER
124 #define TRANS_NETFILTER_IPV4
125 #endif
127 #ifdef HAVE_LINUX_IF_H
128 #include <linux/if.h>
129 #endif
131 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
132 #include <linux/netfilter_ipv6/ip6_tables.h>
133 #if defined(IP6T_SO_ORIGINAL_DST)
134 #define TRANS_NETFILTER
135 #define TRANS_NETFILTER_IPV6
136 #endif
137 #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
139 #ifdef HAVE_FCNTL_H
140 #include <fcntl.h>
141 #endif
142 #ifdef HAVE_SYS_IOCTL_H
143 #include <sys/ioctl.h>
144 #endif
145 #ifdef HAVE_SYS_PARAM_H
146 #include <sys/param.h>
147 #endif
149 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
150 #include <net/if.h>
151 #include <net/pfvar.h>
152 #define TRANS_PF
153 #endif
155 #ifdef IP_TRANSPARENT
156 #define TRANS_TPROXY
157 #endif
159 #define SOCKS4_GRANTED 90
160 #define SOCKS4_REJECT 91
162 static int connection_ap_handshake_process_socks(entry_connection_t *conn);
163 static int connection_ap_process_natd(entry_connection_t *conn);
164 static int connection_exit_connect_dir(edge_connection_t *exitconn);
165 static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
166 static int connection_ap_supports_optimistic_data(const entry_connection_t *);
168 /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
169 * invalid. */
170 edge_connection_t *
171 TO_EDGE_CONN(connection_t *c)
173 tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
174 c->magic == ENTRY_CONNECTION_MAGIC);
175 return DOWNCAST(edge_connection_t, c);
178 entry_connection_t *
179 TO_ENTRY_CONN(connection_t *c)
181 tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
182 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
185 entry_connection_t *
186 EDGE_TO_ENTRY_CONN(edge_connection_t *c)
188 tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
189 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
192 /** An AP stream has failed/finished. If it hasn't already sent back
193 * a socks reply, send one now (based on endreason). Also set
194 * has_sent_end to 1, and mark the conn.
196 MOCK_IMPL(void,
197 connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
198 int line, const char *file))
200 connection_t *base_conn = ENTRY_TO_CONN(conn);
201 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
202 tor_assert(base_conn->type == CONN_TYPE_AP);
203 ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
205 /* If this is a rendezvous stream and it is failing without ever
206 * being attached to a circuit, assume that an attempt to connect to
207 * the destination hidden service has just ended.
209 * XXXX This condition doesn't limit to only streams failing
210 * without ever being attached. That sloppiness should be harmless,
211 * but we should fix it someday anyway. */
212 if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
213 connection_edge_is_rendezvous_stream(edge_conn)) {
214 if (edge_conn->rend_data) {
215 rend_client_note_connection_attempt_ended(edge_conn->rend_data);
219 if (base_conn->marked_for_close) {
220 /* This call will warn as appropriate. */
221 connection_mark_for_close_(base_conn, line, file);
222 return;
225 if (!conn->socks_request->has_finished) {
226 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
227 log_warn(LD_BUG,
228 "stream (marked at %s:%d) sending two socks replies?",
229 file, line);
231 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
232 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
233 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
234 connection_ap_handshake_socks_resolved(conn,
235 RESOLVED_TYPE_ERROR_TRANSIENT,
236 0, NULL, -1, -1);
237 else /* unknown or no handshake at all. send no response. */
238 conn->socks_request->has_finished = 1;
241 connection_mark_and_flush_(base_conn, line, file);
243 ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
246 /** There was an EOF. Send an end and mark the connection for close.
249 connection_edge_reached_eof(edge_connection_t *conn)
251 if (connection_get_inbuf_len(TO_CONN(conn)) &&
252 connection_state_is_open(TO_CONN(conn))) {
253 /* it still has stuff to process. don't let it die yet. */
254 return 0;
256 log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
257 conn->base_.s);
258 if (!conn->base_.marked_for_close) {
259 /* only mark it if not already marked. it's possible to
260 * get the 'end' right around when the client hangs up on us. */
261 connection_edge_end(conn, END_STREAM_REASON_DONE);
262 if (conn->base_.type == CONN_TYPE_AP) {
263 /* eof, so don't send a socks reply back */
264 if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
265 EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
267 connection_mark_for_close(TO_CONN(conn));
269 return 0;
272 /** Handle new bytes on conn->inbuf based on state:
273 * - If it's waiting for socks info, try to read another step of the
274 * socks handshake out of conn->inbuf.
275 * - If it's waiting for the original destination, fetch it.
276 * - If it's open, then package more relay cells from the stream.
277 * - Else, leave the bytes on inbuf alone for now.
279 * Mark and return -1 if there was an unexpected error with the conn,
280 * else return 0.
283 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
285 tor_assert(conn);
287 switch (conn->base_.state) {
288 case AP_CONN_STATE_SOCKS_WAIT:
289 if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
290 /* already marked */
291 return -1;
293 return 0;
294 case AP_CONN_STATE_NATD_WAIT:
295 if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
296 /* already marked */
297 return -1;
299 return 0;
300 case AP_CONN_STATE_HTTP_CONNECT_WAIT:
301 if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn)) < 0) {
302 return -1;
304 return 0;
305 case AP_CONN_STATE_OPEN:
306 if (! conn->base_.linked) {
307 note_user_activity(approx_time());
310 /* falls through. */
311 case EXIT_CONN_STATE_OPEN:
312 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
313 /* (We already sent an end cell if possible) */
314 connection_mark_for_close(TO_CONN(conn));
315 return -1;
317 return 0;
318 case AP_CONN_STATE_CONNECT_WAIT:
319 if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
320 log_info(LD_EDGE,
321 "data from edge while in '%s' state. Sending it anyway. "
322 "package_partial=%d, buflen=%ld",
323 conn_state_to_string(conn->base_.type, conn->base_.state),
324 package_partial,
325 (long)connection_get_inbuf_len(TO_CONN(conn)));
326 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
327 /* (We already sent an end cell if possible) */
328 connection_mark_for_close(TO_CONN(conn));
329 return -1;
331 return 0;
333 /* Fall through if the connection is on a circuit without optimistic
334 * data support. */
335 /* Falls through. */
336 case EXIT_CONN_STATE_CONNECTING:
337 case AP_CONN_STATE_RENDDESC_WAIT:
338 case AP_CONN_STATE_CIRCUIT_WAIT:
339 case AP_CONN_STATE_RESOLVE_WAIT:
340 case AP_CONN_STATE_CONTROLLER_WAIT:
341 log_info(LD_EDGE,
342 "data from edge while in '%s' state. Leaving it on buffer.",
343 conn_state_to_string(conn->base_.type, conn->base_.state));
344 return 0;
346 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
347 tor_fragile_assert();
348 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
349 connection_mark_for_close(TO_CONN(conn));
350 return -1;
353 /** This edge needs to be closed, because its circuit has closed.
354 * Mark it for close and return 0.
357 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
359 if (!conn->base_.marked_for_close) {
360 log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
361 (unsigned) circ_id);
362 if (conn->base_.type == CONN_TYPE_AP) {
363 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
364 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
365 control_event_stream_bandwidth(conn);
366 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
367 END_STREAM_REASON_DESTROY);
368 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
369 } else {
370 /* closing the circuit, nothing to send an END to */
371 conn->edge_has_sent_end = 1;
372 conn->end_reason = END_STREAM_REASON_DESTROY;
373 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
374 connection_mark_and_flush(TO_CONN(conn));
377 conn->cpath_layer = NULL;
378 conn->on_circuit = NULL;
379 return 0;
382 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
383 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
384 * is not a client connection, set the relay end cell's reason for closing
385 * as <b>reason</b> */
386 static int
387 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
388 uint8_t reason, crypt_path_t *cpath_layer)
390 char payload[1];
392 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
393 /* Never send the server an informative reason code; it doesn't need to
394 * know why the client stream is failing. */
395 reason = END_STREAM_REASON_MISC;
398 payload[0] = (char) reason;
400 /* Note: we have to use relay_send_command_from_edge here, not
401 * connection_edge_end or connection_edge_send_command, since those require
402 * that we have a stream connected to a circuit, and we don't connect to a
403 * circuit until we have a pending/successful resolve. */
404 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
405 payload, 1, cpath_layer);
408 /* If the connection <b>conn</b> is attempting to connect to an external
409 * destination that is an hidden service and the reason is a connection
410 * refused or timeout, log it so the operator can take appropriate actions.
411 * The log statement is a rate limited warning. */
412 static void
413 warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
415 tor_assert(conn);
417 if (conn->base_.type == CONN_TYPE_EXIT &&
418 connection_edge_is_rendezvous_stream(conn) &&
419 (reason == END_STREAM_REASON_CONNECTREFUSED ||
420 reason == END_STREAM_REASON_TIMEOUT)) {
421 #define WARN_FAILED_HS_CONNECTION 300
422 static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
423 char *m;
424 if ((m = rate_limit_log(&warn_limit, approx_time()))) {
425 log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
426 (conn->base_.socket_family == AF_UNIX) ?
427 safe_str(conn->base_.address) :
428 safe_str(fmt_addrport(&conn->base_.addr, conn->base_.port)),
429 stream_end_reason_to_string(reason));
430 tor_free(m);
435 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
436 * remember that we've done so. If this is not a client connection, set the
437 * relay end cell's reason for closing as <b>reason</b>.
439 * Return -1 if this function has already been called on this conn,
440 * else return 0.
443 connection_edge_end(edge_connection_t *conn, uint8_t reason)
445 char payload[RELAY_PAYLOAD_SIZE];
446 size_t payload_len=1;
447 circuit_t *circ;
448 uint8_t control_reason = reason;
450 if (conn->edge_has_sent_end) {
451 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
452 "on an already ended stream?", reason);
453 tor_fragile_assert();
454 return -1;
457 if (conn->base_.marked_for_close) {
458 log_warn(LD_BUG,
459 "called on conn that's already marked for close at %s:%d.",
460 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
461 return 0;
464 circ = circuit_get_by_edge_conn(conn);
465 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
466 /* If this is a client circuit, don't send the server an informative
467 * reason code; it doesn't need to know why the client stream is
468 * failing. */
469 reason = END_STREAM_REASON_MISC;
472 payload[0] = (char)reason;
473 if (reason == END_STREAM_REASON_EXITPOLICY &&
474 !connection_edge_is_rendezvous_stream(conn)) {
475 int addrlen;
476 if (tor_addr_family(&conn->base_.addr) == AF_INET) {
477 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
478 addrlen = 4;
479 } else {
480 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
481 addrlen = 16;
483 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
484 payload_len += 4+addrlen;
487 if (circ && !circ->marked_for_close) {
488 log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
489 conn->base_.s);
491 if (CIRCUIT_IS_ORIGIN(circ)) {
492 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
493 connection_half_edge_add(conn, origin_circ);
496 connection_edge_send_command(conn, RELAY_COMMAND_END,
497 payload, payload_len);
498 /* We'll log warn if the connection was an hidden service and couldn't be
499 * made because the service wasn't available. */
500 warn_if_hs_unreachable(conn, control_reason);
501 } else {
502 log_debug(LD_EDGE,"No circ to send end on conn "
503 "(fd "TOR_SOCKET_T_FORMAT").",
504 conn->base_.s);
507 conn->edge_has_sent_end = 1;
508 conn->end_reason = control_reason;
509 return 0;
513 * Helper function for bsearch.
515 * As per smartlist_bsearch, return < 0 if key preceeds member,
516 * > 0 if member preceeds key, and 0 if they are equal.
518 * This is equivalent to subtraction of the values of key - member
519 * (why does no one ever say that explicitly?).
521 static int
522 connection_half_edge_compare_bsearch(const void *key, const void **member)
524 const half_edge_t *e2;
525 tor_assert(key);
526 tor_assert(member && *(half_edge_t**)member);
527 e2 = *(const half_edge_t **)member;
529 return *(const streamid_t*)key - e2->stream_id;
532 /** Total number of half_edge_t objects allocated */
533 static size_t n_half_conns_allocated = 0;
536 * Add a half-closed connection to the list, to watch for activity.
538 * These connections are removed from the list upon receiving an end
539 * cell.
541 STATIC void
542 connection_half_edge_add(const edge_connection_t *conn,
543 origin_circuit_t *circ)
545 half_edge_t *half_conn = NULL;
546 int insert_at = 0;
547 int ignored;
549 /* Double-check for re-insertion. This should not happen,
550 * but this check is cheap compared to the sort anyway */
551 if (connection_half_edge_find_stream_id(circ->half_streams,
552 conn->stream_id)) {
553 log_warn(LD_BUG, "Duplicate stream close for stream %d on circuit %d",
554 conn->stream_id, circ->global_identifier);
555 return;
558 half_conn = tor_malloc_zero(sizeof(half_edge_t));
559 ++n_half_conns_allocated;
561 if (!circ->half_streams) {
562 circ->half_streams = smartlist_new();
565 half_conn->stream_id = conn->stream_id;
567 // How many sendme's should I expect?
568 half_conn->sendmes_pending =
569 (STREAMWINDOW_START-conn->package_window)/STREAMWINDOW_INCREMENT;
571 // Is there a connected cell pending?
572 half_conn->connected_pending = conn->base_.state ==
573 AP_CONN_STATE_CONNECT_WAIT;
575 /* Data should only arrive if we're not waiting on a resolved cell.
576 * It can arrive after waiting on connected, because of optimistic
577 * data. */
578 if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
579 // How many more data cells can arrive on this id?
580 half_conn->data_pending = conn->deliver_window;
583 insert_at = smartlist_bsearch_idx(circ->half_streams, &half_conn->stream_id,
584 connection_half_edge_compare_bsearch,
585 &ignored);
586 smartlist_insert(circ->half_streams, insert_at, half_conn);
589 /** Release space held by <b>he</b> */
590 void
591 half_edge_free_(half_edge_t *he)
593 if (!he)
594 return;
595 --n_half_conns_allocated;
596 tor_free(he);
599 /** Return the number of bytes devoted to storing info on half-open streams. */
600 size_t
601 half_streams_get_total_allocation(void)
603 return n_half_conns_allocated * sizeof(half_edge_t);
607 * Find a stream_id_t in the list in O(lg(n)).
609 * Returns NULL if the list is empty or element is not found.
610 * Returns a pointer to the element if found.
612 STATIC half_edge_t *
613 connection_half_edge_find_stream_id(const smartlist_t *half_conns,
614 streamid_t stream_id)
616 if (!half_conns)
617 return NULL;
619 return smartlist_bsearch(half_conns, &stream_id,
620 connection_half_edge_compare_bsearch);
624 * Check if this stream_id is in a half-closed state. If so,
625 * check if it still has data cells pending, and decrement that
626 * window if so.
628 * Return 1 if the data window was not empty.
629 * Return 0 otherwise.
632 connection_half_edge_is_valid_data(const smartlist_t *half_conns,
633 streamid_t stream_id)
635 half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
636 stream_id);
638 if (!half)
639 return 0;
641 if (half->data_pending > 0) {
642 half->data_pending--;
643 return 1;
646 return 0;
650 * Check if this stream_id is in a half-closed state. If so,
651 * check if it still has a connected cell pending, and decrement
652 * that window if so.
654 * Return 1 if the connected window was not empty.
655 * Return 0 otherwise.
658 connection_half_edge_is_valid_connected(const smartlist_t *half_conns,
659 streamid_t stream_id)
661 half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
662 stream_id);
664 if (!half)
665 return 0;
667 if (half->connected_pending) {
668 half->connected_pending = 0;
669 return 1;
672 return 0;
676 * Check if this stream_id is in a half-closed state. If so,
677 * check if it still has sendme cells pending, and decrement that
678 * window if so.
680 * Return 1 if the sendme window was not empty.
681 * Return 0 otherwise.
684 connection_half_edge_is_valid_sendme(const smartlist_t *half_conns,
685 streamid_t stream_id)
687 half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
688 stream_id);
690 if (!half)
691 return 0;
693 if (half->sendmes_pending > 0) {
694 half->sendmes_pending--;
695 return 1;
698 return 0;
702 * Check if this stream_id is in a half-closed state. If so, remove
703 * it from the list. No other data should come after the END cell.
705 * Return 1 if stream_id was in half-closed state.
706 * Return 0 otherwise.
709 connection_half_edge_is_valid_end(smartlist_t *half_conns,
710 streamid_t stream_id)
712 half_edge_t *half;
713 int found, remove_idx;
715 if (!half_conns)
716 return 0;
718 remove_idx = smartlist_bsearch_idx(half_conns, &stream_id,
719 connection_half_edge_compare_bsearch,
720 &found);
721 if (!found)
722 return 0;
724 half = smartlist_get(half_conns, remove_idx);
725 smartlist_del_keeporder(half_conns, remove_idx);
726 half_edge_free(half);
727 return 1;
731 * Streams that were used to send a RESOLVE cell are closed
732 * when they get the RESOLVED, without an end. So treat
733 * a RESOLVED just like an end, and remove from the list.
736 connection_half_edge_is_valid_resolved(smartlist_t *half_conns,
737 streamid_t stream_id)
739 return connection_half_edge_is_valid_end(half_conns, stream_id);
742 /** An error has just occurred on an operation on an edge connection
743 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
744 * appropriate relay end cell to the other end of the connection's circuit.
747 connection_edge_end_errno(edge_connection_t *conn)
749 uint8_t reason;
750 tor_assert(conn);
751 reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
752 return connection_edge_end(conn, reason);
755 /** We just wrote some data to <b>conn</b>; act appropriately.
757 * (That is, if it's open, consider sending a stream-level sendme cell if we
758 * have just flushed enough.)
761 connection_edge_flushed_some(edge_connection_t *conn)
763 switch (conn->base_.state) {
764 case AP_CONN_STATE_OPEN:
765 if (! conn->base_.linked) {
766 note_user_activity(approx_time());
769 /* falls through. */
770 case EXIT_CONN_STATE_OPEN:
771 sendme_connection_edge_consider_sending(conn);
772 break;
774 return 0;
777 /** Connection <b>conn</b> has finished writing and has no bytes left on
778 * its outbuf.
780 * If it's in state 'open', stop writing, consider responding with a
781 * sendme, and return.
782 * Otherwise, stop writing and return.
784 * If <b>conn</b> is broken, mark it for close and return -1, else
785 * return 0.
788 connection_edge_finished_flushing(edge_connection_t *conn)
790 tor_assert(conn);
792 switch (conn->base_.state) {
793 case AP_CONN_STATE_OPEN:
794 case EXIT_CONN_STATE_OPEN:
795 sendme_connection_edge_consider_sending(conn);
796 return 0;
797 case AP_CONN_STATE_SOCKS_WAIT:
798 case AP_CONN_STATE_NATD_WAIT:
799 case AP_CONN_STATE_RENDDESC_WAIT:
800 case AP_CONN_STATE_CIRCUIT_WAIT:
801 case AP_CONN_STATE_CONNECT_WAIT:
802 case AP_CONN_STATE_CONTROLLER_WAIT:
803 case AP_CONN_STATE_RESOLVE_WAIT:
804 case AP_CONN_STATE_HTTP_CONNECT_WAIT:
805 return 0;
806 default:
807 log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
808 tor_fragile_assert();
809 return -1;
811 return 0;
814 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
815 * able to generate. */
816 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
817 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
819 /** Set the buffer at <b>payload_out</b> -- which must have at least
820 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
821 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
822 * that the name resolution that led us to <b>addr</b> will be valid for
823 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
824 * success. */
825 STATIC int
826 connected_cell_format_payload(uint8_t *payload_out,
827 const tor_addr_t *addr,
828 uint32_t ttl)
830 const sa_family_t family = tor_addr_family(addr);
831 int connected_payload_len;
833 /* should be needless */
834 memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
836 if (family == AF_INET) {
837 set_uint32(payload_out, tor_addr_to_ipv4n(addr));
838 connected_payload_len = 4;
839 } else if (family == AF_INET6) {
840 set_uint32(payload_out, 0);
841 set_uint8(payload_out + 4, 6);
842 memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
843 connected_payload_len = 21;
844 } else {
845 return -1;
848 set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
849 connected_payload_len += 4;
851 tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
853 return connected_payload_len;
856 /* This is an onion service client connection: Export the client circuit ID
857 * according to the HAProxy proxy protocol. */
858 STATIC void
859 export_hs_client_circuit_id(edge_connection_t *edge_conn,
860 hs_circuit_id_protocol_t protocol)
862 /* We only support HAProxy right now. */
863 if (protocol != HS_CIRCUIT_ID_PROTOCOL_HAPROXY)
864 return;
866 char *buf = NULL;
867 const char dst_ipv6[] = "::1";
868 /* See RFC4193 regarding fc00::/7 */
869 const char src_ipv6_prefix[] = "fc00:dead:beef:4dad:";
870 uint16_t dst_port = 0;
871 uint16_t src_port = 1; /* default value */
872 uint32_t gid = 0; /* default value */
874 /* Generate a GID and source port for this client */
875 if (edge_conn->on_circuit != NULL) {
876 gid = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit)->global_identifier;
877 src_port = gid & 0x0000ffff;
880 /* Grab the original dest port from the hs ident */
881 if (edge_conn->hs_ident) {
882 dst_port = edge_conn->hs_ident->orig_virtual_port;
885 /* Build the string */
886 tor_asprintf(&buf, "PROXY TCP6 %s:%x:%x %s %d %d\r\n",
887 src_ipv6_prefix,
888 gid >> 16, gid & 0x0000ffff,
889 dst_ipv6, src_port, dst_port);
891 connection_buf_add(buf, strlen(buf), TO_CONN(edge_conn));
893 tor_free(buf);
896 /** Connected handler for exit connections: start writing pending
897 * data, deliver 'CONNECTED' relay cells as appropriate, and check
898 * any pending data that may have been received. */
900 connection_edge_finished_connecting(edge_connection_t *edge_conn)
902 connection_t *conn;
904 tor_assert(edge_conn);
905 tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
906 conn = TO_CONN(edge_conn);
907 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
909 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
910 escaped_safe_str(conn->address), conn->port,
911 safe_str(fmt_and_decorate_addr(&conn->addr)));
913 rep_hist_note_exit_stream_opened(conn->port);
915 conn->state = EXIT_CONN_STATE_OPEN;
917 connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
918 if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
919 * cells */
920 connection_start_writing(conn);
921 /* deliver a 'connected' relay cell back through the circuit. */
922 if (connection_edge_is_rendezvous_stream(edge_conn)) {
923 if (connection_edge_send_command(edge_conn,
924 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
925 return 0; /* circuit is closed, don't continue */
926 } else {
927 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
928 int connected_payload_len =
929 connected_cell_format_payload(connected_payload, &conn->addr,
930 edge_conn->address_ttl);
931 if (connected_payload_len < 0)
932 return -1;
934 if (connection_edge_send_command(edge_conn,
935 RELAY_COMMAND_CONNECTED,
936 (char*)connected_payload, connected_payload_len) < 0)
937 return 0; /* circuit is closed, don't continue */
939 tor_assert(edge_conn->package_window > 0);
940 /* in case the server has written anything */
941 return connection_edge_process_inbuf(edge_conn, 1);
944 /** A list of all the entry_connection_t * objects that are not marked
945 * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
947 * (Right now, we check in several places to make sure that this list is
948 * correct. When it's incorrect, we'll fix it, and log a BUG message.)
950 static smartlist_t *pending_entry_connections = NULL;
952 static int untried_pending_connections = 0;
955 * Mainloop event to tell us to scan for pending connections that can
956 * be attached.
958 static mainloop_event_t *attach_pending_entry_connections_ev = NULL;
960 /** Common code to connection_(ap|exit)_about_to_close. */
961 static void
962 connection_edge_about_to_close(edge_connection_t *edge_conn)
964 if (!edge_conn->edge_has_sent_end) {
965 connection_t *conn = TO_CONN(edge_conn);
966 log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
967 "hasn't sent end yet?",
968 conn->marked_for_close_file, conn->marked_for_close);
969 tor_fragile_assert();
973 /** Called when we're about to finally unlink and free an AP (client)
974 * connection: perform necessary accounting and cleanup */
975 void
976 connection_ap_about_to_close(entry_connection_t *entry_conn)
978 circuit_t *circ;
979 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
980 connection_t *conn = ENTRY_TO_CONN(entry_conn);
982 connection_edge_about_to_close(edge_conn);
984 if (entry_conn->socks_request->has_finished == 0) {
985 /* since conn gets removed right after this function finishes,
986 * there's no point trying to send back a reply at this point. */
987 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
988 " back a socks reply.",
989 conn->marked_for_close_file, conn->marked_for_close);
991 if (!edge_conn->end_reason) {
992 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
993 " set end_reason.",
994 conn->marked_for_close_file, conn->marked_for_close);
996 if (entry_conn->dns_server_request) {
997 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
998 " replied to DNS request.",
999 conn->marked_for_close_file, conn->marked_for_close);
1000 dnsserv_reject_request(entry_conn);
1003 if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1004 smartlist_remove(pending_entry_connections, entry_conn);
1007 #if 1
1008 /* Check to make sure that this isn't in pending_entry_connections if it
1009 * didn't actually belong there. */
1010 if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
1011 connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
1012 "about_to_close");
1014 #endif /* 1 */
1016 control_event_stream_bandwidth(edge_conn);
1017 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
1018 edge_conn->end_reason);
1019 circ = circuit_get_by_edge_conn(edge_conn);
1020 if (circ)
1021 circuit_detach_stream(circ, edge_conn);
1024 /** Called when we're about to finally unlink and free an exit
1025 * connection: perform necessary accounting and cleanup */
1026 void
1027 connection_exit_about_to_close(edge_connection_t *edge_conn)
1029 circuit_t *circ;
1030 connection_t *conn = TO_CONN(edge_conn);
1032 connection_edge_about_to_close(edge_conn);
1034 circ = circuit_get_by_edge_conn(edge_conn);
1035 if (circ)
1036 circuit_detach_stream(circ, edge_conn);
1037 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
1038 connection_dns_remove(edge_conn);
1042 /** Define a schedule for how long to wait between retrying
1043 * application connections. Rather than waiting a fixed amount of
1044 * time between each retry, we wait 10 seconds each for the first
1045 * two tries, and 15 seconds for each retry after
1046 * that. Hopefully this will improve the expected user experience. */
1047 static int
1048 compute_retry_timeout(entry_connection_t *conn)
1050 int timeout = get_options()->CircuitStreamTimeout;
1051 if (timeout) /* if our config options override the default, use them */
1052 return timeout;
1053 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
1054 return 10;
1055 return 15;
1058 /** Find all general-purpose AP streams waiting for a response that sent their
1059 * begin/resolve cell too long ago. Detach from their current circuit, and
1060 * mark their current circuit as unsuitable for new streams. Then call
1061 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
1062 * available) or launch a new one.
1064 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
1065 * retry attempt).
1067 void
1068 connection_ap_expire_beginning(void)
1070 edge_connection_t *conn;
1071 entry_connection_t *entry_conn;
1072 circuit_t *circ;
1073 time_t now = time(NULL);
1074 const or_options_t *options = get_options();
1075 int severity;
1076 int cutoff;
1077 int seconds_idle, seconds_since_born;
1078 smartlist_t *conns = get_connection_array();
1080 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1081 if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
1082 continue;
1083 entry_conn = TO_ENTRY_CONN(base_conn);
1084 conn = ENTRY_TO_EDGE_CONN(entry_conn);
1085 /* if it's an internal linked connection, don't yell its status. */
1086 severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
1087 ? LOG_INFO : LOG_NOTICE;
1088 seconds_idle = (int)( now - base_conn->timestamp_last_read_allowed );
1089 seconds_since_born = (int)( now - base_conn->timestamp_created );
1091 if (base_conn->state == AP_CONN_STATE_OPEN)
1092 continue;
1094 /* We already consider SocksTimeout in
1095 * connection_ap_handshake_attach_circuit(), but we need to consider
1096 * it here too because controllers that put streams in controller_wait
1097 * state never ask Tor to attach the circuit. */
1098 if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
1099 if (seconds_since_born >= options->SocksTimeout) {
1100 log_fn(severity, LD_APP,
1101 "Tried for %d seconds to get a connection to %s:%d. "
1102 "Giving up. (%s)",
1103 seconds_since_born,
1104 safe_str_client(entry_conn->socks_request->address),
1105 entry_conn->socks_request->port,
1106 conn_state_to_string(CONN_TYPE_AP, base_conn->state));
1107 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1109 continue;
1112 /* We're in state connect_wait or resolve_wait now -- waiting for a
1113 * reply to our relay cell. See if we want to retry/give up. */
1115 cutoff = compute_retry_timeout(entry_conn);
1116 if (seconds_idle < cutoff)
1117 continue;
1118 circ = circuit_get_by_edge_conn(conn);
1119 if (!circ) { /* it's vanished? */
1120 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
1121 safe_str_client(entry_conn->socks_request->address));
1122 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1123 continue;
1125 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
1126 if (seconds_idle >= options->SocksTimeout) {
1127 log_fn(severity, LD_REND,
1128 "Rend stream is %d seconds late. Giving up on address"
1129 " '%s.onion'.",
1130 seconds_idle,
1131 safe_str_client(entry_conn->socks_request->address));
1132 /* Roll back path bias use state so that we probe the circuit
1133 * if nothing else succeeds on it */
1134 pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
1136 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1137 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1139 continue;
1142 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1143 circ->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
1144 circ->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
1145 circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
1146 circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
1147 log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
1148 "The purpose on the circuit was %s; it was in state %s, "
1149 "path_state %s.",
1150 circuit_purpose_to_string(circ->purpose),
1151 circuit_state_to_string(circ->state),
1152 CIRCUIT_IS_ORIGIN(circ) ?
1153 pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
1154 "none");
1156 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
1157 "We tried for %d seconds to connect to '%s' using exit %s."
1158 " Retrying on a new circuit.",
1159 seconds_idle,
1160 safe_str_client(entry_conn->socks_request->address),
1161 conn->cpath_layer ?
1162 extend_info_describe(conn->cpath_layer->extend_info):
1163 "*unnamed*");
1164 /* send an end down the circuit */
1165 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1166 /* un-mark it as ending, since we're going to reuse it */
1167 conn->edge_has_sent_end = 0;
1168 conn->end_reason = 0;
1169 /* make us not try this circuit again, but allow
1170 * current streams on it to survive if they can */
1171 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
1173 /* give our stream another 'cutoff' seconds to try */
1174 conn->base_.timestamp_last_read_allowed += cutoff;
1175 if (entry_conn->num_socks_retries < 250) /* avoid overflow */
1176 entry_conn->num_socks_retries++;
1177 /* move it back into 'pending' state, and try to attach. */
1178 if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
1179 END_STREAM_REASON_TIMEOUT)<0) {
1180 if (!base_conn->marked_for_close)
1181 connection_mark_unattached_ap(entry_conn,
1182 END_STREAM_REASON_CANT_ATTACH);
1184 } SMARTLIST_FOREACH_END(base_conn);
1188 * As connection_ap_attach_pending, but first scans the entire connection
1189 * array to see if any elements are missing.
1191 void
1192 connection_ap_rescan_and_attach_pending(void)
1194 entry_connection_t *entry_conn;
1195 smartlist_t *conns = get_connection_array();
1197 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1198 pending_entry_connections = smartlist_new();
1200 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1201 if (conn->marked_for_close ||
1202 conn->type != CONN_TYPE_AP ||
1203 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1204 continue;
1206 entry_conn = TO_ENTRY_CONN(conn);
1207 tor_assert(entry_conn);
1208 if (! smartlist_contains(pending_entry_connections, entry_conn)) {
1209 log_warn(LD_BUG, "Found a connection %p that was supposed to be "
1210 "in pending_entry_connections, but wasn't. No worries; "
1211 "adding it.",
1212 pending_entry_connections);
1213 untried_pending_connections = 1;
1214 connection_ap_mark_as_pending_circuit(entry_conn);
1217 } SMARTLIST_FOREACH_END(conn);
1219 connection_ap_attach_pending(1);
1222 #ifdef DEBUGGING_17659
1223 #define UNMARK() do { \
1224 entry_conn->marked_pending_circ_line = 0; \
1225 entry_conn->marked_pending_circ_file = 0; \
1226 } while (0)
1227 #else /* !(defined(DEBUGGING_17659)) */
1228 #define UNMARK() do { } while (0)
1229 #endif /* defined(DEBUGGING_17659) */
1231 /** Tell any AP streams that are listed as waiting for a new circuit to try
1232 * again. If there is an available circuit for a stream, attach it. Otherwise,
1233 * launch a new circuit.
1235 * If <b>retry</b> is false, only check the list if it contains at least one
1236 * streams that we have not yet tried to attach to a circuit.
1238 void
1239 connection_ap_attach_pending(int retry)
1241 if (PREDICT_UNLIKELY(!pending_entry_connections)) {
1242 return;
1245 if (untried_pending_connections == 0 && !retry)
1246 return;
1248 /* Don't allow any modifications to list while we are iterating over
1249 * it. We'll put streams back on this list if we can't attach them
1250 * immediately. */
1251 smartlist_t *pending = pending_entry_connections;
1252 pending_entry_connections = smartlist_new();
1254 SMARTLIST_FOREACH_BEGIN(pending,
1255 entry_connection_t *, entry_conn) {
1256 connection_t *conn = ENTRY_TO_CONN(entry_conn);
1257 tor_assert(conn && entry_conn);
1258 if (conn->marked_for_close) {
1259 UNMARK();
1260 continue;
1262 if (conn->magic != ENTRY_CONNECTION_MAGIC) {
1263 log_warn(LD_BUG, "%p has impossible magic value %u.",
1264 entry_conn, (unsigned)conn->magic);
1265 UNMARK();
1266 continue;
1268 if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
1269 log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
1270 "is %s. Why is it on pending_entry_connections?",
1271 entry_conn,
1272 conn_state_to_string(conn->type, conn->state));
1273 UNMARK();
1274 continue;
1277 /* Okay, we're through the sanity checks. Try to handle this stream. */
1278 if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
1279 if (!conn->marked_for_close)
1280 connection_mark_unattached_ap(entry_conn,
1281 END_STREAM_REASON_CANT_ATTACH);
1284 if (! conn->marked_for_close &&
1285 conn->type == CONN_TYPE_AP &&
1286 conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1287 /* Is it still waiting for a circuit? If so, we didn't attach it,
1288 * so it's still pending. Put it back on the list.
1290 if (!smartlist_contains(pending_entry_connections, entry_conn)) {
1291 smartlist_add(pending_entry_connections, entry_conn);
1292 continue;
1296 /* If we got here, then we either closed the connection, or
1297 * we attached it. */
1298 UNMARK();
1299 } SMARTLIST_FOREACH_END(entry_conn);
1301 smartlist_free(pending);
1302 untried_pending_connections = 0;
1305 static void
1306 attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
1308 (void)ev;
1309 (void)arg;
1310 connection_ap_attach_pending(0);
1313 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
1315 * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
1316 * should not already be pending a circuit. The circuit will get
1317 * launched or the connection will get attached the next time we
1318 * call connection_ap_attach_pending().
1320 void
1321 connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn,
1322 const char *fname, int lineno)
1324 connection_t *conn = ENTRY_TO_CONN(entry_conn);
1325 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1326 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
1327 if (conn->marked_for_close)
1328 return;
1330 if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
1331 pending_entry_connections = smartlist_new();
1333 if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
1334 attach_pending_entry_connections_ev = mainloop_event_postloop_new(
1335 attach_pending_entry_connections_cb, NULL);
1337 if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
1338 entry_conn))) {
1339 log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
1340 "(Called from %s:%d.)",
1341 entry_conn, fname, lineno);
1342 #ifdef DEBUGGING_17659
1343 const char *f2 = entry_conn->marked_pending_circ_file;
1344 log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
1345 f2 ? f2 : "<NULL>",
1346 entry_conn->marked_pending_circ_line);
1347 #endif /* defined(DEBUGGING_17659) */
1348 log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
1349 return;
1352 #ifdef DEBUGGING_17659
1353 entry_conn->marked_pending_circ_line = (uint16_t) lineno;
1354 entry_conn->marked_pending_circ_file = fname;
1355 #endif
1357 untried_pending_connections = 1;
1358 smartlist_add(pending_entry_connections, entry_conn);
1360 mainloop_event_activate(attach_pending_entry_connections_ev);
1363 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
1364 void
1365 connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
1367 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1368 return;
1369 UNMARK();
1370 smartlist_remove(pending_entry_connections, entry_conn);
1373 /** Mark <b>entry_conn</b> as waiting for a rendezvous descriptor. This
1374 * function will remove the entry connection from the waiting for a circuit
1375 * list (pending_entry_connections).
1377 * This pattern is used across the code base because a connection in state
1378 * AP_CONN_STATE_RENDDESC_WAIT must not be in the pending list. */
1379 void
1380 connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
1382 tor_assert(entry_conn);
1384 connection_ap_mark_as_non_pending_circuit(entry_conn);
1385 ENTRY_TO_CONN(entry_conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
1388 /* DOCDOC */
1389 void
1390 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
1391 const char *where)
1393 if (pending_entry_connections &&
1394 smartlist_contains(pending_entry_connections, entry_conn)) {
1395 log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
1396 entry_conn, where);
1397 connection_ap_mark_as_non_pending_circuit(entry_conn);
1401 /** Tell any AP streams that are waiting for a one-hop tunnel to
1402 * <b>failed_digest</b> that they are going to fail. */
1403 /* XXXX We should get rid of this function, and instead attach
1404 * one-hop streams to circ->p_streams so they get marked in
1405 * circuit_mark_for_close like normal p_streams. */
1406 void
1407 connection_ap_fail_onehop(const char *failed_digest,
1408 cpath_build_state_t *build_state)
1410 entry_connection_t *entry_conn;
1411 char digest[DIGEST_LEN];
1412 smartlist_t *conns = get_connection_array();
1413 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1414 if (conn->marked_for_close ||
1415 conn->type != CONN_TYPE_AP ||
1416 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1417 continue;
1418 entry_conn = TO_ENTRY_CONN(conn);
1419 if (!entry_conn->want_onehop)
1420 continue;
1421 if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
1422 tor_memneq(digest, failed_digest, DIGEST_LEN))
1423 continue;
1424 if (tor_digest_is_zero(digest)) {
1425 /* we don't know the digest; have to compare addr:port */
1426 tor_addr_t addr;
1427 if (!build_state || !build_state->chosen_exit ||
1428 !entry_conn->socks_request) {
1429 continue;
1431 if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
1432 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
1433 build_state->chosen_exit->port != entry_conn->socks_request->port)
1434 continue;
1436 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
1437 "just failed.", entry_conn->chosen_exit_name,
1438 entry_conn->socks_request->address);
1439 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1440 } SMARTLIST_FOREACH_END(conn);
1443 /** A circuit failed to finish on its last hop <b>info</b>. If there
1444 * are any streams waiting with this exit node in mind, but they
1445 * don't absolutely require it, make them give up on it.
1447 void
1448 circuit_discard_optional_exit_enclaves(extend_info_t *info)
1450 entry_connection_t *entry_conn;
1451 const node_t *r1, *r2;
1453 smartlist_t *conns = get_connection_array();
1454 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1455 if (conn->marked_for_close ||
1456 conn->type != CONN_TYPE_AP ||
1457 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1458 continue;
1459 entry_conn = TO_ENTRY_CONN(conn);
1460 if (!entry_conn->chosen_exit_optional &&
1461 !entry_conn->chosen_exit_retries)
1462 continue;
1463 r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
1464 NNF_NO_WARN_UNNAMED);
1465 r2 = node_get_by_id(info->identity_digest);
1466 if (!r1 || !r2 || r1 != r2)
1467 continue;
1468 tor_assert(entry_conn->socks_request);
1469 if (entry_conn->chosen_exit_optional) {
1470 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
1471 safe_str_client(entry_conn->chosen_exit_name),
1472 escaped_safe_str_client(entry_conn->socks_request->address));
1473 entry_conn->chosen_exit_optional = 0;
1474 tor_free(entry_conn->chosen_exit_name); /* clears it */
1475 /* if this port is dangerous, warn or reject it now that we don't
1476 * think it'll be using an enclave. */
1477 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1479 if (entry_conn->chosen_exit_retries) {
1480 if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
1481 clear_trackexithost_mappings(entry_conn->chosen_exit_name);
1482 tor_free(entry_conn->chosen_exit_name); /* clears it */
1483 /* if this port is dangerous, warn or reject it now that we don't
1484 * think it'll be using an enclave. */
1485 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1488 } SMARTLIST_FOREACH_END(conn);
1491 /** The AP connection <b>conn</b> has just failed while attaching or
1492 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1493 * might work. Detach the circuit, and either reattach it, launch a
1494 * new circuit, tell the controller, or give up as appropriate.
1496 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1499 connection_ap_detach_retriable(entry_connection_t *conn,
1500 origin_circuit_t *circ,
1501 int reason)
1503 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
1504 ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
1506 /* Roll back path bias use state so that we probe the circuit
1507 * if nothing else succeeds on it */
1508 pathbias_mark_use_rollback(circ);
1510 if (conn->pending_optimistic_data) {
1511 buf_set_to_copy(&conn->sending_optimistic_data,
1512 conn->pending_optimistic_data);
1515 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
1516 /* If we're attaching streams ourself, or if this connection is
1517 * a tunneled directory connection, then just attach it. */
1518 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
1519 circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1520 connection_ap_mark_as_pending_circuit(conn);
1521 } else {
1522 CONNECTION_AP_EXPECT_NONPENDING(conn);
1523 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
1524 circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1526 return 0;
1529 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1530 * reject depending on our config options. */
1531 static int
1532 consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
1534 const or_options_t *options = get_options();
1535 int reject = smartlist_contains_int_as_string(
1536 options->RejectPlaintextPorts, port);
1538 if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
1539 log_warn(LD_APP, "Application request to port %d: this port is "
1540 "commonly used for unencrypted protocols. Please make sure "
1541 "you don't send anything you would mind the rest of the "
1542 "Internet reading!%s", port, reject ? " Closing." : "");
1543 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1544 port, reject ? "REJECT" : "WARN");
1547 if (reject) {
1548 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1549 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1550 return -1;
1553 return 0;
1556 /** How many times do we try connecting with an exit configured via
1557 * TrackHostExits before concluding that it won't work any more and trying a
1558 * different one? */
1559 #define TRACKHOSTEXITS_RETRIES 5
1561 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1562 * asked us to leave streams unattached. Return 0 in that case.
1564 * See connection_ap_handshake_rewrite_and_attach()'s
1565 * documentation for arguments and return value.
1567 MOCK_IMPL(int,
1568 connection_ap_rewrite_and_attach_if_allowed,(entry_connection_t *conn,
1569 origin_circuit_t *circ,
1570 crypt_path_t *cpath))
1572 const or_options_t *options = get_options();
1574 if (options->LeaveStreamsUnattached) {
1575 CONNECTION_AP_EXPECT_NONPENDING(conn);
1576 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
1577 return 0;
1579 return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1582 /* Try to perform any map-based rewriting of the target address in
1583 * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1584 * conn->socks_request.address as appropriate.
1586 STATIC void
1587 connection_ap_handshake_rewrite(entry_connection_t *conn,
1588 rewrite_result_t *out)
1590 socks_request_t *socks = conn->socks_request;
1591 const or_options_t *options = get_options();
1592 tor_addr_t addr_tmp;
1594 /* Initialize all the fields of 'out' to reasonable defaults */
1595 out->automap = 0;
1596 out->exit_source = ADDRMAPSRC_NONE;
1597 out->map_expires = TIME_MAX;
1598 out->end_reason = 0;
1599 out->should_close = 0;
1600 out->orig_address[0] = 0;
1602 /* We convert all incoming addresses to lowercase. */
1603 tor_strlower(socks->address);
1604 /* Remember the original address. */
1605 strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
1606 log_debug(LD_APP,"Client asked for %s:%d",
1607 safe_str_client(socks->address),
1608 socks->port);
1610 /* Check for whether this is a .exit address. By default, those are
1611 * disallowed when they're coming straight from the client, but you're
1612 * allowed to have them in MapAddress commands and so forth. */
1613 if (!strcmpend(socks->address, ".exit")) {
1614 log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
1615 "security risks.");
1616 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1617 escaped(socks->address));
1618 out->end_reason = END_STREAM_REASON_TORPROTOCOL;
1619 out->should_close = 1;
1620 return;
1623 /* Remember the original address so we can tell the user about what
1624 * they actually said, not just what it turned into. */
1625 /* XXX yes, this is the same as out->orig_address above. One is
1626 * in the output, and one is in the connection. */
1627 if (! conn->original_dest_address) {
1628 /* Is the 'if' necessary here? XXXX */
1629 conn->original_dest_address = tor_strdup(conn->socks_request->address);
1632 /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1633 * these only for non-reverse lookups, since they don't exist for those.
1634 * We also need to do this before we consider automapping, since we might
1635 * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1636 * we'd need to automap it. */
1637 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
1638 const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
1639 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1640 rewrite_flags, &out->map_expires, &out->exit_source)) {
1641 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1642 REMAP_STREAM_SOURCE_CACHE);
1646 /* Now see if we need to create or return an existing Hostname->IP
1647 * automapping. Automapping happens when we're asked to resolve a
1648 * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1649 * suffix listed in AutomapHostsSuffixes. It's a handy feature
1650 * that lets you have Tor assign e.g. IPv6 addresses for .onion
1651 * names, and return them safely from DNSPort.
1653 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1654 tor_addr_parse(&addr_tmp, socks->address)<0 &&
1655 options->AutomapHostsOnResolve) {
1656 /* Check the suffix... */
1657 out->automap = addressmap_address_should_automap(socks->address, options);
1658 if (out->automap) {
1659 /* If we get here, then we should apply an automapping for this. */
1660 const char *new_addr;
1661 /* We return an IPv4 address by default, or an IPv6 address if we
1662 * are allowed to do so. */
1663 int addr_type = RESOLVED_TYPE_IPV4;
1664 if (conn->socks_request->socks_version != 4) {
1665 if (!conn->entry_cfg.ipv4_traffic ||
1666 (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
1667 conn->entry_cfg.prefer_ipv6_virtaddr)
1668 addr_type = RESOLVED_TYPE_IPV6;
1670 /* Okay, register the target address as automapped, and find the new
1671 * address we're supposed to give as a resolve answer. (Return a cached
1672 * value if we've looked up this address before.
1674 new_addr = addressmap_register_virtual_address(
1675 addr_type, tor_strdup(socks->address));
1676 if (! new_addr) {
1677 log_warn(LD_APP, "Unable to automap address %s",
1678 escaped_safe_str(socks->address));
1679 out->end_reason = END_STREAM_REASON_INTERNAL;
1680 out->should_close = 1;
1681 return;
1683 log_info(LD_APP, "Automapping %s to %s",
1684 escaped_safe_str_client(socks->address),
1685 safe_str_client(new_addr));
1686 strlcpy(socks->address, new_addr, sizeof(socks->address));
1690 /* Now handle reverse lookups, if they're in the cache. This doesn't
1691 * happen too often, since client-side DNS caching is off by default,
1692 * and very deprecated. */
1693 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1694 unsigned rewrite_flags = 0;
1695 if (conn->entry_cfg.use_cached_ipv4_answers)
1696 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1697 if (conn->entry_cfg.use_cached_ipv6_answers)
1698 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1700 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1701 rewrite_flags, &out->map_expires)) {
1702 char *result = tor_strdup(socks->address);
1703 /* remember _what_ is supposed to have been resolved. */
1704 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1705 out->orig_address);
1706 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1707 strlen(result), (uint8_t*)result,
1709 out->map_expires);
1710 tor_free(result);
1711 out->end_reason = END_STREAM_REASON_DONE |
1712 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
1713 out->should_close = 1;
1714 return;
1717 /* Hang on, did we find an answer saying that this is a reverse lookup for
1718 * an internal address? If so, we should reject it if we're configured to
1719 * do so. */
1720 if (options->ClientDNSRejectInternalAddresses) {
1721 /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1722 tor_addr_t addr;
1723 int ok;
1724 ok = tor_addr_parse_PTR_name(
1725 &addr, socks->address, AF_UNSPEC, 1);
1726 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1727 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1728 0, NULL, -1, TIME_MAX);
1729 out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
1730 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
1731 out->should_close = 1;
1732 return;
1737 /* If we didn't automap it before, then this is still the address that
1738 * came straight from the user, mapped according to any
1739 * MapAddress/MAPADDRESS commands. Now apply other mappings,
1740 * including previously registered Automap entries (IP back to
1741 * hostname), TrackHostExits entries, and client-side DNS cache
1742 * entries (if they're turned on).
1744 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
1745 !out->automap) {
1746 unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
1747 addressmap_entry_source_t exit_source2;
1748 if (conn->entry_cfg.use_cached_ipv4_answers)
1749 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1750 if (conn->entry_cfg.use_cached_ipv6_answers)
1751 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1752 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1753 rewrite_flags, &out->map_expires, &exit_source2)) {
1754 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1755 REMAP_STREAM_SOURCE_CACHE);
1757 if (out->exit_source == ADDRMAPSRC_NONE) {
1758 /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1759 * the original source of a .exit. */
1760 out->exit_source = exit_source2;
1764 /* Check to see whether we're about to use an address in the virtual
1765 * range without actually having gotten it from an Automap. */
1766 if (!out->automap && address_is_in_virtual_range(socks->address)) {
1767 /* This address was probably handed out by
1768 * client_dns_get_unmapped_address, but the mapping was discarded for some
1769 * reason. Or the user typed in a virtual address range manually. We
1770 * *don't* want to send the address through Tor; that's likely to fail,
1771 * and may leak information.
1773 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1774 safe_str_client(socks->address));
1775 out->end_reason = END_STREAM_REASON_INTERNAL;
1776 out->should_close = 1;
1777 return;
1781 /** We just received a SOCKS request in <b>conn</b> to an onion address of type
1782 * <b>addresstype</b>. Start connecting to the onion service. */
1783 static int
1784 connection_ap_handle_onion(entry_connection_t *conn,
1785 socks_request_t *socks,
1786 origin_circuit_t *circ,
1787 hostname_type_t addresstype)
1789 time_t now = approx_time();
1790 connection_t *base_conn = ENTRY_TO_CONN(conn);
1792 /* If .onion address requests are disabled, refuse the request */
1793 if (!conn->entry_cfg.onion_traffic) {
1794 log_warn(LD_APP, "Onion address %s requested from a port with .onion "
1795 "disabled", safe_str_client(socks->address));
1796 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1797 return -1;
1800 /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
1801 * for hidden service addresses. */
1802 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1803 /* if it's a resolve request, fail it right now, rather than
1804 * building all the circuits and then realizing it won't work. */
1805 log_warn(LD_APP,
1806 "Resolve requests to hidden services not allowed. Failing.");
1807 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1808 0,NULL,-1,TIME_MAX);
1809 connection_mark_unattached_ap(conn,
1810 END_STREAM_REASON_SOCKSPROTOCOL |
1811 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1812 return -1;
1815 /* If we were passed a circuit, then we need to fail. .onion addresses
1816 * only work when we launch our own circuits for now. */
1817 if (circ) {
1818 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1819 "supported for .onion addresses currently. Failing.");
1820 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1821 return -1;
1824 /* Interface: Regardless of HS version after the block below we should have
1825 set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
1826 const char *onion_address = NULL;
1827 int rend_cache_lookup_result = -ENOENT;
1828 int descriptor_is_usable = 0;
1830 if (addresstype == ONION_V2_HOSTNAME) { /* it's a v2 hidden service */
1831 rend_cache_entry_t *entry = NULL;
1832 /* Look up if we have client authorization configured for this hidden
1833 * service. If we do, associate it with the rend_data. */
1834 rend_service_authorization_t *client_auth =
1835 rend_client_lookup_service_authorization(socks->address);
1837 const uint8_t *cookie = NULL;
1838 rend_auth_type_t auth_type = REND_NO_AUTH;
1839 if (client_auth) {
1840 log_info(LD_REND, "Using previously configured client authorization "
1841 "for hidden service request.");
1842 auth_type = client_auth->auth_type;
1843 cookie = client_auth->descriptor_cookie;
1846 /* Fill in the rend_data field so we can start doing a connection to
1847 * a hidden service. */
1848 rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
1849 rend_data_client_create(socks->address, NULL, (char *) cookie,
1850 auth_type);
1851 if (rend_data == NULL) {
1852 return -1;
1854 onion_address = rend_data_get_address(rend_data);
1855 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1856 safe_str_client(onion_address));
1858 rend_cache_lookup_result = rend_cache_lookup_entry(onion_address,-1,
1859 &entry);
1860 if (!rend_cache_lookup_result && entry) {
1861 descriptor_is_usable = rend_client_any_intro_points_usable(entry);
1863 } else { /* it's a v3 hidden service */
1864 tor_assert(addresstype == ONION_V3_HOSTNAME);
1865 const hs_descriptor_t *cached_desc = NULL;
1866 int retval;
1867 /* Create HS conn identifier with HS pubkey */
1868 hs_ident_edge_conn_t *hs_conn_ident =
1869 tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
1871 retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
1872 NULL, NULL);
1873 if (retval < 0) {
1874 log_warn(LD_GENERAL, "failed to parse hs address");
1875 tor_free(hs_conn_ident);
1876 return -1;
1878 ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
1880 onion_address = socks->address;
1882 /* Check the v3 desc cache */
1883 cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
1884 if (cached_desc) {
1885 rend_cache_lookup_result = 0;
1886 descriptor_is_usable =
1887 hs_client_any_intro_points_usable(&hs_conn_ident->identity_pk,
1888 cached_desc);
1889 log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
1890 (descriptor_is_usable) ? "usable" : "unusable",
1891 safe_str_client(onion_address),
1892 (descriptor_is_usable) ? "Not fetching." : "Refecting.");
1893 } else {
1894 rend_cache_lookup_result = -ENOENT;
1898 /* Lookup the given onion address. If invalid, stop right now.
1899 * Otherwise, we might have it in the cache or not. */
1900 unsigned int refetch_desc = 0;
1901 if (rend_cache_lookup_result < 0) {
1902 switch (-rend_cache_lookup_result) {
1903 case EINVAL:
1904 /* We should already have rejected this address! */
1905 log_warn(LD_BUG,"Invalid service name '%s'",
1906 safe_str_client(onion_address));
1907 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1908 return -1;
1909 case ENOENT:
1910 /* We didn't have this; we should look it up. */
1911 log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
1912 safe_str_client(onion_address));
1913 refetch_desc = 1;
1914 break;
1915 default:
1916 log_warn(LD_BUG, "Unknown cache lookup error %d",
1917 rend_cache_lookup_result);
1918 return -1;
1922 /* Help predict that we'll want to do hidden service circuits in the
1923 * future. We're not sure if it will need a stable circuit yet, but
1924 * we know we'll need *something*. */
1925 rep_hist_note_used_internal(now, 0, 1);
1927 /* Now we have a descriptor but is it usable or not? If not, refetch.
1928 * Also, a fetch could have been requested if the onion address was not
1929 * found in the cache previously. */
1930 if (refetch_desc || !descriptor_is_usable) {
1931 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
1932 connection_ap_mark_as_non_pending_circuit(conn);
1933 base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1934 if (addresstype == ONION_V2_HOSTNAME) {
1935 tor_assert(edge_conn->rend_data);
1936 rend_client_refetch_v2_renddesc(edge_conn->rend_data);
1937 /* Whatever the result of the refetch, we don't go further. */
1938 return 0;
1939 } else {
1940 tor_assert(addresstype == ONION_V3_HOSTNAME);
1941 tor_assert(edge_conn->hs_ident);
1942 /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
1943 * went and act accordingly. */
1944 int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
1945 switch (ret) {
1946 case HS_CLIENT_FETCH_MISSING_INFO:
1947 /* Keeping the connection in descriptor wait state is fine because
1948 * once we get enough dirinfo or a new live consensus, the HS client
1949 * subsystem is notified and every connection in that state will
1950 * trigger a fetch for the service key. */
1951 case HS_CLIENT_FETCH_LAUNCHED:
1952 case HS_CLIENT_FETCH_PENDING:
1953 case HS_CLIENT_FETCH_HAVE_DESC:
1954 return 0;
1955 case HS_CLIENT_FETCH_ERROR:
1956 case HS_CLIENT_FETCH_NO_HSDIRS:
1957 case HS_CLIENT_FETCH_NOT_ALLOWED:
1958 /* Can't proceed further and better close the SOCKS request. */
1959 return -1;
1964 /* We have the descriptor! So launch a connection to the HS. */
1965 log_info(LD_REND, "Descriptor is here. Great.");
1967 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1968 /* We'll try to attach it at the next event loop, or whenever
1969 * we call connection_ap_attach_pending() */
1970 connection_ap_mark_as_pending_circuit(conn);
1971 return 0;
1974 /** Connection <b>conn</b> just finished its socks handshake, or the
1975 * controller asked us to take care of it. If <b>circ</b> is defined,
1976 * then that's where we'll want to attach it. Otherwise we have to
1977 * figure it out ourselves.
1979 * First, parse whether it's a .exit address, remap it, and so on. Then
1980 * if it's for a general circuit, try to attach it to a circuit (or launch
1981 * one as needed), else if it's for a rendezvous circuit, fetch a
1982 * rendezvous descriptor first (or attach/launch a circuit if the
1983 * rendezvous descriptor is already here and fresh enough).
1985 * The stream will exit from the hop
1986 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1987 * <b>cpath</b> is NULL.
1990 connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
1991 origin_circuit_t *circ,
1992 crypt_path_t *cpath)
1994 socks_request_t *socks = conn->socks_request;
1995 const or_options_t *options = get_options();
1996 connection_t *base_conn = ENTRY_TO_CONN(conn);
1997 time_t now = time(NULL);
1998 rewrite_result_t rr;
2000 /* First we'll do the rewrite part. Let's see if we get a reasonable
2001 * answer.
2003 memset(&rr, 0, sizeof(rr));
2004 connection_ap_handshake_rewrite(conn,&rr);
2006 if (rr.should_close) {
2007 /* connection_ap_handshake_rewrite told us to close the connection:
2008 * either because it sent back an answer, or because it sent back an
2009 * error */
2010 connection_mark_unattached_ap(conn, rr.end_reason);
2011 if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
2012 return 0;
2013 else
2014 return -1;
2017 const time_t map_expires = rr.map_expires;
2018 const int automap = rr.automap;
2019 const addressmap_entry_source_t exit_source = rr.exit_source;
2021 /* Now, we parse the address to see if it's an .onion or .exit or
2022 * other special address.
2024 const hostname_type_t addresstype = parse_extended_hostname(socks->address);
2026 /* Now see whether the hostname is bogus. This could happen because of an
2027 * onion hostname whose format we don't recognize. */
2028 if (addresstype == BAD_HOSTNAME) {
2029 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2030 escaped(socks->address));
2031 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2032 return -1;
2035 /* If this is a .exit hostname, strip off the .name.exit part, and
2036 * see whether we're willing to connect there, and and otherwise handle the
2037 * .exit address.
2039 * We'll set chosen_exit_name and/or close the connection as appropriate.
2041 if (addresstype == EXIT_HOSTNAME) {
2042 /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
2043 * not ExcludeExitNodes. */
2044 routerset_t *excludeset = options->StrictNodes ?
2045 options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
2046 const node_t *node = NULL;
2048 /* If this .exit was added by an AUTOMAP, then it came straight from
2049 * a user. That's not safe. */
2050 if (exit_source == ADDRMAPSRC_AUTOMAP) {
2051 /* Whoops; this one is stale. It must have gotten added earlier?
2052 * (Probably this is not possible, since AllowDotExit no longer
2053 * exists.) */
2054 log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
2055 safe_str_client(socks->address));
2056 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2057 escaped(socks->address));
2058 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2059 tor_assert_nonfatal_unreached();
2060 return -1;
2063 /* Double-check to make sure there are no .exits coming from
2064 * impossible/weird sources. */
2065 if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
2066 /* It shouldn't be possible to get a .exit address from any of these
2067 * sources. */
2068 log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
2069 ".exit part. Refusing.",
2070 safe_str_client(socks->address));
2071 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2072 escaped(socks->address));
2073 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2074 return -1;
2077 tor_assert(!automap);
2079 /* Now, find the character before the .(name) part.
2080 * (The ".exit" part got stripped off by "parse_extended_hostname").
2082 * We're going to put the exit name into conn->chosen_exit_name, and
2083 * look up a node correspondingly. */
2084 char *s = strrchr(socks->address,'.');
2085 if (s) {
2086 /* The address was of the form "(stuff).(name).exit */
2087 if (s[1] != '\0') {
2088 /* Looks like a real .exit one. */
2089 conn->chosen_exit_name = tor_strdup(s+1);
2090 node = node_get_by_nickname(conn->chosen_exit_name, 0);
2092 if (exit_source == ADDRMAPSRC_TRACKEXIT) {
2093 /* We 5 tries before it expires the addressmap */
2094 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
2096 *s = 0;
2097 } else {
2098 /* Oops, the address was (stuff)..exit. That's not okay. */
2099 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
2100 safe_str_client(socks->address));
2101 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2102 escaped(socks->address));
2103 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2104 return -1;
2106 } else {
2107 /* It looks like they just asked for "foo.exit". That's a special
2108 * form that means (foo's address).foo.exit. */
2110 conn->chosen_exit_name = tor_strdup(socks->address);
2111 node = node_get_by_nickname(conn->chosen_exit_name, 0);
2112 if (node) {
2113 *socks->address = 0;
2114 node_get_address_string(node, socks->address, sizeof(socks->address));
2118 /* Now make sure that the chosen exit exists... */
2119 if (!node) {
2120 log_warn(LD_APP,
2121 "Unrecognized relay in exit address '%s.exit'. Refusing.",
2122 safe_str_client(socks->address));
2123 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2124 return -1;
2126 /* ...and make sure that it isn't excluded. */
2127 if (routerset_contains_node(excludeset, node)) {
2128 log_warn(LD_APP,
2129 "Excluded relay in exit address '%s.exit'. Refusing.",
2130 safe_str_client(socks->address));
2131 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2132 return -1;
2134 /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
2135 Bar is not listed in it? I say yes, but our revised manpage branch
2136 implies no. */
2139 /* Now, we handle everything that isn't a .onion address. */
2140 if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {
2141 /* Not a hidden-service request. It's either a hostname or an IP,
2142 * possibly with a .exit that we stripped off. We're going to check
2143 * if we're allowed to connect/resolve there, and then launch the
2144 * appropriate request. */
2146 /* Check for funny characters in the address. */
2147 if (address_is_invalid_destination(socks->address, 1)) {
2148 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2149 escaped(socks->address));
2150 log_warn(LD_APP,
2151 "Destination '%s' seems to be an invalid hostname. Failing.",
2152 safe_str_client(socks->address));
2153 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2154 return -1;
2157 /* socks->address is a non-onion hostname or IP address.
2158 * If we can't do any non-onion requests, refuse the connection.
2159 * If we have a hostname but can't do DNS, refuse the connection.
2160 * If we have an IP address, but we can't use that address family,
2161 * refuse the connection.
2163 * If we can do DNS requests, and we can use at least one address family,
2164 * then we have to resolve the address first. Then we'll know if it
2165 * resolves to a usable address family. */
2167 /* First, check if all non-onion traffic is disabled */
2168 if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
2169 && !conn->entry_cfg.ipv6_traffic) {
2170 log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
2171 "or IP address %s because Port has OnionTrafficOnly set (or "
2172 "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
2173 safe_str_client(socks->address));
2174 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2175 return -1;
2178 /* Then check if we have a hostname or IP address, and whether DNS or
2179 * the IP address family are permitted. Reject if not. */
2180 tor_addr_t dummy_addr;
2181 int socks_family = tor_addr_parse(&dummy_addr, socks->address);
2182 /* family will be -1 for a non-onion hostname that's not an IP */
2183 if (socks_family == -1) {
2184 if (!conn->entry_cfg.dns_request) {
2185 log_warn(LD_APP, "Refusing to connect to hostname %s "
2186 "because Port has NoDNSRequest set.",
2187 safe_str_client(socks->address));
2188 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2189 return -1;
2191 } else if (socks_family == AF_INET) {
2192 if (!conn->entry_cfg.ipv4_traffic) {
2193 log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
2194 "Port has NoIPv4Traffic set.",
2195 safe_str_client(socks->address));
2196 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2197 return -1;
2199 } else if (socks_family == AF_INET6) {
2200 if (!conn->entry_cfg.ipv6_traffic) {
2201 log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
2202 "Port has NoIPv6Traffic set.",
2203 safe_str_client(socks->address));
2204 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2205 return -1;
2207 } else {
2208 tor_assert_nonfatal_unreached_once();
2211 /* See if this is a hostname lookup that we can answer immediately.
2212 * (For example, an attempt to look up the IP address for an IP address.)
2214 if (socks->command == SOCKS_COMMAND_RESOLVE) {
2215 tor_addr_t answer;
2216 /* Reply to resolves immediately if we can. */
2217 if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
2218 /* remember _what_ is supposed to have been resolved. */
2219 strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
2220 connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
2221 map_expires);
2222 connection_mark_unattached_ap(conn,
2223 END_STREAM_REASON_DONE |
2224 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
2225 return 0;
2227 tor_assert(!automap);
2228 rep_hist_note_used_resolve(now); /* help predict this next time */
2229 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
2230 /* Now see if this is a connect request that we can reject immediately */
2232 tor_assert(!automap);
2233 /* Don't allow connections to port 0. */
2234 if (socks->port == 0) {
2235 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
2236 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2237 return -1;
2239 /* You can't make connections to internal addresses, by default.
2240 * Exceptions are begindir requests (where the address is meaningless),
2241 * or cases where you've hand-configured a particular exit, thereby
2242 * making the local address meaningful. */
2243 if (options->ClientRejectInternalAddresses &&
2244 !conn->use_begindir && !conn->chosen_exit_name && !circ) {
2245 /* If we reach this point then we don't want to allow internal
2246 * addresses. Check if we got one. */
2247 tor_addr_t addr;
2248 if (tor_addr_hostname_is_local(socks->address) ||
2249 (tor_addr_parse(&addr, socks->address) >= 0 &&
2250 tor_addr_is_internal(&addr, 0))) {
2251 /* If this is an explicit private address with no chosen exit node,
2252 * then we really don't want to try to connect to it. That's
2253 * probably an error. */
2254 if (conn->is_transparent_ap) {
2255 #define WARN_INTRVL_LOOP 300
2256 static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
2257 char *m;
2258 if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
2259 log_warn(LD_NET,
2260 "Rejecting request for anonymous connection to private "
2261 "address %s on a TransPort or NATDPort. Possible loop "
2262 "in your NAT rules?%s", safe_str_client(socks->address),
2264 tor_free(m);
2266 } else {
2267 #define WARN_INTRVL_PRIV 300
2268 static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
2269 char *m;
2270 if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
2271 log_warn(LD_NET,
2272 "Rejecting SOCKS request for anonymous connection to "
2273 "private address %s.%s",
2274 safe_str_client(socks->address),m);
2275 tor_free(m);
2278 connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
2279 return -1;
2281 } /* end "if we should check for internal addresses" */
2283 /* Okay. We're still doing a CONNECT, and it wasn't a private
2284 * address. Here we do special handling for literal IP addresses,
2285 * to see if we should reject this preemptively, and to set up
2286 * fields in conn->entry_cfg to tell the exit what AF we want. */
2288 tor_addr_t addr;
2289 /* XXX Duplicate call to tor_addr_parse. */
2290 if (tor_addr_parse(&addr, socks->address) >= 0) {
2291 /* If we reach this point, it's an IPv4 or an IPv6 address. */
2292 sa_family_t family = tor_addr_family(&addr);
2294 if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
2295 (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
2296 /* You can't do an IPv4 address on a v6-only socks listener,
2297 * or vice versa. */
2298 log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
2299 "family that this listener does not support.");
2300 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2301 return -1;
2302 } else if (family == AF_INET6 && socks->socks_version == 4) {
2303 /* You can't make a socks4 request to an IPv6 address. Socks4
2304 * doesn't support that. */
2305 log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
2306 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2307 return -1;
2308 } else if (socks->socks_version == 4 &&
2309 !conn->entry_cfg.ipv4_traffic) {
2310 /* You can't do any kind of Socks4 request when IPv4 is forbidden.
2312 * XXX raise this check outside the enclosing block? */
2313 log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
2314 "no IPv4 traffic supported.");
2315 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2316 return -1;
2317 } else if (family == AF_INET6) {
2318 /* Tell the exit: we won't accept any ipv4 connection to an IPv6
2319 * address. */
2320 conn->entry_cfg.ipv4_traffic = 0;
2321 } else if (family == AF_INET) {
2322 /* Tell the exit: we won't accept any ipv6 connection to an IPv4
2323 * address. */
2324 conn->entry_cfg.ipv6_traffic = 0;
2329 /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
2330 if (socks->socks_version == 4)
2331 conn->entry_cfg.ipv6_traffic = 0;
2333 /* Still handling CONNECT. Now, check for exit enclaves. (Which we
2334 * don't do on BEGIN_DIR, or when there is a chosen exit.)
2336 * TODO: Should we remove this? Exit enclaves are nutty and don't
2337 * work very well
2339 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
2340 /* see if we can find a suitable enclave exit */
2341 const node_t *r =
2342 router_find_exact_exit_enclave(socks->address, socks->port);
2343 if (r) {
2344 log_info(LD_APP,
2345 "Redirecting address %s to exit at enclave router %s",
2346 safe_str_client(socks->address), node_describe(r));
2347 /* use the hex digest, not nickname, in case there are two
2348 routers with this nickname */
2349 conn->chosen_exit_name =
2350 tor_strdup(hex_str(r->identity, DIGEST_LEN));
2351 conn->chosen_exit_optional = 1;
2355 /* Still handling CONNECT: warn or reject if it's using a dangerous
2356 * port. */
2357 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
2358 if (consider_plaintext_ports(conn, socks->port) < 0)
2359 return -1;
2361 /* Remember the port so that we will predict that more requests
2362 there will happen in the future. */
2363 if (!conn->use_begindir) {
2364 /* help predict this next time */
2365 rep_hist_note_used_port(now, socks->port);
2367 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
2368 rep_hist_note_used_resolve(now); /* help predict this next time */
2369 /* no extra processing needed */
2370 } else {
2371 /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2372 tor_fragile_assert();
2375 /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2376 * address, and decided not to reject it for any number of reasons. Now
2377 * mark the connection as waiting for a circuit, and try to attach it!
2379 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2381 /* If we were given a circuit to attach to, try to attach. Otherwise,
2382 * try to find a good one and attach to that. */
2383 int rv;
2384 if (circ) {
2385 rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
2386 } else {
2387 /* We'll try to attach it at the next event loop, or whenever
2388 * we call connection_ap_attach_pending() */
2389 connection_ap_mark_as_pending_circuit(conn);
2390 rv = 0;
2393 /* If the above function returned 0 then we're waiting for a circuit.
2394 * if it returned 1, we're attached. Both are okay. But if it returned
2395 * -1, there was an error, so make sure the connection is marked, and
2396 * return -1. */
2397 if (rv < 0) {
2398 if (!base_conn->marked_for_close)
2399 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2400 return -1;
2403 return 0;
2404 } else {
2405 /* If we get here, it's a request for a .onion address! */
2406 tor_assert(addresstype == ONION_V2_HOSTNAME ||
2407 addresstype == ONION_V3_HOSTNAME);
2408 tor_assert(!automap);
2409 return connection_ap_handle_onion(conn, socks, circ, addresstype);
2412 return 0; /* unreached but keeps the compiler happy */
2415 #ifdef TRANS_PF
2416 static int pf_socket = -1;
2418 get_pf_socket(void)
2420 int pf;
2421 /* This should be opened before dropping privileges. */
2422 if (pf_socket >= 0)
2423 return pf_socket;
2425 #if defined(OpenBSD)
2426 /* only works on OpenBSD */
2427 pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
2428 #else
2429 /* works on NetBSD and FreeBSD */
2430 pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
2431 #endif /* defined(OpenBSD) */
2433 if (pf < 0) {
2434 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
2435 return -1;
2438 pf_socket = pf;
2439 return pf_socket;
2441 #endif /* defined(TRANS_PF) */
2443 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2444 defined(TRANS_TPROXY)
2445 /** Try fill in the address of <b>req</b> from the socket configured
2446 * with <b>conn</b>. */
2447 static int
2448 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
2450 struct sockaddr_storage orig_dst;
2451 socklen_t orig_dst_len = sizeof(orig_dst);
2452 tor_addr_t addr;
2454 #ifdef TRANS_TPROXY
2455 if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
2456 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2457 &orig_dst_len) < 0) {
2458 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2459 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2460 return -1;
2462 goto done;
2464 #endif /* defined(TRANS_TPROXY) */
2466 #ifdef TRANS_NETFILTER
2467 int rv = -1;
2468 switch (ENTRY_TO_CONN(conn)->socket_family) {
2469 #ifdef TRANS_NETFILTER_IPV4
2470 case AF_INET:
2471 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
2472 (struct sockaddr*)&orig_dst, &orig_dst_len);
2473 break;
2474 #endif /* defined(TRANS_NETFILTER_IPV4) */
2475 #ifdef TRANS_NETFILTER_IPV6
2476 case AF_INET6:
2477 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
2478 (struct sockaddr*)&orig_dst, &orig_dst_len);
2479 break;
2480 #endif /* defined(TRANS_NETFILTER_IPV6) */
2481 default:
2482 log_warn(LD_BUG,
2483 "Received transparent data from an unsuported socket family %d",
2484 ENTRY_TO_CONN(conn)->socket_family);
2485 return -1;
2487 if (rv < 0) {
2488 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2489 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
2490 return -1;
2492 goto done;
2493 #elif defined(TRANS_PF)
2494 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2495 &orig_dst_len) < 0) {
2496 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2497 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2498 return -1;
2500 goto done;
2501 #else
2502 (void)conn;
2503 (void)req;
2504 log_warn(LD_BUG, "Unable to determine destination from socket.");
2505 return -1;
2506 #endif /* defined(TRANS_NETFILTER) || ... */
2508 done:
2509 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
2510 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2512 return 0;
2514 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2516 #ifdef TRANS_PF
2517 static int
2518 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
2520 struct sockaddr_storage proxy_addr;
2521 socklen_t proxy_addr_len = sizeof(proxy_addr);
2522 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
2523 struct pfioc_natlook pnl;
2524 tor_addr_t addr;
2525 int pf = -1;
2527 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
2528 &proxy_addr_len) < 0) {
2529 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2530 log_warn(LD_NET, "getsockname() to determine transocks destination "
2531 "failed: %s", tor_socket_strerror(e));
2532 return -1;
2535 #ifdef __FreeBSD__
2536 if (get_options()->TransProxyType_parsed == TPT_IPFW) {
2537 /* ipfw(8) is used and in this case getsockname returned the original
2538 destination */
2539 if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
2540 tor_fragile_assert();
2541 return -1;
2544 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
2546 return 0;
2548 #endif /* defined(__FreeBSD__) */
2550 memset(&pnl, 0, sizeof(pnl));
2551 pnl.proto = IPPROTO_TCP;
2552 pnl.direction = PF_OUT;
2553 if (proxy_sa->sa_family == AF_INET) {
2554 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
2555 pnl.af = AF_INET;
2556 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
2557 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2558 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
2559 pnl.dport = sin->sin_port;
2560 } else if (proxy_sa->sa_family == AF_INET6) {
2561 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
2562 pnl.af = AF_INET6;
2563 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
2564 sizeof(struct in6_addr));
2565 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2566 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
2567 pnl.dport = sin6->sin6_port;
2568 } else {
2569 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
2570 (int)proxy_sa->sa_family);
2571 return -1;
2574 pf = get_pf_socket();
2575 if (pf<0)
2576 return -1;
2578 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
2579 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
2580 return -1;
2583 if (pnl.af == AF_INET) {
2584 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
2585 } else if (pnl.af == AF_INET6) {
2586 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
2587 } else {
2588 tor_fragile_assert();
2589 return -1;
2592 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2593 req->port = ntohs(pnl.rdport);
2595 return 0;
2597 #endif /* defined(TRANS_PF) */
2599 /** Fetch the original destination address and port from a
2600 * system-specific interface and put them into a
2601 * socks_request_t as if they came from a socks request.
2603 * Return -1 if an error prevents fetching the destination,
2604 * else return 0.
2606 static int
2607 connection_ap_get_original_destination(entry_connection_t *conn,
2608 socks_request_t *req)
2610 #ifdef TRANS_NETFILTER
2611 return destination_from_socket(conn, req);
2612 #elif defined(TRANS_PF)
2613 const or_options_t *options = get_options();
2615 if (options->TransProxyType_parsed == TPT_PF_DIVERT)
2616 return destination_from_socket(conn, req);
2618 if (options->TransProxyType_parsed == TPT_DEFAULT ||
2619 options->TransProxyType_parsed == TPT_IPFW)
2620 return destination_from_pf(conn, req);
2622 (void)conn;
2623 (void)req;
2624 log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
2625 options->TransProxyType);
2626 return -1;
2627 #else
2628 (void)conn;
2629 (void)req;
2630 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
2631 "transparent proxy method was configured.");
2632 return -1;
2633 #endif /* defined(TRANS_NETFILTER) || ... */
2636 /** connection_edge_process_inbuf() found a conn in state
2637 * socks_wait. See if conn->inbuf has the right bytes to proceed with
2638 * the socks handshake.
2640 * If the handshake is complete, send it to
2641 * connection_ap_handshake_rewrite_and_attach().
2643 * Return -1 if an unexpected error with conn occurs (and mark it for close),
2644 * else return 0.
2646 static int
2647 connection_ap_handshake_process_socks(entry_connection_t *conn)
2649 socks_request_t *socks;
2650 int sockshere;
2651 const or_options_t *options = get_options();
2652 int had_reply = 0;
2653 connection_t *base_conn = ENTRY_TO_CONN(conn);
2655 tor_assert(conn);
2656 tor_assert(base_conn->type == CONN_TYPE_AP);
2657 tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
2658 tor_assert(conn->socks_request);
2659 socks = conn->socks_request;
2661 log_debug(LD_APP,"entered.");
2663 sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2664 options->TestSocks, options->SafeSocks);
2666 if (socks->replylen) {
2667 had_reply = 1;
2668 connection_buf_add((const char*)socks->reply, socks->replylen,
2669 base_conn);
2670 socks->replylen = 0;
2671 if (sockshere == -1) {
2672 /* An invalid request just got a reply, no additional
2673 * one is necessary. */
2674 socks->has_finished = 1;
2678 if (sockshere == 0) {
2679 log_debug(LD_APP,"socks handshake not all here yet.");
2680 return 0;
2681 } else if (sockshere == -1) {
2682 if (!had_reply) {
2683 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2684 connection_ap_handshake_socks_reply(conn, NULL, 0,
2685 END_STREAM_REASON_SOCKSPROTOCOL);
2687 connection_mark_unattached_ap(conn,
2688 END_STREAM_REASON_SOCKSPROTOCOL |
2689 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
2690 return -1;
2691 } /* else socks handshake is done, continue processing */
2693 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2694 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2695 else
2696 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2698 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2701 /** connection_init_accepted_conn() found a new trans AP conn.
2702 * Get the original destination and send it to
2703 * connection_ap_handshake_rewrite_and_attach().
2705 * Return -1 if an unexpected error with conn (and it should be marked
2706 * for close), else return 0.
2709 connection_ap_process_transparent(entry_connection_t *conn)
2711 socks_request_t *socks;
2713 tor_assert(conn);
2714 tor_assert(conn->socks_request);
2715 socks = conn->socks_request;
2717 /* pretend that a socks handshake completed so we don't try to
2718 * send a socks reply down a transparent conn */
2719 socks->command = SOCKS_COMMAND_CONNECT;
2720 socks->has_finished = 1;
2722 log_debug(LD_APP,"entered.");
2724 if (connection_ap_get_original_destination(conn, socks) < 0) {
2725 log_warn(LD_APP,"Fetching original destination failed. Closing.");
2726 connection_mark_unattached_ap(conn,
2727 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
2728 return -1;
2730 /* we have the original destination */
2732 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2734 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2737 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2738 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2739 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2740 * form of the original destination.
2742 * If the original destination is complete, send it to
2743 * connection_ap_handshake_rewrite_and_attach().
2745 * Return -1 if an unexpected error with conn (and it should be marked
2746 * for close), else return 0.
2748 static int
2749 connection_ap_process_natd(entry_connection_t *conn)
2751 char tmp_buf[36], *tbuf, *daddr;
2752 size_t tlen = 30;
2753 int err, port_ok;
2754 socks_request_t *socks;
2756 tor_assert(conn);
2757 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
2758 tor_assert(conn->socks_request);
2759 socks = conn->socks_request;
2761 log_debug(LD_APP,"entered.");
2763 /* look for LF-terminated "[DEST ip_addr port]"
2764 * where ip_addr is a dotted-quad and port is in string form */
2765 err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2766 if (err == 0)
2767 return 0;
2768 if (err < 0) {
2769 log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2770 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2771 return -1;
2774 if (strcmpstart(tmp_buf, "[DEST ")) {
2775 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2776 "said: %s",
2777 escaped(tmp_buf));
2778 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2779 return -1;
2782 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2783 if (!(tbuf = strchr(tbuf, ' '))) {
2784 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2785 "said: %s",
2786 escaped(tmp_buf));
2787 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2788 return -1;
2790 *tbuf++ = '\0';
2792 /* pretend that a socks handshake completed so we don't try to
2793 * send a socks reply down a natd conn */
2794 strlcpy(socks->address, daddr, sizeof(socks->address));
2795 socks->port = (uint16_t)
2796 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2797 if (!port_ok) {
2798 log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2799 "of range.", escaped(tbuf));
2800 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2801 return -1;
2804 socks->command = SOCKS_COMMAND_CONNECT;
2805 socks->has_finished = 1;
2807 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2809 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
2811 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2814 static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
2815 "HTTP/1.0 405 Method Not Allowed\r\n"
2816 "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
2817 "<html>\n"
2818 "<head>\n"
2819 "<title>This is an HTTP CONNECT tunnel, not an full HTTP Proxy</title>\n"
2820 "</head>\n"
2821 "<body>\n"
2822 "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
2823 "<p>\n"
2824 "It appears you have configured your web browser to use this Tor port as\n"
2825 "an HTTP proxy.\n"
2826 "</p><p>\n"
2827 "This is not correct: This port is configured as a CONNECT tunnel, not\n"
2828 "an HTTP proxy. Please configure your client accordingly. You can also\n"
2829 "use HTTPS, then the client should automatically use HTTP CONNECT."
2830 "</p>\n"
2831 "<p>\n"
2832 "See <a href=\"https://www.torproject.org/documentation.html\">"
2833 "https://www.torproject.org/documentation.html</a> for more "
2834 "information.\n"
2835 "</p>\n"
2836 "</body>\n"
2837 "</html>\n";
2839 /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
2840 * but we have not yet received a full HTTP CONNECT request. Try to parse an
2841 * HTTP CONNECT request from the connection's inbuf. On success, set up the
2842 * connection's socks_request field and try to attach the connection. On
2843 * failure, send an HTTP reply, and mark the connection.
2845 STATIC int
2846 connection_ap_process_http_connect(entry_connection_t *conn)
2848 if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
2849 return -1;
2851 char *headers = NULL, *body = NULL;
2852 char *command = NULL, *addrport = NULL;
2853 char *addr = NULL;
2854 size_t bodylen = 0;
2856 const char *errmsg = NULL;
2857 int rv = 0;
2859 const int http_status =
2860 fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
2861 &body, &bodylen, 1024, 0);
2862 if (http_status < 0) {
2863 /* Bad http status */
2864 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2865 goto err;
2866 } else if (http_status == 0) {
2867 /* no HTTP request yet. */
2868 goto done;
2871 const int cmd_status = parse_http_command(headers, &command, &addrport);
2872 if (cmd_status < 0) {
2873 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2874 goto err;
2876 tor_assert(command);
2877 tor_assert(addrport);
2878 if (strcasecmp(command, "connect")) {
2879 errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
2880 goto err;
2883 tor_assert(conn->socks_request);
2884 socks_request_t *socks = conn->socks_request;
2885 uint16_t port;
2886 if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
2887 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2888 goto err;
2890 if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
2891 errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
2892 goto err;
2895 /* Abuse the 'username' and 'password' fields here. They are already an
2896 * abuse. */
2898 char *authorization = http_get_header(headers, "Proxy-Authorization: ");
2899 if (authorization) {
2900 socks->username = authorization; // steal reference
2901 socks->usernamelen = strlen(authorization);
2903 char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
2904 if (isolation) {
2905 socks->password = isolation; // steal reference
2906 socks->passwordlen = strlen(isolation);
2910 socks->command = SOCKS_COMMAND_CONNECT;
2911 socks->listener_type = CONN_TYPE_AP_HTTP_CONNECT_LISTENER;
2912 strlcpy(socks->address, addr, sizeof(socks->address));
2913 socks->port = port;
2915 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2917 rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2919 // XXXX send a "100 Continue" message?
2921 goto done;
2923 err:
2924 if (BUG(errmsg == NULL))
2925 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2926 log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
2927 connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
2928 /* Mark it as "has_finished" so that we don't try to send an extra socks
2929 * reply. */
2930 conn->socks_request->has_finished = 1;
2931 connection_mark_unattached_ap(conn,
2932 END_STREAM_REASON_HTTPPROTOCOL|
2933 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
2935 done:
2936 tor_free(headers);
2937 tor_free(body);
2938 tor_free(command);
2939 tor_free(addrport);
2940 tor_free(addr);
2941 return rv;
2944 /** Iterate over the two bytes of stream_id until we get one that is not
2945 * already in use; return it. Return 0 if can't get a unique stream_id.
2947 streamid_t
2948 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2950 edge_connection_t *tmpconn;
2951 streamid_t test_stream_id;
2952 uint32_t attempts=0;
2954 again:
2955 test_stream_id = circ->next_stream_id++;
2956 if (++attempts > 1<<16) {
2957 /* Make sure we don't loop forever if all stream_id's are used. */
2958 log_warn(LD_APP,"No unused stream IDs. Failing.");
2959 return 0;
2961 if (test_stream_id == 0)
2962 goto again;
2963 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2964 if (tmpconn->stream_id == test_stream_id)
2965 goto again;
2967 if (connection_half_edge_find_stream_id(circ->half_streams,
2968 test_stream_id))
2969 goto again;
2971 return test_stream_id;
2974 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
2975 * an exit that supports optimistic data. */
2976 static int
2977 connection_ap_supports_optimistic_data(const entry_connection_t *conn)
2979 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2980 /* We can only send optimistic data if we're connected to an open
2981 general circuit. */
2982 if (edge_conn->on_circuit == NULL ||
2983 edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
2984 (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
2985 edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
2986 edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
2987 edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
2988 return 0;
2990 return conn->may_use_optimistic_data;
2993 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
2994 * RELAY_BEGIN cell for <b>ap_conn</b>. */
2995 static uint32_t
2996 connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
2998 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2999 const node_t *exitnode = NULL;
3000 const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
3001 uint32_t flags = 0;
3003 /* No flags for begindir */
3004 if (ap_conn->use_begindir)
3005 return 0;
3007 /* No flags for hidden services. */
3008 if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
3009 return 0;
3011 /* If only IPv4 is supported, no flags */
3012 if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
3013 return 0;
3015 if (! cpath_layer ||
3016 ! cpath_layer->extend_info)
3017 return 0;
3019 if (!ap_conn->entry_cfg.ipv4_traffic)
3020 flags |= BEGIN_FLAG_IPV4_NOT_OK;
3022 exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
3024 if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
3025 tor_addr_t a;
3026 tor_addr_make_null(&a, AF_INET6);
3027 if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
3028 exitnode)
3029 != ADDR_POLICY_REJECTED) {
3030 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
3031 * no point. */
3032 flags |= BEGIN_FLAG_IPV6_OK;
3036 if (flags == BEGIN_FLAG_IPV6_OK) {
3037 /* When IPv4 and IPv6 are both allowed, consider whether to say we
3038 * prefer IPv6. Otherwise there's no point in declaring a preference */
3039 if (ap_conn->entry_cfg.prefer_ipv6)
3040 flags |= BEGIN_FLAG_IPV6_PREFERRED;
3043 if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
3044 log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
3045 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
3046 "not going to work. Did you perhaps ask for an IPv6 address "
3047 "on an IPv4Only port, or vice versa?");
3050 return flags;
3053 /** Write a relay begin cell, using destaddr and destport from ap_conn's
3054 * socks_request field, and send it down circ.
3056 * If ap_conn is broken, mark it for close and return -1. Else return 0.
3058 MOCK_IMPL(int,
3059 connection_ap_handshake_send_begin,(entry_connection_t *ap_conn))
3061 char payload[CELL_PAYLOAD_SIZE];
3062 int payload_len;
3063 int begin_type;
3064 const or_options_t *options = get_options();
3065 origin_circuit_t *circ;
3066 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3067 connection_t *base_conn = TO_CONN(edge_conn);
3068 tor_assert(edge_conn->on_circuit);
3069 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3071 tor_assert(base_conn->type == CONN_TYPE_AP);
3072 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
3073 tor_assert(ap_conn->socks_request);
3074 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
3076 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3077 if (edge_conn->stream_id==0) {
3078 /* XXXX+ Instead of closing this stream, we should make it get
3079 * retried on another circuit. */
3080 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3082 /* Mark this circuit "unusable for new streams". */
3083 mark_circuit_unusable_for_new_conns(circ);
3084 return -1;
3087 /* Set up begin cell flags. */
3088 edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
3090 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
3091 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
3092 ap_conn->socks_request->address : "",
3093 ap_conn->socks_request->port);
3094 payload_len = (int)strlen(payload)+1;
3095 if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
3096 set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
3097 payload_len += 4;
3100 log_info(LD_APP,
3101 "Sending relay cell %d on circ %u to begin stream %d.",
3102 (int)ap_conn->use_begindir,
3103 (unsigned)circ->base_.n_circ_id,
3104 edge_conn->stream_id);
3106 begin_type = ap_conn->use_begindir ?
3107 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
3109 /* Check that circuits are anonymised, based on their type. */
3110 if (begin_type == RELAY_COMMAND_BEGIN) {
3111 /* This connection is a standard OR connection.
3112 * Make sure its path length is anonymous, or that we're in a
3113 * non-anonymous mode. */
3114 assert_circ_anonymity_ok(circ, options);
3115 } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
3116 /* This connection is a begindir directory connection.
3117 * Look at the linked directory connection to access the directory purpose.
3118 * If a BEGINDIR connection is ever not linked, that's a bug. */
3119 if (BUG(!base_conn->linked)) {
3120 return -1;
3122 connection_t *linked_dir_conn_base = base_conn->linked_conn;
3123 /* If the linked connection has been unlinked by other code, we can't send
3124 * a begin cell on it. */
3125 if (!linked_dir_conn_base) {
3126 return -1;
3128 /* Sensitive directory connections must have an anonymous path length.
3129 * Otherwise, directory connections are typically one-hop.
3130 * This matches the earlier check for directory connection path anonymity
3131 * in directory_initiate_request(). */
3132 if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
3133 TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
3134 TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
3135 assert_circ_anonymity_ok(circ, options);
3137 } else {
3138 /* This code was written for the two connection types BEGIN and BEGIN_DIR
3140 tor_assert_unreached();
3143 if (connection_edge_send_command(edge_conn, begin_type,
3144 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
3145 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
3146 return -1; /* circuit is closed, don't continue */
3148 edge_conn->package_window = STREAMWINDOW_START;
3149 edge_conn->deliver_window = STREAMWINDOW_START;
3150 base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
3151 log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
3152 ", n_circ_id %u",
3153 base_conn->s, (unsigned)circ->base_.n_circ_id);
3154 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
3156 /* If there's queued-up data, send it now */
3157 if ((connection_get_inbuf_len(base_conn) ||
3158 ap_conn->sending_optimistic_data) &&
3159 connection_ap_supports_optimistic_data(ap_conn)) {
3160 log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
3161 (long)connection_get_inbuf_len(base_conn),
3162 ap_conn->sending_optimistic_data ?
3163 (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
3164 if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
3165 connection_mark_for_close(base_conn);
3169 return 0;
3172 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
3173 * socks_request field, and send it down circ.
3175 * If ap_conn is broken, mark it for close and return -1. Else return 0.
3178 connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
3180 int payload_len, command;
3181 const char *string_addr;
3182 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
3183 origin_circuit_t *circ;
3184 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3185 connection_t *base_conn = TO_CONN(edge_conn);
3186 tor_assert(edge_conn->on_circuit);
3187 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3189 tor_assert(base_conn->type == CONN_TYPE_AP);
3190 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
3191 tor_assert(ap_conn->socks_request);
3192 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
3194 command = ap_conn->socks_request->command;
3195 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
3197 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3198 if (edge_conn->stream_id==0) {
3199 /* XXXX+ Instead of closing this stream, we should make it get
3200 * retried on another circuit. */
3201 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3203 /* Mark this circuit "unusable for new streams". */
3204 mark_circuit_unusable_for_new_conns(circ);
3205 return -1;
3208 if (command == SOCKS_COMMAND_RESOLVE) {
3209 string_addr = ap_conn->socks_request->address;
3210 payload_len = (int)strlen(string_addr)+1;
3211 } else {
3212 /* command == SOCKS_COMMAND_RESOLVE_PTR */
3213 const char *a = ap_conn->socks_request->address;
3214 tor_addr_t addr;
3215 int r;
3217 /* We're doing a reverse lookup. The input could be an IP address, or
3218 * could be an .in-addr.arpa or .ip6.arpa address */
3219 r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
3220 if (r <= 0) {
3221 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
3222 safe_str_client(a));
3223 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3224 return -1;
3227 r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
3228 if (r < 0) {
3229 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
3230 safe_str_client(a));
3231 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3232 return -1;
3235 string_addr = inaddr_buf;
3236 payload_len = (int)strlen(inaddr_buf)+1;
3237 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
3240 log_debug(LD_APP,
3241 "Sending relay cell to begin stream %d.", edge_conn->stream_id);
3243 if (connection_edge_send_command(edge_conn,
3244 RELAY_COMMAND_RESOLVE,
3245 string_addr, payload_len) < 0)
3246 return -1; /* circuit is closed, don't continue */
3248 if (!base_conn->address) {
3249 /* This might be unnecessary. XXXX */
3250 base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
3252 base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
3253 log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
3254 ", n_circ_id %u",
3255 base_conn->s, (unsigned)circ->base_.n_circ_id);
3256 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
3257 return 0;
3260 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
3261 * new linked connection pair, and attach one side to the conn, connection_add
3262 * it, initialize it to circuit_wait, and call
3263 * connection_ap_handshake_attach_circuit(conn) on it.
3265 * Return the newly created end of the linked connection pair, or -1 if error.
3267 entry_connection_t *
3268 connection_ap_make_link(connection_t *partner,
3269 char *address, uint16_t port,
3270 const char *digest,
3271 int session_group, int isolation_flags,
3272 int use_begindir, int want_onehop)
3274 entry_connection_t *conn;
3275 connection_t *base_conn;
3277 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
3278 want_onehop ? "direct" : "anonymized",
3279 safe_str_client(address), port);
3281 conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
3282 base_conn = ENTRY_TO_CONN(conn);
3283 base_conn->linked = 1; /* so that we can add it safely below. */
3285 /* populate conn->socks_request */
3287 /* leave version at zero, so the socks_reply is empty */
3288 conn->socks_request->socks_version = 0;
3289 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
3290 strlcpy(conn->socks_request->address, address,
3291 sizeof(conn->socks_request->address));
3292 conn->socks_request->port = port;
3293 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
3294 conn->want_onehop = want_onehop;
3295 conn->use_begindir = use_begindir;
3296 if (use_begindir) {
3297 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
3298 conn->chosen_exit_name[0] = '$';
3299 tor_assert(digest);
3300 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
3301 digest, DIGEST_LEN);
3304 /* Populate isolation fields. */
3305 conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
3306 conn->original_dest_address = tor_strdup(address);
3307 conn->entry_cfg.session_group = session_group;
3308 conn->entry_cfg.isolation_flags = isolation_flags;
3310 base_conn->address = tor_strdup("(Tor_internal)");
3311 tor_addr_make_unspec(&base_conn->addr);
3312 base_conn->port = 0;
3314 connection_link_connections(partner, base_conn);
3316 if (connection_add(base_conn) < 0) { /* no space, forget it */
3317 connection_free(base_conn);
3318 return NULL;
3321 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
3323 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3325 /* attaching to a dirty circuit is fine */
3326 connection_ap_mark_as_pending_circuit(conn);
3327 log_info(LD_APP,"... application connection created and linked.");
3328 return conn;
3331 /** Notify any interested controller connections about a new hostname resolve
3332 * or resolve error. Takes the same arguments as does
3333 * connection_ap_handshake_socks_resolved(). */
3334 static void
3335 tell_controller_about_resolved_result(entry_connection_t *conn,
3336 int answer_type,
3337 size_t answer_len,
3338 const char *answer,
3339 int ttl,
3340 time_t expires)
3342 expires = time(NULL) + ttl;
3343 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
3344 char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
3345 control_event_address_mapped(conn->socks_request->address,
3346 cp, expires, NULL, 0);
3347 tor_free(cp);
3348 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3349 char *cp = tor_strndup(answer, answer_len);
3350 control_event_address_mapped(conn->socks_request->address,
3351 cp, expires, NULL, 0);
3352 tor_free(cp);
3353 } else {
3354 control_event_address_mapped(conn->socks_request->address,
3355 "<error>", time(NULL)+ttl,
3356 "error=yes", 0);
3361 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
3362 * as the answer.
3364 void
3365 connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
3366 const tor_addr_t *answer,
3367 int ttl,
3368 time_t expires)
3370 if (tor_addr_family(answer) == AF_INET) {
3371 uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
3372 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
3373 (uint8_t*)&a,
3374 ttl, expires);
3375 } else if (tor_addr_family(answer) == AF_INET6) {
3376 const uint8_t *a = tor_addr_to_in6_addr8(answer);
3377 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
3379 ttl, expires);
3380 } else {
3381 log_warn(LD_BUG, "Got called with address of unexpected family %d",
3382 tor_addr_family(answer));
3383 connection_ap_handshake_socks_resolved(conn,
3384 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
3388 /** Send an answer to an AP connection that has requested a DNS lookup via
3389 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
3390 * for unreachable; the answer should be in the format specified in the socks
3391 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
3392 * certain errors or for values that didn't come via DNS. <b>expires</b> is
3393 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
3395 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
3396 * interface and those that use it less ugly. */
3397 MOCK_IMPL(void,
3398 connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
3399 int answer_type,
3400 size_t answer_len,
3401 const uint8_t *answer,
3402 int ttl,
3403 time_t expires))
3405 char buf[384];
3406 size_t replylen;
3408 if (ttl >= 0) {
3409 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3410 tor_addr_t a;
3411 tor_addr_from_ipv4n(&a, get_uint32(answer));
3412 if (! tor_addr_is_null(&a)) {
3413 client_dns_set_addressmap(conn,
3414 conn->socks_request->address, &a,
3415 conn->chosen_exit_name, ttl);
3417 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3418 tor_addr_t a;
3419 tor_addr_from_ipv6_bytes(&a, (char*)answer);
3420 if (! tor_addr_is_null(&a)) {
3421 client_dns_set_addressmap(conn,
3422 conn->socks_request->address, &a,
3423 conn->chosen_exit_name, ttl);
3425 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3426 char *cp = tor_strndup((char*)answer, answer_len);
3427 client_dns_set_reverse_addressmap(conn,
3428 conn->socks_request->address,
3430 conn->chosen_exit_name, ttl);
3431 tor_free(cp);
3435 if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
3436 if (conn->dns_server_request) {
3437 /* We had a request on our DNS port: answer it. */
3438 dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
3439 conn->socks_request->has_finished = 1;
3440 return;
3441 } else {
3442 /* This must be a request from the controller. Since answers to those
3443 * requests are not cached, they do not generate an ADDRMAP event on
3444 * their own. */
3445 tell_controller_about_resolved_result(conn, answer_type, answer_len,
3446 (char*)answer, ttl, expires);
3447 conn->socks_request->has_finished = 1;
3448 return;
3450 /* We shouldn't need to free conn here; it gets marked by the caller. */
3453 if (conn->socks_request->socks_version == 4) {
3454 buf[0] = 0x00; /* version */
3455 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3456 buf[1] = SOCKS4_GRANTED;
3457 set_uint16(buf+2, 0);
3458 memcpy(buf+4, answer, 4); /* address */
3459 replylen = SOCKS4_NETWORK_LEN;
3460 } else { /* "error" */
3461 buf[1] = SOCKS4_REJECT;
3462 memset(buf+2, 0, 6);
3463 replylen = SOCKS4_NETWORK_LEN;
3465 } else if (conn->socks_request->socks_version == 5) {
3466 /* SOCKS5 */
3467 buf[0] = 0x05; /* version */
3468 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3469 buf[1] = SOCKS5_SUCCEEDED;
3470 buf[2] = 0; /* reserved */
3471 buf[3] = 0x01; /* IPv4 address type */
3472 memcpy(buf+4, answer, 4); /* address */
3473 set_uint16(buf+8, 0); /* port == 0. */
3474 replylen = 10;
3475 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3476 buf[1] = SOCKS5_SUCCEEDED;
3477 buf[2] = 0; /* reserved */
3478 buf[3] = 0x04; /* IPv6 address type */
3479 memcpy(buf+4, answer, 16); /* address */
3480 set_uint16(buf+20, 0); /* port == 0. */
3481 replylen = 22;
3482 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3483 buf[1] = SOCKS5_SUCCEEDED;
3484 buf[2] = 0; /* reserved */
3485 buf[3] = 0x03; /* Domainname address type */
3486 buf[4] = (char)answer_len;
3487 memcpy(buf+5, answer, answer_len); /* address */
3488 set_uint16(buf+5+answer_len, 0); /* port == 0. */
3489 replylen = 5+answer_len+2;
3490 } else {
3491 buf[1] = SOCKS5_HOST_UNREACHABLE;
3492 memset(buf+2, 0, 8);
3493 replylen = 10;
3495 } else {
3496 /* no socks version info; don't send anything back */
3497 return;
3499 connection_ap_handshake_socks_reply(conn, buf, replylen,
3500 (answer_type == RESOLVED_TYPE_IPV4 ||
3501 answer_type == RESOLVED_TYPE_IPV6 ||
3502 answer_type == RESOLVED_TYPE_HOSTNAME) ?
3503 0 : END_STREAM_REASON_RESOLVEFAILED);
3506 /** Send a socks reply to stream <b>conn</b>, using the appropriate
3507 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
3508 * handshaking.
3510 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
3511 * and return, else reply based on <b>endreason</b> (one of
3512 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
3513 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
3515 void
3516 connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
3517 size_t replylen, int endreason)
3519 char buf[256];
3520 socks5_reply_status_t status =
3521 stream_end_reason_to_socks5_response(endreason);
3523 tor_assert(conn->socks_request); /* make sure it's an AP stream */
3525 if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3526 control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
3527 STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
3528 endreason);
3531 /* Flag this stream's circuit as having completed a stream successfully
3532 * (for path bias) */
3533 if (status == SOCKS5_SUCCEEDED ||
3534 endreason == END_STREAM_REASON_RESOLVEFAILED ||
3535 endreason == END_STREAM_REASON_CONNECTREFUSED ||
3536 endreason == END_STREAM_REASON_CONNRESET ||
3537 endreason == END_STREAM_REASON_NOROUTE ||
3538 endreason == END_STREAM_REASON_RESOURCELIMIT) {
3539 if (!conn->edge_.on_circuit ||
3540 !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
3541 if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
3542 log_info(LD_BUG,
3543 "No origin circuit for successful SOCKS stream %"PRIu64
3544 ". Reason: %d",
3545 (ENTRY_TO_CONN(conn)->global_identifier),
3546 endreason);
3549 * Else DNS remaps and failed hidden service lookups can send us
3550 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3552 * Perhaps we could make the test more precise; we can tell hidden
3553 * services by conn->edge_.renddata != NULL; anything analogous for
3554 * the DNS remap case?
3556 } else {
3557 // XXX: Hrmm. It looks like optimistic data can't go through this
3558 // codepath, but someone should probably test it and make sure.
3559 // We don't want to mark optimistically opened streams as successful.
3560 pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
3564 if (conn->socks_request->has_finished) {
3565 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
3566 "connection_ap_handshake_socks_reply.");
3567 return;
3569 if (replylen) { /* we already have a reply in mind */
3570 connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
3571 conn->socks_request->has_finished = 1;
3572 return;
3574 if (conn->socks_request->listener_type ==
3575 CONN_TYPE_AP_HTTP_CONNECT_LISTENER) {
3576 const char *response = end_reason_to_http_connect_response_line(endreason);
3577 if (!response) {
3578 response = "HTTP/1.0 400 Bad Request\r\n\r\n";
3580 connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
3581 } else if (conn->socks_request->socks_version == 4) {
3582 memset(buf,0,SOCKS4_NETWORK_LEN);
3583 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
3584 /* leave version, destport, destip zero */
3585 connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
3586 } else if (conn->socks_request->socks_version == 5) {
3587 size_t buf_len;
3588 memset(buf,0,sizeof(buf));
3589 if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
3590 buf[0] = 5; /* version 5 */
3591 buf[1] = (char)status;
3592 buf[2] = 0;
3593 buf[3] = 1; /* ipv4 addr */
3594 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3595 buf_len = 10;
3596 } else { /* AF_INET6. */
3597 buf[0] = 5; /* version 5 */
3598 buf[1] = (char)status;
3599 buf[2] = 0;
3600 buf[3] = 4; /* ipv6 addr */
3601 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3602 buf_len = 22;
3604 connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
3606 /* If socks_version isn't 4 or 5, don't send anything.
3607 * This can happen in the case of AP bridges. */
3608 conn->socks_request->has_finished = 1;
3609 return;
3612 /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
3613 * place the result in <b>bcell</b>. On success return 0; on failure return
3614 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
3615 * the client.
3617 * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
3618 * we don't.
3620 STATIC int
3621 begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
3622 uint8_t *end_reason_out)
3624 relay_header_t rh;
3625 const uint8_t *body, *nul;
3627 memset(bcell, 0, sizeof(*bcell));
3628 *end_reason_out = END_STREAM_REASON_MISC;
3630 relay_header_unpack(&rh, cell->payload);
3631 if (rh.length > RELAY_PAYLOAD_SIZE) {
3632 return -2; /*XXXX why not TORPROTOCOL? */
3635 bcell->stream_id = rh.stream_id;
3637 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3638 bcell->is_begindir = 1;
3639 return 0;
3640 } else if (rh.command != RELAY_COMMAND_BEGIN) {
3641 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3642 *end_reason_out = END_STREAM_REASON_INTERNAL;
3643 return -1;
3646 body = cell->payload + RELAY_HEADER_SIZE;
3647 nul = memchr(body, 0, rh.length);
3648 if (! nul) {
3649 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3650 "Relay begin cell has no \\0. Closing.");
3651 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3652 return -1;
3655 if (tor_addr_port_split(LOG_PROTOCOL_WARN,
3656 (char*)(body),
3657 &bcell->address,&bcell->port)<0) {
3658 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3659 "Unable to parse addr:port in relay begin cell. Closing.");
3660 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3661 return -1;
3663 if (bcell->port == 0) {
3664 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3665 "Missing port in relay begin cell. Closing.");
3666 tor_free(bcell->address);
3667 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3668 return -1;
3670 if (body + rh.length >= nul + 4)
3671 bcell->flags = ntohl(get_uint32(nul+1));
3673 return 0;
3676 /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
3677 * connection, attach it to the circ and connect it. Return 0 on success
3678 * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
3679 * where the caller should close the circuit. */
3680 static int
3681 handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
3683 int ret;
3684 origin_circuit_t *origin_circ;
3686 assert_circuit_ok(circ);
3687 tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
3688 tor_assert(conn);
3690 log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
3691 "to the service destination.");
3693 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3694 conn->base_.address = tor_strdup("(rendezvous)");
3695 conn->base_.state = EXIT_CONN_STATE_CONNECTING;
3697 /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
3698 * service. */
3699 if (origin_circ->rend_data) {
3700 conn->rend_data = rend_data_dup(origin_circ->rend_data);
3701 tor_assert(connection_edge_is_rendezvous_stream(conn));
3702 ret = rend_service_set_connection_addr_port(conn, origin_circ);
3703 } else if (origin_circ->hs_ident) {
3704 /* Setup the identifier to be the one for the circuit service. */
3705 conn->hs_ident =
3706 hs_ident_edge_conn_new(&origin_circ->hs_ident->identity_pk);
3707 tor_assert(connection_edge_is_rendezvous_stream(conn));
3708 ret = hs_service_set_conn_addr_port(origin_circ, conn);
3709 } else {
3710 /* We should never get here if the circuit's purpose is rendezvous. */
3711 tor_assert_nonfatal_unreached();
3712 return -1;
3714 if (ret < 0) {
3715 log_info(LD_REND, "Didn't find rendezvous service (addr%s, port %d)",
3716 fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port);
3717 /* Send back reason DONE because we want to make hidden service port
3718 * scanning harder thus instead of returning that the exit policy
3719 * didn't match, which makes it obvious that the port is closed,
3720 * return DONE and kill the circuit. That way, a user (malicious or
3721 * not) needs one circuit per bad port unless it matches the policy of
3722 * the hidden service. */
3723 relay_send_end_cell_from_edge(conn->stream_id, circ,
3724 END_STREAM_REASON_DONE,
3725 origin_circ->cpath->prev);
3726 connection_free_(TO_CONN(conn));
3728 /* Drop the circuit here since it might be someone deliberately
3729 * scanning the hidden service ports. Note that this mitigates port
3730 * scanning by adding more work on the attacker side to successfully
3731 * scan but does not fully solve it. */
3732 if (ret < -1) {
3733 return END_CIRC_AT_ORIGIN;
3734 } else {
3735 return 0;
3739 /* Link the circuit and the connection crypt path. */
3740 conn->cpath_layer = origin_circ->cpath->prev;
3742 /* If this is the first stream on this circuit, tell circpad */
3743 if (!origin_circ->p_streams)
3744 circpad_machine_event_circ_has_streams(origin_circ);
3746 /* Add it into the linked list of p_streams on this circuit */
3747 conn->next_stream = origin_circ->p_streams;
3748 origin_circ->p_streams = conn;
3749 conn->on_circuit = circ;
3750 assert_circuit_ok(circ);
3752 hs_inc_rdv_stream_counter(origin_circ);
3754 /* If it's an onion service connection, we might want to include the proxy
3755 * protocol header: */
3756 if (conn->hs_ident) {
3757 hs_circuit_id_protocol_t circuit_id_protocol =
3758 hs_service_exports_circuit_id(&conn->hs_ident->identity_pk);
3759 export_hs_client_circuit_id(conn, circuit_id_protocol);
3762 /* Connect tor to the hidden service destination. */
3763 connection_exit_connect(conn);
3765 /* For path bias: This circuit was used successfully */
3766 pathbias_mark_use_success(origin_circ);
3767 return 0;
3770 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
3771 * an exit hop for the circuit, or we are the origin and it is a
3772 * rendezvous begin.
3774 * Launch a new exit connection and initialize things appropriately.
3776 * If it's a rendezvous stream, call connection_exit_connect() on
3777 * it.
3779 * For general streams, call dns_resolve() on it first, and only call
3780 * connection_exit_connect() if the dns answer is already known.
3782 * Note that we don't call connection_add() on the new stream! We wait
3783 * for connection_exit_connect() to do that.
3785 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
3786 * Else return 0.
3789 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
3791 edge_connection_t *n_stream;
3792 relay_header_t rh;
3793 char *address = NULL;
3794 uint16_t port = 0;
3795 or_circuit_t *or_circ = NULL;
3796 origin_circuit_t *origin_circ = NULL;
3797 crypt_path_t *layer_hint = NULL;
3798 const or_options_t *options = get_options();
3799 begin_cell_t bcell;
3800 int rv;
3801 uint8_t end_reason=0;
3803 assert_circuit_ok(circ);
3804 if (!CIRCUIT_IS_ORIGIN(circ)) {
3805 or_circ = TO_OR_CIRCUIT(circ);
3806 } else {
3807 tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
3808 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3809 layer_hint = origin_circ->cpath->prev;
3812 relay_header_unpack(&rh, cell->payload);
3813 if (rh.length > RELAY_PAYLOAD_SIZE)
3814 return -END_CIRC_REASON_TORPROTOCOL;
3816 if (!server_mode(options) &&
3817 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
3818 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3819 "Relay begin cell at non-server. Closing.");
3820 relay_send_end_cell_from_edge(rh.stream_id, circ,
3821 END_STREAM_REASON_EXITPOLICY, NULL);
3822 return 0;
3825 rv = begin_cell_parse(cell, &bcell, &end_reason);
3826 if (rv < -1) {
3827 return -END_CIRC_REASON_TORPROTOCOL;
3828 } else if (rv == -1) {
3829 tor_free(bcell.address);
3830 relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
3831 return 0;
3834 if (! bcell.is_begindir) {
3835 /* Steal reference */
3836 address = bcell.address;
3837 port = bcell.port;
3839 if (or_circ && or_circ->p_chan) {
3840 const int client_chan = channel_is_client(or_circ->p_chan);
3841 if ((client_chan ||
3842 (!connection_or_digest_is_known_relay(
3843 or_circ->p_chan->identity_digest) &&
3844 should_refuse_unknown_exits(options)))) {
3845 /* Don't let clients use us as a single-hop proxy. It attracts
3846 * attackers and users who'd be better off with, well, single-hop
3847 * proxies. */
3848 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3849 "Attempt by %s to open a stream %s. Closing.",
3850 safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
3851 client_chan ? "on first hop of circuit" :
3852 "from unknown relay");
3853 relay_send_end_cell_from_edge(rh.stream_id, circ,
3854 client_chan ?
3855 END_STREAM_REASON_TORPROTOCOL :
3856 END_STREAM_REASON_MISC,
3857 NULL);
3858 tor_free(address);
3859 return 0;
3862 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3863 if (!directory_permits_begindir_requests(options) ||
3864 circ->purpose != CIRCUIT_PURPOSE_OR) {
3865 relay_send_end_cell_from_edge(rh.stream_id, circ,
3866 END_STREAM_REASON_NOTDIRECTORY, layer_hint);
3867 return 0;
3869 /* Make sure to get the 'real' address of the previous hop: the
3870 * caller might want to know whether the remote IP address has changed,
3871 * and we might already have corrected base_.addr[ess] for the relay's
3872 * canonical IP address. */
3873 if (or_circ && or_circ->p_chan)
3874 address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
3875 else
3876 address = tor_strdup("127.0.0.1");
3877 port = 1; /* XXXX This value is never actually used anywhere, and there
3878 * isn't "really" a connection here. But we
3879 * need to set it to something nonzero. */
3880 } else {
3881 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3882 relay_send_end_cell_from_edge(rh.stream_id, circ,
3883 END_STREAM_REASON_INTERNAL, layer_hint);
3884 return 0;
3887 if (! options->IPv6Exit) {
3888 /* I don't care if you prefer IPv6; I can't give you any. */
3889 bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
3890 /* If you don't want IPv4, I can't help. */
3891 if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
3892 tor_free(address);
3893 relay_send_end_cell_from_edge(rh.stream_id, circ,
3894 END_STREAM_REASON_EXITPOLICY, layer_hint);
3895 return 0;
3899 log_debug(LD_EXIT,"Creating new exit connection.");
3900 /* The 'AF_INET' here is temporary; we might need to change it later in
3901 * connection_exit_connect(). */
3902 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
3904 /* Remember the tunneled request ID in the new edge connection, so that
3905 * we can measure download times. */
3906 n_stream->dirreq_id = circ->dirreq_id;
3908 n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
3909 n_stream->begincell_flags = bcell.flags;
3910 n_stream->stream_id = rh.stream_id;
3911 n_stream->base_.port = port;
3912 /* leave n_stream->s at -1, because it's not yet valid */
3913 n_stream->package_window = STREAMWINDOW_START;
3914 n_stream->deliver_window = STREAMWINDOW_START;
3916 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
3917 int ret;
3918 tor_free(address);
3919 /* We handle this circuit and stream in this function for all supported
3920 * hidden service version. */
3921 ret = handle_hs_exit_conn(circ, n_stream);
3923 if (ret == 0) {
3924 /* This was a valid cell. Count it as delivered + overhead. */
3925 circuit_read_valid_data(origin_circ, rh.length);
3927 return ret;
3929 tor_strlower(address);
3930 n_stream->base_.address = address;
3931 n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3932 /* default to failed, change in dns_resolve if it turns out not to fail */
3934 /* If we're hibernating or shutting down, we refuse to open new streams. */
3935 if (we_are_hibernating()) {
3936 relay_send_end_cell_from_edge(rh.stream_id, circ,
3937 END_STREAM_REASON_HIBERNATING, NULL);
3938 connection_free_(TO_CONN(n_stream));
3939 return 0;
3942 n_stream->on_circuit = circ;
3944 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3945 tor_addr_t tmp_addr;
3946 tor_assert(or_circ);
3947 if (or_circ->p_chan &&
3948 channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
3949 tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
3951 return connection_exit_connect_dir(n_stream);
3954 log_debug(LD_EXIT,"about to start the dns_resolve().");
3956 /* send it off to the gethostbyname farm */
3957 switch (dns_resolve(n_stream)) {
3958 case 1: /* resolve worked; now n_stream is attached to circ. */
3959 assert_circuit_ok(circ);
3960 log_debug(LD_EXIT,"about to call connection_exit_connect().");
3961 connection_exit_connect(n_stream);
3962 return 0;
3963 case -1: /* resolve failed */
3964 relay_send_end_cell_from_edge(rh.stream_id, circ,
3965 END_STREAM_REASON_RESOLVEFAILED, NULL);
3966 /* n_stream got freed. don't touch it. */
3967 break;
3968 case 0: /* resolve added to pending list */
3969 assert_circuit_ok(circ);
3970 break;
3972 return 0;
3976 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
3977 * circuit <b>circ</b>;
3978 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
3981 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
3983 edge_connection_t *dummy_conn;
3984 relay_header_t rh;
3986 assert_circuit_ok(TO_CIRCUIT(circ));
3987 relay_header_unpack(&rh, cell->payload);
3988 if (rh.length > RELAY_PAYLOAD_SIZE)
3989 return -1;
3991 /* This 'dummy_conn' only exists to remember the stream ID
3992 * associated with the resolve request; and to make the
3993 * implementation of dns.c more uniform. (We really only need to
3994 * remember the circuit, the stream ID, and the hostname to be
3995 * resolved; but if we didn't store them in a connection like this,
3996 * the housekeeping in dns.c would get way more complicated.)
3998 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
3999 dummy_conn->stream_id = rh.stream_id;
4000 dummy_conn->base_.address = tor_strndup(
4001 (char*)cell->payload+RELAY_HEADER_SIZE,
4002 rh.length);
4003 dummy_conn->base_.port = 0;
4004 dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4005 dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
4007 dummy_conn->on_circuit = TO_CIRCUIT(circ);
4009 /* send it off to the gethostbyname farm */
4010 switch (dns_resolve(dummy_conn)) {
4011 case -1: /* Impossible to resolve; a resolved cell was sent. */
4012 /* Connection freed; don't touch it. */
4013 return 0;
4014 case 1: /* The result was cached; a resolved cell was sent. */
4015 if (!dummy_conn->base_.marked_for_close)
4016 connection_free_(TO_CONN(dummy_conn));
4017 return 0;
4018 case 0: /* resolve added to pending list */
4019 assert_circuit_ok(TO_CIRCUIT(circ));
4020 break;
4022 return 0;
4025 /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
4026 * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
4028 static int
4029 my_exit_policy_rejects(const tor_addr_t *addr,
4030 uint16_t port,
4031 const char **why_rejected)
4033 if (router_compare_to_my_exit_policy(addr, port)) {
4034 *why_rejected = "";
4035 return 1;
4036 } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
4037 *why_rejected = " (IPv6 address without IPv6Exit configured)";
4038 return 1;
4040 return 0;
4043 /** Connect to conn's specified addr and port. If it worked, conn
4044 * has now been added to the connection_array.
4046 * Send back a connected cell. Include the resolved IP of the destination
4047 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
4048 * streams must not reveal what IP they connected to.)
4050 void
4051 connection_exit_connect(edge_connection_t *edge_conn)
4053 const tor_addr_t *addr;
4054 uint16_t port;
4055 connection_t *conn = TO_CONN(edge_conn);
4056 int socket_error = 0, result;
4057 const char *why_failed_exit_policy = NULL;
4059 /* Apply exit policy to non-rendezvous connections. */
4060 if (! connection_edge_is_rendezvous_stream(edge_conn) &&
4061 my_exit_policy_rejects(&edge_conn->base_.addr,
4062 edge_conn->base_.port,
4063 &why_failed_exit_policy)) {
4064 if (BUG(!why_failed_exit_policy))
4065 why_failed_exit_policy = "";
4066 log_info(LD_EXIT,"%s:%d failed exit policy%s. Closing.",
4067 escaped_safe_str_client(conn->address), conn->port,
4068 why_failed_exit_policy);
4069 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
4070 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4071 connection_free(conn);
4072 return;
4075 #ifdef HAVE_SYS_UN_H
4076 if (conn->socket_family != AF_UNIX) {
4077 #else
4079 #endif /* defined(HAVE_SYS_UN_H) */
4080 addr = &conn->addr;
4081 port = conn->port;
4083 if (tor_addr_family(addr) == AF_INET6)
4084 conn->socket_family = AF_INET6;
4086 log_debug(LD_EXIT, "about to try connecting");
4087 result = connection_connect(conn, conn->address,
4088 addr, port, &socket_error);
4089 #ifdef HAVE_SYS_UN_H
4090 } else {
4092 * In the AF_UNIX case, we expect to have already had conn->port = 1,
4093 * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
4094 * case in connection_handle_listener_read()), and conn->address should
4095 * have the socket path to connect to.
4097 tor_assert(conn->address && strlen(conn->address) > 0);
4099 log_debug(LD_EXIT, "about to try connecting");
4100 result = connection_connect_unix(conn, conn->address, &socket_error);
4101 #endif /* defined(HAVE_SYS_UN_H) */
4104 switch (result) {
4105 case -1: {
4106 int reason = errno_to_stream_end_reason(socket_error);
4107 connection_edge_end(edge_conn, reason);
4108 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4109 connection_free(conn);
4110 return;
4112 case 0:
4113 conn->state = EXIT_CONN_STATE_CONNECTING;
4115 connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
4116 /* writable indicates finish;
4117 * readable/error indicates broken link in windows-land. */
4118 return;
4119 /* case 1: fall through */
4122 conn->state = EXIT_CONN_STATE_OPEN;
4123 if (connection_get_outbuf_len(conn)) {
4124 /* in case there are any queued data cells, from e.g. optimistic data */
4125 connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
4126 } else {
4127 connection_watch_events(conn, READ_EVENT);
4130 /* also, deliver a 'connected' cell back through the circuit. */
4131 if (connection_edge_is_rendezvous_stream(edge_conn)) {
4132 /* don't send an address back! */
4133 connection_edge_send_command(edge_conn,
4134 RELAY_COMMAND_CONNECTED,
4135 NULL, 0);
4136 } else { /* normal stream */
4137 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
4138 int connected_payload_len =
4139 connected_cell_format_payload(connected_payload, &conn->addr,
4140 edge_conn->address_ttl);
4141 if (connected_payload_len < 0) {
4142 connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
4143 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4144 connection_free(conn);
4145 return;
4148 connection_edge_send_command(edge_conn,
4149 RELAY_COMMAND_CONNECTED,
4150 (char*)connected_payload,
4151 connected_payload_len);
4155 /** Given an exit conn that should attach to us as a directory server, open a
4156 * bridge connection with a linked connection pair, create a new directory
4157 * conn, and join them together. Return 0 on success (or if there was an
4158 * error we could send back an end cell for). Return -(some circuit end
4159 * reason) if the circuit needs to be torn down. Either connects
4160 * <b>exitconn</b>, frees it, or marks it, as appropriate.
4162 static int
4163 connection_exit_connect_dir(edge_connection_t *exitconn)
4165 dir_connection_t *dirconn = NULL;
4166 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
4168 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
4170 exitconn->base_.state = EXIT_CONN_STATE_OPEN;
4172 dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
4174 tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
4175 dirconn->base_.port = 0;
4176 dirconn->base_.address = tor_strdup(exitconn->base_.address);
4177 dirconn->base_.type = CONN_TYPE_DIR;
4178 dirconn->base_.purpose = DIR_PURPOSE_SERVER;
4179 dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
4181 /* Note that the new dir conn belongs to the same tunneled request as
4182 * the edge conn, so that we can measure download times. */
4183 dirconn->dirreq_id = exitconn->dirreq_id;
4185 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
4187 if (connection_add(TO_CONN(exitconn))<0) {
4188 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4189 connection_free_(TO_CONN(exitconn));
4190 connection_free_(TO_CONN(dirconn));
4191 return 0;
4194 /* link exitconn to circ, now that we know we can use it. */
4195 exitconn->next_stream = circ->n_streams;
4196 circ->n_streams = exitconn;
4198 if (connection_add(TO_CONN(dirconn))<0) {
4199 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4200 connection_close_immediate(TO_CONN(exitconn));
4201 connection_mark_for_close(TO_CONN(exitconn));
4202 connection_free_(TO_CONN(dirconn));
4203 return 0;
4206 connection_start_reading(TO_CONN(dirconn));
4207 connection_start_reading(TO_CONN(exitconn));
4209 if (connection_edge_send_command(exitconn,
4210 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
4211 connection_mark_for_close(TO_CONN(exitconn));
4212 connection_mark_for_close(TO_CONN(dirconn));
4213 return 0;
4216 return 0;
4219 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
4220 * it is a general stream.
4223 connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
4225 tor_assert(conn);
4226 /* It should not be possible to set both of these structs */
4227 tor_assert_nonfatal(!(conn->rend_data && conn->hs_ident));
4229 if (conn->rend_data || conn->hs_ident) {
4230 return 1;
4232 return 0;
4235 /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
4236 * to exit from it, or 0 if it probably will not allow it.
4237 * (We might be uncertain if conn's destination address has not yet been
4238 * resolved.)
4241 connection_ap_can_use_exit(const entry_connection_t *conn,
4242 const node_t *exit_node)
4244 const or_options_t *options = get_options();
4246 tor_assert(conn);
4247 tor_assert(conn->socks_request);
4248 tor_assert(exit_node);
4250 /* If a particular exit node has been requested for the new connection,
4251 * make sure the exit node of the existing circuit matches exactly.
4253 if (conn->chosen_exit_name) {
4254 const node_t *chosen_exit =
4255 node_get_by_nickname(conn->chosen_exit_name, 0);
4256 if (!chosen_exit || tor_memneq(chosen_exit->identity,
4257 exit_node->identity, DIGEST_LEN)) {
4258 /* doesn't match */
4259 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
4260 // conn->chosen_exit_name, exit->nickname);
4261 return 0;
4265 if (conn->use_begindir) {
4266 /* Internal directory fetches do not count as exiting. */
4267 return 1;
4270 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
4271 tor_addr_t addr, *addrp = NULL;
4272 addr_policy_result_t r;
4273 if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
4274 addrp = &addr;
4275 } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
4276 tor_addr_make_null(&addr, AF_INET6);
4277 addrp = &addr;
4278 } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
4279 tor_addr_make_null(&addr, AF_INET);
4280 addrp = &addr;
4282 r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,
4283 exit_node);
4284 if (r == ADDR_POLICY_REJECTED)
4285 return 0; /* We know the address, and the exit policy rejects it. */
4286 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
4287 return 0; /* We don't know the addr, but the exit policy rejects most
4288 * addresses with this port. Since the user didn't ask for
4289 * this node, err on the side of caution. */
4290 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
4291 /* Don't send DNS requests to non-exit servers by default. */
4292 if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
4293 return 0;
4295 if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
4296 /* Not a suitable exit. Refuse it. */
4297 return 0;
4300 return 1;
4303 /** If address is of the form "y.onion" with a well-formed handle y:
4304 * Put a NUL after y, lower-case it, and return ONION_V2_HOSTNAME or
4305 * ONION_V3_HOSTNAME depending on the HS version.
4307 * If address is of the form "x.y.onion" with a well-formed handle x:
4308 * Drop "x.", put a NUL after y, lower-case it, and return
4309 * ONION_V2_HOSTNAME or ONION_V3_HOSTNAME depending on the HS version.
4311 * If address is of the form "y.onion" with a badly-formed handle y:
4312 * Return BAD_HOSTNAME and log a message.
4314 * If address is of the form "y.exit":
4315 * Put a NUL after y and return EXIT_HOSTNAME.
4317 * Otherwise:
4318 * Return NORMAL_HOSTNAME and change nothing.
4320 hostname_type_t
4321 parse_extended_hostname(char *address)
4323 char *s;
4324 char *q;
4325 char query[HS_SERVICE_ADDR_LEN_BASE32+1];
4327 s = strrchr(address,'.');
4328 if (!s)
4329 return NORMAL_HOSTNAME; /* no dot, thus normal */
4330 if (!strcmp(s+1,"exit")) {
4331 *s = 0; /* NUL-terminate it */
4332 return EXIT_HOSTNAME; /* .exit */
4334 if (strcmp(s+1,"onion"))
4335 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
4337 /* so it is .onion */
4338 *s = 0; /* NUL-terminate it */
4339 /* locate a 'sub-domain' component, in order to remove it */
4340 q = strrchr(address, '.');
4341 if (q == address) {
4342 goto failed; /* reject sub-domain, as DNS does */
4344 q = (NULL == q) ? address : q + 1;
4345 if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
4346 HS_SERVICE_ADDR_LEN_BASE32+1)
4347 goto failed;
4348 if (q != address) {
4349 memmove(address, q, strlen(q) + 1 /* also get \0 */);
4351 if (rend_valid_v2_service_id(query)) {
4352 return ONION_V2_HOSTNAME; /* success */
4354 if (hs_address_is_valid(query)) {
4355 return ONION_V3_HOSTNAME;
4357 failed:
4358 /* otherwise, return to previous state and return 0 */
4359 *s = '.';
4360 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
4361 safe_str_client(address));
4362 return BAD_HOSTNAME;
4365 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
4366 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
4367 * at <b>b</b>. */
4368 static int
4369 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
4371 if (a == NULL) {
4372 return (b == NULL);
4373 } else if (b == NULL) {
4374 return 0;
4375 } else if (alen != blen) {
4376 return 0;
4377 } else {
4378 return tor_memeq(a, b, alen);
4383 * Return true iff none of the isolation flags and fields in <b>conn</b>
4384 * should prevent it from being attached to <b>circ</b>.
4387 connection_edge_compatible_with_circuit(const entry_connection_t *conn,
4388 const origin_circuit_t *circ)
4390 const uint8_t iso = conn->entry_cfg.isolation_flags;
4391 const socks_request_t *sr = conn->socks_request;
4393 /* If circ has never been used for an isolated connection, we can
4394 * totally use it for this one. */
4395 if (!circ->isolation_values_set)
4396 return 1;
4398 /* If circ has been used for connections having more than one value
4399 * for some field f, it will have the corresponding bit set in
4400 * isolation_flags_mixed. If isolation_flags_mixed has any bits
4401 * in common with iso, then conn must be isolated from at least
4402 * one stream that has been attached to circ. */
4403 if ((iso & circ->isolation_flags_mixed) != 0) {
4404 /* For at least one field where conn is isolated, the circuit
4405 * already has mixed streams. */
4406 return 0;
4409 if (! conn->original_dest_address) {
4410 log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
4411 "having set conn->original_dest_address");
4412 ((entry_connection_t*)conn)->original_dest_address =
4413 tor_strdup(conn->socks_request->address);
4416 if ((iso & ISO_STREAM) &&
4417 (circ->associated_isolated_stream_global_id !=
4418 ENTRY_TO_CONN(conn)->global_identifier))
4419 return 0;
4421 if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
4422 return 0;
4423 if ((iso & ISO_DESTADDR) &&
4424 strcasecmp(conn->original_dest_address, circ->dest_address))
4425 return 0;
4426 if ((iso & ISO_SOCKSAUTH) &&
4427 (! memeq_opt(sr->username, sr->usernamelen,
4428 circ->socks_username, circ->socks_username_len) ||
4429 ! memeq_opt(sr->password, sr->passwordlen,
4430 circ->socks_password, circ->socks_password_len)))
4431 return 0;
4432 if ((iso & ISO_CLIENTPROTO) &&
4433 (conn->socks_request->listener_type != circ->client_proto_type ||
4434 conn->socks_request->socks_version != circ->client_proto_socksver))
4435 return 0;
4436 if ((iso & ISO_CLIENTADDR) &&
4437 !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4438 return 0;
4439 if ((iso & ISO_SESSIONGRP) &&
4440 conn->entry_cfg.session_group != circ->session_group)
4441 return 0;
4442 if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
4443 return 0;
4445 return 1;
4449 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
4450 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
4451 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
4452 * a bitfield of isolation flags that we would have to set in
4453 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
4454 * <b>circ</b> has had no streams attached to it.
4457 connection_edge_update_circuit_isolation(const entry_connection_t *conn,
4458 origin_circuit_t *circ,
4459 int dry_run)
4461 const socks_request_t *sr = conn->socks_request;
4462 if (! conn->original_dest_address) {
4463 log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
4464 "having set conn->original_dest_address");
4465 ((entry_connection_t*)conn)->original_dest_address =
4466 tor_strdup(conn->socks_request->address);
4469 if (!circ->isolation_values_set) {
4470 if (dry_run)
4471 return -1;
4472 circ->associated_isolated_stream_global_id =
4473 ENTRY_TO_CONN(conn)->global_identifier;
4474 circ->dest_port = conn->socks_request->port;
4475 circ->dest_address = tor_strdup(conn->original_dest_address);
4476 circ->client_proto_type = conn->socks_request->listener_type;
4477 circ->client_proto_socksver = conn->socks_request->socks_version;
4478 tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
4479 circ->session_group = conn->entry_cfg.session_group;
4480 circ->nym_epoch = conn->nym_epoch;
4481 circ->socks_username = sr->username ?
4482 tor_memdup(sr->username, sr->usernamelen) : NULL;
4483 circ->socks_password = sr->password ?
4484 tor_memdup(sr->password, sr->passwordlen) : NULL;
4485 circ->socks_username_len = sr->usernamelen;
4486 circ->socks_password_len = sr->passwordlen;
4488 circ->isolation_values_set = 1;
4489 return 0;
4490 } else {
4491 uint8_t mixed = 0;
4492 if (conn->socks_request->port != circ->dest_port)
4493 mixed |= ISO_DESTPORT;
4494 if (strcasecmp(conn->original_dest_address, circ->dest_address))
4495 mixed |= ISO_DESTADDR;
4496 if (!memeq_opt(sr->username, sr->usernamelen,
4497 circ->socks_username, circ->socks_username_len) ||
4498 !memeq_opt(sr->password, sr->passwordlen,
4499 circ->socks_password, circ->socks_password_len))
4500 mixed |= ISO_SOCKSAUTH;
4501 if ((conn->socks_request->listener_type != circ->client_proto_type ||
4502 conn->socks_request->socks_version != circ->client_proto_socksver))
4503 mixed |= ISO_CLIENTPROTO;
4504 if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4505 mixed |= ISO_CLIENTADDR;
4506 if (conn->entry_cfg.session_group != circ->session_group)
4507 mixed |= ISO_SESSIONGRP;
4508 if (conn->nym_epoch != circ->nym_epoch)
4509 mixed |= ISO_NYM_EPOCH;
4511 if (dry_run)
4512 return mixed;
4514 if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
4515 log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
4516 "isolation flags.");
4518 circ->isolation_flags_mixed |= mixed;
4519 return 0;
4524 * Clear the isolation settings on <b>circ</b>.
4526 * This only works on an open circuit that has never had a stream attached to
4527 * it, and whose isolation settings are hypothetical. (We set hypothetical
4528 * isolation settings on circuits as we're launching them, so that we
4529 * know whether they can handle more streams or whether we need to launch
4530 * even more circuits. Once the circuit is open, if it turns out that
4531 * we no longer have any streams to attach to it, we clear the isolation flags
4532 * and data so that other streams can have a chance.)
4534 void
4535 circuit_clear_isolation(origin_circuit_t *circ)
4537 if (circ->isolation_any_streams_attached) {
4538 log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
4539 return;
4541 if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
4542 log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
4543 "circuit");
4544 return;
4547 circ->isolation_values_set = 0;
4548 circ->isolation_flags_mixed = 0;
4549 circ->associated_isolated_stream_global_id = 0;
4550 circ->client_proto_type = 0;
4551 circ->client_proto_socksver = 0;
4552 circ->dest_port = 0;
4553 tor_addr_make_unspec(&circ->client_addr);
4554 tor_free(circ->dest_address);
4555 circ->session_group = -1;
4556 circ->nym_epoch = 0;
4557 if (circ->socks_username) {
4558 memwipe(circ->socks_username, 0x11, circ->socks_username_len);
4559 tor_free(circ->socks_username);
4561 if (circ->socks_password) {
4562 memwipe(circ->socks_password, 0x05, circ->socks_password_len);
4563 tor_free(circ->socks_password);
4565 circ->socks_username_len = circ->socks_password_len = 0;
4568 /** Send an END and mark for close the given edge connection conn using the
4569 * given reason that has to be a stream reason.
4571 * Note: We don't unattached the AP connection (if applicable) because we
4572 * don't want to flush the remaining data. This function aims at ending
4573 * everything quickly regardless of the connection state.
4575 * This function can't fail and does nothing if conn is NULL. */
4576 void
4577 connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
4579 if (!conn) {
4580 return;
4583 connection_edge_end(conn, reason);
4584 connection_mark_for_close(TO_CONN(conn));
4587 /** Free all storage held in module-scoped variables for connection_edge.c */
4588 void
4589 connection_edge_free_all(void)
4591 untried_pending_connections = 0;
4592 smartlist_free(pending_entry_connections);
4593 pending_entry_connections = NULL;
4594 mainloop_event_free(attach_pending_entry_connections_ev);