Don't use log_err for non-criticial warnings.
[tor/rransom.git] / src / or / connection_edge.c
blob0970cda4b912fec15449dd0b8972238aec2e4731
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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_edge.c
9 * \brief Handle edge streams.
10 **/
12 #include "or.h"
13 #include "buffers.h"
14 #include "circuitlist.h"
15 #include "circuituse.h"
16 #include "config.h"
17 #include "connection.h"
18 #include "connection_edge.h"
19 #include "connection_or.h"
20 #include "control.h"
21 #include "dns.h"
22 #include "dnsserv.h"
23 #include "dirserv.h"
24 #include "hibernate.h"
25 #include "main.h"
26 #include "policies.h"
27 #include "reasons.h"
28 #include "relay.h"
29 #include "rendclient.h"
30 #include "rendcommon.h"
31 #include "rendservice.h"
32 #include "rephist.h"
33 #include "router.h"
34 #include "routerlist.h"
36 #ifdef HAVE_LINUX_TYPES_H
37 #include <linux/types.h>
38 #endif
39 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
40 #include <linux/netfilter_ipv4.h>
41 #define TRANS_NETFILTER
42 #endif
44 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
45 #include <net/if.h>
46 #include <net/pfvar.h>
47 #define TRANS_PF
48 #endif
50 #define SOCKS4_GRANTED 90
51 #define SOCKS4_REJECT 91
53 static int connection_ap_handshake_process_socks(edge_connection_t *conn);
54 static int connection_ap_process_natd(edge_connection_t *conn);
55 static int connection_exit_connect_dir(edge_connection_t *exitconn);
56 static int address_is_in_virtual_range(const char *addr);
57 static int consider_plaintext_ports(edge_connection_t *conn, uint16_t port);
58 static void clear_trackexithost_mappings(const char *exitname);
60 /** An AP stream has failed/finished. If it hasn't already sent back
61 * a socks reply, send one now (based on endreason). Also set
62 * has_sent_end to 1, and mark the conn.
64 void
65 _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
66 int line, const char *file)
68 tor_assert(conn->_base.type == CONN_TYPE_AP);
69 conn->edge_has_sent_end = 1; /* no circ yet */
71 if (conn->_base.marked_for_close) {
72 /* This call will warn as appropriate. */
73 _connection_mark_for_close(TO_CONN(conn), line, file);
74 return;
77 if (!conn->socks_request->has_finished) {
78 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
79 log_warn(LD_BUG,
80 "stream (marked at %s:%d) sending two socks replies?",
81 file, line);
83 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
84 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
85 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
86 connection_ap_handshake_socks_resolved(conn,
87 RESOLVED_TYPE_ERROR_TRANSIENT,
88 0, NULL, -1, -1);
89 else /* unknown or no handshake at all. send no response. */
90 conn->socks_request->has_finished = 1;
93 _connection_mark_for_close(TO_CONN(conn), line, file);
94 conn->_base.hold_open_until_flushed = 1;
95 conn->end_reason = endreason;
98 /** There was an EOF. Send an end and mark the connection for close.
101 connection_edge_reached_eof(edge_connection_t *conn)
103 if (buf_datalen(conn->_base.inbuf) &&
104 connection_state_is_open(TO_CONN(conn))) {
105 /* it still has stuff to process. don't let it die yet. */
106 return 0;
108 log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
109 if (!conn->_base.marked_for_close) {
110 /* only mark it if not already marked. it's possible to
111 * get the 'end' right around when the client hangs up on us. */
112 connection_edge_end(conn, END_STREAM_REASON_DONE);
113 if (conn->socks_request) /* eof, so don't send a socks reply back */
114 conn->socks_request->has_finished = 1;
115 connection_mark_for_close(TO_CONN(conn));
117 return 0;
120 /** Handle new bytes on conn->inbuf based on state:
121 * - If it's waiting for socks info, try to read another step of the
122 * socks handshake out of conn->inbuf.
123 * - If it's waiting for the original destination, fetch it.
124 * - If it's open, then package more relay cells from the stream.
125 * - Else, leave the bytes on inbuf alone for now.
127 * Mark and return -1 if there was an unexpected error with the conn,
128 * else return 0.
131 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
133 tor_assert(conn);
135 switch (conn->_base.state) {
136 case AP_CONN_STATE_SOCKS_WAIT:
137 if (connection_ap_handshake_process_socks(conn) < 0) {
138 /* already marked */
139 return -1;
141 return 0;
142 case AP_CONN_STATE_NATD_WAIT:
143 if (connection_ap_process_natd(conn) < 0) {
144 /* already marked */
145 return -1;
147 return 0;
148 case AP_CONN_STATE_OPEN:
149 case EXIT_CONN_STATE_OPEN:
150 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
151 /* (We already sent an end cell if possible) */
152 connection_mark_for_close(TO_CONN(conn));
153 return -1;
155 return 0;
156 case EXIT_CONN_STATE_CONNECTING:
157 case AP_CONN_STATE_RENDDESC_WAIT:
158 case AP_CONN_STATE_CIRCUIT_WAIT:
159 case AP_CONN_STATE_CONNECT_WAIT:
160 case AP_CONN_STATE_RESOLVE_WAIT:
161 case AP_CONN_STATE_CONTROLLER_WAIT:
162 log_info(LD_EDGE,
163 "data from edge while in '%s' state. Leaving it on buffer.",
164 conn_state_to_string(conn->_base.type, conn->_base.state));
165 return 0;
167 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
168 tor_fragile_assert();
169 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
170 connection_mark_for_close(TO_CONN(conn));
171 return -1;
174 /** This edge needs to be closed, because its circuit has closed.
175 * Mark it for close and return 0.
178 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
180 if (!conn->_base.marked_for_close) {
181 log_info(LD_EDGE,
182 "CircID %d: At an edge. Marking connection for close.", circ_id);
183 if (conn->_base.type == CONN_TYPE_AP) {
184 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
185 control_event_stream_bandwidth(conn);
186 control_event_stream_status(conn, STREAM_EVENT_CLOSED,
187 END_STREAM_REASON_DESTROY);
188 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
189 } else {
190 /* closing the circuit, nothing to send an END to */
191 conn->edge_has_sent_end = 1;
192 conn->end_reason = END_STREAM_REASON_DESTROY;
193 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
194 connection_mark_for_close(TO_CONN(conn));
195 conn->_base.hold_open_until_flushed = 1;
198 conn->cpath_layer = NULL;
199 conn->on_circuit = NULL;
200 return 0;
203 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
204 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
205 * is not a client connection, set the relay end cell's reason for closing
206 * as <b>reason</b> */
207 static int
208 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
209 uint8_t reason, crypt_path_t *cpath_layer)
211 char payload[1];
213 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
214 /* Never send the server an informative reason code; it doesn't need to
215 * know why the client stream is failing. */
216 reason = END_STREAM_REASON_MISC;
219 payload[0] = (char) reason;
221 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
222 payload, 1, cpath_layer);
225 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
226 * remember that we've done so. If this is not a client connection, set the
227 * relay end cell's reason for closing as <b>reason</b>.
229 * Return -1 if this function has already been called on this conn,
230 * else return 0.
233 connection_edge_end(edge_connection_t *conn, uint8_t reason)
235 char payload[RELAY_PAYLOAD_SIZE];
236 size_t payload_len=1;
237 circuit_t *circ;
238 uint8_t control_reason = reason;
240 if (conn->edge_has_sent_end) {
241 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
242 "on an already ended stream?", reason);
243 tor_fragile_assert();
244 return -1;
247 if (conn->_base.marked_for_close) {
248 log_warn(LD_BUG,
249 "called on conn that's already marked for close at %s:%d.",
250 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
251 return 0;
254 circ = circuit_get_by_edge_conn(conn);
255 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
256 /* If this is a client circuit, don't send the server an informative
257 * reason code; it doesn't need to know why the client stream is
258 * failing. */
259 reason = END_STREAM_REASON_MISC;
262 payload[0] = (char)reason;
263 if (reason == END_STREAM_REASON_EXITPOLICY &&
264 !connection_edge_is_rendezvous_stream(conn)) {
265 int addrlen;
266 if (tor_addr_family(&conn->_base.addr) == AF_INET) {
267 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
268 addrlen = 4;
269 } else {
270 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
271 addrlen = 16;
273 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
274 payload_len += 4+addrlen;
277 if (circ && !circ->marked_for_close) {
278 log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
279 connection_edge_send_command(conn, RELAY_COMMAND_END,
280 payload, payload_len);
281 } else {
282 log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
283 conn->_base.s);
286 conn->edge_has_sent_end = 1;
287 conn->end_reason = control_reason;
288 return 0;
291 /** An error has just occurred on an operation on an edge connection
292 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
293 * appropriate relay end cell to the other end of the connection's circuit.
296 connection_edge_end_errno(edge_connection_t *conn)
298 uint8_t reason;
299 tor_assert(conn);
300 reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
301 return connection_edge_end(conn, reason);
304 /** Connection <b>conn</b> has finished writing and has no bytes left on
305 * its outbuf.
307 * If it's in state 'open', stop writing, consider responding with a
308 * sendme, and return.
309 * Otherwise, stop writing and return.
311 * If <b>conn</b> is broken, mark it for close and return -1, else
312 * return 0.
315 connection_edge_finished_flushing(edge_connection_t *conn)
317 tor_assert(conn);
319 switch (conn->_base.state) {
320 case AP_CONN_STATE_OPEN:
321 case EXIT_CONN_STATE_OPEN:
322 connection_stop_writing(TO_CONN(conn));
323 connection_edge_consider_sending_sendme(conn);
324 return 0;
325 case AP_CONN_STATE_SOCKS_WAIT:
326 case AP_CONN_STATE_NATD_WAIT:
327 case AP_CONN_STATE_RENDDESC_WAIT:
328 case AP_CONN_STATE_CIRCUIT_WAIT:
329 case AP_CONN_STATE_CONNECT_WAIT:
330 case AP_CONN_STATE_CONTROLLER_WAIT:
331 connection_stop_writing(TO_CONN(conn));
332 return 0;
333 default:
334 log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
335 tor_fragile_assert();
336 return -1;
338 return 0;
341 /** Connected handler for exit connections: start writing pending
342 * data, deliver 'CONNECTED' relay cells as appropriate, and check
343 * any pending data that may have been received. */
345 connection_edge_finished_connecting(edge_connection_t *edge_conn)
347 connection_t *conn;
349 tor_assert(edge_conn);
350 tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
351 conn = TO_CONN(edge_conn);
352 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
354 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
355 escaped_safe_str(conn->address), conn->port,
356 safe_str(fmt_addr(&conn->addr)));
358 rep_hist_note_exit_stream_opened(conn->port);
360 conn->state = EXIT_CONN_STATE_OPEN;
361 connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
362 if (connection_wants_to_flush(conn)) /* in case there are any queued relay
363 * cells */
364 connection_start_writing(conn);
365 /* deliver a 'connected' relay cell back through the circuit. */
366 if (connection_edge_is_rendezvous_stream(edge_conn)) {
367 if (connection_edge_send_command(edge_conn,
368 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
369 return 0; /* circuit is closed, don't continue */
370 } else {
371 char connected_payload[20];
372 int connected_payload_len;
373 if (tor_addr_family(&conn->addr) == AF_INET) {
374 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
375 set_uint32(connected_payload+4,
376 htonl(dns_clip_ttl(edge_conn->address_ttl)));
377 connected_payload_len = 8;
378 } else {
379 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
380 set_uint32(connected_payload+16,
381 htonl(dns_clip_ttl(edge_conn->address_ttl)));
382 connected_payload_len = 20;
384 if (connection_edge_send_command(edge_conn,
385 RELAY_COMMAND_CONNECTED,
386 connected_payload, connected_payload_len) < 0)
387 return 0; /* circuit is closed, don't continue */
389 tor_assert(edge_conn->package_window > 0);
390 /* in case the server has written anything */
391 return connection_edge_process_inbuf(edge_conn, 1);
394 /** Define a schedule for how long to wait between retrying
395 * application connections. Rather than waiting a fixed amount of
396 * time between each retry, we wait 10 seconds each for the first
397 * two tries, and 15 seconds for each retry after
398 * that. Hopefully this will improve the expected user experience. */
399 static int
400 compute_retry_timeout(edge_connection_t *conn)
402 int timeout = get_options()->CircuitStreamTimeout;
403 if (timeout) /* if our config options override the default, use them */
404 return timeout;
405 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
406 return 10;
407 return 15;
410 /** Find all general-purpose AP streams waiting for a response that sent their
411 * begin/resolve cell too long ago. Detach from their current circuit, and
412 * mark their current circuit as unsuitable for new streams. Then call
413 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
414 * available) or launch a new one.
416 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
417 * retry attempt).
419 void
420 connection_ap_expire_beginning(void)
422 edge_connection_t *conn;
423 circuit_t *circ;
424 time_t now = time(NULL);
425 or_options_t *options = get_options();
426 int severity;
427 int cutoff;
428 int seconds_idle, seconds_since_born;
429 smartlist_t *conns = get_connection_array();
431 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
432 if (c->type != CONN_TYPE_AP || c->marked_for_close)
433 continue;
434 conn = TO_EDGE_CONN(c);
435 /* if it's an internal linked connection, don't yell its status. */
436 severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
437 ? LOG_INFO : LOG_NOTICE;
438 seconds_idle = (int)( now - conn->_base.timestamp_lastread );
439 seconds_since_born = (int)( now - conn->_base.timestamp_created );
441 if (conn->_base.state == AP_CONN_STATE_OPEN)
442 continue;
444 /* We already consider SocksTimeout in
445 * connection_ap_handshake_attach_circuit(), but we need to consider
446 * it here too because controllers that put streams in controller_wait
447 * state never ask Tor to attach the circuit. */
448 if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
449 if (seconds_since_born >= options->SocksTimeout) {
450 log_fn(severity, LD_APP,
451 "Tried for %d seconds to get a connection to %s:%d. "
452 "Giving up. (%s)",
453 seconds_since_born,
454 safe_str_client(conn->socks_request->address),
455 conn->socks_request->port,
456 conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
457 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
459 continue;
462 /* We're in state connect_wait or resolve_wait now -- waiting for a
463 * reply to our relay cell. See if we want to retry/give up. */
465 cutoff = compute_retry_timeout(conn);
466 if (seconds_idle < cutoff)
467 continue;
468 circ = circuit_get_by_edge_conn(conn);
469 if (!circ) { /* it's vanished? */
470 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
471 safe_str_client(conn->socks_request->address));
472 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
473 continue;
475 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
476 if (seconds_idle >= options->SocksTimeout) {
477 log_fn(severity, LD_REND,
478 "Rend stream is %d seconds late. Giving up on address"
479 " '%s.onion'.",
480 seconds_idle,
481 safe_str_client(conn->socks_request->address));
482 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
483 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
485 continue;
487 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
488 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
489 "We tried for %d seconds to connect to '%s' using exit '%s'."
490 " Retrying on a new circuit.",
491 seconds_idle,
492 safe_str_client(conn->socks_request->address),
493 conn->cpath_layer ?
494 conn->cpath_layer->extend_info->nickname : "*unnamed*");
495 /* send an end down the circuit */
496 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
497 /* un-mark it as ending, since we're going to reuse it */
498 conn->edge_has_sent_end = 0;
499 conn->end_reason = 0;
500 /* kludge to make us not try this circuit again, yet to allow
501 * current streams on it to survive if they can: make it
502 * unattractive to use for new streams */
503 tor_assert(circ->timestamp_dirty);
504 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
505 /* give our stream another 'cutoff' seconds to try */
506 conn->_base.timestamp_lastread += cutoff;
507 if (conn->num_socks_retries < 250) /* avoid overflow */
508 conn->num_socks_retries++;
509 /* move it back into 'pending' state, and try to attach. */
510 if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
511 END_STREAM_REASON_TIMEOUT)<0) {
512 if (!conn->_base.marked_for_close)
513 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
515 } SMARTLIST_FOREACH_END(conn);
518 /** Tell any AP streams that are waiting for a new circuit to try again,
519 * either attaching to an available circ or launching a new one.
521 void
522 connection_ap_attach_pending(void)
524 edge_connection_t *edge_conn;
525 smartlist_t *conns = get_connection_array();
526 SMARTLIST_FOREACH(conns, connection_t *, conn,
528 if (conn->marked_for_close ||
529 conn->type != CONN_TYPE_AP ||
530 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
531 continue;
532 edge_conn = TO_EDGE_CONN(conn);
533 if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
534 if (!edge_conn->_base.marked_for_close)
535 connection_mark_unattached_ap(edge_conn,
536 END_STREAM_REASON_CANT_ATTACH);
541 /** Tell any AP streams that are waiting for a one-hop tunnel to
542 * <b>failed_digest</b> that they are going to fail. */
543 /* XXX022 We should get rid of this function, and instead attach
544 * one-hop streams to circ->p_streams so they get marked in
545 * circuit_mark_for_close like normal p_streams. */
546 void
547 connection_ap_fail_onehop(const char *failed_digest,
548 cpath_build_state_t *build_state)
550 edge_connection_t *edge_conn;
551 char digest[DIGEST_LEN];
552 smartlist_t *conns = get_connection_array();
553 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
554 if (conn->marked_for_close ||
555 conn->type != CONN_TYPE_AP ||
556 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
557 continue;
558 edge_conn = TO_EDGE_CONN(conn);
559 if (!edge_conn->want_onehop)
560 continue;
561 if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
562 memcmp(digest, failed_digest, DIGEST_LEN))
563 continue;
564 if (tor_digest_is_zero(digest)) {
565 /* we don't know the digest; have to compare addr:port */
566 tor_addr_t addr;
567 if (!build_state || !build_state->chosen_exit ||
568 !edge_conn->socks_request || !edge_conn->socks_request->address)
569 continue;
570 if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
571 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
572 build_state->chosen_exit->port != edge_conn->socks_request->port)
573 continue;
575 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
576 "just failed.", edge_conn->chosen_exit_name,
577 edge_conn->socks_request->address);
578 connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
579 } SMARTLIST_FOREACH_END(conn);
582 /** A circuit failed to finish on its last hop <b>info</b>. If there
583 * are any streams waiting with this exit node in mind, but they
584 * don't absolutely require it, make them give up on it.
586 void
587 circuit_discard_optional_exit_enclaves(extend_info_t *info)
589 edge_connection_t *edge_conn;
590 routerinfo_t *r1, *r2;
592 smartlist_t *conns = get_connection_array();
593 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
594 if (conn->marked_for_close ||
595 conn->type != CONN_TYPE_AP ||
596 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
597 continue;
598 edge_conn = TO_EDGE_CONN(conn);
599 if (!edge_conn->chosen_exit_optional &&
600 !edge_conn->chosen_exit_retries)
601 continue;
602 r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
603 r2 = router_get_by_digest(info->identity_digest);
604 if (!r1 || !r2 || r1 != r2)
605 continue;
606 tor_assert(edge_conn->socks_request);
607 if (edge_conn->chosen_exit_optional) {
608 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
609 safe_str_client(edge_conn->chosen_exit_name),
610 escaped_safe_str_client(edge_conn->socks_request->address));
611 edge_conn->chosen_exit_optional = 0;
612 tor_free(edge_conn->chosen_exit_name); /* clears it */
613 /* if this port is dangerous, warn or reject it now that we don't
614 * think it'll be using an enclave. */
615 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
617 if (edge_conn->chosen_exit_retries) {
618 if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
619 clear_trackexithost_mappings(edge_conn->chosen_exit_name);
620 tor_free(edge_conn->chosen_exit_name); /* clears it */
621 /* if this port is dangerous, warn or reject it now that we don't
622 * think it'll be using an enclave. */
623 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
626 } SMARTLIST_FOREACH_END(conn);
629 /** The AP connection <b>conn</b> has just failed while attaching or
630 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
631 * might work. Detach the circuit, and either reattach it, launch a
632 * new circuit, tell the controller, or give up as a appropriate.
634 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
637 connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
638 int reason)
640 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
641 conn->_base.timestamp_lastread = time(NULL);
642 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
643 /* If we're attaching streams ourself, or if this connection is
644 * a tunneled directory connection, then just attach it. */
645 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
646 circuit_detach_stream(TO_CIRCUIT(circ),conn);
647 return connection_ap_handshake_attach_circuit(conn);
648 } else {
649 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
650 circuit_detach_stream(TO_CIRCUIT(circ),conn);
651 return 0;
655 /** A client-side struct to remember requests to rewrite addresses
656 * to new addresses. These structs are stored in the hash table
657 * "addressmap" below.
659 * There are 5 ways to set an address mapping:
660 * - A MapAddress command from the controller [permanent]
661 * - An AddressMap directive in the torrc [permanent]
662 * - When a TrackHostExits torrc directive is triggered [temporary]
663 * - When a DNS resolve succeeds [temporary]
664 * - When a DNS resolve fails [temporary]
666 * When an addressmap request is made but one is already registered,
667 * the new one is replaced only if the currently registered one has
668 * no "new_address" (that is, it's in the process of DNS resolve),
669 * or if the new one is permanent (expires==0 or 1).
671 * (We overload the 'expires' field, using "0" for mappings set via
672 * the configuration file, "1" for mappings set from the control
673 * interface, and other values for DNS and TrackHostExit mappings that can
674 * expire.)
676 typedef struct {
677 char *new_address;
678 time_t expires;
679 addressmap_entry_source_t source:3;
680 short num_resolve_failures;
681 } addressmap_entry_t;
683 /** Entry for mapping addresses to which virtual address we mapped them to. */
684 typedef struct {
685 char *ipv4_address;
686 char *hostname_address;
687 } virtaddress_entry_t;
689 /** A hash table to store client-side address rewrite instructions. */
690 static strmap_t *addressmap=NULL;
692 * Table mapping addresses to which virtual address, if any, we
693 * assigned them to.
695 * We maintain the following invariant: if [A,B] is in
696 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
697 * must be in addressmap. We do not require that the converse hold:
698 * if it fails, then we could end up mapping two virtual addresses to
699 * the same address, which is no disaster.
701 static strmap_t *virtaddress_reversemap=NULL;
703 /** Initialize addressmap. */
704 void
705 addressmap_init(void)
707 addressmap = strmap_new();
708 virtaddress_reversemap = strmap_new();
711 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
712 static void
713 addressmap_ent_free(void *_ent)
715 addressmap_entry_t *ent;
716 if (!_ent)
717 return;
719 ent = _ent;
720 tor_free(ent->new_address);
721 tor_free(ent);
724 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
725 static void
726 addressmap_virtaddress_ent_free(void *_ent)
728 virtaddress_entry_t *ent;
729 if (!_ent)
730 return;
732 ent = _ent;
733 tor_free(ent->ipv4_address);
734 tor_free(ent->hostname_address);
735 tor_free(ent);
738 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
739 static void
740 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
742 if (ent && ent->new_address &&
743 address_is_in_virtual_range(ent->new_address)) {
744 virtaddress_entry_t *ve =
745 strmap_get(virtaddress_reversemap, ent->new_address);
746 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
747 if (ve) {
748 if (!strcmp(address, ve->ipv4_address))
749 tor_free(ve->ipv4_address);
750 if (!strcmp(address, ve->hostname_address))
751 tor_free(ve->hostname_address);
752 if (!ve->ipv4_address && !ve->hostname_address) {
753 tor_free(ve);
754 strmap_remove(virtaddress_reversemap, ent->new_address);
760 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
761 * client address maps. */
762 static void
763 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
765 addressmap_virtaddress_remove(address, ent);
766 addressmap_ent_free(ent);
769 /** Unregister all TrackHostExits mappings from any address to
770 * *.exitname.exit. */
771 static void
772 clear_trackexithost_mappings(const char *exitname)
774 char *suffix;
775 size_t suffix_len;
776 if (!addressmap || !exitname)
777 return;
778 suffix_len = strlen(exitname) + 16;
779 suffix = tor_malloc(suffix_len);
780 tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
781 tor_strlower(suffix);
783 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
784 if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
785 addressmap_ent_remove(address, ent);
786 MAP_DEL_CURRENT(address);
788 } STRMAP_FOREACH_END;
790 tor_free(suffix);
793 /** Remove all entries from the addressmap that were set via the
794 * configuration file or the command line. */
795 void
796 addressmap_clear_configured(void)
798 addressmap_get_mappings(NULL, 0, 0, 0);
801 /** Remove all entries from the addressmap that are set to expire, ever. */
802 void
803 addressmap_clear_transient(void)
805 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
808 /** Clean out entries from the addressmap cache that were
809 * added long enough ago that they are no longer valid.
811 void
812 addressmap_clean(time_t now)
814 addressmap_get_mappings(NULL, 2, now, 0);
817 /** Free all the elements in the addressmap, and free the addressmap
818 * itself. */
819 void
820 addressmap_free_all(void)
822 strmap_free(addressmap, addressmap_ent_free);
823 addressmap = NULL;
825 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
826 virtaddress_reversemap = NULL;
829 /** Look at address, and rewrite it until it doesn't want any
830 * more rewrites; but don't get into an infinite loop.
831 * Don't write more than maxlen chars into address. Return true if the
832 * address changed; false otherwise. Set *<b>expires_out</b> to the
833 * expiry time of the result, or to <b>time_max</b> if the result does
834 * not expire.
837 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
839 addressmap_entry_t *ent;
840 int rewrites;
841 char *cp;
842 time_t expires = TIME_MAX;
844 for (rewrites = 0; rewrites < 16; rewrites++) {
845 ent = strmap_get(addressmap, address);
847 if (!ent || !ent->new_address) {
848 if (expires_out)
849 *expires_out = expires;
850 return (rewrites > 0); /* done, no rewrite needed */
853 cp = tor_strdup(escaped_safe_str_client(ent->new_address));
854 log_info(LD_APP, "Addressmap: rewriting %s to %s",
855 escaped_safe_str_client(address), cp);
856 if (ent->expires > 1 && ent->expires < expires)
857 expires = ent->expires;
858 tor_free(cp);
859 strlcpy(address, ent->new_address, maxlen);
861 log_warn(LD_CONFIG,
862 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
863 escaped_safe_str_client(address));
864 /* it's fine to rewrite a rewrite, but don't loop forever */
865 if (expires_out)
866 *expires_out = TIME_MAX;
867 return 1;
870 /** If we have a cached reverse DNS entry for the address stored in the
871 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
872 * rewrite to the cached value and return 1. Otherwise return 0. Set
873 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
874 * if the result does not expire. */
875 static int
876 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
878 size_t len = maxlen + 16;
879 char *s = tor_malloc(len), *cp;
880 addressmap_entry_t *ent;
881 int r = 0;
882 tor_snprintf(s, len, "REVERSE[%s]", address);
883 ent = strmap_get(addressmap, s);
884 if (ent) {
885 cp = tor_strdup(escaped_safe_str_client(ent->new_address));
886 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
887 escaped_safe_str_client(s), cp);
888 tor_free(cp);
889 strlcpy(address, ent->new_address, maxlen);
890 r = 1;
893 if (expires_out)
894 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
896 tor_free(s);
897 return r;
900 /** Return 1 if <b>address</b> is already registered, else return 0. If address
901 * is already registered, and <b>update_expires</b> is non-zero, then update
902 * the expiry time on the mapping with update_expires if it is a
903 * mapping created by TrackHostExits. */
905 addressmap_have_mapping(const char *address, int update_expiry)
907 addressmap_entry_t *ent;
908 if (!(ent=strmap_get_lc(addressmap, address)))
909 return 0;
910 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
911 ent->expires=time(NULL) + update_expiry;
912 return 1;
915 /** Register a request to map <b>address</b> to <b>new_address</b>,
916 * which will expire on <b>expires</b> (or 0 if never expires from
917 * config file, 1 if never expires from controller, 2 if never expires
918 * (virtual address mapping) from the controller.)
920 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
921 * free as appropriate. We will leave address alone.
923 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
924 * any mappings that exist from <b>address</b>.
926 void
927 addressmap_register(const char *address, char *new_address, time_t expires,
928 addressmap_entry_source_t source)
930 addressmap_entry_t *ent;
932 ent = strmap_get(addressmap, address);
933 if (!new_address || !strcasecmp(address,new_address)) {
934 /* Remove the mapping, if any. */
935 tor_free(new_address);
936 if (ent) {
937 addressmap_ent_remove(address,ent);
938 strmap_remove(addressmap, address);
940 return;
942 if (!ent) { /* make a new one and register it */
943 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
944 strmap_set(addressmap, address, ent);
945 } else if (ent->new_address) { /* we need to clean up the old mapping. */
946 if (expires > 1) {
947 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
948 "since it's already mapped to '%s'",
949 safe_str_client(address),
950 safe_str_client(new_address),
951 safe_str_client(ent->new_address));
952 tor_free(new_address);
953 return;
955 if (address_is_in_virtual_range(ent->new_address) &&
956 expires != 2) {
957 /* XXX This isn't the perfect test; we want to avoid removing
958 * mappings set from the control interface _as virtual mapping */
959 addressmap_virtaddress_remove(address, ent);
961 tor_free(ent->new_address);
962 } /* else { we have an in-progress resolve with no mapping. } */
964 ent->new_address = new_address;
965 ent->expires = expires==2 ? 1 : expires;
966 ent->num_resolve_failures = 0;
967 ent->source = source;
969 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
970 safe_str_client(address),
971 safe_str_client(ent->new_address));
972 control_event_address_mapped(address, ent->new_address, expires, NULL);
975 /** An attempt to resolve <b>address</b> failed at some OR.
976 * Increment the number of resolve failures we have on record
977 * for it, and then return that number.
980 client_dns_incr_failures(const char *address)
982 addressmap_entry_t *ent = strmap_get(addressmap, address);
983 if (!ent) {
984 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
985 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
986 strmap_set(addressmap,address,ent);
988 if (ent->num_resolve_failures < SHORT_MAX)
989 ++ent->num_resolve_failures; /* don't overflow */
990 log_info(LD_APP, "Address %s now has %d resolve failures.",
991 safe_str_client(address),
992 ent->num_resolve_failures);
993 return ent->num_resolve_failures;
996 /** If <b>address</b> is in the client DNS addressmap, reset
997 * the number of resolve failures we have on record for it.
998 * This is used when we fail a stream because it won't resolve:
999 * otherwise future attempts on that address will only try once.
1001 void
1002 client_dns_clear_failures(const char *address)
1004 addressmap_entry_t *ent = strmap_get(addressmap, address);
1005 if (ent)
1006 ent->num_resolve_failures = 0;
1009 /** Record the fact that <b>address</b> resolved to <b>name</b>.
1010 * We can now use this in subsequent streams via addressmap_rewrite()
1011 * so we can more correctly choose an exit that will allow <b>address</b>.
1013 * If <b>exitname</b> is defined, then append the addresses with
1014 * ".exitname.exit" before registering the mapping.
1016 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1017 * <b>ttl</b>seconds; otherwise, we use the default.
1019 static void
1020 client_dns_set_addressmap_impl(const char *address, const char *name,
1021 const char *exitname,
1022 int ttl)
1024 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
1025 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
1026 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
1027 char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
1029 tor_assert(address);
1030 tor_assert(name);
1032 if (ttl<0)
1033 ttl = DEFAULT_DNS_TTL;
1034 else
1035 ttl = dns_clip_ttl(ttl);
1037 if (exitname) {
1038 /* XXXX fails to ever get attempts to get an exit address of
1039 * google.com.digest[=~]nickname.exit; we need a syntax for this that
1040 * won't make strict RFC952-compliant applications (like us) barf. */
1041 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1042 "%s.%s.exit", address, exitname);
1043 tor_snprintf(extendedval, sizeof(extendedval),
1044 "%s.%s.exit", name, exitname);
1045 } else {
1046 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1047 "%s", address);
1048 tor_snprintf(extendedval, sizeof(extendedval),
1049 "%s", name);
1051 addressmap_register(extendedaddress, tor_strdup(extendedval),
1052 time(NULL) + ttl, ADDRMAPSRC_DNS);
1055 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1056 * We can now use this in subsequent streams via addressmap_rewrite()
1057 * so we can more correctly choose an exit that will allow <b>address</b>.
1059 * If <b>exitname</b> is defined, then append the addresses with
1060 * ".exitname.exit" before registering the mapping.
1062 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1063 * <b>ttl</b>seconds; otherwise, we use the default.
1065 void
1066 client_dns_set_addressmap(const char *address, uint32_t val,
1067 const char *exitname,
1068 int ttl)
1070 struct in_addr in;
1071 char valbuf[INET_NTOA_BUF_LEN];
1073 tor_assert(address);
1075 if (tor_inet_aton(address, &in))
1076 return; /* If address was an IP address already, don't add a mapping. */
1077 in.s_addr = htonl(val);
1078 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
1080 client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
1083 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1084 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1086 * If <b>exitname</b> is defined, then append the addresses with
1087 * ".exitname.exit" before registering the mapping.
1089 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1090 * <b>ttl</b>seconds; otherwise, we use the default.
1092 static void
1093 client_dns_set_reverse_addressmap(const char *address, const char *v,
1094 const char *exitname,
1095 int ttl)
1097 size_t len = strlen(address) + 16;
1098 char *s = tor_malloc(len);
1099 tor_snprintf(s, len, "REVERSE[%s]", address);
1100 client_dns_set_addressmap_impl(s, v, exitname, ttl);
1101 tor_free(s);
1104 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1105 * These addresses should map to localhost, so even if the
1106 * application accidentally tried to connect to them directly (not
1107 * via Tor), it wouldn't get too far astray.
1109 * These options are configured by parse_virtual_addr_network().
1111 /** Which network should we use for virtual IPv4 addresses? Only the first
1112 * bits of this value are fixed. */
1113 static uint32_t virtual_addr_network = 0x7fc00000u;
1114 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1115 static maskbits_t virtual_addr_netmask_bits = 10;
1116 /** What's the next virtual address we will hand out? */
1117 static uint32_t next_virtual_addr = 0x7fc00000u;
1119 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1120 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1121 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1122 * string and return -1 on failure. If validate_only is false, sets the
1123 * actual virtual address range to the parsed value. */
1125 parse_virtual_addr_network(const char *val, int validate_only,
1126 char **msg)
1128 uint32_t addr;
1129 uint16_t port_min, port_max;
1130 maskbits_t bits;
1132 if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
1133 if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
1134 return -1;
1137 if (port_min != 1 || port_max != 65535) {
1138 if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
1139 return -1;
1142 if (bits > 16) {
1143 if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
1144 "network or larger");
1145 return -1;
1148 if (validate_only)
1149 return 0;
1151 virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
1152 virtual_addr_netmask_bits = bits;
1154 if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
1155 next_virtual_addr = addr;
1157 return 0;
1161 * Return true iff <b>addr</b> is likely to have been returned by
1162 * client_dns_get_unused_address.
1164 static int
1165 address_is_in_virtual_range(const char *address)
1167 struct in_addr in;
1168 tor_assert(address);
1169 if (!strcasecmpend(address, ".virtual")) {
1170 return 1;
1171 } else if (tor_inet_aton(address, &in)) {
1172 uint32_t addr = ntohl(in.s_addr);
1173 if (!addr_mask_cmp_bits(addr, virtual_addr_network,
1174 virtual_addr_netmask_bits))
1175 return 1;
1177 return 0;
1180 /** Return a newly allocated string holding an address of <b>type</b>
1181 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1182 * and that is very unlikely to be the address of any real host.
1184 static char *
1185 addressmap_get_virtual_address(int type)
1187 char buf[64];
1188 struct in_addr in;
1189 tor_assert(addressmap);
1191 if (type == RESOLVED_TYPE_HOSTNAME) {
1192 char rand[10];
1193 do {
1194 crypto_rand(rand, sizeof(rand));
1195 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
1196 strlcat(buf, ".virtual", sizeof(buf));
1197 } while (strmap_get(addressmap, buf));
1198 return tor_strdup(buf);
1199 } else if (type == RESOLVED_TYPE_IPV4) {
1200 // This is an imperfect estimate of how many addresses are available, but
1201 // that's ok.
1202 uint32_t available = 1u << (32-virtual_addr_netmask_bits);
1203 while (available) {
1204 /* Don't hand out any .0 or .255 address. */
1205 while ((next_virtual_addr & 0xff) == 0 ||
1206 (next_virtual_addr & 0xff) == 0xff) {
1207 ++next_virtual_addr;
1209 in.s_addr = htonl(next_virtual_addr);
1210 tor_inet_ntoa(&in, buf, sizeof(buf));
1211 if (!strmap_get(addressmap, buf)) {
1212 ++next_virtual_addr;
1213 break;
1216 ++next_virtual_addr;
1217 --available;
1218 log_info(LD_CONFIG, "%d addrs available", (int)available);
1219 if (! --available) {
1220 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
1221 return NULL;
1223 if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
1224 virtual_addr_netmask_bits))
1225 next_virtual_addr = virtual_addr_network;
1227 return tor_strdup(buf);
1228 } else {
1229 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
1230 return NULL;
1234 /** A controller has requested that we map some address of type
1235 * <b>type</b> to the address <b>new_address</b>. Choose an address
1236 * that is unlikely to be used, and map it, and return it in a newly
1237 * allocated string. If another address of the same type is already
1238 * mapped to <b>new_address</b>, try to return a copy of that address.
1240 * The string in <b>new_address</b> may be freed, or inserted into a map
1241 * as appropriate.
1243 const char *
1244 addressmap_register_virtual_address(int type, char *new_address)
1246 char **addrp;
1247 virtaddress_entry_t *vent;
1249 tor_assert(new_address);
1250 tor_assert(addressmap);
1251 tor_assert(virtaddress_reversemap);
1253 vent = strmap_get(virtaddress_reversemap, new_address);
1254 if (!vent) {
1255 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
1256 strmap_set(virtaddress_reversemap, new_address, vent);
1259 addrp = (type == RESOLVED_TYPE_IPV4) ?
1260 &vent->ipv4_address : &vent->hostname_address;
1261 if (*addrp) {
1262 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1263 if (ent && ent->new_address &&
1264 !strcasecmp(new_address, ent->new_address)) {
1265 tor_free(new_address);
1266 return tor_strdup(*addrp);
1267 } else
1268 log_warn(LD_BUG,
1269 "Internal confusion: I thought that '%s' was mapped to by "
1270 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1271 safe_str_client(new_address),
1272 safe_str_client(*addrp),
1273 safe_str_client(*addrp),
1274 ent?safe_str_client(ent->new_address):"(nothing)");
1277 tor_free(*addrp);
1278 *addrp = addressmap_get_virtual_address(type);
1279 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1280 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_CONTROLLER);
1282 #if 0
1284 /* Try to catch possible bugs */
1285 addressmap_entry_t *ent;
1286 ent = strmap_get(addressmap, *addrp);
1287 tor_assert(ent);
1288 tor_assert(!strcasecmp(ent->new_address,new_address));
1289 vent = strmap_get(virtaddress_reversemap, new_address);
1290 tor_assert(vent);
1291 tor_assert(!strcasecmp(*addrp,
1292 (type == RESOLVED_TYPE_IPV4) ?
1293 vent->ipv4_address : vent->hostname_address));
1294 log_info(LD_APP, "Map from %s to %s okay.",
1295 safe_str_client(*addrp),
1296 safe_str_client(new_address));
1298 #endif
1300 return *addrp;
1303 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1304 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1305 * should be true if we're using this address as a client; false if we're
1306 * using it as a server.
1309 address_is_invalid_destination(const char *address, int client)
1311 if (client) {
1312 if (get_options()->AllowNonRFC953Hostnames)
1313 return 0;
1314 } else {
1315 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1316 return 0;
1319 while (*address) {
1320 if (TOR_ISALNUM(*address) ||
1321 *address == '-' ||
1322 *address == '.' ||
1323 *address == '_') /* Underscore is not allowed, but Windows does it
1324 * sometimes, just to thumb its nose at the IETF. */
1325 ++address;
1326 else
1327 return 1;
1329 return 0;
1332 /** Iterate over all address mappings which have expiry times between
1333 * min_expires and max_expires, inclusive. If sl is provided, add an
1334 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1335 * the expiry time if want_expiry is false. If sl is NULL, remove the
1336 * mappings.
1338 void
1339 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1340 time_t max_expires, int want_expiry)
1342 strmap_iter_t *iter;
1343 const char *key;
1344 void *_val;
1345 addressmap_entry_t *val;
1347 if (!addressmap)
1348 addressmap_init();
1350 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1351 strmap_iter_get(iter, &key, &_val);
1352 val = _val;
1353 if (val->expires >= min_expires && val->expires <= max_expires) {
1354 if (!sl) {
1355 iter = strmap_iter_next_rmv(addressmap,iter);
1356 addressmap_ent_remove(key, val);
1357 continue;
1358 } else if (val->new_address) {
1359 size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
1360 char *line = tor_malloc(len);
1361 if (want_expiry) {
1362 if (val->expires < 3 || val->expires == TIME_MAX)
1363 tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
1364 else {
1365 char time[ISO_TIME_LEN+1];
1366 format_iso_time(time, val->expires);
1367 tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
1368 time);
1370 } else {
1371 tor_snprintf(line, len, "%s %s", key, val->new_address);
1373 smartlist_add(sl, line);
1376 iter = strmap_iter_next(addressmap,iter);
1380 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1381 * reject depending on our config options. */
1382 static int
1383 consider_plaintext_ports(edge_connection_t *conn, uint16_t port)
1385 or_options_t *options = get_options();
1386 int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
1388 if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
1389 log_warn(LD_APP, "Application request to port %d: this port is "
1390 "commonly used for unencrypted protocols. Please make sure "
1391 "you don't send anything you would mind the rest of the "
1392 "Internet reading!%s", port, reject ? " Closing." : "");
1393 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1394 port, reject ? "REJECT" : "WARN");
1397 if (reject) {
1398 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1399 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1400 return -1;
1403 return 0;
1406 /** How many times do we try connecting with an exit configured via
1407 * TrackHostExits before concluding that it won't work any more and trying a
1408 * different one? */
1409 #define TRACKHOSTEXITS_RETRIES 5
1411 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1412 * asked us to leave streams unattached. Return 0 in that case.
1414 * See connection_ap_handshake_rewrite_and_attach()'s
1415 * documentation for arguments and return value.
1418 connection_ap_rewrite_and_attach_if_allowed(edge_connection_t *conn,
1419 origin_circuit_t *circ,
1420 crypt_path_t *cpath)
1422 or_options_t *options = get_options();
1424 if (options->LeaveStreamsUnattached) {
1425 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1426 return 0;
1428 return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1431 /** Connection <b>conn</b> just finished its socks handshake, or the
1432 * controller asked us to take care of it. If <b>circ</b> is defined,
1433 * then that's where we'll want to attach it. Otherwise we have to
1434 * figure it out ourselves.
1436 * First, parse whether it's a .exit address, remap it, and so on. Then
1437 * if it's for a general circuit, try to attach it to a circuit (or launch
1438 * one as needed), else if it's for a rendezvous circuit, fetch a
1439 * rendezvous descriptor first (or attach/launch a circuit if the
1440 * rendezvous descriptor is already here and fresh enough).
1442 * The stream will exit from the hop
1443 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1444 * <b>cpath</b> is NULL.
1447 connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
1448 origin_circuit_t *circ,
1449 crypt_path_t *cpath)
1451 socks_request_t *socks = conn->socks_request;
1452 hostname_type_t addresstype;
1453 or_options_t *options = get_options();
1454 struct in_addr addr_tmp;
1455 int automap = 0;
1456 char orig_address[MAX_SOCKS_ADDR_LEN];
1457 time_t map_expires = TIME_MAX;
1458 int remapped_to_exit = 0;
1459 time_t now = time(NULL);
1461 tor_strlower(socks->address); /* normalize it */
1462 strlcpy(orig_address, socks->address, sizeof(orig_address));
1463 log_debug(LD_APP,"Client asked for %s:%d",
1464 safe_str_client(socks->address),
1465 socks->port);
1467 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1468 !tor_inet_aton(socks->address, &addr_tmp) &&
1469 options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
1470 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
1471 if (!strcasecmpend(socks->address, cp)) {
1472 automap = 1;
1473 break;
1475 if (automap) {
1476 const char *new_addr;
1477 new_addr = addressmap_register_virtual_address(
1478 RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
1479 tor_assert(new_addr);
1480 log_info(LD_APP, "Automapping %s to %s",
1481 escaped_safe_str_client(socks->address),
1482 safe_str_client(new_addr));
1483 strlcpy(socks->address, new_addr, sizeof(socks->address));
1487 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1488 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1489 &map_expires)) {
1490 char *result = tor_strdup(socks->address);
1491 /* remember _what_ is supposed to have been resolved. */
1492 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1493 orig_address);
1494 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1495 strlen(result), result, -1,
1496 map_expires);
1497 connection_mark_unattached_ap(conn,
1498 END_STREAM_REASON_DONE |
1499 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1500 return 0;
1502 if (options->ClientDNSRejectInternalAddresses) {
1503 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1504 tor_addr_t addr;
1505 int ok;
1506 ok = tor_addr_parse_reverse_lookup_name(
1507 &addr, socks->address, AF_UNSPEC, 1);
1508 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1509 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1510 0, NULL, -1, TIME_MAX);
1511 connection_mark_unattached_ap(conn,
1512 END_STREAM_REASON_SOCKSPROTOCOL |
1513 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1514 return -1;
1517 } else if (!automap) {
1518 int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
1519 /* For address map controls, remap the address. */
1520 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1521 &map_expires)) {
1522 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1523 REMAP_STREAM_SOURCE_CACHE);
1524 if (started_without_chosen_exit &&
1525 !strcasecmpend(socks->address, ".exit") &&
1526 map_expires < TIME_MAX)
1527 remapped_to_exit = 1;
1531 if (!automap && address_is_in_virtual_range(socks->address)) {
1532 /* This address was probably handed out by client_dns_get_unmapped_address,
1533 * but the mapping was discarded for some reason. We *don't* want to send
1534 * the address through Tor; that's likely to fail, and may leak
1535 * information.
1537 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1538 safe_str_client(socks->address));
1539 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
1540 return -1;
1543 /* Parse the address provided by SOCKS. Modify it in-place if it
1544 * specifies a hidden-service (.onion) or particular exit node (.exit).
1546 addresstype = parse_extended_hostname(socks->address,
1547 remapped_to_exit || options->AllowDotExit);
1549 if (addresstype == BAD_HOSTNAME) {
1550 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
1551 safe_str_client(socks->address));
1552 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1553 escaped(socks->address));
1554 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1555 return -1;
1558 if (addresstype == EXIT_HOSTNAME) {
1559 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1560 * node, and conn->address to hold only the address portion. */
1561 char *s = strrchr(socks->address,'.');
1562 tor_assert(!automap);
1563 if (s) {
1564 if (s[1] != '\0') {
1565 conn->chosen_exit_name = tor_strdup(s+1);
1566 if (remapped_to_exit) /* 5 tries before it expires the addressmap */
1567 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1568 *s = 0;
1569 } else {
1570 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1571 safe_str_client(socks->address));
1572 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1573 escaped(socks->address));
1574 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1575 return -1;
1577 } else {
1578 routerinfo_t *r;
1579 conn->chosen_exit_name = tor_strdup(socks->address);
1580 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1581 *socks->address = 0;
1582 if (r) {
1583 strlcpy(socks->address, r->address, sizeof(socks->address));
1584 } else {
1585 log_warn(LD_APP,
1586 "Unrecognized server in exit address '%s.exit'. Refusing.",
1587 safe_str_client(socks->address));
1588 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1589 return -1;
1594 if (addresstype != ONION_HOSTNAME) {
1595 /* not a hidden-service request (i.e. normal or .exit) */
1596 if (address_is_invalid_destination(socks->address, 1)) {
1597 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1598 escaped(socks->address));
1599 log_warn(LD_APP,
1600 "Destination '%s' seems to be an invalid hostname. Failing.",
1601 safe_str_client(socks->address));
1602 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1603 return -1;
1606 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1607 uint32_t answer;
1608 struct in_addr in;
1609 /* Reply to resolves immediately if we can. */
1610 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1611 /* leave it in network order */
1612 answer = in.s_addr;
1613 /* remember _what_ is supposed to have been resolved. */
1614 strlcpy(socks->address, orig_address, sizeof(socks->address));
1615 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1616 (char*)&answer,-1,map_expires);
1617 connection_mark_unattached_ap(conn,
1618 END_STREAM_REASON_DONE |
1619 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1620 return 0;
1622 tor_assert(!automap);
1623 rep_hist_note_used_resolve(now); /* help predict this next time */
1624 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1625 tor_assert(!automap);
1626 if (socks->port == 0) {
1627 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1628 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1629 return -1;
1632 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1633 /* see if we can find a suitable enclave exit */
1634 routerinfo_t *r =
1635 router_find_exact_exit_enclave(socks->address, socks->port);
1636 if (r) {
1637 log_info(LD_APP,
1638 "Redirecting address %s to exit at enclave router %s",
1639 safe_str_client(socks->address), r->nickname);
1640 /* use the hex digest, not nickname, in case there are two
1641 routers with this nickname */
1642 conn->chosen_exit_name =
1643 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1644 conn->chosen_exit_optional = 1;
1648 /* warn or reject if it's using a dangerous port */
1649 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1650 if (consider_plaintext_ports(conn, socks->port) < 0)
1651 return -1;
1653 if (!conn->use_begindir) {
1654 /* help predict this next time */
1655 rep_hist_note_used_port(now, socks->port);
1657 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1658 rep_hist_note_used_resolve(now); /* help predict this next time */
1659 /* no extra processing needed */
1660 } else {
1661 tor_fragile_assert();
1663 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1664 if ((circ && connection_ap_handshake_attach_chosen_circuit(
1665 conn, circ, cpath) < 0) ||
1666 (!circ &&
1667 connection_ap_handshake_attach_circuit(conn) < 0)) {
1668 if (!conn->_base.marked_for_close)
1669 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1670 return -1;
1672 return 0;
1673 } else {
1674 /* it's a hidden-service request */
1675 rend_cache_entry_t *entry;
1676 int r;
1677 rend_service_authorization_t *client_auth;
1678 tor_assert(!automap);
1679 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1680 /* if it's a resolve request, fail it right now, rather than
1681 * building all the circuits and then realizing it won't work. */
1682 log_warn(LD_APP,
1683 "Resolve requests to hidden services not allowed. Failing.");
1684 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1685 0,NULL,-1,TIME_MAX);
1686 connection_mark_unattached_ap(conn,
1687 END_STREAM_REASON_SOCKSPROTOCOL |
1688 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1689 return -1;
1692 if (circ) {
1693 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1694 "supported for .onion addresses currently. Failing.");
1695 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1696 return -1;
1699 conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1700 strlcpy(conn->rend_data->onion_address, socks->address,
1701 sizeof(conn->rend_data->onion_address));
1702 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1703 safe_str_client(conn->rend_data->onion_address));
1704 /* see if we already have it cached */
1705 r = rend_cache_lookup_entry(conn->rend_data->onion_address, -1, &entry);
1706 if (r<0) {
1707 log_warn(LD_BUG,"Invalid service name '%s'",
1708 safe_str_client(conn->rend_data->onion_address));
1709 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1710 return -1;
1713 /* Help predict this next time. We're not sure if it will need
1714 * a stable circuit yet, but we know we'll need *something*. */
1715 rep_hist_note_used_internal(now, 0, 1);
1717 /* Look up if we have client authorization for it. */
1718 client_auth = rend_client_lookup_service_authorization(
1719 conn->rend_data->onion_address);
1720 if (client_auth) {
1721 log_info(LD_REND, "Using previously configured client authorization "
1722 "for hidden service request.");
1723 memcpy(conn->rend_data->descriptor_cookie,
1724 client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
1725 conn->rend_data->auth_type = client_auth->auth_type;
1727 if (r==0) {
1728 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1729 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1730 safe_str_client(conn->rend_data->onion_address));
1731 rend_client_refetch_v2_renddesc(conn->rend_data);
1732 } else { /* r > 0 */
1733 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1734 log_info(LD_REND, "Descriptor is here. Great.");
1735 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1736 if (!conn->_base.marked_for_close)
1737 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1738 return -1;
1741 return 0;
1743 return 0; /* unreached but keeps the compiler happy */
1746 #ifdef TRANS_PF
1747 static int pf_socket = -1;
1749 get_pf_socket(void)
1751 int pf;
1752 /* This should be opened before dropping privileges. */
1753 if (pf_socket >= 0)
1754 return pf_socket;
1756 #ifdef OPENBSD
1757 /* only works on OpenBSD */
1758 pf = open("/dev/pf", O_RDONLY);
1759 #else
1760 /* works on NetBSD and FreeBSD */
1761 pf = open("/dev/pf", O_RDWR);
1762 #endif
1764 if (pf < 0) {
1765 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1766 return -1;
1769 pf_socket = pf;
1770 return pf_socket;
1772 #endif
1774 /** Fetch the original destination address and port from a
1775 * system-specific interface and put them into a
1776 * socks_request_t as if they came from a socks request.
1778 * Return -1 if an error prevents fetching the destination,
1779 * else return 0.
1781 static int
1782 connection_ap_get_original_destination(edge_connection_t *conn,
1783 socks_request_t *req)
1785 #ifdef TRANS_NETFILTER
1786 /* Linux 2.4+ */
1787 struct sockaddr_storage orig_dst;
1788 socklen_t orig_dst_len = sizeof(orig_dst);
1789 tor_addr_t addr;
1791 if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
1792 (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
1793 int e = tor_socket_errno(conn->_base.s);
1794 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1795 return -1;
1798 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1799 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1801 return 0;
1802 #elif defined(TRANS_PF)
1803 struct sockaddr_storage proxy_addr;
1804 socklen_t proxy_addr_len = sizeof(proxy_addr);
1805 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1806 struct pfioc_natlook pnl;
1807 tor_addr_t addr;
1808 int pf = -1;
1810 if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
1811 &proxy_addr_len) < 0) {
1812 int e = tor_socket_errno(conn->_base.s);
1813 log_warn(LD_NET, "getsockname() to determine transocks destination "
1814 "failed: %s", tor_socket_strerror(e));
1815 return -1;
1818 memset(&pnl, 0, sizeof(pnl));
1819 pnl.proto = IPPROTO_TCP;
1820 pnl.direction = PF_OUT;
1821 if (proxy_sa->sa_family == AF_INET) {
1822 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1823 pnl.af = AF_INET;
1824 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&conn->_base.addr);
1825 pnl.sport = htons(conn->_base.port);
1826 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1827 pnl.dport = sin->sin_port;
1828 } else if (proxy_sa->sa_family == AF_INET6) {
1829 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1830 pnl.af = AF_INET6;
1831 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&conn->_base.addr),
1832 sizeof(struct in6_addr));
1833 pnl.sport = htons(conn->_base.port);
1834 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1835 pnl.dport = sin6->sin6_port;
1836 } else {
1837 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1838 (int)proxy_sa->sa_family);
1839 return -1;
1842 pf = get_pf_socket();
1843 if (pf<0)
1844 return -1;
1846 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1847 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1848 return -1;
1851 if (pnl.af == AF_INET) {
1852 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1853 } else if (pnl.af == AF_INET6) {
1854 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1855 } else {
1856 tor_fragile_assert();
1857 return -1;
1860 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1861 req->port = ntohs(pnl.rdport);
1863 return 0;
1864 #else
1865 (void)conn;
1866 (void)req;
1867 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1868 "transparent proxy method was configured.");
1869 return -1;
1870 #endif
1873 /** connection_edge_process_inbuf() found a conn in state
1874 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1875 * the socks handshake.
1877 * If the handshake is complete, send it to
1878 * connection_ap_handshake_rewrite_and_attach().
1880 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1881 * else return 0.
1883 static int
1884 connection_ap_handshake_process_socks(edge_connection_t *conn)
1886 socks_request_t *socks;
1887 int sockshere;
1888 or_options_t *options = get_options();
1890 tor_assert(conn);
1891 tor_assert(conn->_base.type == CONN_TYPE_AP);
1892 tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
1893 tor_assert(conn->socks_request);
1894 socks = conn->socks_request;
1896 log_debug(LD_APP,"entered.");
1898 sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
1899 options->TestSocks, options->SafeSocks);
1900 if (sockshere == 0) {
1901 if (socks->replylen) {
1902 connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
1903 /* zero it out so we can do another round of negotiation */
1904 socks->replylen = 0;
1905 } else {
1906 log_debug(LD_APP,"socks handshake not all here yet.");
1908 return 0;
1909 } else if (sockshere == -1) {
1910 if (socks->replylen) { /* we should send reply back */
1911 log_debug(LD_APP,"reply is already set for us. Using it.");
1912 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1913 END_STREAM_REASON_SOCKSPROTOCOL);
1915 } else {
1916 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
1917 connection_ap_handshake_socks_reply(conn, NULL, 0,
1918 END_STREAM_REASON_SOCKSPROTOCOL);
1920 connection_mark_unattached_ap(conn,
1921 END_STREAM_REASON_SOCKSPROTOCOL |
1922 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1923 return -1;
1924 } /* else socks handshake is done, continue processing */
1926 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
1927 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1928 else
1929 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
1931 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
1934 /** connection_init_accepted_conn() found a new trans AP conn.
1935 * Get the original destination and send it to
1936 * connection_ap_handshake_rewrite_and_attach().
1938 * Return -1 if an unexpected error with conn (and it should be marked
1939 * for close), else return 0.
1942 connection_ap_process_transparent(edge_connection_t *conn)
1944 socks_request_t *socks;
1946 tor_assert(conn);
1947 tor_assert(conn->_base.type == CONN_TYPE_AP);
1948 tor_assert(conn->socks_request);
1949 socks = conn->socks_request;
1951 /* pretend that a socks handshake completed so we don't try to
1952 * send a socks reply down a transparent conn */
1953 socks->command = SOCKS_COMMAND_CONNECT;
1954 socks->has_finished = 1;
1956 log_debug(LD_APP,"entered.");
1958 if (connection_ap_get_original_destination(conn, socks) < 0) {
1959 log_warn(LD_APP,"Fetching original destination failed. Closing.");
1960 connection_mark_unattached_ap(conn,
1961 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
1962 return -1;
1964 /* we have the original destination */
1966 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1968 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
1971 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1972 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1973 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1974 * form of the original destination.
1976 * If the original destination is complete, send it to
1977 * connection_ap_handshake_rewrite_and_attach().
1979 * Return -1 if an unexpected error with conn (and it should be marked
1980 * for close), else return 0.
1982 static int
1983 connection_ap_process_natd(edge_connection_t *conn)
1985 char tmp_buf[36], *tbuf, *daddr;
1986 size_t tlen = 30;
1987 int err, port_ok;
1988 socks_request_t *socks;
1990 tor_assert(conn);
1991 tor_assert(conn->_base.type == CONN_TYPE_AP);
1992 tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
1993 tor_assert(conn->socks_request);
1994 socks = conn->socks_request;
1996 log_debug(LD_APP,"entered.");
1998 /* look for LF-terminated "[DEST ip_addr port]"
1999 * where ip_addr is a dotted-quad and port is in string form */
2000 err = fetch_from_buf_line(conn->_base.inbuf, tmp_buf, &tlen);
2001 if (err == 0)
2002 return 0;
2003 if (err < 0) {
2004 log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
2005 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2006 return -1;
2009 if (strcmpstart(tmp_buf, "[DEST ")) {
2010 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
2011 "said: %s",
2012 escaped(tmp_buf));
2013 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2014 return -1;
2017 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2018 if (!(tbuf = strchr(tbuf, ' '))) {
2019 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
2020 "said: %s",
2021 escaped(tmp_buf));
2022 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2023 return -1;
2025 *tbuf++ = '\0';
2027 /* pretend that a socks handshake completed so we don't try to
2028 * send a socks reply down a natd conn */
2029 strlcpy(socks->address, daddr, sizeof(socks->address));
2030 socks->port = (uint16_t)
2031 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2032 if (!port_ok) {
2033 log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
2034 "of range.", escaped(tbuf));
2035 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2036 return -1;
2039 socks->command = SOCKS_COMMAND_CONNECT;
2040 socks->has_finished = 1;
2042 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2044 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2046 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2049 /** Iterate over the two bytes of stream_id until we get one that is not
2050 * already in use; return it. Return 0 if can't get a unique stream_id.
2052 static streamid_t
2053 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2055 edge_connection_t *tmpconn;
2056 streamid_t test_stream_id;
2057 uint32_t attempts=0;
2059 again:
2060 test_stream_id = circ->next_stream_id++;
2061 if (++attempts > 1<<16) {
2062 /* Make sure we don't loop forever if all stream_id's are used. */
2063 log_warn(LD_APP,"No unused stream IDs. Failing.");
2064 return 0;
2066 if (test_stream_id == 0)
2067 goto again;
2068 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2069 if (tmpconn->stream_id == test_stream_id)
2070 goto again;
2071 return test_stream_id;
2074 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2075 * socks_request field, and send it down circ.
2077 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2080 connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
2082 char payload[CELL_PAYLOAD_SIZE];
2083 int payload_len;
2084 int begin_type;
2085 origin_circuit_t *circ;
2086 tor_assert(ap_conn->on_circuit);
2087 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2089 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2090 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2091 tor_assert(ap_conn->socks_request);
2092 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2094 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2095 if (ap_conn->stream_id==0) {
2096 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2097 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2098 return -1;
2101 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2102 (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2103 ap_conn->socks_request->address : "",
2104 ap_conn->socks_request->port);
2105 payload_len = (int)strlen(payload)+1;
2107 log_debug(LD_APP,
2108 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2110 begin_type = ap_conn->use_begindir ?
2111 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2112 if (begin_type == RELAY_COMMAND_BEGIN) {
2113 tor_assert(circ->build_state->onehop_tunnel == 0);
2116 if (connection_edge_send_command(ap_conn, begin_type,
2117 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2118 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2119 return -1; /* circuit is closed, don't continue */
2121 ap_conn->package_window = STREAMWINDOW_START;
2122 ap_conn->deliver_window = STREAMWINDOW_START;
2123 ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
2124 log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
2125 ap_conn->_base.s, circ->_base.n_circ_id);
2126 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2127 return 0;
2130 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2131 * socks_request field, and send it down circ.
2133 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2136 connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
2138 int payload_len, command;
2139 const char *string_addr;
2140 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2141 origin_circuit_t *circ;
2142 tor_assert(ap_conn->on_circuit);
2143 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2145 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2146 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2147 tor_assert(ap_conn->socks_request);
2148 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2150 command = ap_conn->socks_request->command;
2151 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2153 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2154 if (ap_conn->stream_id==0) {
2155 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2156 /*XXXX022 _close_ the circuit because it's full? That sounds dumb. */
2157 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2158 return -1;
2161 if (command == SOCKS_COMMAND_RESOLVE) {
2162 string_addr = ap_conn->socks_request->address;
2163 payload_len = (int)strlen(string_addr)+1;
2164 } else {
2165 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2166 const char *a = ap_conn->socks_request->address;
2167 tor_addr_t addr;
2168 int r;
2170 /* We're doing a reverse lookup. The input could be an IP address, or
2171 * could be an .in-addr.arpa or .ip6.arpa address */
2172 r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
2173 if (r <= 0) {
2174 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2175 safe_str_client(a));
2176 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2177 return -1;
2180 r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2181 if (r < 0) {
2182 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2183 safe_str_client(a));
2184 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2185 return -1;
2188 string_addr = inaddr_buf;
2189 payload_len = (int)strlen(inaddr_buf)+1;
2190 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
2193 log_debug(LD_APP,
2194 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2196 if (connection_edge_send_command(ap_conn,
2197 RELAY_COMMAND_RESOLVE,
2198 string_addr, payload_len) < 0)
2199 return -1; /* circuit is closed, don't continue */
2201 tor_free(ap_conn->_base.address); /* Maybe already set by dnsserv. */
2202 ap_conn->_base.address = tor_strdup("(Tor_internal)");
2203 ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
2204 log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
2205 ap_conn->_base.s, circ->_base.n_circ_id);
2206 control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
2207 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2208 return 0;
2211 /** Make an AP connection_t, make a new linked connection pair, and attach
2212 * one side to the conn, connection_add it, initialize it to circuit_wait,
2213 * and call connection_ap_handshake_attach_circuit(conn) on it.
2215 * Return the other end of the linked connection pair, or -1 if error.
2217 edge_connection_t *
2218 connection_ap_make_link(char *address, uint16_t port,
2219 const char *digest, int use_begindir, int want_onehop)
2221 edge_connection_t *conn;
2223 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2224 want_onehop ? "direct" : "anonymized",
2225 safe_str_client(address), port);
2227 conn = edge_connection_new(CONN_TYPE_AP, AF_INET);
2228 conn->_base.linked = 1; /* so that we can add it safely below. */
2230 /* populate conn->socks_request */
2232 /* leave version at zero, so the socks_reply is empty */
2233 conn->socks_request->socks_version = 0;
2234 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2235 strlcpy(conn->socks_request->address, address,
2236 sizeof(conn->socks_request->address));
2237 conn->socks_request->port = port;
2238 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2239 conn->want_onehop = want_onehop;
2240 conn->use_begindir = use_begindir;
2241 if (use_begindir) {
2242 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2243 conn->chosen_exit_name[0] = '$';
2244 tor_assert(digest);
2245 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2246 digest, DIGEST_LEN);
2249 conn->_base.address = tor_strdup("(Tor_internal)");
2250 tor_addr_make_unspec(&conn->_base.addr);
2251 conn->_base.port = 0;
2253 if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
2254 connection_free(TO_CONN(conn));
2255 return NULL;
2258 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2260 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2262 /* attaching to a dirty circuit is fine */
2263 if (connection_ap_handshake_attach_circuit(conn) < 0) {
2264 if (!conn->_base.marked_for_close)
2265 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2266 return NULL;
2269 log_info(LD_APP,"... application connection created and linked.");
2270 return conn;
2273 /** Notify any interested controller connections about a new hostname resolve
2274 * or resolve error. Takes the same arguments as does
2275 * connection_ap_handshake_socks_resolved(). */
2276 static void
2277 tell_controller_about_resolved_result(edge_connection_t *conn,
2278 int answer_type,
2279 size_t answer_len,
2280 const char *answer,
2281 int ttl,
2282 time_t expires)
2285 if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
2286 answer_type == RESOLVED_TYPE_HOSTNAME)) {
2287 return; /* we already told the controller. */
2288 } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2289 struct in_addr in;
2290 char buf[INET_NTOA_BUF_LEN];
2291 in.s_addr = get_uint32(answer);
2292 tor_inet_ntoa(&in, buf, sizeof(buf));
2293 control_event_address_mapped(conn->socks_request->address,
2294 buf, expires, NULL);
2295 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len <256) {
2296 char *cp = tor_strndup(answer, answer_len);
2297 control_event_address_mapped(conn->socks_request->address,
2298 cp, expires, NULL);
2299 tor_free(cp);
2300 } else {
2301 control_event_address_mapped(conn->socks_request->address,
2302 "<error>",
2303 time(NULL)+ttl,
2304 "error=yes");
2308 /** Send an answer to an AP connection that has requested a DNS lookup via
2309 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2310 * for unreachable; the answer should be in the format specified in the socks
2311 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2312 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2313 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2315 /* XXXX022 the use of the ttl and expires fields is nutty. Let's make this
2316 * interface and those that use it less ugly. */
2317 void
2318 connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2319 int answer_type,
2320 size_t answer_len,
2321 const char *answer,
2322 int ttl,
2323 time_t expires)
2325 char buf[384];
2326 size_t replylen;
2328 if (ttl >= 0) {
2329 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2330 uint32_t a = ntohl(get_uint32(answer));
2331 if (a)
2332 client_dns_set_addressmap(conn->socks_request->address, a,
2333 conn->chosen_exit_name, ttl);
2334 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2335 char *cp = tor_strndup(answer, answer_len);
2336 client_dns_set_reverse_addressmap(conn->socks_request->address,
2338 conn->chosen_exit_name, ttl);
2339 tor_free(cp);
2343 if (conn->is_dns_request) {
2344 if (conn->dns_server_request) {
2345 /* We had a request on our DNS port: answer it. */
2346 dnsserv_resolved(conn, answer_type, answer_len, answer, ttl);
2347 conn->socks_request->has_finished = 1;
2348 return;
2349 } else {
2350 /* This must be a request from the controller. We already sent
2351 * a mapaddress if there's a ttl. */
2352 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2353 answer, ttl, expires);
2354 conn->socks_request->has_finished = 1;
2355 return;
2357 /* We shouldn't need to free conn here; it gets marked by the caller. */
2360 if (conn->socks_request->socks_version == 4) {
2361 buf[0] = 0x00; /* version */
2362 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2363 buf[1] = SOCKS4_GRANTED;
2364 set_uint16(buf+2, 0);
2365 memcpy(buf+4, answer, 4); /* address */
2366 replylen = SOCKS4_NETWORK_LEN;
2367 } else { /* "error" */
2368 buf[1] = SOCKS4_REJECT;
2369 memset(buf+2, 0, 6);
2370 replylen = SOCKS4_NETWORK_LEN;
2372 } else if (conn->socks_request->socks_version == 5) {
2373 /* SOCKS5 */
2374 buf[0] = 0x05; /* version */
2375 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2376 buf[1] = SOCKS5_SUCCEEDED;
2377 buf[2] = 0; /* reserved */
2378 buf[3] = 0x01; /* IPv4 address type */
2379 memcpy(buf+4, answer, 4); /* address */
2380 set_uint16(buf+8, 0); /* port == 0. */
2381 replylen = 10;
2382 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2383 buf[1] = SOCKS5_SUCCEEDED;
2384 buf[2] = 0; /* reserved */
2385 buf[3] = 0x04; /* IPv6 address type */
2386 memcpy(buf+4, answer, 16); /* address */
2387 set_uint16(buf+20, 0); /* port == 0. */
2388 replylen = 22;
2389 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2390 buf[1] = SOCKS5_SUCCEEDED;
2391 buf[2] = 0; /* reserved */
2392 buf[3] = 0x03; /* Domainname address type */
2393 buf[4] = (char)answer_len;
2394 memcpy(buf+5, answer, answer_len); /* address */
2395 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2396 replylen = 5+answer_len+2;
2397 } else {
2398 buf[1] = SOCKS5_HOST_UNREACHABLE;
2399 memset(buf+2, 0, 8);
2400 replylen = 10;
2402 } else {
2403 /* no socks version info; don't send anything back */
2404 return;
2406 connection_ap_handshake_socks_reply(conn, buf, replylen,
2407 (answer_type == RESOLVED_TYPE_IPV4 ||
2408 answer_type == RESOLVED_TYPE_IPV6) ?
2409 0 : END_STREAM_REASON_RESOLVEFAILED);
2412 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2413 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2414 * handshaking.
2416 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2417 * and return, else reply based on <b>endreason</b> (one of
2418 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2419 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2421 void
2422 connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2423 size_t replylen, int endreason)
2425 char buf[256];
2426 socks5_reply_status_t status =
2427 stream_end_reason_to_socks5_response(endreason);
2429 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2431 control_event_stream_status(conn,
2432 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2433 endreason);
2435 if (conn->socks_request->has_finished) {
2436 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2437 "connection_ap_handshake_socks_reply.");
2438 return;
2440 if (replylen) { /* we already have a reply in mind */
2441 connection_write_to_buf(reply, replylen, TO_CONN(conn));
2442 conn->socks_request->has_finished = 1;
2443 return;
2445 if (conn->socks_request->socks_version == 4) {
2446 memset(buf,0,SOCKS4_NETWORK_LEN);
2447 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2448 /* leave version, destport, destip zero */
2449 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
2450 } else if (conn->socks_request->socks_version == 5) {
2451 buf[0] = 5; /* version 5 */
2452 buf[1] = (char)status;
2453 buf[2] = 0;
2454 buf[3] = 1; /* ipv4 addr */
2455 memset(buf+4,0,6); /* Set external addr/port to 0.
2456 The spec doesn't seem to say what to do here. -RD */
2457 connection_write_to_buf(buf,10,TO_CONN(conn));
2459 /* If socks_version isn't 4 or 5, don't send anything.
2460 * This can happen in the case of AP bridges. */
2461 conn->socks_request->has_finished = 1;
2462 return;
2465 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2466 * an exit hop for the circuit, or we are the origin and it is a
2467 * rendezvous begin.
2469 * Launch a new exit connection and initialize things appropriately.
2471 * If it's a rendezvous stream, call connection_exit_connect() on
2472 * it.
2474 * For general streams, call dns_resolve() on it first, and only call
2475 * connection_exit_connect() if the dns answer is already known.
2477 * Note that we don't call connection_add() on the new stream! We wait
2478 * for connection_exit_connect() to do that.
2480 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2481 * Else return 0.
2484 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2486 edge_connection_t *n_stream;
2487 relay_header_t rh;
2488 char *address=NULL;
2489 uint16_t port;
2490 or_circuit_t *or_circ = NULL;
2491 or_options_t *options = get_options();
2493 assert_circuit_ok(circ);
2494 if (!CIRCUIT_IS_ORIGIN(circ))
2495 or_circ = TO_OR_CIRCUIT(circ);
2497 relay_header_unpack(&rh, cell->payload);
2499 /* Note: we have to use relay_send_command_from_edge here, not
2500 * connection_edge_end or connection_edge_send_command, since those require
2501 * that we have a stream connected to a circuit, and we don't connect to a
2502 * circuit until we have a pending/successful resolve. */
2504 if (!server_mode(options) &&
2505 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2506 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2507 "Relay begin cell at non-server. Closing.");
2508 relay_send_end_cell_from_edge(rh.stream_id, circ,
2509 END_STREAM_REASON_EXITPOLICY, NULL);
2510 return 0;
2513 if (rh.command == RELAY_COMMAND_BEGIN) {
2514 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
2515 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2516 "Relay begin cell has no \\0. Closing.");
2517 relay_send_end_cell_from_edge(rh.stream_id, circ,
2518 END_STREAM_REASON_TORPROTOCOL, NULL);
2519 return 0;
2521 if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
2522 &address,NULL,&port)<0) {
2523 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2524 "Unable to parse addr:port in relay begin cell. Closing.");
2525 relay_send_end_cell_from_edge(rh.stream_id, circ,
2526 END_STREAM_REASON_TORPROTOCOL, NULL);
2527 return 0;
2529 if (port==0) {
2530 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2531 "Missing port in relay begin cell. Closing.");
2532 relay_send_end_cell_from_edge(rh.stream_id, circ,
2533 END_STREAM_REASON_TORPROTOCOL, NULL);
2534 tor_free(address);
2535 return 0;
2537 if (or_circ && or_circ->p_conn && !options->AllowSingleHopExits &&
2538 (or_circ->is_first_hop ||
2539 (!connection_or_digest_is_known_relay(
2540 or_circ->p_conn->identity_digest) &&
2541 should_refuse_unknown_exits(options)))) {
2542 /* Don't let clients use us as a single-hop proxy, unless the user
2543 * has explicitly allowed that in the config. It attracts attackers
2544 * and users who'd be better off with, well, single-hop proxies.
2546 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2547 "Attempt by %s to open a stream %s. Closing.",
2548 safe_str(or_circ->p_conn->_base.address),
2549 or_circ->is_first_hop ? "on first hop of circuit" :
2550 "from unknown relay");
2551 relay_send_end_cell_from_edge(rh.stream_id, circ,
2552 or_circ->is_first_hop ?
2553 END_STREAM_REASON_TORPROTOCOL :
2554 END_STREAM_REASON_MISC,
2555 NULL);
2556 tor_free(address);
2557 return 0;
2559 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2560 if (!directory_permits_begindir_requests(options) ||
2561 circ->purpose != CIRCUIT_PURPOSE_OR) {
2562 relay_send_end_cell_from_edge(rh.stream_id, circ,
2563 END_STREAM_REASON_NOTDIRECTORY, NULL);
2564 return 0;
2566 /* Make sure to get the 'real' address of the previous hop: the
2567 * caller might want to know whether his IP address has changed, and
2568 * we might already have corrected _base.addr[ess] for the relay's
2569 * canonical IP address. */
2570 if (or_circ && or_circ->p_conn)
2571 address = tor_dup_addr(&or_circ->p_conn->real_addr);
2572 else
2573 address = tor_strdup("127.0.0.1");
2574 port = 1; /* XXXX This value is never actually used anywhere, and there
2575 * isn't "really" a connection here. But we
2576 * need to set it to something nonzero. */
2577 } else {
2578 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2579 relay_send_end_cell_from_edge(rh.stream_id, circ,
2580 END_STREAM_REASON_INTERNAL, NULL);
2581 return 0;
2584 log_debug(LD_EXIT,"Creating new exit connection.");
2585 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2587 /* Remember the tunneled request ID in the new edge connection, so that
2588 * we can measure download times. */
2589 TO_CONN(n_stream)->dirreq_id = circ->dirreq_id;
2591 n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
2593 n_stream->stream_id = rh.stream_id;
2594 n_stream->_base.port = port;
2595 /* leave n_stream->s at -1, because it's not yet valid */
2596 n_stream->package_window = STREAMWINDOW_START;
2597 n_stream->deliver_window = STREAMWINDOW_START;
2599 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
2600 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2601 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
2602 n_stream->_base.address = tor_strdup("(rendezvous)");
2603 n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
2604 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
2605 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
2606 assert_circuit_ok(circ);
2607 if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
2608 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
2609 n_stream->_base.port);
2610 relay_send_end_cell_from_edge(rh.stream_id, circ,
2611 END_STREAM_REASON_EXITPOLICY,
2612 origin_circ->cpath->prev);
2613 connection_free(TO_CONN(n_stream));
2614 tor_free(address);
2615 return 0;
2617 assert_circuit_ok(circ);
2618 log_debug(LD_REND,"Finished assigning addr/port");
2619 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
2621 /* add it into the linked list of p_streams on this circuit */
2622 n_stream->next_stream = origin_circ->p_streams;
2623 n_stream->on_circuit = circ;
2624 origin_circ->p_streams = n_stream;
2625 assert_circuit_ok(circ);
2627 connection_exit_connect(n_stream);
2628 tor_free(address);
2629 return 0;
2631 tor_strlower(address);
2632 n_stream->_base.address = address;
2633 n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2634 /* default to failed, change in dns_resolve if it turns out not to fail */
2636 if (we_are_hibernating()) {
2637 relay_send_end_cell_from_edge(rh.stream_id, circ,
2638 END_STREAM_REASON_HIBERNATING, NULL);
2639 connection_free(TO_CONN(n_stream));
2640 return 0;
2643 n_stream->on_circuit = circ;
2645 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2646 tor_assert(or_circ);
2647 if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->real_addr))
2648 tor_addr_copy(&n_stream->_base.addr, &or_circ->p_conn->real_addr);
2649 return connection_exit_connect_dir(n_stream);
2652 log_debug(LD_EXIT,"about to start the dns_resolve().");
2654 /* send it off to the gethostbyname farm */
2655 switch (dns_resolve(n_stream)) {
2656 case 1: /* resolve worked; now n_stream is attached to circ. */
2657 assert_circuit_ok(circ);
2658 log_debug(LD_EXIT,"about to call connection_exit_connect().");
2659 connection_exit_connect(n_stream);
2660 return 0;
2661 case -1: /* resolve failed */
2662 relay_send_end_cell_from_edge(rh.stream_id, circ,
2663 END_STREAM_REASON_RESOLVEFAILED, NULL);
2664 /* n_stream got freed. don't touch it. */
2665 break;
2666 case 0: /* resolve added to pending list */
2667 assert_circuit_ok(circ);
2668 break;
2670 return 0;
2674 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2675 * circuit <b>circ</b>;
2676 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2679 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
2681 edge_connection_t *dummy_conn;
2682 relay_header_t rh;
2684 assert_circuit_ok(TO_CIRCUIT(circ));
2685 relay_header_unpack(&rh, cell->payload);
2687 /* This 'dummy_conn' only exists to remember the stream ID
2688 * associated with the resolve request; and to make the
2689 * implementation of dns.c more uniform. (We really only need to
2690 * remember the circuit, the stream ID, and the hostname to be
2691 * resolved; but if we didn't store them in a connection like this,
2692 * the housekeeping in dns.c would get way more complicated.)
2694 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2695 dummy_conn->stream_id = rh.stream_id;
2696 dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
2697 rh.length);
2698 dummy_conn->_base.port = 0;
2699 dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2700 dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
2702 dummy_conn->on_circuit = TO_CIRCUIT(circ);
2704 /* send it off to the gethostbyname farm */
2705 switch (dns_resolve(dummy_conn)) {
2706 case -1: /* Impossible to resolve; a resolved cell was sent. */
2707 /* Connection freed; don't touch it. */
2708 return 0;
2709 case 1: /* The result was cached; a resolved cell was sent. */
2710 if (!dummy_conn->_base.marked_for_close)
2711 connection_free(TO_CONN(dummy_conn));
2712 return 0;
2713 case 0: /* resolve added to pending list */
2714 assert_circuit_ok(TO_CIRCUIT(circ));
2715 break;
2717 return 0;
2720 /** Connect to conn's specified addr and port. If it worked, conn
2721 * has now been added to the connection_array.
2723 * Send back a connected cell. Include the resolved IP of the destination
2724 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2725 * streams must not reveal what IP they connected to.)
2727 void
2728 connection_exit_connect(edge_connection_t *edge_conn)
2730 const tor_addr_t *addr;
2731 uint16_t port;
2732 connection_t *conn = TO_CONN(edge_conn);
2733 int socket_error = 0;
2735 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
2736 router_compare_to_my_exit_policy(edge_conn)) {
2737 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
2738 escaped_safe_str_client(conn->address), conn->port);
2739 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
2740 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2741 connection_free(conn);
2742 return;
2745 addr = &conn->addr;
2746 port = conn->port;
2748 log_debug(LD_EXIT,"about to try connecting");
2749 switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
2750 case -1:
2751 /* XXX021 use socket_error below rather than trying to piece things
2752 * together from the current errno, which may have been clobbered. */
2753 connection_edge_end_errno(edge_conn);
2754 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2755 connection_free(conn);
2756 return;
2757 case 0:
2758 conn->state = EXIT_CONN_STATE_CONNECTING;
2760 connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
2761 /* writable indicates finish;
2762 * readable/error indicates broken link in windows-land. */
2763 return;
2764 /* case 1: fall through */
2767 conn->state = EXIT_CONN_STATE_OPEN;
2768 if (connection_wants_to_flush(conn)) {
2769 /* in case there are any queued data cells */
2770 log_warn(LD_BUG,"newly connected conn had data waiting!");
2771 // connection_start_writing(conn);
2773 connection_watch_events(conn, READ_EVENT);
2775 /* also, deliver a 'connected' cell back through the circuit. */
2776 if (connection_edge_is_rendezvous_stream(edge_conn)) {
2777 /* rendezvous stream */
2778 /* don't send an address back! */
2779 connection_edge_send_command(edge_conn,
2780 RELAY_COMMAND_CONNECTED,
2781 NULL, 0);
2782 } else { /* normal stream */
2783 char connected_payload[20];
2784 int connected_payload_len;
2785 if (tor_addr_family(&conn->addr) == AF_INET) {
2786 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
2787 connected_payload_len = 4;
2788 } else {
2789 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
2790 connected_payload_len = 16;
2792 set_uint32(connected_payload+connected_payload_len,
2793 htonl(dns_clip_ttl(edge_conn->address_ttl)));
2794 connected_payload_len += 4;
2795 connection_edge_send_command(edge_conn,
2796 RELAY_COMMAND_CONNECTED,
2797 connected_payload, connected_payload_len);
2801 /** Given an exit conn that should attach to us as a directory server, open a
2802 * bridge connection with a linked connection pair, create a new directory
2803 * conn, and join them together. Return 0 on success (or if there was an
2804 * error we could send back an end cell for). Return -(some circuit end
2805 * reason) if the circuit needs to be torn down. Either connects
2806 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2808 static int
2809 connection_exit_connect_dir(edge_connection_t *exitconn)
2811 dir_connection_t *dirconn = NULL;
2812 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
2814 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
2816 exitconn->_base.state = EXIT_CONN_STATE_OPEN;
2818 dirconn = dir_connection_new(AF_INET);
2820 tor_addr_copy(&dirconn->_base.addr, &exitconn->_base.addr);
2821 dirconn->_base.port = 0;
2822 dirconn->_base.address = tor_strdup(exitconn->_base.address);
2823 dirconn->_base.type = CONN_TYPE_DIR;
2824 dirconn->_base.purpose = DIR_PURPOSE_SERVER;
2825 dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2827 /* Note that the new dir conn belongs to the same tunneled request as
2828 * the edge conn, so that we can measure download times. */
2829 TO_CONN(dirconn)->dirreq_id = TO_CONN(exitconn)->dirreq_id;
2831 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
2833 if (connection_add(TO_CONN(exitconn))<0) {
2834 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2835 connection_free(TO_CONN(exitconn));
2836 connection_free(TO_CONN(dirconn));
2837 return 0;
2840 /* link exitconn to circ, now that we know we can use it. */
2841 exitconn->next_stream = circ->n_streams;
2842 circ->n_streams = exitconn;
2844 if (connection_add(TO_CONN(dirconn))<0) {
2845 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2846 connection_close_immediate(TO_CONN(exitconn));
2847 connection_mark_for_close(TO_CONN(exitconn));
2848 connection_free(TO_CONN(dirconn));
2849 return 0;
2852 connection_start_reading(TO_CONN(dirconn));
2853 connection_start_reading(TO_CONN(exitconn));
2855 if (connection_edge_send_command(exitconn,
2856 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
2857 connection_mark_for_close(TO_CONN(exitconn));
2858 connection_mark_for_close(TO_CONN(dirconn));
2859 return 0;
2862 return 0;
2865 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2866 * it is a general stream.
2869 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
2871 tor_assert(conn);
2872 if (conn->rend_data)
2873 return 1;
2874 return 0;
2877 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2878 * to exit from it, or 0 if it probably will not allow it.
2879 * (We might be uncertain if conn's destination address has not yet been
2880 * resolved.)
2882 * If <b>excluded_means_no</b> is 1 and Exclude*Nodes is set and excludes
2883 * this relay, return 0.
2886 connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit,
2887 int excluded_means_no)
2889 or_options_t *options = get_options();
2891 tor_assert(conn);
2892 tor_assert(conn->_base.type == CONN_TYPE_AP);
2893 tor_assert(conn->socks_request);
2894 tor_assert(exit);
2896 /* If a particular exit node has been requested for the new connection,
2897 * make sure the exit node of the existing circuit matches exactly.
2899 if (conn->chosen_exit_name) {
2900 routerinfo_t *chosen_exit =
2901 router_get_by_nickname(conn->chosen_exit_name, 1);
2902 if (!chosen_exit || memcmp(chosen_exit->cache_info.identity_digest,
2903 exit->cache_info.identity_digest, DIGEST_LEN)) {
2904 /* doesn't match */
2905 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2906 // conn->chosen_exit_name, exit->nickname);
2907 return 0;
2911 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2912 !conn->use_begindir) {
2913 struct in_addr in;
2914 uint32_t addr = 0;
2915 addr_policy_result_t r;
2916 if (tor_inet_aton(conn->socks_request->address, &in))
2917 addr = ntohl(in.s_addr);
2918 r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
2919 exit->exit_policy);
2920 if (r == ADDR_POLICY_REJECTED)
2921 return 0; /* We know the address, and the exit policy rejects it. */
2922 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
2923 return 0; /* We don't know the addr, but the exit policy rejects most
2924 * addresses with this port. Since the user didn't ask for
2925 * this node, err on the side of caution. */
2926 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2927 /* Can't support reverse lookups without eventdns. */
2928 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
2929 exit->has_old_dnsworkers)
2930 return 0;
2932 /* Don't send DNS requests to non-exit servers by default. */
2933 if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
2934 return 0;
2936 if (options->_ExcludeExitNodesUnion &&
2937 (options->StrictNodes || excluded_means_no) &&
2938 routerset_contains_router(options->_ExcludeExitNodesUnion, exit)) {
2939 /* If we are trying to avoid this node as exit, and we have StrictNodes
2940 * set, then this is not a suitable exit. Refuse it.
2942 * If we don't have StrictNodes set, then this function gets called in
2943 * two contexts. First, we've got a circuit open and we want to know
2944 * whether we can use it. In that case, we somehow built this circuit
2945 * despite having the last hop in ExcludeExitNodes, so we should be
2946 * willing to use it. Second, we are evaluating whether this is an
2947 * acceptable exit for a new circuit. In that case, skip it. */
2948 return 0;
2951 return 1;
2954 /** If address is of the form "y.onion" with a well-formed handle y:
2955 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2957 * If address is of the form "y.exit" and <b>allowdotexit</b> is true:
2958 * Put a NUL after y and return EXIT_HOSTNAME.
2960 * Otherwise:
2961 * Return NORMAL_HOSTNAME and change nothing.
2963 hostname_type_t
2964 parse_extended_hostname(char *address, int allowdotexit)
2966 char *s;
2967 char query[REND_SERVICE_ID_LEN_BASE32+1];
2969 s = strrchr(address,'.');
2970 if (!s)
2971 return NORMAL_HOSTNAME; /* no dot, thus normal */
2972 if (!strcmp(s+1,"exit")) {
2973 if (allowdotexit) {
2974 *s = 0; /* NUL-terminate it */
2975 return EXIT_HOSTNAME; /* .exit */
2976 } else {
2977 log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
2978 "security risks. Set AllowDotExit in your torrc to enable "
2979 "it.");
2980 /* FFFF send a controller event too to notify Vidalia users */
2981 return BAD_HOSTNAME;
2984 if (strcmp(s+1,"onion"))
2985 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
2987 /* so it is .onion */
2988 *s = 0; /* NUL-terminate it */
2989 if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
2990 REND_SERVICE_ID_LEN_BASE32+1)
2991 goto failed;
2992 if (rend_valid_service_id(query)) {
2993 return ONION_HOSTNAME; /* success */
2995 failed:
2996 /* otherwise, return to previous state and return 0 */
2997 *s = '.';
2998 return BAD_HOSTNAME;