As an exit node, scrub the IP address to which we are exiting in the logs. Bugfix...
[tor/rransom.git] / src / or / connection_edge.c
bloba157bdbb2e95a60b47ea87872fb6c83727dda97d
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-2008, 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"
14 #ifdef HAVE_LINUX_TYPES_H
15 #include <linux/types.h>
16 #endif
17 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
18 #include <linux/netfilter_ipv4.h>
19 #define TRANS_NETFILTER
20 #endif
22 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
23 #include <net/if.h>
24 #include <net/pfvar.h>
25 #define TRANS_PF
26 #endif
28 #define SOCKS4_GRANTED 90
29 #define SOCKS4_REJECT 91
31 static int connection_ap_handshake_process_socks(edge_connection_t *conn);
32 static int connection_ap_process_natd(edge_connection_t *conn);
33 static int connection_exit_connect_dir(edge_connection_t *exitconn);
34 static int address_is_in_virtual_range(const char *addr);
35 static int consider_plaintext_ports(edge_connection_t *conn, uint16_t port);
36 static void clear_trackexithost_mappings(const char *exitname);
38 /** An AP stream has failed/finished. If it hasn't already sent back
39 * a socks reply, send one now (based on endreason). Also set
40 * has_sent_end to 1, and mark the conn.
42 void
43 _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
44 int line, const char *file)
46 tor_assert(conn->_base.type == CONN_TYPE_AP);
47 conn->edge_has_sent_end = 1; /* no circ yet */
49 if (conn->_base.marked_for_close) {
50 /* This call will warn as appropriate. */
51 _connection_mark_for_close(TO_CONN(conn), line, file);
52 return;
55 if (!conn->socks_request->has_finished) {
56 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
57 log_warn(LD_BUG,
58 "stream (marked at %s:%d) sending two socks replies?",
59 file, line);
61 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
62 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
63 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
64 connection_ap_handshake_socks_resolved(conn,
65 RESOLVED_TYPE_ERROR_TRANSIENT,
66 0, NULL, -1, -1);
67 else /* unknown or no handshake at all. send no response. */
68 conn->socks_request->has_finished = 1;
71 _connection_mark_for_close(TO_CONN(conn), line, file);
72 conn->_base.hold_open_until_flushed = 1;
73 conn->end_reason = endreason;
76 /** There was an EOF. Send an end and mark the connection for close.
78 int
79 connection_edge_reached_eof(edge_connection_t *conn)
81 if (buf_datalen(conn->_base.inbuf) &&
82 connection_state_is_open(TO_CONN(conn))) {
83 /* it still has stuff to process. don't let it die yet. */
84 return 0;
86 log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
87 if (!conn->_base.marked_for_close) {
88 /* only mark it if not already marked. it's possible to
89 * get the 'end' right around when the client hangs up on us. */
90 connection_edge_end(conn, END_STREAM_REASON_DONE);
91 if (conn->socks_request) /* eof, so don't send a socks reply back */
92 conn->socks_request->has_finished = 1;
93 connection_mark_for_close(TO_CONN(conn));
95 return 0;
98 /** Handle new bytes on conn->inbuf based on state:
99 * - If it's waiting for socks info, try to read another step of the
100 * socks handshake out of conn->inbuf.
101 * - If it's waiting for the original destination, fetch it.
102 * - If it's open, then package more relay cells from the stream.
103 * - Else, leave the bytes on inbuf alone for now.
105 * Mark and return -1 if there was an unexpected error with the conn,
106 * else return 0.
109 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
111 tor_assert(conn);
113 switch (conn->_base.state) {
114 case AP_CONN_STATE_SOCKS_WAIT:
115 if (connection_ap_handshake_process_socks(conn) < 0) {
116 /* already marked */
117 return -1;
119 return 0;
120 case AP_CONN_STATE_NATD_WAIT:
121 if (connection_ap_process_natd(conn) < 0) {
122 /* already marked */
123 return -1;
125 return 0;
126 case AP_CONN_STATE_OPEN:
127 case EXIT_CONN_STATE_OPEN:
128 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
129 /* (We already sent an end cell if possible) */
130 connection_mark_for_close(TO_CONN(conn));
131 return -1;
133 return 0;
134 case EXIT_CONN_STATE_CONNECTING:
135 case AP_CONN_STATE_RENDDESC_WAIT:
136 case AP_CONN_STATE_CIRCUIT_WAIT:
137 case AP_CONN_STATE_CONNECT_WAIT:
138 case AP_CONN_STATE_RESOLVE_WAIT:
139 case AP_CONN_STATE_CONTROLLER_WAIT:
140 log_info(LD_EDGE,
141 "data from edge while in '%s' state. Leaving it on buffer.",
142 conn_state_to_string(conn->_base.type, conn->_base.state));
143 return 0;
145 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
146 tor_fragile_assert();
147 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
148 connection_mark_for_close(TO_CONN(conn));
149 return -1;
152 /** This edge needs to be closed, because its circuit has closed.
153 * Mark it for close and return 0.
156 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
158 if (!conn->_base.marked_for_close) {
159 log_info(LD_EDGE,
160 "CircID %d: At an edge. Marking connection for close.", circ_id);
161 if (conn->_base.type == CONN_TYPE_AP) {
162 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
163 control_event_stream_status(conn, STREAM_EVENT_CLOSED,
164 END_STREAM_REASON_DESTROY);
165 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
166 } else {
167 /* closing the circuit, nothing to send an END to */
168 conn->edge_has_sent_end = 1;
169 conn->end_reason = END_STREAM_REASON_DESTROY;
170 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
171 connection_mark_for_close(TO_CONN(conn));
172 conn->_base.hold_open_until_flushed = 1;
175 conn->cpath_layer = NULL;
176 conn->on_circuit = NULL;
177 return 0;
180 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
181 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
182 * is not a client connection, set the relay end cell's reason for closing
183 * as <b>reason</b> */
184 static int
185 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
186 uint8_t reason, crypt_path_t *cpath_layer)
188 char payload[1];
190 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
191 /* Never send the server an informative reason code; it doesn't need to
192 * know why the client stream is failing. */
193 reason = END_STREAM_REASON_MISC;
196 payload[0] = (char) reason;
198 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
199 payload, 1, cpath_layer);
202 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
203 * remember that we've done so. If this is not a client connection, set the
204 * relay end cell's reason for closing as <b>reason</b>.
206 * Return -1 if this function has already been called on this conn,
207 * else return 0.
210 connection_edge_end(edge_connection_t *conn, uint8_t reason)
212 char payload[RELAY_PAYLOAD_SIZE];
213 size_t payload_len=1;
214 circuit_t *circ;
215 uint8_t control_reason = reason;
217 if (conn->edge_has_sent_end) {
218 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
219 "on an already ended stream?", reason);
220 tor_fragile_assert();
221 return -1;
224 if (conn->_base.marked_for_close) {
225 log_warn(LD_BUG,
226 "called on conn that's already marked for close at %s:%d.",
227 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
228 return 0;
231 circ = circuit_get_by_edge_conn(conn);
232 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
233 /* If this is a client circuit, don't send the server an informative
234 * reason code; it doesn't need to know why the client stream is
235 * failing. */
236 reason = END_STREAM_REASON_MISC;
239 payload[0] = (char)reason;
240 if (reason == END_STREAM_REASON_EXITPOLICY &&
241 !connection_edge_is_rendezvous_stream(conn)) {
242 int addrlen;
243 if (tor_addr_family(&conn->_base.addr) == AF_INET) {
244 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
245 addrlen = 4;
246 } else {
247 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
248 addrlen = 16;
250 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
251 payload_len += 4+addrlen;
254 if (circ && !circ->marked_for_close) {
255 log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
256 connection_edge_send_command(conn, RELAY_COMMAND_END,
257 payload, payload_len);
258 } else {
259 log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
260 conn->_base.s);
263 conn->edge_has_sent_end = 1;
264 conn->end_reason = control_reason;
265 return 0;
268 /** An error has just occured on an operation on an edge connection
269 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
270 * appropriate relay end cell to the other end of the connection's circuit.
273 connection_edge_end_errno(edge_connection_t *conn)
275 uint8_t reason;
276 tor_assert(conn);
277 reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
278 return connection_edge_end(conn, reason);
281 /** Connection <b>conn</b> has finished writing and has no bytes left on
282 * its outbuf.
284 * If it's in state 'open', stop writing, consider responding with a
285 * sendme, and return.
286 * Otherwise, stop writing and return.
288 * If <b>conn</b> is broken, mark it for close and return -1, else
289 * return 0.
292 connection_edge_finished_flushing(edge_connection_t *conn)
294 tor_assert(conn);
296 switch (conn->_base.state) {
297 case AP_CONN_STATE_OPEN:
298 case EXIT_CONN_STATE_OPEN:
299 connection_stop_writing(TO_CONN(conn));
300 connection_edge_consider_sending_sendme(conn);
301 return 0;
302 case AP_CONN_STATE_SOCKS_WAIT:
303 case AP_CONN_STATE_NATD_WAIT:
304 case AP_CONN_STATE_RENDDESC_WAIT:
305 case AP_CONN_STATE_CIRCUIT_WAIT:
306 case AP_CONN_STATE_CONNECT_WAIT:
307 case AP_CONN_STATE_CONTROLLER_WAIT:
308 connection_stop_writing(TO_CONN(conn));
309 return 0;
310 default:
311 log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
312 tor_fragile_assert();
313 return -1;
315 return 0;
318 /** Connected handler for exit connections: start writing pending
319 * data, deliver 'CONNECTED' relay cells as appropriate, and check
320 * any pending data that may have been received. */
322 connection_edge_finished_connecting(edge_connection_t *edge_conn)
324 connection_t *conn;
326 tor_assert(edge_conn);
327 tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
328 conn = TO_CONN(edge_conn);
329 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
331 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
332 escaped_safe_str(conn->address),conn->port,
333 safe_str(fmt_addr(&conn->addr)));
335 conn->state = EXIT_CONN_STATE_OPEN;
336 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
337 if (connection_wants_to_flush(conn)) /* in case there are any queued relay
338 * cells */
339 connection_start_writing(conn);
340 /* deliver a 'connected' relay cell back through the circuit. */
341 if (connection_edge_is_rendezvous_stream(edge_conn)) {
342 if (connection_edge_send_command(edge_conn,
343 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
344 return 0; /* circuit is closed, don't continue */
345 } else {
346 char connected_payload[20];
347 int connected_payload_len;
348 if (tor_addr_family(&conn->addr) == AF_INET) {
349 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
350 set_uint32(connected_payload+4,
351 htonl(dns_clip_ttl(edge_conn->address_ttl)));
352 connected_payload_len = 8;
353 } else {
354 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
355 set_uint32(connected_payload+16,
356 htonl(dns_clip_ttl(edge_conn->address_ttl)));
357 connected_payload_len = 20;
359 if (connection_edge_send_command(edge_conn,
360 RELAY_COMMAND_CONNECTED,
361 connected_payload, connected_payload_len) < 0)
362 return 0; /* circuit is closed, don't continue */
364 tor_assert(edge_conn->package_window > 0);
365 /* in case the server has written anything */
366 return connection_edge_process_inbuf(edge_conn, 1);
369 /** Define a schedule for how long to wait between retrying
370 * application connections. Rather than waiting a fixed amount of
371 * time between each retry, we wait 10 seconds each for the first
372 * two tries, and 15 seconds for each retry after
373 * that. Hopefully this will improve the expected user experience. */
374 static int
375 compute_retry_timeout(edge_connection_t *conn)
377 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
378 return 10;
379 return 15;
382 /** Find all general-purpose AP streams waiting for a response that sent their
383 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
384 * mark their current circuit as unsuitable for new streams. Then call
385 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
386 * available) or launch a new one.
388 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
389 * retry attempt).
391 void
392 connection_ap_expire_beginning(void)
394 edge_connection_t *conn;
395 circuit_t *circ;
396 time_t now = time(NULL);
397 or_options_t *options = get_options();
398 int severity;
399 int cutoff;
400 int seconds_idle;
401 smartlist_t *conns = get_connection_array();
403 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
404 if (c->type != CONN_TYPE_AP || c->marked_for_close)
405 continue;
406 conn = TO_EDGE_CONN(c);
407 /* if it's an internal linked connection, don't yell its status. */
408 severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
409 ? LOG_INFO : LOG_NOTICE;
410 seconds_idle = (int)( now - conn->_base.timestamp_lastread );
412 /* XXX021 this clause was originally thought redundant with the
413 * clause in connection_ap_handshake_attach_circuit(). But actually,
414 * we need it because controllers that put streams in controller_wait
415 * state never go to the other clause. we should fix so it compares
416 * seconds since timestamp_created, not since last read. -RD */
417 if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
418 if (seconds_idle >= options->SocksTimeout) {
419 log_fn(severity, LD_APP,
420 "Tried for %d seconds to get a connection to %s:%d. "
421 "Giving up. (%s)",
422 seconds_idle, safe_str(conn->socks_request->address),
423 conn->socks_request->port,
424 conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
425 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
427 continue;
430 if (conn->_base.state == AP_CONN_STATE_OPEN)
431 continue;
433 /* We're in state connect_wait or resolve_wait now -- waiting for a
434 * reply to our relay cell. See if we want to retry/give up. */
436 cutoff = compute_retry_timeout(conn);
437 if (seconds_idle < cutoff)
438 continue;
439 circ = circuit_get_by_edge_conn(conn);
440 if (!circ) { /* it's vanished? */
441 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
442 safe_str(conn->socks_request->address));
443 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
444 continue;
446 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
447 if (seconds_idle >= options->SocksTimeout) {
448 log_fn(severity, LD_REND,
449 "Rend stream is %d seconds late. Giving up on address"
450 " '%s.onion'.",
451 seconds_idle,
452 safe_str(conn->socks_request->address));
453 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
454 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
456 continue;
458 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
459 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
460 "We tried for %d seconds to connect to '%s' using exit '%s'."
461 " Retrying on a new circuit.",
462 seconds_idle, safe_str(conn->socks_request->address),
463 conn->cpath_layer ?
464 conn->cpath_layer->extend_info->nickname : "*unnamed*");
465 /* send an end down the circuit */
466 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
467 /* un-mark it as ending, since we're going to reuse it */
468 conn->edge_has_sent_end = 0;
469 conn->end_reason = 0;
470 /* kludge to make us not try this circuit again, yet to allow
471 * current streams on it to survive if they can: make it
472 * unattractive to use for new streams */
473 tor_assert(circ->timestamp_dirty);
474 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
475 /* give our stream another 'cutoff' seconds to try */
476 conn->_base.timestamp_lastread += cutoff;
477 if (conn->num_socks_retries < 250) /* avoid overflow */
478 conn->num_socks_retries++;
479 /* move it back into 'pending' state, and try to attach. */
480 if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
481 END_STREAM_REASON_TIMEOUT)<0) {
482 if (!conn->_base.marked_for_close)
483 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
485 } SMARTLIST_FOREACH_END(conn);
488 /** Tell any AP streams that are waiting for a new circuit to try again,
489 * either attaching to an available circ or launching a new one.
491 void
492 connection_ap_attach_pending(void)
494 edge_connection_t *edge_conn;
495 smartlist_t *conns = get_connection_array();
496 SMARTLIST_FOREACH(conns, connection_t *, conn,
498 if (conn->marked_for_close ||
499 conn->type != CONN_TYPE_AP ||
500 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
501 continue;
502 edge_conn = TO_EDGE_CONN(conn);
503 if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
504 if (!edge_conn->_base.marked_for_close)
505 connection_mark_unattached_ap(edge_conn,
506 END_STREAM_REASON_CANT_ATTACH);
511 /** Tell any AP streams that are waiting for a onehop tunnel to
512 * <b>failed_digest</b> that they are going to fail. */
513 /* XXX022 We should get rid of this function, and instead attach
514 * onehop streams to circ->p_streams so they get marked in
515 * circuit_mark_for_close like normal p_streams. */
516 void
517 connection_ap_fail_onehop(const char *failed_digest,
518 cpath_build_state_t *build_state)
520 edge_connection_t *edge_conn;
521 char digest[DIGEST_LEN];
522 smartlist_t *conns = get_connection_array();
523 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
524 if (conn->marked_for_close ||
525 conn->type != CONN_TYPE_AP ||
526 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
527 continue;
528 edge_conn = TO_EDGE_CONN(conn);
529 if (!edge_conn->want_onehop)
530 continue;
531 if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
532 memcmp(digest, failed_digest, DIGEST_LEN))
533 continue;
534 if (tor_digest_is_zero(digest)) {
535 /* we don't know the digest; have to compare addr:port */
536 tor_addr_t addr;
537 if (!build_state || !build_state->chosen_exit ||
538 !edge_conn->socks_request || !edge_conn->socks_request->address)
539 continue;
540 if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
541 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
542 build_state->chosen_exit->port != edge_conn->socks_request->port)
543 continue;
545 log_info(LD_APP, "Closing onehop stream to '%s/%s' because the OR conn "
546 "just failed.", edge_conn->chosen_exit_name,
547 edge_conn->socks_request->address);
548 connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
549 } SMARTLIST_FOREACH_END(conn);
552 /** A circuit failed to finish on its last hop <b>info</b>. If there
553 * are any streams waiting with this exit node in mind, but they
554 * don't absolutely require it, make them give up on it.
556 void
557 circuit_discard_optional_exit_enclaves(extend_info_t *info)
559 edge_connection_t *edge_conn;
560 routerinfo_t *r1, *r2;
562 smartlist_t *conns = get_connection_array();
563 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
564 if (conn->marked_for_close ||
565 conn->type != CONN_TYPE_AP ||
566 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
567 continue;
568 edge_conn = TO_EDGE_CONN(conn);
569 if (!edge_conn->chosen_exit_optional &&
570 !edge_conn->chosen_exit_retries)
571 continue;
572 r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
573 r2 = router_get_by_nickname(info->nickname, 0);
574 if (!r1 || !r2 || r1 != r2)
575 continue;
576 tor_assert(edge_conn->socks_request);
577 if (edge_conn->chosen_exit_optional) {
578 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
579 safe_str(edge_conn->chosen_exit_name),
580 escaped_safe_str(edge_conn->socks_request->address));
581 edge_conn->chosen_exit_optional = 0;
582 tor_free(edge_conn->chosen_exit_name); /* clears it */
583 /* if this port is dangerous, warn or reject it now that we don't
584 * think it'll be using an enclave. */
585 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
587 if (edge_conn->chosen_exit_retries) {
588 if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
589 clear_trackexithost_mappings(edge_conn->chosen_exit_name);
590 tor_free(edge_conn->chosen_exit_name); /* clears it */
591 /* if this port is dangerous, warn or reject it now that we don't
592 * think it'll be using an enclave. */
593 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
596 } SMARTLIST_FOREACH_END(conn);
599 /** The AP connection <b>conn</b> has just failed while attaching or
600 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
601 * might work. Detach the circuit, and either reattach it, launch a
602 * new circuit, tell the controller, or give up as a appropriate.
604 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
607 connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
608 int reason)
610 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
611 conn->_base.timestamp_lastread = time(NULL);
612 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
613 /* If we're attaching streams ourself, or if this connection is
614 * a tunneled directory connection, then just attach it. */
615 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
616 circuit_detach_stream(TO_CIRCUIT(circ),conn);
617 return connection_ap_handshake_attach_circuit(conn);
618 } else {
619 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
620 circuit_detach_stream(TO_CIRCUIT(circ),conn);
621 return 0;
625 /** A client-side struct to remember requests to rewrite addresses
626 * to new addresses. These structs are stored in the hash table
627 * "addressmap" below.
629 * There are 5 ways to set an address mapping:
630 * - A MapAddress command from the controller [permanent]
631 * - An AddressMap directive in the torrc [permanent]
632 * - When a TrackHostExits torrc directive is triggered [temporary]
633 * - When a dns resolve succeeds [temporary]
634 * - When a dns resolve fails [temporary]
636 * When an addressmap request is made but one is already registered,
637 * the new one is replaced only if the currently registered one has
638 * no "new_address" (that is, it's in the process of dns resolve),
639 * or if the new one is permanent (expires==0 or 1).
641 * (We overload the 'expires' field, using "0" for mappings set via
642 * the configuration file, "1" for mappings set from the control
643 * interface, and other values for DNS and TrackHostExit mappings that can
644 * expire.)
646 typedef struct {
647 char *new_address;
648 time_t expires;
649 addressmap_entry_source_t source:3;
650 short num_resolve_failures;
651 } addressmap_entry_t;
653 /** Entry for mapping addresses to which virtual address we mapped them to. */
654 typedef struct {
655 char *ipv4_address;
656 char *hostname_address;
657 } virtaddress_entry_t;
659 /** A hash table to store client-side address rewrite instructions. */
660 static strmap_t *addressmap=NULL;
662 * Table mapping addresses to which virtual address, if any, we
663 * assigned them to.
665 * We maintain the following invariant: if [A,B] is in
666 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
667 * must be in addressmap. We do not require that the converse hold:
668 * if it fails, then we could end up mapping two virtual addresses to
669 * the same address, which is no disaster.
671 static strmap_t *virtaddress_reversemap=NULL;
673 /** Initialize addressmap. */
674 void
675 addressmap_init(void)
677 addressmap = strmap_new();
678 virtaddress_reversemap = strmap_new();
681 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
682 static void
683 addressmap_ent_free(void *_ent)
685 addressmap_entry_t *ent = _ent;
686 tor_free(ent->new_address);
687 tor_free(ent);
690 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
691 static void
692 addressmap_virtaddress_ent_free(void *_ent)
694 virtaddress_entry_t *ent = _ent;
695 tor_free(ent->ipv4_address);
696 tor_free(ent->hostname_address);
697 tor_free(ent);
700 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
701 static void
702 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
704 if (ent && ent->new_address &&
705 address_is_in_virtual_range(ent->new_address)) {
706 virtaddress_entry_t *ve =
707 strmap_get(virtaddress_reversemap, ent->new_address);
708 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
709 if (ve) {
710 if (!strcmp(address, ve->ipv4_address))
711 tor_free(ve->ipv4_address);
712 if (!strcmp(address, ve->hostname_address))
713 tor_free(ve->hostname_address);
714 if (!ve->ipv4_address && !ve->hostname_address) {
715 tor_free(ve);
716 strmap_remove(virtaddress_reversemap, ent->new_address);
722 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
723 * client address maps. */
724 static void
725 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
727 addressmap_virtaddress_remove(address, ent);
728 addressmap_ent_free(ent);
731 /** Unregister all TrackHostExits mappings from any address to
732 * *.exitname.exit. */
733 static void
734 clear_trackexithost_mappings(const char *exitname)
736 char *suffix;
737 size_t suffix_len;
738 if (!addressmap || !exitname)
739 return;
740 suffix_len = strlen(exitname) + 16;
741 suffix = tor_malloc(suffix_len);
742 tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
743 tor_strlower(suffix);
745 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
746 if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
747 addressmap_ent_remove(address, ent);
748 MAP_DEL_CURRENT(address);
750 } STRMAP_FOREACH_END;
752 tor_free(suffix);
755 /** Remove all entries from the addressmap that were set via the
756 * configuration file or the command line. */
757 void
758 addressmap_clear_configured(void)
760 addressmap_get_mappings(NULL, 0, 0, 0);
763 /** Remove all entries from the addressmap that are set to expire, ever. */
764 void
765 addressmap_clear_transient(void)
767 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
770 /** Clean out entries from the addressmap cache that were
771 * added long enough ago that they are no longer valid.
773 void
774 addressmap_clean(time_t now)
776 addressmap_get_mappings(NULL, 2, now, 0);
779 /** Free all the elements in the addressmap, and free the addressmap
780 * itself. */
781 void
782 addressmap_free_all(void)
784 if (addressmap) {
785 strmap_free(addressmap, addressmap_ent_free);
786 addressmap = NULL;
788 if (virtaddress_reversemap) {
789 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
790 virtaddress_reversemap = NULL;
794 /** Look at address, and rewrite it until it doesn't want any
795 * more rewrites; but don't get into an infinite loop.
796 * Don't write more than maxlen chars into address. Return true if the
797 * address changed; false otherwise. Set *<b>expires_out</b> to the
798 * expiry time of the result, or to <b>time_max</b> if the result does
799 * not expire.
802 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
804 addressmap_entry_t *ent;
805 int rewrites;
806 char *cp;
807 time_t expires = TIME_MAX;
809 for (rewrites = 0; rewrites < 16; rewrites++) {
810 ent = strmap_get(addressmap, address);
812 if (!ent || !ent->new_address) {
813 if (expires_out)
814 *expires_out = expires;
815 return (rewrites > 0); /* done, no rewrite needed */
818 cp = tor_strdup(escaped_safe_str(ent->new_address));
819 log_info(LD_APP, "Addressmap: rewriting %s to %s",
820 escaped_safe_str(address), cp);
821 if (ent->expires > 1 && ent->expires < expires)
822 expires = ent->expires;
823 tor_free(cp);
824 strlcpy(address, ent->new_address, maxlen);
826 log_warn(LD_CONFIG,
827 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
828 escaped_safe_str(address));
829 /* it's fine to rewrite a rewrite, but don't loop forever */
830 if (expires_out)
831 *expires_out = TIME_MAX;
832 return 1;
835 /** If we have a cached reverse DNS entry for the address stored in the
836 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
837 * rewrite to the cached value and return 1. Otherwise return 0. Set
838 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
839 * if the result does not expire. */
840 static int
841 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
843 size_t len = maxlen + 16;
844 char *s = tor_malloc(len), *cp;
845 addressmap_entry_t *ent;
846 int r = 0;
847 tor_snprintf(s, len, "REVERSE[%s]", address);
848 ent = strmap_get(addressmap, s);
849 if (ent) {
850 cp = tor_strdup(escaped_safe_str(ent->new_address));
851 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
852 escaped_safe_str(s), cp);
853 tor_free(cp);
854 strlcpy(address, ent->new_address, maxlen);
855 r = 1;
858 if (expires_out)
859 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
861 tor_free(s);
862 return r;
865 /** Return 1 if <b>address</b> is already registered, else return 0. If address
866 * is already registered, and <b>update_expires</b> is non-zero, then update
867 * the expiry time on the mapping with update_expires if it is a
868 * mapping created by TrackHostExits. */
870 addressmap_have_mapping(const char *address, int update_expiry)
872 addressmap_entry_t *ent;
873 if (!(ent=strmap_get_lc(addressmap, address)))
874 return 0;
875 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
876 ent->expires=time(NULL) + update_expiry;
877 return 1;
880 /** Register a request to map <b>address</b> to <b>new_address</b>,
881 * which will expire on <b>expires</b> (or 0 if never expires from
882 * config file, 1 if never expires from controller, 2 if never expires
883 * (virtual address mapping) from the controller.)
885 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
886 * free as appropriate. We will leave address alone.
888 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
889 * any mappings that exist from <b>address</b>.
891 void
892 addressmap_register(const char *address, char *new_address, time_t expires,
893 addressmap_entry_source_t source)
895 addressmap_entry_t *ent;
897 ent = strmap_get(addressmap, address);
898 if (!new_address || !strcasecmp(address,new_address)) {
899 /* Remove the mapping, if any. */
900 tor_free(new_address);
901 if (ent) {
902 addressmap_ent_remove(address,ent);
903 strmap_remove(addressmap, address);
905 return;
907 if (!ent) { /* make a new one and register it */
908 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
909 strmap_set(addressmap, address, ent);
910 } else if (ent->new_address) { /* we need to clean up the old mapping. */
911 if (expires > 1) {
912 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
913 "since it's already mapped to '%s'",
914 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
915 tor_free(new_address);
916 return;
918 if (address_is_in_virtual_range(ent->new_address) &&
919 expires != 2) {
920 /* XXX This isn't the perfect test; we want to avoid removing
921 * mappings set from the control interface _as virtual mapping */
922 addressmap_virtaddress_remove(address, ent);
924 tor_free(ent->new_address);
925 } /* else { we have an in-progress resolve with no mapping. } */
927 ent->new_address = new_address;
928 ent->expires = expires==2 ? 1 : expires;
929 ent->num_resolve_failures = 0;
930 ent->source = source;
932 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
933 safe_str(address), safe_str(ent->new_address));
934 control_event_address_mapped(address, ent->new_address, expires, NULL);
937 /** An attempt to resolve <b>address</b> failed at some OR.
938 * Increment the number of resolve failures we have on record
939 * for it, and then return that number.
942 client_dns_incr_failures(const char *address)
944 addressmap_entry_t *ent = strmap_get(addressmap, address);
945 if (!ent) {
946 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
947 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
948 strmap_set(addressmap,address,ent);
950 if (ent->num_resolve_failures < SHORT_MAX)
951 ++ent->num_resolve_failures; /* don't overflow */
952 log_info(LD_APP, "Address %s now has %d resolve failures.",
953 safe_str(address), ent->num_resolve_failures);
954 return ent->num_resolve_failures;
957 /** If <b>address</b> is in the client dns addressmap, reset
958 * the number of resolve failures we have on record for it.
959 * This is used when we fail a stream because it won't resolve:
960 * otherwise future attempts on that address will only try once.
962 void
963 client_dns_clear_failures(const char *address)
965 addressmap_entry_t *ent = strmap_get(addressmap, address);
966 if (ent)
967 ent->num_resolve_failures = 0;
970 /** Record the fact that <b>address</b> resolved to <b>name</b>.
971 * We can now use this in subsequent streams via addressmap_rewrite()
972 * so we can more correctly choose an exit that will allow <b>address</b>.
974 * If <b>exitname</b> is defined, then append the addresses with
975 * ".exitname.exit" before registering the mapping.
977 * If <b>ttl</b> is nonnegative, the mapping will be valid for
978 * <b>ttl</b>seconds; otherwise, we use the default.
980 static void
981 client_dns_set_addressmap_impl(const char *address, const char *name,
982 const char *exitname,
983 int ttl)
985 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
986 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
987 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
988 char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
990 tor_assert(address);
991 tor_assert(name);
993 if (ttl<0)
994 ttl = DEFAULT_DNS_TTL;
995 else
996 ttl = dns_clip_ttl(ttl);
998 if (exitname) {
999 /* XXXX fails to ever get attempts to get an exit address of
1000 * google.com.digest[=~]nickname.exit; we need a syntax for this that
1001 * won't make strict RFC952-compliant applications (like us) barf. */
1002 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1003 "%s.%s.exit", address, exitname);
1004 tor_snprintf(extendedval, sizeof(extendedval),
1005 "%s.%s.exit", name, exitname);
1006 } else {
1007 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1008 "%s", address);
1009 tor_snprintf(extendedval, sizeof(extendedval),
1010 "%s", name);
1012 addressmap_register(extendedaddress, tor_strdup(extendedval),
1013 time(NULL) + ttl, ADDRMAPSRC_DNS);
1016 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1017 * We can now use this in subsequent streams via addressmap_rewrite()
1018 * so we can more correctly choose an exit that will allow <b>address</b>.
1020 * If <b>exitname</b> is defined, then append the addresses with
1021 * ".exitname.exit" before registering the mapping.
1023 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1024 * <b>ttl</b>seconds; otherwise, we use the default.
1026 void
1027 client_dns_set_addressmap(const char *address, uint32_t val,
1028 const char *exitname,
1029 int ttl)
1031 struct in_addr in;
1032 char valbuf[INET_NTOA_BUF_LEN];
1034 tor_assert(address);
1036 if (tor_inet_aton(address, &in))
1037 return; /* If address was an IP address already, don't add a mapping. */
1038 in.s_addr = htonl(val);
1039 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
1041 client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
1044 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1045 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1047 * If <b>exitname</b> is defined, then append the addresses with
1048 * ".exitname.exit" before registering the mapping.
1050 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1051 * <b>ttl</b>seconds; otherwise, we use the default.
1053 static void
1054 client_dns_set_reverse_addressmap(const char *address, const char *v,
1055 const char *exitname,
1056 int ttl)
1058 size_t len = strlen(address) + 16;
1059 char *s = tor_malloc(len);
1060 tor_snprintf(s, len, "REVERSE[%s]", address);
1061 client_dns_set_addressmap_impl(s, v, exitname, ttl);
1062 tor_free(s);
1065 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1066 * These addresses should map to localhost, so even if the
1067 * application accidentally tried to connect to them directly (not
1068 * via Tor), it wouldn't get too far astray.
1070 * These options are configured by parse_virtual_addr_network().
1072 /** Which network should we use for virtual IPv4 addresses? Only the first
1073 * bits of this value are fixed. */
1074 static uint32_t virtual_addr_network = 0x7fc00000u;
1075 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1076 static maskbits_t virtual_addr_netmask_bits = 10;
1077 /** What's the next virtual address we will hand out? */
1078 static uint32_t next_virtual_addr = 0x7fc00000u;
1080 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1081 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1082 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1083 * string and return -1 on failure. If validate_only is false, sets the
1084 * actual virtual address range to the parsed value. */
1086 parse_virtual_addr_network(const char *val, int validate_only,
1087 char **msg)
1089 uint32_t addr;
1090 uint16_t port_min, port_max;
1091 maskbits_t bits;
1093 if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
1094 if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
1095 return -1;
1098 if (port_min != 1 || port_max != 65535) {
1099 if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
1100 return -1;
1103 if (bits > 16) {
1104 if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
1105 "network or larger");
1106 return -1;
1109 if (validate_only)
1110 return 0;
1112 virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
1113 virtual_addr_netmask_bits = bits;
1115 if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
1116 next_virtual_addr = addr;
1118 return 0;
1122 * Return true iff <b>addr</b> is likely to have been returned by
1123 * client_dns_get_unused_address.
1125 static int
1126 address_is_in_virtual_range(const char *address)
1128 struct in_addr in;
1129 tor_assert(address);
1130 if (!strcasecmpend(address, ".virtual")) {
1131 return 1;
1132 } else if (tor_inet_aton(address, &in)) {
1133 uint32_t addr = ntohl(in.s_addr);
1134 if (!addr_mask_cmp_bits(addr, virtual_addr_network,
1135 virtual_addr_netmask_bits))
1136 return 1;
1138 return 0;
1141 /** Return a newly allocated string holding an address of <b>type</b>
1142 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1143 * and that is very unlikely to be the address of any real host.
1145 static char *
1146 addressmap_get_virtual_address(int type)
1148 char buf[64];
1149 struct in_addr in;
1150 tor_assert(addressmap);
1152 if (type == RESOLVED_TYPE_HOSTNAME) {
1153 char rand[10];
1154 do {
1155 crypto_rand(rand, sizeof(rand));
1156 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
1157 strlcat(buf, ".virtual", sizeof(buf));
1158 } while (strmap_get(addressmap, buf));
1159 return tor_strdup(buf);
1160 } else if (type == RESOLVED_TYPE_IPV4) {
1161 // This is an imperfect estimate of how many addresses are available, but
1162 // that's ok.
1163 uint32_t available = 1u << (32-virtual_addr_netmask_bits);
1164 while (available) {
1165 /* Don't hand out any .0 or .255 address. */
1166 while ((next_virtual_addr & 0xff) == 0 ||
1167 (next_virtual_addr & 0xff) == 0xff) {
1168 ++next_virtual_addr;
1170 in.s_addr = htonl(next_virtual_addr);
1171 tor_inet_ntoa(&in, buf, sizeof(buf));
1172 if (!strmap_get(addressmap, buf)) {
1173 ++next_virtual_addr;
1174 break;
1177 ++next_virtual_addr;
1178 --available;
1179 log_info(LD_CONFIG, "%d addrs available", (int)available);
1180 if (! --available) {
1181 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
1182 return NULL;
1184 if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
1185 virtual_addr_netmask_bits))
1186 next_virtual_addr = virtual_addr_network;
1188 return tor_strdup(buf);
1189 } else {
1190 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
1191 return NULL;
1195 /** A controller has requested that we map some address of type
1196 * <b>type</b> to the address <b>new_address</b>. Choose an address
1197 * that is unlikely to be used, and map it, and return it in a newly
1198 * allocated string. If another address of the same type is already
1199 * mapped to <b>new_address</b>, try to return a copy of that address.
1201 * The string in <b>new_address</b> may be freed, or inserted into a map
1202 * as appropriate.
1204 const char *
1205 addressmap_register_virtual_address(int type, char *new_address)
1207 char **addrp;
1208 virtaddress_entry_t *vent;
1210 tor_assert(new_address);
1211 tor_assert(addressmap);
1212 tor_assert(virtaddress_reversemap);
1214 vent = strmap_get(virtaddress_reversemap, new_address);
1215 if (!vent) {
1216 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
1217 strmap_set(virtaddress_reversemap, new_address, vent);
1220 addrp = (type == RESOLVED_TYPE_IPV4) ?
1221 &vent->ipv4_address : &vent->hostname_address;
1222 if (*addrp) {
1223 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1224 if (ent && ent->new_address &&
1225 !strcasecmp(new_address, ent->new_address)) {
1226 tor_free(new_address);
1227 return tor_strdup(*addrp);
1228 } else
1229 log_warn(LD_BUG,
1230 "Internal confusion: I thought that '%s' was mapped to by "
1231 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1232 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
1233 ent?safe_str(ent->new_address):"(nothing)");
1236 tor_free(*addrp);
1237 *addrp = addressmap_get_virtual_address(type);
1238 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1239 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_CONTROLLER);
1241 #if 0
1243 /* Try to catch possible bugs */
1244 addressmap_entry_t *ent;
1245 ent = strmap_get(addressmap, *addrp);
1246 tor_assert(ent);
1247 tor_assert(!strcasecmp(ent->new_address,new_address));
1248 vent = strmap_get(virtaddress_reversemap, new_address);
1249 tor_assert(vent);
1250 tor_assert(!strcasecmp(*addrp,
1251 (type == RESOLVED_TYPE_IPV4) ?
1252 vent->ipv4_address : vent->hostname_address));
1253 log_info(LD_APP, "Map from %s to %s okay.",
1254 safe_str(*addrp),safe_str(new_address));
1256 #endif
1258 return *addrp;
1261 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1262 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1263 * should be true if we're using this address as a client; false if we're
1264 * using it as a server.
1267 address_is_invalid_destination(const char *address, int client)
1269 if (client) {
1270 if (get_options()->AllowNonRFC953Hostnames)
1271 return 0;
1272 } else {
1273 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1274 return 0;
1277 while (*address) {
1278 if (TOR_ISALNUM(*address) ||
1279 *address == '-' ||
1280 *address == '.' ||
1281 *address == '_') /* Underscore is not allowed, but Windows does it
1282 * sometimes, just to thumb its nose at the IETF. */
1283 ++address;
1284 else
1285 return 1;
1287 return 0;
1290 /** Iterate over all address mappings which have expiry times between
1291 * min_expires and max_expires, inclusive. If sl is provided, add an
1292 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1293 * the expiry time if want_expiry is false. If sl is NULL, remove the
1294 * mappings.
1296 void
1297 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1298 time_t max_expires, int want_expiry)
1300 strmap_iter_t *iter;
1301 const char *key;
1302 void *_val;
1303 addressmap_entry_t *val;
1305 if (!addressmap)
1306 addressmap_init();
1308 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1309 strmap_iter_get(iter, &key, &_val);
1310 val = _val;
1311 if (val->expires >= min_expires && val->expires <= max_expires) {
1312 if (!sl) {
1313 iter = strmap_iter_next_rmv(addressmap,iter);
1314 addressmap_ent_remove(key, val);
1315 continue;
1316 } else if (val->new_address) {
1317 size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
1318 char *line = tor_malloc(len);
1319 if (want_expiry) {
1320 if (val->expires < 3 || val->expires == TIME_MAX)
1321 tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
1322 else {
1323 char time[ISO_TIME_LEN+1];
1324 format_iso_time(time, val->expires);
1325 tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
1326 time);
1328 } else {
1329 tor_snprintf(line, len, "%s %s", key, val->new_address);
1331 smartlist_add(sl, line);
1334 iter = strmap_iter_next(addressmap,iter);
1338 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1339 * reject depending on our config options. */
1340 static int
1341 consider_plaintext_ports(edge_connection_t *conn, uint16_t port)
1343 or_options_t *options = get_options();
1344 int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
1346 if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
1347 log_warn(LD_APP, "Application request to port %d: this port is "
1348 "commonly used for unencrypted protocols. Please make sure "
1349 "you don't send anything you would mind the rest of the "
1350 "Internet reading!%s", port, reject ? " Closing." : "");
1351 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1352 port, reject ? "REJECT" : "WARN");
1355 if (reject) {
1356 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1357 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1358 return -1;
1361 return 0;
1364 /** How many times do we try connecting with an exit configured via
1365 * TrackHostExits before concluding that it won't work any more and trying a
1366 * different one? */
1367 #define TRACKHOSTEXITS_RETRIES 5
1369 /** Connection <b>conn</b> just finished its socks handshake, or the
1370 * controller asked us to take care of it. If <b>circ</b> is defined,
1371 * then that's where we'll want to attach it. Otherwise we have to
1372 * figure it out ourselves.
1374 * First, parse whether it's a .exit address, remap it, and so on. Then
1375 * if it's for a general circuit, try to attach it to a circuit (or launch
1376 * one as needed), else if it's for a rendezvous circuit, fetch a
1377 * rendezvous descriptor first (or attach/launch a circuit if the
1378 * rendezvous descriptor is already here and fresh enough).
1380 * The stream will exit from the hop
1381 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1382 * <b>cpath</b> is NULL.
1385 connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
1386 origin_circuit_t *circ,
1387 crypt_path_t *cpath)
1389 socks_request_t *socks = conn->socks_request;
1390 hostname_type_t addresstype;
1391 or_options_t *options = get_options();
1392 struct in_addr addr_tmp;
1393 int automap = 0;
1394 char orig_address[MAX_SOCKS_ADDR_LEN];
1395 time_t map_expires = TIME_MAX;
1396 int remapped_to_exit = 0;
1397 time_t now = time(NULL);
1399 tor_strlower(socks->address); /* normalize it */
1400 strlcpy(orig_address, socks->address, sizeof(orig_address));
1401 log_debug(LD_APP,"Client asked for %s:%d",
1402 safe_str(socks->address),
1403 socks->port);
1405 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1406 !tor_inet_aton(socks->address, &addr_tmp) &&
1407 options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
1408 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
1409 if (!strcasecmpend(socks->address, cp)) {
1410 automap = 1;
1411 break;
1413 if (automap) {
1414 const char *new_addr;
1415 new_addr = addressmap_register_virtual_address(
1416 RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
1417 tor_assert(new_addr);
1418 log_info(LD_APP, "Automapping %s to %s",
1419 escaped_safe_str(socks->address), safe_str(new_addr));
1420 strlcpy(socks->address, new_addr, sizeof(socks->address));
1424 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1425 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1426 &map_expires)) {
1427 char *result = tor_strdup(socks->address);
1428 /* remember _what_ is supposed to have been resolved. */
1429 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1430 orig_address);
1431 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1432 strlen(result), result, -1,
1433 map_expires);
1434 connection_mark_unattached_ap(conn,
1435 END_STREAM_REASON_DONE |
1436 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1437 return 0;
1439 if (options->ClientDNSRejectInternalAddresses) {
1440 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1441 tor_addr_t addr;
1442 int ok;
1443 ok = tor_addr_parse_reverse_lookup_name(
1444 &addr, socks->address, AF_UNSPEC, 1);
1445 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1446 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1447 0, NULL, -1, TIME_MAX);
1448 connection_mark_unattached_ap(conn,
1449 END_STREAM_REASON_SOCKSPROTOCOL |
1450 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1451 return -1;
1454 } else if (!automap) {
1455 int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
1456 /* For address map controls, remap the address. */
1457 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1458 &map_expires)) {
1459 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1460 REMAP_STREAM_SOURCE_CACHE);
1461 if (started_without_chosen_exit &&
1462 !strcasecmpend(socks->address, ".exit") &&
1463 map_expires < TIME_MAX)
1464 remapped_to_exit = 1;
1468 if (!automap && address_is_in_virtual_range(socks->address)) {
1469 /* This address was probably handed out by client_dns_get_unmapped_address,
1470 * but the mapping was discarded for some reason. We *don't* want to send
1471 * the address through Tor; that's likely to fail, and may leak
1472 * information.
1474 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1475 socks->address); /* don't safe_str() this yet. */
1476 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
1477 return -1;
1480 /* Parse the address provided by SOCKS. Modify it in-place if it
1481 * specifies a hidden-service (.onion) or particular exit node (.exit).
1483 addresstype = parse_extended_hostname(socks->address);
1485 if (addresstype == BAD_HOSTNAME) {
1486 log_warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
1487 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1488 escaped(socks->address));
1489 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1490 return -1;
1493 if (addresstype == EXIT_HOSTNAME) {
1494 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1495 * node, and conn->address to hold only the address portion.*/
1496 char *s = strrchr(socks->address,'.');
1497 tor_assert(!automap);
1498 if (s) {
1499 if (s[1] != '\0') {
1500 conn->chosen_exit_name = tor_strdup(s+1);
1501 if (remapped_to_exit) /* 5 tries before it expires the addressmap */
1502 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1503 *s = 0;
1504 } else {
1505 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1506 safe_str(socks->address));
1507 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1508 escaped(socks->address));
1509 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1510 return -1;
1512 } else {
1513 routerinfo_t *r;
1514 conn->chosen_exit_name = tor_strdup(socks->address);
1515 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1516 *socks->address = 0;
1517 if (r) {
1518 strlcpy(socks->address, r->address, sizeof(socks->address));
1519 } else {
1520 log_warn(LD_APP,
1521 "Unrecognized server in exit address '%s.exit'. Refusing.",
1522 safe_str(socks->address));
1523 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1524 return -1;
1529 if (addresstype != ONION_HOSTNAME) {
1530 /* not a hidden-service request (i.e. normal or .exit) */
1531 if (address_is_invalid_destination(socks->address, 1)) {
1532 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1533 escaped(socks->address));
1534 log_warn(LD_APP,
1535 "Destination '%s' seems to be an invalid hostname. Failing.",
1536 safe_str(socks->address));
1537 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1538 return -1;
1541 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1542 uint32_t answer;
1543 struct in_addr in;
1544 /* Reply to resolves immediately if we can. */
1545 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
1546 log_warn(LD_APP,"Address to be resolved is too large. Failing.");
1547 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1548 escaped(socks->address));
1549 connection_ap_handshake_socks_resolved(conn,
1550 RESOLVED_TYPE_ERROR_TRANSIENT,
1551 0,NULL,-1,TIME_MAX);
1552 connection_mark_unattached_ap(conn,
1553 END_STREAM_REASON_SOCKSPROTOCOL |
1554 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1555 return -1;
1557 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1558 /* leave it in network order */
1559 answer = in.s_addr;
1560 /* remember _what_ is supposed to have been resolved. */
1561 strlcpy(socks->address, orig_address, sizeof(socks->address));
1562 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1563 (char*)&answer,-1,map_expires);
1564 connection_mark_unattached_ap(conn,
1565 END_STREAM_REASON_DONE |
1566 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1567 return 0;
1569 tor_assert(!automap);
1570 rep_hist_note_used_resolve(now); /* help predict this next time */
1571 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1572 tor_assert(!automap);
1573 if (socks->port == 0) {
1574 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1575 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1576 return -1;
1579 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1580 /* see if we can find a suitable enclave exit */
1581 routerinfo_t *r =
1582 router_find_exact_exit_enclave(socks->address, socks->port);
1583 if (r) {
1584 log_info(LD_APP,
1585 "Redirecting address %s to exit at enclave router %s",
1586 safe_str(socks->address), r->nickname);
1587 /* use the hex digest, not nickname, in case there are two
1588 routers with this nickname */
1589 conn->chosen_exit_name =
1590 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1591 conn->chosen_exit_optional = 1;
1595 /* warn or reject if it's using a dangerous port */
1596 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1597 if (consider_plaintext_ports(conn, socks->port) < 0)
1598 return -1;
1600 if (!conn->use_begindir) {
1601 /* help predict this next time */
1602 rep_hist_note_used_port(now, socks->port);
1604 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1605 rep_hist_note_used_resolve(now); /* help predict this next time */
1606 /* no extra processing needed */
1607 } else {
1608 tor_fragile_assert();
1610 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1611 if ((circ && connection_ap_handshake_attach_chosen_circuit(
1612 conn, circ, cpath) < 0) ||
1613 (!circ &&
1614 connection_ap_handshake_attach_circuit(conn) < 0)) {
1615 if (!conn->_base.marked_for_close)
1616 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1617 return -1;
1619 return 0;
1620 } else {
1621 /* it's a hidden-service request */
1622 rend_cache_entry_t *entry;
1623 int r;
1624 rend_service_authorization_t *client_auth;
1625 tor_assert(!automap);
1626 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1627 /* if it's a resolve request, fail it right now, rather than
1628 * building all the circuits and then realizing it won't work. */
1629 log_warn(LD_APP,
1630 "Resolve requests to hidden services not allowed. Failing.");
1631 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1632 0,NULL,-1,TIME_MAX);
1633 connection_mark_unattached_ap(conn,
1634 END_STREAM_REASON_SOCKSPROTOCOL |
1635 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1636 return -1;
1639 if (circ) {
1640 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1641 "supported for .onion addresses currently. Failing.");
1642 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1643 return -1;
1646 conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1647 strlcpy(conn->rend_data->onion_address, socks->address,
1648 sizeof(conn->rend_data->onion_address));
1649 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1650 safe_str(conn->rend_data->onion_address));
1651 /* see if we already have it cached */
1652 r = rend_cache_lookup_entry(conn->rend_data->onion_address, -1, &entry);
1653 if (r<0) {
1654 log_warn(LD_BUG,"Invalid service name '%s'",
1655 safe_str(conn->rend_data->onion_address));
1656 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1657 return -1;
1660 /* Help predict this next time. We're not sure if it will need
1661 * a stable circuit yet, but we know we'll need *something*. */
1662 rep_hist_note_used_internal(now, 0, 1);
1664 /* Look up if we have client authorization for it. */
1665 client_auth = rend_client_lookup_service_authorization(
1666 conn->rend_data->onion_address);
1667 if (client_auth) {
1668 log_info(LD_REND, "Using previously configured client authorization "
1669 "for hidden service request.");
1670 memcpy(conn->rend_data->descriptor_cookie,
1671 client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
1672 conn->rend_data->auth_type = client_auth->auth_type;
1674 if (r==0) {
1675 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1676 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1677 safe_str(conn->rend_data->onion_address));
1678 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1679 * arrives first. Exception: When using client authorization, only
1680 * fetch v2 descriptors.*/
1681 rend_client_refetch_v2_renddesc(conn->rend_data);
1682 if (conn->rend_data->auth_type == REND_NO_AUTH)
1683 rend_client_refetch_renddesc(conn->rend_data->onion_address);
1684 } else { /* r > 0 */
1685 /** How long after we receive a hidden service descriptor do we consider
1686 * it valid? */
1687 #define NUM_SECONDS_BEFORE_HS_REFETCH (60*15)
1688 if (now - entry->received < NUM_SECONDS_BEFORE_HS_REFETCH) {
1689 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1690 log_info(LD_REND, "Descriptor is here and fresh enough. Great.");
1691 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1692 if (!conn->_base.marked_for_close)
1693 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1694 return -1;
1696 } else {
1697 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1698 log_info(LD_REND, "Stale descriptor %s. Refetching.",
1699 safe_str(conn->rend_data->onion_address));
1700 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1701 * arrives first. Exception: When using client authorization, only
1702 * fetch v2 descriptors.*/
1703 rend_client_refetch_v2_renddesc(conn->rend_data);
1704 if (conn->rend_data->auth_type == REND_NO_AUTH)
1705 rend_client_refetch_renddesc(conn->rend_data->onion_address);
1708 return 0;
1710 return 0; /* unreached but keeps the compiler happy */
1713 #ifdef TRANS_PF
1714 static int pf_socket = -1;
1716 get_pf_socket(void)
1718 int pf;
1719 /* This should be opened before dropping privs. */
1720 if (pf_socket >= 0)
1721 return pf_socket;
1723 #ifdef OPENBSD
1724 /* only works on OpenBSD */
1725 pf = open("/dev/pf", O_RDONLY);
1726 #else
1727 /* works on NetBSD and FreeBSD */
1728 pf = open("/dev/pf", O_RDWR);
1729 #endif
1731 if (pf < 0) {
1732 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1733 return -1;
1736 pf_socket = pf;
1737 return pf_socket;
1739 #endif
1741 /** Fetch the original destination address and port from a
1742 * system-specific interface and put them into a
1743 * socks_request_t as if they came from a socks request.
1745 * Return -1 if an error prevents fetching the destination,
1746 * else return 0.
1748 static int
1749 connection_ap_get_original_destination(edge_connection_t *conn,
1750 socks_request_t *req)
1752 #ifdef TRANS_NETFILTER
1753 /* Linux 2.4+ */
1754 struct sockaddr_storage orig_dst;
1755 socklen_t orig_dst_len = sizeof(orig_dst);
1756 tor_addr_t addr;
1758 if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
1759 (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
1760 int e = tor_socket_errno(conn->_base.s);
1761 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1762 return -1;
1765 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1766 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1768 return 0;
1769 #elif defined(TRANS_PF)
1770 struct sockaddr_storage proxy_addr;
1771 socklen_t proxy_addr_len = sizeof(proxy_addr);
1772 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1773 struct pfioc_natlook pnl;
1774 tor_addr_t addr;
1775 int pf = -1;
1777 if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
1778 &proxy_addr_len) < 0) {
1779 int e = tor_socket_errno(conn->_base.s);
1780 log_warn(LD_NET, "getsockname() to determine transocks destination "
1781 "failed: %s", tor_socket_strerror(e));
1782 return -1;
1785 memset(&pnl, 0, sizeof(pnl));
1786 pnl.proto = IPPROTO_TCP;
1787 pnl.direction = PF_OUT;
1788 if (proxy_sa->sa_family == AF_INET) {
1789 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1790 pnl.af = AF_INET;
1791 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&conn->_base.addr);
1792 pnl.sport = htons(conn->_base.port);
1793 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1794 pnl.dport = sin->sin_port;
1795 } else if (proxy_sa->sa_family == AF_INET6) {
1796 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1797 pnl.af = AF_INET6;
1798 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&conn->_base.addr),
1799 sizeof(struct in6_addr));
1800 pnl.sport = htons(conn->_base.port);
1801 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1802 pnl.dport = sin6->sin6_port;
1803 } else {
1804 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1805 (int)proxy_sa->sa_family);
1806 return -1;
1809 pf = get_pf_socket();
1810 if (pf<0)
1811 return -1;
1813 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1814 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1815 return -1;
1818 if (pnl.af == AF_INET) {
1819 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1820 } else if (pnl.af == AF_INET6) {
1821 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1822 } else {
1823 tor_fragile_assert();
1824 return -1;
1827 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1828 req->port = ntohs(pnl.rdport);
1830 return 0;
1831 #else
1832 (void)conn;
1833 (void)req;
1834 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1835 "transparent proxy method was configured.");
1836 return -1;
1837 #endif
1840 /** connection_edge_process_inbuf() found a conn in state
1841 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1842 * the socks handshake.
1844 * If the handshake is complete, send it to
1845 * connection_ap_handshake_rewrite_and_attach().
1847 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1848 * else return 0.
1850 static int
1851 connection_ap_handshake_process_socks(edge_connection_t *conn)
1853 socks_request_t *socks;
1854 int sockshere;
1855 or_options_t *options = get_options();
1857 tor_assert(conn);
1858 tor_assert(conn->_base.type == CONN_TYPE_AP);
1859 tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
1860 tor_assert(conn->socks_request);
1861 socks = conn->socks_request;
1863 log_debug(LD_APP,"entered.");
1865 sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
1866 options->TestSocks, options->SafeSocks);
1867 if (sockshere == 0) {
1868 if (socks->replylen) {
1869 connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
1870 /* zero it out so we can do another round of negotiation */
1871 socks->replylen = 0;
1872 } else {
1873 log_debug(LD_APP,"socks handshake not all here yet.");
1875 return 0;
1876 } else if (sockshere == -1) {
1877 if (socks->replylen) { /* we should send reply back */
1878 log_debug(LD_APP,"reply is already set for us. Using it.");
1879 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1880 END_STREAM_REASON_SOCKSPROTOCOL);
1882 } else {
1883 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
1884 connection_ap_handshake_socks_reply(conn, NULL, 0,
1885 END_STREAM_REASON_SOCKSPROTOCOL);
1887 connection_mark_unattached_ap(conn,
1888 END_STREAM_REASON_SOCKSPROTOCOL |
1889 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1890 return -1;
1891 } /* else socks handshake is done, continue processing */
1893 if (hostname_is_noconnect_address(socks->address))
1895 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1896 control_event_stream_status(conn, STREAM_EVENT_CLOSED, 0);
1897 connection_mark_unattached_ap(conn, END_STREAM_REASON_DONE);
1898 return -1;
1901 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
1902 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1903 else
1904 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
1906 if (options->LeaveStreamsUnattached) {
1907 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1908 return 0;
1910 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1913 /** connection_init_accepted_conn() found a new trans AP conn.
1914 * Get the original destination and send it to
1915 * connection_ap_handshake_rewrite_and_attach().
1917 * Return -1 if an unexpected error with conn (and it should be marked
1918 * for close), else return 0.
1921 connection_ap_process_transparent(edge_connection_t *conn)
1923 socks_request_t *socks;
1924 or_options_t *options = get_options();
1926 tor_assert(conn);
1927 tor_assert(conn->_base.type == CONN_TYPE_AP);
1928 tor_assert(conn->socks_request);
1929 socks = conn->socks_request;
1931 /* pretend that a socks handshake completed so we don't try to
1932 * send a socks reply down a transparent conn */
1933 socks->command = SOCKS_COMMAND_CONNECT;
1934 socks->has_finished = 1;
1936 log_debug(LD_APP,"entered.");
1938 if (connection_ap_get_original_destination(conn, socks) < 0) {
1939 log_warn(LD_APP,"Fetching original destination failed. Closing.");
1940 connection_mark_unattached_ap(conn,
1941 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
1942 return -1;
1944 /* we have the original destination */
1946 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1948 if (options->LeaveStreamsUnattached) {
1949 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1950 return 0;
1952 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1955 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1956 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1957 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1958 * form of the original destination.
1960 * If the original destination is complete, send it to
1961 * connection_ap_handshake_rewrite_and_attach().
1963 * Return -1 if an unexpected error with conn (and it should be marked
1964 * for close), else return 0.
1966 static int
1967 connection_ap_process_natd(edge_connection_t *conn)
1969 char tmp_buf[36], *tbuf, *daddr;
1970 size_t tlen = 30;
1971 int err, port_ok;
1972 socks_request_t *socks;
1973 or_options_t *options = get_options();
1975 tor_assert(conn);
1976 tor_assert(conn->_base.type == CONN_TYPE_AP);
1977 tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
1978 tor_assert(conn->socks_request);
1979 socks = conn->socks_request;
1981 log_debug(LD_APP,"entered.");
1983 /* look for LF-terminated "[DEST ip_addr port]"
1984 * where ip_addr is a dotted-quad and port is in string form */
1985 err = fetch_from_buf_line(conn->_base.inbuf, tmp_buf, &tlen);
1986 if (err == 0)
1987 return 0;
1988 if (err < 0) {
1989 log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
1990 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1991 return -1;
1994 if (strcmpstart(tmp_buf, "[DEST ")) {
1995 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1996 "said: %s",
1997 escaped(tmp_buf));
1998 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1999 return -1;
2002 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2003 if (!(tbuf = strchr(tbuf, ' '))) {
2004 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
2005 "said: %s",
2006 escaped(tmp_buf));
2007 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2008 return -1;
2010 *tbuf++ = '\0';
2012 /* pretend that a socks handshake completed so we don't try to
2013 * send a socks reply down a natd conn */
2014 strlcpy(socks->address, daddr, sizeof(socks->address));
2015 socks->port = (uint16_t)
2016 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2017 if (!port_ok) {
2018 log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
2019 "of range.", escaped(tbuf));
2020 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2021 return -1;
2024 socks->command = SOCKS_COMMAND_CONNECT;
2025 socks->has_finished = 1;
2027 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2029 if (options->LeaveStreamsUnattached) {
2030 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2031 return 0;
2033 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2035 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
2038 /** Iterate over the two bytes of stream_id until we get one that is not
2039 * already in use; return it. Return 0 if can't get a unique stream_id.
2041 static streamid_t
2042 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2044 edge_connection_t *tmpconn;
2045 streamid_t test_stream_id;
2046 uint32_t attempts=0;
2048 again:
2049 test_stream_id = circ->next_stream_id++;
2050 if (++attempts > 1<<16) {
2051 /* Make sure we don't loop forever if all stream_id's are used. */
2052 log_warn(LD_APP,"No unused stream IDs. Failing.");
2053 return 0;
2055 if (test_stream_id == 0)
2056 goto again;
2057 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2058 if (tmpconn->stream_id == test_stream_id)
2059 goto again;
2060 return test_stream_id;
2063 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2064 * socks_request field, and send it down circ.
2066 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2069 connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
2071 char payload[CELL_PAYLOAD_SIZE];
2072 int payload_len;
2073 int begin_type;
2074 origin_circuit_t *circ;
2075 tor_assert(ap_conn->on_circuit);
2076 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2078 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2079 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2080 tor_assert(ap_conn->socks_request);
2081 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2083 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2084 if (ap_conn->stream_id==0) {
2085 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2086 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2087 return -1;
2090 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2091 (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2092 ap_conn->socks_request->address : "",
2093 ap_conn->socks_request->port);
2094 payload_len = (int)strlen(payload)+1;
2096 log_debug(LD_APP,
2097 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2099 begin_type = ap_conn->use_begindir ?
2100 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2101 if (begin_type == RELAY_COMMAND_BEGIN) {
2102 tor_assert(circ->build_state->onehop_tunnel == 0);
2105 if (connection_edge_send_command(ap_conn, begin_type,
2106 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2107 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2108 return -1; /* circuit is closed, don't continue */
2110 ap_conn->package_window = STREAMWINDOW_START;
2111 ap_conn->deliver_window = STREAMWINDOW_START;
2112 ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
2113 log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
2114 ap_conn->_base.s, circ->_base.n_circ_id);
2115 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2116 return 0;
2119 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2120 * socks_request field, and send it down circ.
2122 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2125 connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
2127 int payload_len, command;
2128 const char *string_addr;
2129 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2130 origin_circuit_t *circ;
2131 tor_assert(ap_conn->on_circuit);
2132 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2134 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2135 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2136 tor_assert(ap_conn->socks_request);
2137 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2139 command = ap_conn->socks_request->command;
2140 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2142 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2143 if (ap_conn->stream_id==0) {
2144 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2145 /*XXXX022 _close_ the circuit because it's full? That sounds dumb. */
2146 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2147 return -1;
2150 if (command == SOCKS_COMMAND_RESOLVE) {
2151 string_addr = ap_conn->socks_request->address;
2152 payload_len = (int)strlen(string_addr)+1;
2153 } else {
2154 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2155 const char *a = ap_conn->socks_request->address;
2156 tor_addr_t addr;
2157 int r;
2159 /* We're doing a reverse lookup. The input could be an IP address, or
2160 * could be an .in-addr.arpa or .ip6.arpa address */
2161 r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
2162 if (r <= 0) {
2163 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2164 safe_str(a));
2165 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2166 return -1;
2169 r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2170 if (r < 0) {
2171 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2172 safe_str(a));
2173 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2174 return -1;
2177 string_addr = inaddr_buf;
2178 payload_len = (int)strlen(inaddr_buf)+1;
2179 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
2182 if (payload_len > RELAY_PAYLOAD_SIZE) {
2183 /* This should be impossible: we don't accept addresses this big. */
2184 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2185 return -1;
2188 log_debug(LD_APP,
2189 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2191 if (connection_edge_send_command(ap_conn,
2192 RELAY_COMMAND_RESOLVE,
2193 string_addr, payload_len) < 0)
2194 return -1; /* circuit is closed, don't continue */
2196 tor_free(ap_conn->_base.address); /* Maybe already set by dnsserv. */
2197 ap_conn->_base.address = tor_strdup("(Tor_internal)");
2198 ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
2199 log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
2200 ap_conn->_base.s, circ->_base.n_circ_id);
2201 control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
2202 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2203 return 0;
2206 /** Make an AP connection_t, make a new linked connection pair, and attach
2207 * one side to the conn, connection_add it, initialize it to circuit_wait,
2208 * and call connection_ap_handshake_attach_circuit(conn) on it.
2210 * Return the other end of the linked connection pair, or -1 if error.
2212 edge_connection_t *
2213 connection_ap_make_link(char *address, uint16_t port,
2214 const char *digest, int use_begindir, int want_onehop)
2216 edge_connection_t *conn;
2218 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2219 want_onehop ? "direct" : "anonymized" , safe_str(address),port);
2221 conn = edge_connection_new(CONN_TYPE_AP, AF_INET);
2222 conn->_base.linked = 1; /* so that we can add it safely below. */
2224 /* populate conn->socks_request */
2226 /* leave version at zero, so the socks_reply is empty */
2227 conn->socks_request->socks_version = 0;
2228 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2229 strlcpy(conn->socks_request->address, address,
2230 sizeof(conn->socks_request->address));
2231 conn->socks_request->port = port;
2232 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2233 conn->want_onehop = want_onehop;
2234 conn->use_begindir = use_begindir;
2235 if (use_begindir) {
2236 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2237 conn->chosen_exit_name[0] = '$';
2238 tor_assert(digest);
2239 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2240 digest, DIGEST_LEN);
2243 conn->_base.address = tor_strdup("(Tor_internal)");
2244 tor_addr_make_unspec(&conn->_base.addr);
2245 conn->_base.port = 0;
2247 if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
2248 connection_free(TO_CONN(conn));
2249 return NULL;
2252 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2254 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2256 /* attaching to a dirty circuit is fine */
2257 if (connection_ap_handshake_attach_circuit(conn) < 0) {
2258 if (!conn->_base.marked_for_close)
2259 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2260 return NULL;
2263 log_info(LD_APP,"... application connection created and linked.");
2264 return conn;
2267 /** Notify any interested controller connections about a new hostname resolve
2268 * or resolve error. Takes the same arguments as does
2269 * connection_ap_handshake_socks_resolved(). */
2270 static void
2271 tell_controller_about_resolved_result(edge_connection_t *conn,
2272 int answer_type,
2273 size_t answer_len,
2274 const char *answer,
2275 int ttl,
2276 time_t expires)
2279 if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
2280 answer_type == RESOLVED_TYPE_HOSTNAME)) {
2281 return; /* we already told the controller. */
2282 } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2283 struct in_addr in;
2284 char buf[INET_NTOA_BUF_LEN];
2285 in.s_addr = get_uint32(answer);
2286 tor_inet_ntoa(&in, buf, sizeof(buf));
2287 control_event_address_mapped(conn->socks_request->address,
2288 buf, expires, NULL);
2289 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len <256) {
2290 char *cp = tor_strndup(answer, answer_len);
2291 control_event_address_mapped(conn->socks_request->address,
2292 cp, expires, NULL);
2293 tor_free(cp);
2294 } else {
2295 control_event_address_mapped(conn->socks_request->address,
2296 "<error>",
2297 time(NULL)+ttl,
2298 "error=yes");
2302 /** Send an answer to an AP connection that has requested a DNS lookup via
2303 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2304 * for unreachable; the answer should be in the format specified in the socks
2305 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2306 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2307 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2309 /* XXXX022 the use of the ttl and expires fields is nutty. Let's make this
2310 * interface and those that use it less ugly. */
2311 void
2312 connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2313 int answer_type,
2314 size_t answer_len,
2315 const char *answer,
2316 int ttl,
2317 time_t expires)
2319 char buf[384];
2320 size_t replylen;
2322 if (ttl >= 0) {
2323 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2324 uint32_t a = ntohl(get_uint32(answer));
2325 if (a)
2326 client_dns_set_addressmap(conn->socks_request->address, a,
2327 conn->chosen_exit_name, ttl);
2328 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2329 char *cp = tor_strndup(answer, answer_len);
2330 client_dns_set_reverse_addressmap(conn->socks_request->address,
2332 conn->chosen_exit_name, ttl);
2333 tor_free(cp);
2337 if (conn->is_dns_request) {
2338 if (conn->dns_server_request) {
2339 /* We had a request on our DNS port: answer it. */
2340 dnsserv_resolved(conn, answer_type, answer_len, answer, ttl);
2341 conn->socks_request->has_finished = 1;
2342 return;
2343 } else {
2344 /* This must be a request from the controller. We already sent
2345 * a mapaddress if there's a ttl. */
2346 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2347 answer, ttl, expires);
2348 conn->socks_request->has_finished = 1;
2349 return;
2351 /* We shouldn't need to free conn here; it gets marked by the caller. */
2354 if (conn->socks_request->socks_version == 4) {
2355 buf[0] = 0x00; /* version */
2356 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2357 buf[1] = SOCKS4_GRANTED;
2358 set_uint16(buf+2, 0);
2359 memcpy(buf+4, answer, 4); /* address */
2360 replylen = SOCKS4_NETWORK_LEN;
2361 } else { /* "error" */
2362 buf[1] = SOCKS4_REJECT;
2363 memset(buf+2, 0, 6);
2364 replylen = SOCKS4_NETWORK_LEN;
2366 } else if (conn->socks_request->socks_version == 5) {
2367 /* SOCKS5 */
2368 buf[0] = 0x05; /* version */
2369 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2370 buf[1] = SOCKS5_SUCCEEDED;
2371 buf[2] = 0; /* reserved */
2372 buf[3] = 0x01; /* IPv4 address type */
2373 memcpy(buf+4, answer, 4); /* address */
2374 set_uint16(buf+8, 0); /* port == 0. */
2375 replylen = 10;
2376 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2377 buf[1] = SOCKS5_SUCCEEDED;
2378 buf[2] = 0; /* reserved */
2379 buf[3] = 0x04; /* IPv6 address type */
2380 memcpy(buf+4, answer, 16); /* address */
2381 set_uint16(buf+20, 0); /* port == 0. */
2382 replylen = 22;
2383 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2384 buf[1] = SOCKS5_SUCCEEDED;
2385 buf[2] = 0; /* reserved */
2386 buf[3] = 0x03; /* Domainname address type */
2387 buf[4] = (char)answer_len;
2388 memcpy(buf+5, answer, answer_len); /* address */
2389 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2390 replylen = 5+answer_len+2;
2391 } else {
2392 buf[1] = SOCKS5_HOST_UNREACHABLE;
2393 memset(buf+2, 0, 8);
2394 replylen = 10;
2396 } else {
2397 /* no socks version info; don't send anything back */
2398 return;
2400 connection_ap_handshake_socks_reply(conn, buf, replylen,
2401 (answer_type == RESOLVED_TYPE_IPV4 ||
2402 answer_type == RESOLVED_TYPE_IPV6) ?
2403 0 : END_STREAM_REASON_RESOLVEFAILED);
2406 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2407 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2408 * handshaking.
2410 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2411 * and return, else reply based on <b>endreason</b> (one of
2412 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2413 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2415 void
2416 connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2417 size_t replylen, int endreason)
2419 char buf[256];
2420 socks5_reply_status_t status =
2421 stream_end_reason_to_socks5_response(endreason);
2423 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2425 control_event_stream_status(conn,
2426 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2427 endreason);
2429 if (conn->socks_request->has_finished) {
2430 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2431 "connection_ap_handshake_socks_reply.");
2432 return;
2434 if (replylen) { /* we already have a reply in mind */
2435 connection_write_to_buf(reply, replylen, TO_CONN(conn));
2436 conn->socks_request->has_finished = 1;
2437 return;
2439 if (conn->socks_request->socks_version == 4) {
2440 memset(buf,0,SOCKS4_NETWORK_LEN);
2441 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2442 /* leave version, destport, destip zero */
2443 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
2444 } else if (conn->socks_request->socks_version == 5) {
2445 buf[0] = 5; /* version 5 */
2446 buf[1] = (char)status;
2447 buf[2] = 0;
2448 buf[3] = 1; /* ipv4 addr */
2449 memset(buf+4,0,6); /* Set external addr/port to 0.
2450 The spec doesn't seem to say what to do here. -RD */
2451 connection_write_to_buf(buf,10,TO_CONN(conn));
2453 /* If socks_version isn't 4 or 5, don't send anything.
2454 * This can happen in the case of AP bridges. */
2455 conn->socks_request->has_finished = 1;
2456 return;
2459 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2460 * an exit hop for the circuit, or we are the origin and it is a
2461 * rendezvous begin.
2463 * Launch a new exit connection and initialize things appropriately.
2465 * If it's a rendezvous stream, call connection_exit_connect() on
2466 * it.
2468 * For general streams, call dns_resolve() on it first, and only call
2469 * connection_exit_connect() if the dns answer is already known.
2471 * Note that we don't call connection_add() on the new stream! We wait
2472 * for connection_exit_connect() to do that.
2474 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2475 * Else return 0.
2478 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2480 edge_connection_t *n_stream;
2481 relay_header_t rh;
2482 char *address=NULL;
2483 uint16_t port;
2484 or_circuit_t *or_circ = NULL;
2486 assert_circuit_ok(circ);
2487 if (!CIRCUIT_IS_ORIGIN(circ))
2488 or_circ = TO_OR_CIRCUIT(circ);
2490 relay_header_unpack(&rh, cell->payload);
2492 /* Note: we have to use relay_send_command_from_edge here, not
2493 * connection_edge_end or connection_edge_send_command, since those require
2494 * that we have a stream connected to a circuit, and we don't connect to a
2495 * circuit until we have a pending/successful resolve. */
2497 if (!server_mode(get_options()) &&
2498 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2499 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2500 "Relay begin cell at non-server. Closing.");
2501 relay_send_end_cell_from_edge(rh.stream_id, circ,
2502 END_STREAM_REASON_EXITPOLICY, NULL);
2503 return 0;
2506 if (rh.command == RELAY_COMMAND_BEGIN) {
2507 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
2508 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2509 "Relay begin cell has no \\0. Closing.");
2510 relay_send_end_cell_from_edge(rh.stream_id, circ,
2511 END_STREAM_REASON_TORPROTOCOL, NULL);
2512 return 0;
2514 if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
2515 &address,NULL,&port)<0) {
2516 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2517 "Unable to parse addr:port in relay begin cell. Closing.");
2518 relay_send_end_cell_from_edge(rh.stream_id, circ,
2519 END_STREAM_REASON_TORPROTOCOL, NULL);
2520 return 0;
2522 if (port==0) {
2523 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2524 "Missing port in relay begin cell. Closing.");
2525 relay_send_end_cell_from_edge(rh.stream_id, circ,
2526 END_STREAM_REASON_TORPROTOCOL, NULL);
2527 tor_free(address);
2528 return 0;
2530 if (or_circ && or_circ->is_first_hop &&
2531 !get_options()->AllowSingleHopExits) {
2532 /* Don't let clients use us as a single-hop proxy, unless the user
2533 * has explicitly allowed that in the config. It attracts attackers
2534 * and users who'd be better off with, well, single-hop proxies.
2536 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2537 "Attempt to open a stream on first hop of circuit. Closing.");
2538 relay_send_end_cell_from_edge(rh.stream_id, circ,
2539 END_STREAM_REASON_TORPROTOCOL, NULL);
2540 tor_free(address);
2541 return 0;
2543 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2544 if (!directory_permits_begindir_requests(get_options()) ||
2545 circ->purpose != CIRCUIT_PURPOSE_OR) {
2546 relay_send_end_cell_from_edge(rh.stream_id, circ,
2547 END_STREAM_REASON_NOTDIRECTORY, NULL);
2548 return 0;
2550 if (or_circ && or_circ->p_conn && or_circ->p_conn->_base.address)
2551 address = tor_strdup(or_circ->p_conn->_base.address);
2552 else
2553 address = tor_strdup("127.0.0.1");
2554 port = 1; /* XXXX This value is never actually used anywhere, and there
2555 * isn't "really" a connection here. But we
2556 * need to set it to something nonzero. */
2557 } else {
2558 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2559 relay_send_end_cell_from_edge(rh.stream_id, circ,
2560 END_STREAM_REASON_INTERNAL, NULL);
2561 return 0;
2564 log_debug(LD_EXIT,"Creating new exit connection.");
2565 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2566 n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
2568 n_stream->stream_id = rh.stream_id;
2569 n_stream->_base.port = port;
2570 /* leave n_stream->s at -1, because it's not yet valid */
2571 n_stream->package_window = STREAMWINDOW_START;
2572 n_stream->deliver_window = STREAMWINDOW_START;
2574 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
2575 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2576 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
2577 n_stream->_base.address = tor_strdup("(rendezvous)");
2578 n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
2579 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
2580 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
2581 assert_circuit_ok(circ);
2582 if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
2583 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
2584 n_stream->_base.port);
2585 relay_send_end_cell_from_edge(rh.stream_id, circ,
2586 END_STREAM_REASON_EXITPOLICY,
2587 origin_circ->cpath->prev);
2588 connection_free(TO_CONN(n_stream));
2589 tor_free(address);
2590 return 0;
2592 assert_circuit_ok(circ);
2593 log_debug(LD_REND,"Finished assigning addr/port");
2594 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
2596 /* add it into the linked list of n_streams on this circuit */
2597 n_stream->next_stream = origin_circ->p_streams;
2598 n_stream->on_circuit = circ;
2599 origin_circ->p_streams = n_stream;
2600 assert_circuit_ok(circ);
2602 connection_exit_connect(n_stream);
2603 tor_free(address);
2604 return 0;
2606 tor_strlower(address);
2607 n_stream->_base.address = address;
2608 n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2609 /* default to failed, change in dns_resolve if it turns out not to fail */
2611 if (we_are_hibernating()) {
2612 relay_send_end_cell_from_edge(rh.stream_id, circ,
2613 END_STREAM_REASON_HIBERNATING, NULL);
2614 connection_free(TO_CONN(n_stream));
2615 return 0;
2618 n_stream->on_circuit = circ;
2620 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2621 tor_assert(or_circ);
2622 if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->_base.addr))
2623 tor_addr_assign(&n_stream->_base.addr, &or_circ->p_conn->_base.addr);
2624 return connection_exit_connect_dir(n_stream);
2627 log_debug(LD_EXIT,"about to start the dns_resolve().");
2629 /* send it off to the gethostbyname farm */
2630 switch (dns_resolve(n_stream)) {
2631 case 1: /* resolve worked; now n_stream is attached to circ. */
2632 assert_circuit_ok(circ);
2633 log_debug(LD_EXIT,"about to call connection_exit_connect().");
2634 connection_exit_connect(n_stream);
2635 return 0;
2636 case -1: /* resolve failed */
2637 relay_send_end_cell_from_edge(rh.stream_id, circ,
2638 END_STREAM_REASON_RESOLVEFAILED, NULL);
2639 /* n_stream got freed. don't touch it. */
2640 break;
2641 case 0: /* resolve added to pending list */
2642 assert_circuit_ok(circ);
2643 break;
2645 return 0;
2649 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2650 * circuit <b>circ</b>;
2651 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2654 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
2656 edge_connection_t *dummy_conn;
2657 relay_header_t rh;
2659 assert_circuit_ok(TO_CIRCUIT(circ));
2660 relay_header_unpack(&rh, cell->payload);
2662 /* This 'dummy_conn' only exists to remember the stream ID
2663 * associated with the resolve request; and to make the
2664 * implementation of dns.c more uniform. (We really only need to
2665 * remember the circuit, the stream ID, and the hostname to be
2666 * resolved; but if we didn't store them in a connection like this,
2667 * the housekeeping in dns.c would get way more complicated.)
2669 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2670 dummy_conn->stream_id = rh.stream_id;
2671 dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
2672 rh.length);
2673 dummy_conn->_base.port = 0;
2674 dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2675 dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
2677 dummy_conn->on_circuit = TO_CIRCUIT(circ);
2679 /* send it off to the gethostbyname farm */
2680 switch (dns_resolve(dummy_conn)) {
2681 case -1: /* Impossible to resolve; a resolved cell was sent. */
2682 /* Connection freed; don't touch it. */
2683 return 0;
2684 case 1: /* The result was cached; a resolved cell was sent. */
2685 if (!dummy_conn->_base.marked_for_close)
2686 connection_free(TO_CONN(dummy_conn));
2687 return 0;
2688 case 0: /* resolve added to pending list */
2689 assert_circuit_ok(TO_CIRCUIT(circ));
2690 break;
2692 return 0;
2695 /** Connect to conn's specified addr and port. If it worked, conn
2696 * has now been added to the connection_array.
2698 * Send back a connected cell. Include the resolved IP of the destination
2699 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2700 * streams must not reveal what IP they connected to.)
2702 void
2703 connection_exit_connect(edge_connection_t *edge_conn)
2705 const tor_addr_t *addr;
2706 uint16_t port;
2707 connection_t *conn = TO_CONN(edge_conn);
2708 int socket_error = 0;
2710 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
2711 router_compare_to_my_exit_policy(edge_conn)) {
2712 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
2713 escaped_safe_str(conn->address), conn->port);
2714 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
2715 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2716 connection_free(conn);
2717 return;
2720 addr = &conn->addr;
2721 port = conn->port;
2723 log_debug(LD_EXIT,"about to try connecting");
2724 switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
2725 case -1:
2726 /* XXX021 use socket_error below rather than trying to piece things
2727 * together from the current errno, which may have been clobbered. */
2728 connection_edge_end_errno(edge_conn);
2729 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2730 connection_free(conn);
2731 return;
2732 case 0:
2733 conn->state = EXIT_CONN_STATE_CONNECTING;
2735 connection_watch_events(conn, EV_WRITE | EV_READ);
2736 /* writable indicates finish;
2737 * readable/error indicates broken link in windowsland. */
2738 return;
2739 /* case 1: fall through */
2742 conn->state = EXIT_CONN_STATE_OPEN;
2743 if (connection_wants_to_flush(conn)) {
2744 /* in case there are any queued data cells */
2745 log_warn(LD_BUG,"newly connected conn had data waiting!");
2746 // connection_start_writing(conn);
2748 connection_watch_events(conn, EV_READ);
2750 /* also, deliver a 'connected' cell back through the circuit. */
2751 if (connection_edge_is_rendezvous_stream(edge_conn)) {
2752 /* rendezvous stream */
2753 /* don't send an address back! */
2754 connection_edge_send_command(edge_conn,
2755 RELAY_COMMAND_CONNECTED,
2756 NULL, 0);
2757 } else { /* normal stream */
2758 char connected_payload[20];
2759 int connected_payload_len;
2760 if (tor_addr_family(&conn->addr) == AF_INET) {
2761 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
2762 connected_payload_len = 4;
2763 } else {
2764 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
2765 connected_payload_len = 16;
2767 set_uint32(connected_payload+connected_payload_len,
2768 htonl(dns_clip_ttl(edge_conn->address_ttl)));
2769 connected_payload_len += 4;
2770 connection_edge_send_command(edge_conn,
2771 RELAY_COMMAND_CONNECTED,
2772 connected_payload, connected_payload_len);
2776 /** Given an exit conn that should attach to us as a directory server, open a
2777 * bridge connection with a linked connection pair, create a new directory
2778 * conn, and join them together. Return 0 on success (or if there was an
2779 * error we could send back an end cell for). Return -(some circuit end
2780 * reason) if the circuit needs to be torn down. Either connects
2781 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2783 static int
2784 connection_exit_connect_dir(edge_connection_t *exitconn)
2786 dir_connection_t *dirconn = NULL;
2787 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
2789 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
2791 exitconn->_base.state = EXIT_CONN_STATE_OPEN;
2793 dirconn = dir_connection_new(AF_INET);
2795 dirconn->_base.addr = exitconn->_base.addr;
2796 dirconn->_base.port = 0;
2797 dirconn->_base.address = tor_strdup(circ->p_conn->_base.address);
2798 dirconn->_base.type = CONN_TYPE_DIR;
2799 dirconn->_base.purpose = DIR_PURPOSE_SERVER;
2800 dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2802 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
2804 if (connection_add(TO_CONN(exitconn))<0) {
2805 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2806 connection_free(TO_CONN(exitconn));
2807 connection_free(TO_CONN(dirconn));
2808 return 0;
2811 /* link exitconn to circ, now that we know we can use it. */
2812 exitconn->next_stream = circ->n_streams;
2813 circ->n_streams = exitconn;
2815 if (connection_add(TO_CONN(dirconn))<0) {
2816 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2817 connection_close_immediate(TO_CONN(exitconn));
2818 connection_mark_for_close(TO_CONN(exitconn));
2819 connection_free(TO_CONN(dirconn));
2820 return 0;
2823 connection_start_reading(TO_CONN(dirconn));
2824 connection_start_reading(TO_CONN(exitconn));
2826 if (connection_edge_send_command(exitconn,
2827 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
2828 connection_mark_for_close(TO_CONN(exitconn));
2829 connection_mark_for_close(TO_CONN(dirconn));
2830 return 0;
2833 return 0;
2836 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2837 * it is a general stream.
2840 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
2842 tor_assert(conn);
2843 if (conn->rend_data)
2844 return 1;
2845 return 0;
2848 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2849 * to exit from it, or 0 if it probably will not allow it.
2850 * (We might be uncertain if conn's destination address has not yet been
2851 * resolved.)
2854 connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit)
2856 tor_assert(conn);
2857 tor_assert(conn->_base.type == CONN_TYPE_AP);
2858 tor_assert(conn->socks_request);
2859 tor_assert(exit);
2861 /* If a particular exit node has been requested for the new connection,
2862 * make sure the exit node of the existing circuit matches exactly.
2864 if (conn->chosen_exit_name) {
2865 routerinfo_t *chosen_exit =
2866 router_get_by_nickname(conn->chosen_exit_name, 1);
2867 if (!chosen_exit || memcmp(chosen_exit->cache_info.identity_digest,
2868 exit->cache_info.identity_digest, DIGEST_LEN)) {
2869 /* doesn't match */
2870 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2871 // conn->chosen_exit_name, exit->nickname);
2872 return 0;
2876 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2877 !conn->use_begindir) {
2878 struct in_addr in;
2879 uint32_t addr = 0;
2880 addr_policy_result_t r;
2881 if (tor_inet_aton(conn->socks_request->address, &in))
2882 addr = ntohl(in.s_addr);
2883 r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
2884 exit->exit_policy);
2885 if (r == ADDR_POLICY_REJECTED)
2886 return 0; /* We know the address, and the exit policy rejects it. */
2887 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
2888 return 0; /* We don't know the addr, but the exit policy rejects most
2889 * addresses with this port. Since the user didn't ask for
2890 * this node, err on the side of caution. */
2891 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2892 /* Can't support reverse lookups without eventdns. */
2893 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
2894 exit->has_old_dnsworkers)
2895 return 0;
2897 /* Don't send DNS requests to non-exit servers by default. */
2898 if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
2899 return 0;
2901 return 1;
2904 /** If address is of the form "y.onion" with a well-formed handle y:
2905 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2907 * If address is of the form "y.exit":
2908 * Put a NUL after y and return EXIT_HOSTNAME.
2910 * Otherwise:
2911 * Return NORMAL_HOSTNAME and change nothing.
2913 hostname_type_t
2914 parse_extended_hostname(char *address)
2916 char *s;
2917 char query[REND_SERVICE_ID_LEN_BASE32+1];
2919 s = strrchr(address,'.');
2920 if (!s)
2921 return NORMAL_HOSTNAME; /* no dot, thus normal */
2922 if (!strcmp(s+1,"exit")) {
2923 *s = 0; /* nul-terminate it */
2924 return EXIT_HOSTNAME; /* .exit */
2926 if (strcmp(s+1,"onion"))
2927 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
2929 /* so it is .onion */
2930 *s = 0; /* nul-terminate it */
2931 if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
2932 REND_SERVICE_ID_LEN_BASE32+1)
2933 goto failed;
2934 if (rend_valid_service_id(query)) {
2935 return ONION_HOSTNAME; /* success */
2937 failed:
2938 /* otherwise, return to previous state and return 0 */
2939 *s = '.';
2940 return BAD_HOSTNAME;
2943 /** Check if the address is of the form "y.noconnect"
2946 hostname_is_noconnect_address(const char *address)
2948 return ! strcasecmpend(address, ".noconnect");