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