Issues with router_get_by_nickname()
[tor/rransom.git] / src / or / connection_edge.c
blobeba83ba9e97c1b6c467d808067200b1412d8a970
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_edge.c
9 * \brief Handle edge streams.
10 **/
12 #include "or.h"
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_bandwidth(conn);
164 control_event_stream_status(conn, STREAM_EVENT_CLOSED,
165 END_STREAM_REASON_DESTROY);
166 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
167 } else {
168 /* closing the circuit, nothing to send an END to */
169 conn->edge_has_sent_end = 1;
170 conn->end_reason = END_STREAM_REASON_DESTROY;
171 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
172 connection_mark_for_close(TO_CONN(conn));
173 conn->_base.hold_open_until_flushed = 1;
176 conn->cpath_layer = NULL;
177 conn->on_circuit = NULL;
178 return 0;
181 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
182 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
183 * is not a client connection, set the relay end cell's reason for closing
184 * as <b>reason</b> */
185 static int
186 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
187 uint8_t reason, crypt_path_t *cpath_layer)
189 char payload[1];
191 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
192 /* Never send the server an informative reason code; it doesn't need to
193 * know why the client stream is failing. */
194 reason = END_STREAM_REASON_MISC;
197 payload[0] = (char) reason;
199 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
200 payload, 1, cpath_layer);
203 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
204 * remember that we've done so. If this is not a client connection, set the
205 * relay end cell's reason for closing as <b>reason</b>.
207 * Return -1 if this function has already been called on this conn,
208 * else return 0.
211 connection_edge_end(edge_connection_t *conn, uint8_t reason)
213 char payload[RELAY_PAYLOAD_SIZE];
214 size_t payload_len=1;
215 circuit_t *circ;
216 uint8_t control_reason = reason;
218 if (conn->edge_has_sent_end) {
219 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
220 "on an already ended stream?", reason);
221 tor_fragile_assert();
222 return -1;
225 if (conn->_base.marked_for_close) {
226 log_warn(LD_BUG,
227 "called on conn that's already marked for close at %s:%d.",
228 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
229 return 0;
232 circ = circuit_get_by_edge_conn(conn);
233 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
234 /* If this is a client circuit, don't send the server an informative
235 * reason code; it doesn't need to know why the client stream is
236 * failing. */
237 reason = END_STREAM_REASON_MISC;
240 payload[0] = (char)reason;
241 if (reason == END_STREAM_REASON_EXITPOLICY &&
242 !connection_edge_is_rendezvous_stream(conn)) {
243 int addrlen;
244 if (tor_addr_family(&conn->_base.addr) == AF_INET) {
245 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
246 addrlen = 4;
247 } else {
248 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
249 addrlen = 16;
251 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
252 payload_len += 4+addrlen;
255 if (circ && !circ->marked_for_close) {
256 log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
257 connection_edge_send_command(conn, RELAY_COMMAND_END,
258 payload, payload_len);
259 } else {
260 log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
261 conn->_base.s);
264 conn->edge_has_sent_end = 1;
265 conn->end_reason = control_reason;
266 return 0;
269 /** An error has just occurred on an operation on an edge connection
270 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
271 * appropriate relay end cell to the other end of the connection's circuit.
274 connection_edge_end_errno(edge_connection_t *conn)
276 uint8_t reason;
277 tor_assert(conn);
278 reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
279 return connection_edge_end(conn, reason);
282 /** Connection <b>conn</b> has finished writing and has no bytes left on
283 * its outbuf.
285 * If it's in state 'open', stop writing, consider responding with a
286 * sendme, and return.
287 * Otherwise, stop writing and return.
289 * If <b>conn</b> is broken, mark it for close and return -1, else
290 * return 0.
293 connection_edge_finished_flushing(edge_connection_t *conn)
295 tor_assert(conn);
297 switch (conn->_base.state) {
298 case AP_CONN_STATE_OPEN:
299 case EXIT_CONN_STATE_OPEN:
300 connection_stop_writing(TO_CONN(conn));
301 connection_edge_consider_sending_sendme(conn);
302 return 0;
303 case AP_CONN_STATE_SOCKS_WAIT:
304 case AP_CONN_STATE_NATD_WAIT:
305 case AP_CONN_STATE_RENDDESC_WAIT:
306 case AP_CONN_STATE_CIRCUIT_WAIT:
307 case AP_CONN_STATE_CONNECT_WAIT:
308 case AP_CONN_STATE_CONTROLLER_WAIT:
309 connection_stop_writing(TO_CONN(conn));
310 return 0;
311 default:
312 log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
313 tor_fragile_assert();
314 return -1;
316 return 0;
319 /** Connected handler for exit connections: start writing pending
320 * data, deliver 'CONNECTED' relay cells as appropriate, and check
321 * any pending data that may have been received. */
323 connection_edge_finished_connecting(edge_connection_t *edge_conn)
325 connection_t *conn;
327 tor_assert(edge_conn);
328 tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
329 conn = TO_CONN(edge_conn);
330 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
332 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
333 escaped_safe_str(conn->address),conn->port,
334 safe_str(fmt_addr(&conn->addr)));
336 conn->state = EXIT_CONN_STATE_OPEN;
337 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
338 if (connection_wants_to_flush(conn)) /* in case there are any queued relay
339 * cells */
340 connection_start_writing(conn);
341 /* deliver a 'connected' relay cell back through the circuit. */
342 if (connection_edge_is_rendezvous_stream(edge_conn)) {
343 if (connection_edge_send_command(edge_conn,
344 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
345 return 0; /* circuit is closed, don't continue */
346 } else {
347 char connected_payload[20];
348 int connected_payload_len;
349 if (tor_addr_family(&conn->addr) == AF_INET) {
350 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
351 set_uint32(connected_payload+4,
352 htonl(dns_clip_ttl(edge_conn->address_ttl)));
353 connected_payload_len = 8;
354 } else {
355 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
356 set_uint32(connected_payload+16,
357 htonl(dns_clip_ttl(edge_conn->address_ttl)));
358 connected_payload_len = 20;
360 if (connection_edge_send_command(edge_conn,
361 RELAY_COMMAND_CONNECTED,
362 connected_payload, connected_payload_len) < 0)
363 return 0; /* circuit is closed, don't continue */
365 tor_assert(edge_conn->package_window > 0);
366 /* in case the server has written anything */
367 return connection_edge_process_inbuf(edge_conn, 1);
370 /** Define a schedule for how long to wait between retrying
371 * application connections. Rather than waiting a fixed amount of
372 * time between each retry, we wait 10 seconds each for the first
373 * two tries, and 15 seconds for each retry after
374 * that. Hopefully this will improve the expected user experience. */
375 static int
376 compute_retry_timeout(edge_connection_t *conn)
378 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
379 return 10;
380 return 15;
383 /** Find all general-purpose AP streams waiting for a response that sent their
384 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
385 * mark their current circuit as unsuitable for new streams. Then call
386 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
387 * available) or launch a new one.
389 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
390 * retry attempt).
392 void
393 connection_ap_expire_beginning(void)
395 edge_connection_t *conn;
396 circuit_t *circ;
397 time_t now = time(NULL);
398 or_options_t *options = get_options();
399 int severity;
400 int cutoff;
401 int seconds_idle, seconds_since_born;
402 smartlist_t *conns = get_connection_array();
404 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
405 if (c->type != CONN_TYPE_AP || c->marked_for_close)
406 continue;
407 conn = TO_EDGE_CONN(c);
408 /* if it's an internal linked connection, don't yell its status. */
409 severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
410 ? LOG_INFO : LOG_NOTICE;
411 seconds_idle = (int)( now - conn->_base.timestamp_lastread );
412 seconds_since_born = (int)( now - conn->_base.timestamp_created );
414 if (conn->_base.state == AP_CONN_STATE_OPEN)
415 continue;
417 /* We already consider SocksTimeout in
418 * connection_ap_handshake_attach_circuit(), but we need to consider
419 * it here too because controllers that put streams in controller_wait
420 * state never ask Tor to attach the circuit. */
421 if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
422 if (seconds_since_born >= options->SocksTimeout) {
423 log_fn(severity, LD_APP,
424 "Tried for %d seconds to get a connection to %s:%d. "
425 "Giving up. (%s)",
426 seconds_since_born, safe_str(conn->socks_request->address),
427 conn->socks_request->port,
428 conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
429 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
431 continue;
434 /* We're in state connect_wait or resolve_wait now -- waiting for a
435 * reply to our relay cell. See if we want to retry/give up. */
437 cutoff = compute_retry_timeout(conn);
438 if (seconds_idle < cutoff)
439 continue;
440 circ = circuit_get_by_edge_conn(conn);
441 if (!circ) { /* it's vanished? */
442 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
443 safe_str(conn->socks_request->address));
444 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
445 continue;
447 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
448 if (seconds_idle >= options->SocksTimeout) {
449 log_fn(severity, LD_REND,
450 "Rend stream is %d seconds late. Giving up on address"
451 " '%s.onion'.",
452 seconds_idle,
453 safe_str(conn->socks_request->address));
454 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
455 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
457 continue;
459 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
460 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
461 "We tried for %d seconds to connect to '%s' using exit '%s'."
462 " Retrying on a new circuit.",
463 seconds_idle, safe_str(conn->socks_request->address),
464 conn->cpath_layer ?
465 conn->cpath_layer->extend_info->nickname : "*unnamed*");
466 /* send an end down the circuit */
467 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
468 /* un-mark it as ending, since we're going to reuse it */
469 conn->edge_has_sent_end = 0;
470 conn->end_reason = 0;
471 /* kludge to make us not try this circuit again, yet to allow
472 * current streams on it to survive if they can: make it
473 * unattractive to use for new streams */
474 tor_assert(circ->timestamp_dirty);
475 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
476 /* give our stream another 'cutoff' seconds to try */
477 conn->_base.timestamp_lastread += cutoff;
478 if (conn->num_socks_retries < 250) /* avoid overflow */
479 conn->num_socks_retries++;
480 /* move it back into 'pending' state, and try to attach. */
481 if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
482 END_STREAM_REASON_TIMEOUT)<0) {
483 if (!conn->_base.marked_for_close)
484 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
486 } SMARTLIST_FOREACH_END(conn);
489 /** Tell any AP streams that are waiting for a new circuit to try again,
490 * either attaching to an available circ or launching a new one.
492 void
493 connection_ap_attach_pending(void)
495 edge_connection_t *edge_conn;
496 smartlist_t *conns = get_connection_array();
497 SMARTLIST_FOREACH(conns, connection_t *, conn,
499 if (conn->marked_for_close ||
500 conn->type != CONN_TYPE_AP ||
501 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
502 continue;
503 edge_conn = TO_EDGE_CONN(conn);
504 if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
505 if (!edge_conn->_base.marked_for_close)
506 connection_mark_unattached_ap(edge_conn,
507 END_STREAM_REASON_CANT_ATTACH);
512 /** Tell any AP streams that are waiting for a one-hop tunnel to
513 * <b>failed_digest</b> that they are going to fail. */
514 /* XXX022 We should get rid of this function, and instead attach
515 * one-hop streams to circ->p_streams so they get marked in
516 * circuit_mark_for_close like normal p_streams. */
517 void
518 connection_ap_fail_onehop(const char *failed_digest,
519 cpath_build_state_t *build_state)
521 edge_connection_t *edge_conn;
522 char digest[DIGEST_LEN];
523 smartlist_t *conns = get_connection_array();
524 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
525 if (conn->marked_for_close ||
526 conn->type != CONN_TYPE_AP ||
527 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
528 continue;
529 edge_conn = TO_EDGE_CONN(conn);
530 if (!edge_conn->want_onehop)
531 continue;
532 if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
533 memcmp(digest, failed_digest, DIGEST_LEN))
534 continue;
535 if (tor_digest_is_zero(digest)) {
536 /* we don't know the digest; have to compare addr:port */
537 tor_addr_t addr;
538 if (!build_state || !build_state->chosen_exit ||
539 !edge_conn->socks_request || !edge_conn->socks_request->address)
540 continue;
541 if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
542 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
543 build_state->chosen_exit->port != edge_conn->socks_request->port)
544 continue;
546 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
547 "just failed.", edge_conn->chosen_exit_name,
548 edge_conn->socks_request->address);
549 connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
550 } SMARTLIST_FOREACH_END(conn);
553 /** A circuit failed to finish on its last hop <b>info</b>. If there
554 * are any streams waiting with this exit node in mind, but they
555 * don't absolutely require it, make them give up on it.
557 void
558 circuit_discard_optional_exit_enclaves(extend_info_t *info)
560 edge_connection_t *edge_conn;
561 routerinfo_t *r1, *r2;
563 smartlist_t *conns = get_connection_array();
564 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
565 if (conn->marked_for_close ||
566 conn->type != CONN_TYPE_AP ||
567 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
568 continue;
569 edge_conn = TO_EDGE_CONN(conn);
570 if (!edge_conn->chosen_exit_optional &&
571 !edge_conn->chosen_exit_retries)
572 continue;
573 r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
574 r2 = router_get_by_hexdigest(info->identity_digest);
575 if (!r1 || !r2 || r1 != r2)
576 continue;
577 tor_assert(edge_conn->socks_request);
578 if (edge_conn->chosen_exit_optional) {
579 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
580 safe_str(edge_conn->chosen_exit_name),
581 escaped_safe_str(edge_conn->socks_request->address));
582 edge_conn->chosen_exit_optional = 0;
583 tor_free(edge_conn->chosen_exit_name); /* clears it */
584 /* if this port is dangerous, warn or reject it now that we don't
585 * think it'll be using an enclave. */
586 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
588 if (edge_conn->chosen_exit_retries) {
589 if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
590 clear_trackexithost_mappings(edge_conn->chosen_exit_name);
591 tor_free(edge_conn->chosen_exit_name); /* clears it */
592 /* if this port is dangerous, warn or reject it now that we don't
593 * think it'll be using an enclave. */
594 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
597 } SMARTLIST_FOREACH_END(conn);
600 /** The AP connection <b>conn</b> has just failed while attaching or
601 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
602 * might work. Detach the circuit, and either reattach it, launch a
603 * new circuit, tell the controller, or give up as a appropriate.
605 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
608 connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
609 int reason)
611 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
612 conn->_base.timestamp_lastread = time(NULL);
613 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
614 /* If we're attaching streams ourself, or if this connection is
615 * a tunneled directory connection, then just attach it. */
616 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
617 circuit_detach_stream(TO_CIRCUIT(circ),conn);
618 return connection_ap_handshake_attach_circuit(conn);
619 } else {
620 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
621 circuit_detach_stream(TO_CIRCUIT(circ),conn);
622 return 0;
626 /** A client-side struct to remember requests to rewrite addresses
627 * to new addresses. These structs are stored in the hash table
628 * "addressmap" below.
630 * There are 5 ways to set an address mapping:
631 * - A MapAddress command from the controller [permanent]
632 * - An AddressMap directive in the torrc [permanent]
633 * - When a TrackHostExits torrc directive is triggered [temporary]
634 * - When a DNS resolve succeeds [temporary]
635 * - When a DNS resolve fails [temporary]
637 * When an addressmap request is made but one is already registered,
638 * the new one is replaced only if the currently registered one has
639 * no "new_address" (that is, it's in the process of DNS resolve),
640 * or if the new one is permanent (expires==0 or 1).
642 * (We overload the 'expires' field, using "0" for mappings set via
643 * the configuration file, "1" for mappings set from the control
644 * interface, and other values for DNS and TrackHostExit mappings that can
645 * expire.)
647 typedef struct {
648 char *new_address;
649 time_t expires;
650 addressmap_entry_source_t source:3;
651 short num_resolve_failures;
652 } addressmap_entry_t;
654 /** Entry for mapping addresses to which virtual address we mapped them to. */
655 typedef struct {
656 char *ipv4_address;
657 char *hostname_address;
658 } virtaddress_entry_t;
660 /** A hash table to store client-side address rewrite instructions. */
661 static strmap_t *addressmap=NULL;
663 * Table mapping addresses to which virtual address, if any, we
664 * assigned them to.
666 * We maintain the following invariant: if [A,B] is in
667 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
668 * must be in addressmap. We do not require that the converse hold:
669 * if it fails, then we could end up mapping two virtual addresses to
670 * the same address, which is no disaster.
672 static strmap_t *virtaddress_reversemap=NULL;
674 /** Initialize addressmap. */
675 void
676 addressmap_init(void)
678 addressmap = strmap_new();
679 virtaddress_reversemap = strmap_new();
682 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
683 static void
684 addressmap_ent_free(void *_ent)
686 addressmap_entry_t *ent = _ent;
687 tor_free(ent->new_address);
688 tor_free(ent);
691 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
692 static void
693 addressmap_virtaddress_ent_free(void *_ent)
695 virtaddress_entry_t *ent = _ent;
696 tor_free(ent->ipv4_address);
697 tor_free(ent->hostname_address);
698 tor_free(ent);
701 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
702 static void
703 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
705 if (ent && ent->new_address &&
706 address_is_in_virtual_range(ent->new_address)) {
707 virtaddress_entry_t *ve =
708 strmap_get(virtaddress_reversemap, ent->new_address);
709 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
710 if (ve) {
711 if (!strcmp(address, ve->ipv4_address))
712 tor_free(ve->ipv4_address);
713 if (!strcmp(address, ve->hostname_address))
714 tor_free(ve->hostname_address);
715 if (!ve->ipv4_address && !ve->hostname_address) {
716 tor_free(ve);
717 strmap_remove(virtaddress_reversemap, ent->new_address);
723 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
724 * client address maps. */
725 static void
726 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
728 addressmap_virtaddress_remove(address, ent);
729 addressmap_ent_free(ent);
732 /** Unregister all TrackHostExits mappings from any address to
733 * *.exitname.exit. */
734 static void
735 clear_trackexithost_mappings(const char *exitname)
737 char *suffix;
738 size_t suffix_len;
739 if (!addressmap || !exitname)
740 return;
741 suffix_len = strlen(exitname) + 16;
742 suffix = tor_malloc(suffix_len);
743 tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
744 tor_strlower(suffix);
746 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
747 if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
748 addressmap_ent_remove(address, ent);
749 MAP_DEL_CURRENT(address);
751 } STRMAP_FOREACH_END;
753 tor_free(suffix);
756 /** Remove all entries from the addressmap that were set via the
757 * configuration file or the command line. */
758 void
759 addressmap_clear_configured(void)
761 addressmap_get_mappings(NULL, 0, 0, 0);
764 /** Remove all entries from the addressmap that are set to expire, ever. */
765 void
766 addressmap_clear_transient(void)
768 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
771 /** Clean out entries from the addressmap cache that were
772 * added long enough ago that they are no longer valid.
774 void
775 addressmap_clean(time_t now)
777 addressmap_get_mappings(NULL, 2, now, 0);
780 /** Free all the elements in the addressmap, and free the addressmap
781 * itself. */
782 void
783 addressmap_free_all(void)
785 if (addressmap) {
786 strmap_free(addressmap, addressmap_ent_free);
787 addressmap = NULL;
789 if (virtaddress_reversemap) {
790 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
791 virtaddress_reversemap = NULL;
795 /** Look at address, and rewrite it until it doesn't want any
796 * more rewrites; but don't get into an infinite loop.
797 * Don't write more than maxlen chars into address. Return true if the
798 * address changed; false otherwise. Set *<b>expires_out</b> to the
799 * expiry time of the result, or to <b>time_max</b> if the result does
800 * not expire.
803 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
805 addressmap_entry_t *ent;
806 int rewrites;
807 char *cp;
808 time_t expires = TIME_MAX;
810 for (rewrites = 0; rewrites < 16; rewrites++) {
811 ent = strmap_get(addressmap, address);
813 if (!ent || !ent->new_address) {
814 if (expires_out)
815 *expires_out = expires;
816 return (rewrites > 0); /* done, no rewrite needed */
819 cp = tor_strdup(escaped_safe_str(ent->new_address));
820 log_info(LD_APP, "Addressmap: rewriting %s to %s",
821 escaped_safe_str(address), cp);
822 if (ent->expires > 1 && ent->expires < expires)
823 expires = ent->expires;
824 tor_free(cp);
825 strlcpy(address, ent->new_address, maxlen);
827 log_warn(LD_CONFIG,
828 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
829 escaped_safe_str(address));
830 /* it's fine to rewrite a rewrite, but don't loop forever */
831 if (expires_out)
832 *expires_out = TIME_MAX;
833 return 1;
836 /** If we have a cached reverse DNS entry for the address stored in the
837 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
838 * rewrite to the cached value and return 1. Otherwise return 0. Set
839 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
840 * if the result does not expire. */
841 static int
842 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
844 size_t len = maxlen + 16;
845 char *s = tor_malloc(len), *cp;
846 addressmap_entry_t *ent;
847 int r = 0;
848 tor_snprintf(s, len, "REVERSE[%s]", address);
849 ent = strmap_get(addressmap, s);
850 if (ent) {
851 cp = tor_strdup(escaped_safe_str(ent->new_address));
852 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
853 escaped_safe_str(s), cp);
854 tor_free(cp);
855 strlcpy(address, ent->new_address, maxlen);
856 r = 1;
859 if (expires_out)
860 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
862 tor_free(s);
863 return r;
866 /** Return 1 if <b>address</b> is already registered, else return 0. If address
867 * is already registered, and <b>update_expires</b> is non-zero, then update
868 * the expiry time on the mapping with update_expires if it is a
869 * mapping created by TrackHostExits. */
871 addressmap_have_mapping(const char *address, int update_expiry)
873 addressmap_entry_t *ent;
874 if (!(ent=strmap_get_lc(addressmap, address)))
875 return 0;
876 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
877 ent->expires=time(NULL) + update_expiry;
878 return 1;
881 /** Register a request to map <b>address</b> to <b>new_address</b>,
882 * which will expire on <b>expires</b> (or 0 if never expires from
883 * config file, 1 if never expires from controller, 2 if never expires
884 * (virtual address mapping) from the controller.)
886 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
887 * free as appropriate. We will leave address alone.
889 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
890 * any mappings that exist from <b>address</b>.
892 void
893 addressmap_register(const char *address, char *new_address, time_t expires,
894 addressmap_entry_source_t source)
896 addressmap_entry_t *ent;
898 ent = strmap_get(addressmap, address);
899 if (!new_address || !strcasecmp(address,new_address)) {
900 /* Remove the mapping, if any. */
901 tor_free(new_address);
902 if (ent) {
903 addressmap_ent_remove(address,ent);
904 strmap_remove(addressmap, address);
906 return;
908 if (!ent) { /* make a new one and register it */
909 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
910 strmap_set(addressmap, address, ent);
911 } else if (ent->new_address) { /* we need to clean up the old mapping. */
912 if (expires > 1) {
913 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
914 "since it's already mapped to '%s'",
915 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
916 tor_free(new_address);
917 return;
919 if (address_is_in_virtual_range(ent->new_address) &&
920 expires != 2) {
921 /* XXX This isn't the perfect test; we want to avoid removing
922 * mappings set from the control interface _as virtual mapping */
923 addressmap_virtaddress_remove(address, ent);
925 tor_free(ent->new_address);
926 } /* else { we have an in-progress resolve with no mapping. } */
928 ent->new_address = new_address;
929 ent->expires = expires==2 ? 1 : expires;
930 ent->num_resolve_failures = 0;
931 ent->source = source;
933 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
934 safe_str(address), safe_str(ent->new_address));
935 control_event_address_mapped(address, ent->new_address, expires, NULL);
938 /** An attempt to resolve <b>address</b> failed at some OR.
939 * Increment the number of resolve failures we have on record
940 * for it, and then return that number.
943 client_dns_incr_failures(const char *address)
945 addressmap_entry_t *ent = strmap_get(addressmap, address);
946 if (!ent) {
947 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
948 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
949 strmap_set(addressmap,address,ent);
951 if (ent->num_resolve_failures < SHORT_MAX)
952 ++ent->num_resolve_failures; /* don't overflow */
953 log_info(LD_APP, "Address %s now has %d resolve failures.",
954 safe_str(address), ent->num_resolve_failures);
955 return ent->num_resolve_failures;
958 /** If <b>address</b> is in the client DNS addressmap, reset
959 * the number of resolve failures we have on record for it.
960 * This is used when we fail a stream because it won't resolve:
961 * otherwise future attempts on that address will only try once.
963 void
964 client_dns_clear_failures(const char *address)
966 addressmap_entry_t *ent = strmap_get(addressmap, address);
967 if (ent)
968 ent->num_resolve_failures = 0;
971 /** Record the fact that <b>address</b> resolved to <b>name</b>.
972 * We can now use this in subsequent streams via addressmap_rewrite()
973 * so we can more correctly choose an exit that will allow <b>address</b>.
975 * If <b>exitname</b> is defined, then append the addresses with
976 * ".exitname.exit" before registering the mapping.
978 * If <b>ttl</b> is nonnegative, the mapping will be valid for
979 * <b>ttl</b>seconds; otherwise, we use the default.
981 static void
982 client_dns_set_addressmap_impl(const char *address, const char *name,
983 const char *exitname,
984 int ttl)
986 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
987 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
988 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
989 char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
991 tor_assert(address);
992 tor_assert(name);
994 if (ttl<0)
995 ttl = DEFAULT_DNS_TTL;
996 else
997 ttl = dns_clip_ttl(ttl);
999 if (exitname) {
1000 /* XXXX fails to ever get attempts to get an exit address of
1001 * google.com.digest[=~]nickname.exit; we need a syntax for this that
1002 * won't make strict RFC952-compliant applications (like us) barf. */
1003 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1004 "%s.%s.exit", address, exitname);
1005 tor_snprintf(extendedval, sizeof(extendedval),
1006 "%s.%s.exit", name, exitname);
1007 } else {
1008 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1009 "%s", address);
1010 tor_snprintf(extendedval, sizeof(extendedval),
1011 "%s", name);
1013 addressmap_register(extendedaddress, tor_strdup(extendedval),
1014 time(NULL) + ttl, ADDRMAPSRC_DNS);
1017 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1018 * We can now use this in subsequent streams via addressmap_rewrite()
1019 * so we can more correctly choose an exit that will allow <b>address</b>.
1021 * If <b>exitname</b> is defined, then append the addresses with
1022 * ".exitname.exit" before registering the mapping.
1024 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1025 * <b>ttl</b>seconds; otherwise, we use the default.
1027 void
1028 client_dns_set_addressmap(const char *address, uint32_t val,
1029 const char *exitname,
1030 int ttl)
1032 struct in_addr in;
1033 char valbuf[INET_NTOA_BUF_LEN];
1035 tor_assert(address);
1037 if (tor_inet_aton(address, &in))
1038 return; /* If address was an IP address already, don't add a mapping. */
1039 in.s_addr = htonl(val);
1040 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
1042 client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
1045 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1046 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1048 * If <b>exitname</b> is defined, then append the addresses with
1049 * ".exitname.exit" before registering the mapping.
1051 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1052 * <b>ttl</b>seconds; otherwise, we use the default.
1054 static void
1055 client_dns_set_reverse_addressmap(const char *address, const char *v,
1056 const char *exitname,
1057 int ttl)
1059 size_t len = strlen(address) + 16;
1060 char *s = tor_malloc(len);
1061 tor_snprintf(s, len, "REVERSE[%s]", address);
1062 client_dns_set_addressmap_impl(s, v, exitname, ttl);
1063 tor_free(s);
1066 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1067 * These addresses should map to localhost, so even if the
1068 * application accidentally tried to connect to them directly (not
1069 * via Tor), it wouldn't get too far astray.
1071 * These options are configured by parse_virtual_addr_network().
1073 /** Which network should we use for virtual IPv4 addresses? Only the first
1074 * bits of this value are fixed. */
1075 static uint32_t virtual_addr_network = 0x7fc00000u;
1076 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1077 static maskbits_t virtual_addr_netmask_bits = 10;
1078 /** What's the next virtual address we will hand out? */
1079 static uint32_t next_virtual_addr = 0x7fc00000u;
1081 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1082 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1083 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1084 * string and return -1 on failure. If validate_only is false, sets the
1085 * actual virtual address range to the parsed value. */
1087 parse_virtual_addr_network(const char *val, int validate_only,
1088 char **msg)
1090 uint32_t addr;
1091 uint16_t port_min, port_max;
1092 maskbits_t bits;
1094 if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
1095 if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
1096 return -1;
1099 if (port_min != 1 || port_max != 65535) {
1100 if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
1101 return -1;
1104 if (bits > 16) {
1105 if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
1106 "network or larger");
1107 return -1;
1110 if (validate_only)
1111 return 0;
1113 virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
1114 virtual_addr_netmask_bits = bits;
1116 if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
1117 next_virtual_addr = addr;
1119 return 0;
1123 * Return true iff <b>addr</b> is likely to have been returned by
1124 * client_dns_get_unused_address.
1126 static int
1127 address_is_in_virtual_range(const char *address)
1129 struct in_addr in;
1130 tor_assert(address);
1131 if (!strcasecmpend(address, ".virtual")) {
1132 return 1;
1133 } else if (tor_inet_aton(address, &in)) {
1134 uint32_t addr = ntohl(in.s_addr);
1135 if (!addr_mask_cmp_bits(addr, virtual_addr_network,
1136 virtual_addr_netmask_bits))
1137 return 1;
1139 return 0;
1142 /** Return a newly allocated string holding an address of <b>type</b>
1143 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1144 * and that is very unlikely to be the address of any real host.
1146 static char *
1147 addressmap_get_virtual_address(int type)
1149 char buf[64];
1150 struct in_addr in;
1151 tor_assert(addressmap);
1153 if (type == RESOLVED_TYPE_HOSTNAME) {
1154 char rand[10];
1155 do {
1156 crypto_rand(rand, sizeof(rand));
1157 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
1158 strlcat(buf, ".virtual", sizeof(buf));
1159 } while (strmap_get(addressmap, buf));
1160 return tor_strdup(buf);
1161 } else if (type == RESOLVED_TYPE_IPV4) {
1162 // This is an imperfect estimate of how many addresses are available, but
1163 // that's ok.
1164 uint32_t available = 1u << (32-virtual_addr_netmask_bits);
1165 while (available) {
1166 /* Don't hand out any .0 or .255 address. */
1167 while ((next_virtual_addr & 0xff) == 0 ||
1168 (next_virtual_addr & 0xff) == 0xff) {
1169 ++next_virtual_addr;
1171 in.s_addr = htonl(next_virtual_addr);
1172 tor_inet_ntoa(&in, buf, sizeof(buf));
1173 if (!strmap_get(addressmap, buf)) {
1174 ++next_virtual_addr;
1175 break;
1178 ++next_virtual_addr;
1179 --available;
1180 log_info(LD_CONFIG, "%d addrs available", (int)available);
1181 if (! --available) {
1182 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
1183 return NULL;
1185 if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
1186 virtual_addr_netmask_bits))
1187 next_virtual_addr = virtual_addr_network;
1189 return tor_strdup(buf);
1190 } else {
1191 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
1192 return NULL;
1196 /** A controller has requested that we map some address of type
1197 * <b>type</b> to the address <b>new_address</b>. Choose an address
1198 * that is unlikely to be used, and map it, and return it in a newly
1199 * allocated string. If another address of the same type is already
1200 * mapped to <b>new_address</b>, try to return a copy of that address.
1202 * The string in <b>new_address</b> may be freed, or inserted into a map
1203 * as appropriate.
1205 const char *
1206 addressmap_register_virtual_address(int type, char *new_address)
1208 char **addrp;
1209 virtaddress_entry_t *vent;
1211 tor_assert(new_address);
1212 tor_assert(addressmap);
1213 tor_assert(virtaddress_reversemap);
1215 vent = strmap_get(virtaddress_reversemap, new_address);
1216 if (!vent) {
1217 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
1218 strmap_set(virtaddress_reversemap, new_address, vent);
1221 addrp = (type == RESOLVED_TYPE_IPV4) ?
1222 &vent->ipv4_address : &vent->hostname_address;
1223 if (*addrp) {
1224 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1225 if (ent && ent->new_address &&
1226 !strcasecmp(new_address, ent->new_address)) {
1227 tor_free(new_address);
1228 return tor_strdup(*addrp);
1229 } else
1230 log_warn(LD_BUG,
1231 "Internal confusion: I thought that '%s' was mapped to by "
1232 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1233 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
1234 ent?safe_str(ent->new_address):"(nothing)");
1237 tor_free(*addrp);
1238 *addrp = addressmap_get_virtual_address(type);
1239 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1240 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_CONTROLLER);
1242 #if 0
1244 /* Try to catch possible bugs */
1245 addressmap_entry_t *ent;
1246 ent = strmap_get(addressmap, *addrp);
1247 tor_assert(ent);
1248 tor_assert(!strcasecmp(ent->new_address,new_address));
1249 vent = strmap_get(virtaddress_reversemap, new_address);
1250 tor_assert(vent);
1251 tor_assert(!strcasecmp(*addrp,
1252 (type == RESOLVED_TYPE_IPV4) ?
1253 vent->ipv4_address : vent->hostname_address));
1254 log_info(LD_APP, "Map from %s to %s okay.",
1255 safe_str(*addrp),safe_str(new_address));
1257 #endif
1259 return *addrp;
1262 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1263 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1264 * should be true if we're using this address as a client; false if we're
1265 * using it as a server.
1268 address_is_invalid_destination(const char *address, int client)
1270 if (client) {
1271 if (get_options()->AllowNonRFC953Hostnames)
1272 return 0;
1273 } else {
1274 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1275 return 0;
1278 while (*address) {
1279 if (TOR_ISALNUM(*address) ||
1280 *address == '-' ||
1281 *address == '.' ||
1282 *address == '_') /* Underscore is not allowed, but Windows does it
1283 * sometimes, just to thumb its nose at the IETF. */
1284 ++address;
1285 else
1286 return 1;
1288 return 0;
1291 /** Iterate over all address mappings which have expiry times between
1292 * min_expires and max_expires, inclusive. If sl is provided, add an
1293 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1294 * the expiry time if want_expiry is false. If sl is NULL, remove the
1295 * mappings.
1297 void
1298 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1299 time_t max_expires, int want_expiry)
1301 strmap_iter_t *iter;
1302 const char *key;
1303 void *_val;
1304 addressmap_entry_t *val;
1306 if (!addressmap)
1307 addressmap_init();
1309 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1310 strmap_iter_get(iter, &key, &_val);
1311 val = _val;
1312 if (val->expires >= min_expires && val->expires <= max_expires) {
1313 if (!sl) {
1314 iter = strmap_iter_next_rmv(addressmap,iter);
1315 addressmap_ent_remove(key, val);
1316 continue;
1317 } else if (val->new_address) {
1318 size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
1319 char *line = tor_malloc(len);
1320 if (want_expiry) {
1321 if (val->expires < 3 || val->expires == TIME_MAX)
1322 tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
1323 else {
1324 char time[ISO_TIME_LEN+1];
1325 format_iso_time(time, val->expires);
1326 tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
1327 time);
1329 } else {
1330 tor_snprintf(line, len, "%s %s", key, val->new_address);
1332 smartlist_add(sl, line);
1335 iter = strmap_iter_next(addressmap,iter);
1339 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1340 * reject depending on our config options. */
1341 static int
1342 consider_plaintext_ports(edge_connection_t *conn, uint16_t port)
1344 or_options_t *options = get_options();
1345 int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
1347 if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
1348 log_warn(LD_APP, "Application request to port %d: this port is "
1349 "commonly used for unencrypted protocols. Please make sure "
1350 "you don't send anything you would mind the rest of the "
1351 "Internet reading!%s", port, reject ? " Closing." : "");
1352 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1353 port, reject ? "REJECT" : "WARN");
1356 if (reject) {
1357 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1358 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1359 return -1;
1362 return 0;
1365 /** How many times do we try connecting with an exit configured via
1366 * TrackHostExits before concluding that it won't work any more and trying a
1367 * different one? */
1368 #define TRACKHOSTEXITS_RETRIES 5
1370 /** Connection <b>conn</b> just finished its socks handshake, or the
1371 * controller asked us to take care of it. If <b>circ</b> is defined,
1372 * then that's where we'll want to attach it. Otherwise we have to
1373 * figure it out ourselves.
1375 * First, parse whether it's a .exit address, remap it, and so on. Then
1376 * if it's for a general circuit, try to attach it to a circuit (or launch
1377 * one as needed), else if it's for a rendezvous circuit, fetch a
1378 * rendezvous descriptor first (or attach/launch a circuit if the
1379 * rendezvous descriptor is already here and fresh enough).
1381 * The stream will exit from the hop
1382 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1383 * <b>cpath</b> is NULL.
1386 connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
1387 origin_circuit_t *circ,
1388 crypt_path_t *cpath)
1390 socks_request_t *socks = conn->socks_request;
1391 hostname_type_t addresstype;
1392 or_options_t *options = get_options();
1393 struct in_addr addr_tmp;
1394 int automap = 0;
1395 char orig_address[MAX_SOCKS_ADDR_LEN];
1396 time_t map_expires = TIME_MAX;
1397 int remapped_to_exit = 0;
1398 time_t now = time(NULL);
1400 tor_strlower(socks->address); /* normalize it */
1401 strlcpy(orig_address, socks->address, sizeof(orig_address));
1402 log_debug(LD_APP,"Client asked for %s:%d",
1403 safe_str(socks->address),
1404 socks->port);
1406 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1407 !tor_inet_aton(socks->address, &addr_tmp) &&
1408 options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
1409 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
1410 if (!strcasecmpend(socks->address, cp)) {
1411 automap = 1;
1412 break;
1414 if (automap) {
1415 const char *new_addr;
1416 new_addr = addressmap_register_virtual_address(
1417 RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
1418 tor_assert(new_addr);
1419 log_info(LD_APP, "Automapping %s to %s",
1420 escaped_safe_str(socks->address), safe_str(new_addr));
1421 strlcpy(socks->address, new_addr, sizeof(socks->address));
1425 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1426 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1427 &map_expires)) {
1428 char *result = tor_strdup(socks->address);
1429 /* remember _what_ is supposed to have been resolved. */
1430 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1431 orig_address);
1432 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1433 strlen(result), result, -1,
1434 map_expires);
1435 connection_mark_unattached_ap(conn,
1436 END_STREAM_REASON_DONE |
1437 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1438 return 0;
1440 if (options->ClientDNSRejectInternalAddresses) {
1441 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1442 tor_addr_t addr;
1443 int ok;
1444 ok = tor_addr_parse_reverse_lookup_name(
1445 &addr, socks->address, AF_UNSPEC, 1);
1446 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1447 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1448 0, NULL, -1, TIME_MAX);
1449 connection_mark_unattached_ap(conn,
1450 END_STREAM_REASON_SOCKSPROTOCOL |
1451 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1452 return -1;
1455 } else if (!automap) {
1456 int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
1457 /* For address map controls, remap the address. */
1458 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1459 &map_expires)) {
1460 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1461 REMAP_STREAM_SOURCE_CACHE);
1462 if (started_without_chosen_exit &&
1463 !strcasecmpend(socks->address, ".exit") &&
1464 map_expires < TIME_MAX)
1465 remapped_to_exit = 1;
1469 if (!automap && address_is_in_virtual_range(socks->address)) {
1470 /* This address was probably handed out by client_dns_get_unmapped_address,
1471 * but the mapping was discarded for some reason. We *don't* want to send
1472 * the address through Tor; that's likely to fail, and may leak
1473 * information.
1475 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1476 socks->address); /* don't safe_str() this yet. */
1477 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
1478 return -1;
1481 /* Parse the address provided by SOCKS. Modify it in-place if it
1482 * specifies a hidden-service (.onion) or particular exit node (.exit).
1484 addresstype = parse_extended_hostname(socks->address);
1486 if (addresstype == BAD_HOSTNAME) {
1487 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
1488 safe_str(socks->address));
1489 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1490 escaped(socks->address));
1491 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1492 return -1;
1495 if (addresstype == EXIT_HOSTNAME) {
1496 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1497 * node, and conn->address to hold only the address portion.*/
1498 char *s = strrchr(socks->address,'.');
1499 tor_assert(!automap);
1500 if (s) {
1501 if (s[1] != '\0') {
1502 conn->chosen_exit_name = tor_strdup(s+1);
1503 if (remapped_to_exit) /* 5 tries before it expires the addressmap */
1504 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1505 *s = 0;
1506 } else {
1507 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1508 safe_str(socks->address));
1509 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1510 escaped(socks->address));
1511 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1512 return -1;
1514 } else {
1515 routerinfo_t *r;
1516 conn->chosen_exit_name = tor_strdup(socks->address);
1517 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1518 *socks->address = 0;
1519 if (r) {
1520 strlcpy(socks->address, r->address, sizeof(socks->address));
1521 } else {
1522 log_warn(LD_APP,
1523 "Unrecognized server in exit address '%s.exit'. Refusing.",
1524 safe_str(socks->address));
1525 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1526 return -1;
1531 if (addresstype != ONION_HOSTNAME) {
1532 /* not a hidden-service request (i.e. normal or .exit) */
1533 if (address_is_invalid_destination(socks->address, 1)) {
1534 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1535 escaped(socks->address));
1536 log_warn(LD_APP,
1537 "Destination '%s' seems to be an invalid hostname. Failing.",
1538 safe_str(socks->address));
1539 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1540 return -1;
1543 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1544 uint32_t answer;
1545 struct in_addr in;
1546 /* Reply to resolves immediately if we can. */
1547 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
1548 log_warn(LD_APP,"Address to be resolved is too large. Failing.");
1549 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1550 escaped(socks->address));
1551 connection_ap_handshake_socks_resolved(conn,
1552 RESOLVED_TYPE_ERROR_TRANSIENT,
1553 0,NULL,-1,TIME_MAX);
1554 connection_mark_unattached_ap(conn,
1555 END_STREAM_REASON_SOCKSPROTOCOL |
1556 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1557 return -1;
1559 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1560 /* leave it in network order */
1561 answer = in.s_addr;
1562 /* remember _what_ is supposed to have been resolved. */
1563 strlcpy(socks->address, orig_address, sizeof(socks->address));
1564 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1565 (char*)&answer,-1,map_expires);
1566 connection_mark_unattached_ap(conn,
1567 END_STREAM_REASON_DONE |
1568 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1569 return 0;
1571 tor_assert(!automap);
1572 rep_hist_note_used_resolve(now); /* help predict this next time */
1573 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1574 tor_assert(!automap);
1575 if (socks->port == 0) {
1576 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1577 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1578 return -1;
1581 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1582 /* see if we can find a suitable enclave exit */
1583 routerinfo_t *r =
1584 router_find_exact_exit_enclave(socks->address, socks->port);
1585 if (r) {
1586 log_info(LD_APP,
1587 "Redirecting address %s to exit at enclave router %s",
1588 safe_str(socks->address), r->nickname);
1589 /* use the hex digest, not nickname, in case there are two
1590 routers with this nickname */
1591 conn->chosen_exit_name =
1592 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1593 conn->chosen_exit_optional = 1;
1597 /* warn or reject if it's using a dangerous port */
1598 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1599 if (consider_plaintext_ports(conn, socks->port) < 0)
1600 return -1;
1602 if (!conn->use_begindir) {
1603 /* help predict this next time */
1604 rep_hist_note_used_port(now, socks->port);
1606 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1607 rep_hist_note_used_resolve(now); /* help predict this next time */
1608 /* no extra processing needed */
1609 } else {
1610 tor_fragile_assert();
1612 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1613 if ((circ && connection_ap_handshake_attach_chosen_circuit(
1614 conn, circ, cpath) < 0) ||
1615 (!circ &&
1616 connection_ap_handshake_attach_circuit(conn) < 0)) {
1617 if (!conn->_base.marked_for_close)
1618 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1619 return -1;
1621 return 0;
1622 } else {
1623 /* it's a hidden-service request */
1624 rend_cache_entry_t *entry;
1625 int r;
1626 rend_service_authorization_t *client_auth;
1627 tor_assert(!automap);
1628 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1629 /* if it's a resolve request, fail it right now, rather than
1630 * building all the circuits and then realizing it won't work. */
1631 log_warn(LD_APP,
1632 "Resolve requests to hidden services not allowed. Failing.");
1633 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1634 0,NULL,-1,TIME_MAX);
1635 connection_mark_unattached_ap(conn,
1636 END_STREAM_REASON_SOCKSPROTOCOL |
1637 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1638 return -1;
1641 if (circ) {
1642 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1643 "supported for .onion addresses currently. Failing.");
1644 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1645 return -1;
1648 conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1649 strlcpy(conn->rend_data->onion_address, socks->address,
1650 sizeof(conn->rend_data->onion_address));
1651 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1652 safe_str(conn->rend_data->onion_address));
1653 /* see if we already have it cached */
1654 r = rend_cache_lookup_entry(conn->rend_data->onion_address, -1, &entry);
1655 if (r<0) {
1656 log_warn(LD_BUG,"Invalid service name '%s'",
1657 safe_str(conn->rend_data->onion_address));
1658 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1659 return -1;
1662 /* Help predict this next time. We're not sure if it will need
1663 * a stable circuit yet, but we know we'll need *something*. */
1664 rep_hist_note_used_internal(now, 0, 1);
1666 /* Look up if we have client authorization for it. */
1667 client_auth = rend_client_lookup_service_authorization(
1668 conn->rend_data->onion_address);
1669 if (client_auth) {
1670 log_info(LD_REND, "Using previously configured client authorization "
1671 "for hidden service request.");
1672 memcpy(conn->rend_data->descriptor_cookie,
1673 client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
1674 conn->rend_data->auth_type = client_auth->auth_type;
1676 if (r==0) {
1677 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1678 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1679 safe_str(conn->rend_data->onion_address));
1680 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1681 * arrives first. Exception: When using client authorization, only
1682 * fetch v2 descriptors.*/
1683 rend_client_refetch_v2_renddesc(conn->rend_data);
1684 if (conn->rend_data->auth_type == REND_NO_AUTH)
1685 rend_client_refetch_renddesc(conn->rend_data->onion_address);
1686 } else { /* r > 0 */
1687 if (now - entry->received < NUM_SECONDS_BEFORE_HS_REFETCH) {
1688 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1689 log_info(LD_REND, "Descriptor is here and fresh enough. Great.");
1690 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1691 if (!conn->_base.marked_for_close)
1692 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1693 return -1;
1695 } else {
1696 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1697 log_info(LD_REND, "Stale descriptor %s. Re-fetching.",
1698 safe_str(conn->rend_data->onion_address));
1699 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1700 * arrives first. Exception: When using client authorization, only
1701 * fetch v2 descriptors.*/
1702 rend_client_refetch_v2_renddesc(conn->rend_data);
1703 if (conn->rend_data->auth_type == REND_NO_AUTH)
1704 rend_client_refetch_renddesc(conn->rend_data->onion_address);
1707 return 0;
1709 return 0; /* unreached but keeps the compiler happy */
1712 #ifdef TRANS_PF
1713 static int pf_socket = -1;
1715 get_pf_socket(void)
1717 int pf;
1718 /* This should be opened before dropping privileges. */
1719 if (pf_socket >= 0)
1720 return pf_socket;
1722 #ifdef OPENBSD
1723 /* only works on OpenBSD */
1724 pf = open("/dev/pf", O_RDONLY);
1725 #else
1726 /* works on NetBSD and FreeBSD */
1727 pf = open("/dev/pf", O_RDWR);
1728 #endif
1730 if (pf < 0) {
1731 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1732 return -1;
1735 pf_socket = pf;
1736 return pf_socket;
1738 #endif
1740 /** Fetch the original destination address and port from a
1741 * system-specific interface and put them into a
1742 * socks_request_t as if they came from a socks request.
1744 * Return -1 if an error prevents fetching the destination,
1745 * else return 0.
1747 static int
1748 connection_ap_get_original_destination(edge_connection_t *conn,
1749 socks_request_t *req)
1751 #ifdef TRANS_NETFILTER
1752 /* Linux 2.4+ */
1753 struct sockaddr_storage orig_dst;
1754 socklen_t orig_dst_len = sizeof(orig_dst);
1755 tor_addr_t addr;
1757 if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
1758 (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
1759 int e = tor_socket_errno(conn->_base.s);
1760 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1761 return -1;
1764 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1765 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1767 return 0;
1768 #elif defined(TRANS_PF)
1769 struct sockaddr_storage proxy_addr;
1770 socklen_t proxy_addr_len = sizeof(proxy_addr);
1771 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1772 struct pfioc_natlook pnl;
1773 tor_addr_t addr;
1774 int pf = -1;
1776 if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
1777 &proxy_addr_len) < 0) {
1778 int e = tor_socket_errno(conn->_base.s);
1779 log_warn(LD_NET, "getsockname() to determine transocks destination "
1780 "failed: %s", tor_socket_strerror(e));
1781 return -1;
1784 memset(&pnl, 0, sizeof(pnl));
1785 pnl.proto = IPPROTO_TCP;
1786 pnl.direction = PF_OUT;
1787 if (proxy_sa->sa_family == AF_INET) {
1788 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1789 pnl.af = AF_INET;
1790 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&conn->_base.addr);
1791 pnl.sport = htons(conn->_base.port);
1792 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1793 pnl.dport = sin->sin_port;
1794 } else if (proxy_sa->sa_family == AF_INET6) {
1795 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1796 pnl.af = AF_INET6;
1797 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&conn->_base.addr),
1798 sizeof(struct in6_addr));
1799 pnl.sport = htons(conn->_base.port);
1800 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1801 pnl.dport = sin6->sin6_port;
1802 } else {
1803 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1804 (int)proxy_sa->sa_family);
1805 return -1;
1808 pf = get_pf_socket();
1809 if (pf<0)
1810 return -1;
1812 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1813 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1814 return -1;
1817 if (pnl.af == AF_INET) {
1818 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1819 } else if (pnl.af == AF_INET6) {
1820 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1821 } else {
1822 tor_fragile_assert();
1823 return -1;
1826 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1827 req->port = ntohs(pnl.rdport);
1829 return 0;
1830 #else
1831 (void)conn;
1832 (void)req;
1833 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1834 "transparent proxy method was configured.");
1835 return -1;
1836 #endif
1839 /** connection_edge_process_inbuf() found a conn in state
1840 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1841 * the socks handshake.
1843 * If the handshake is complete, send it to
1844 * connection_ap_handshake_rewrite_and_attach().
1846 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1847 * else return 0.
1849 static int
1850 connection_ap_handshake_process_socks(edge_connection_t *conn)
1852 socks_request_t *socks;
1853 int sockshere;
1854 or_options_t *options = get_options();
1856 tor_assert(conn);
1857 tor_assert(conn->_base.type == CONN_TYPE_AP);
1858 tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
1859 tor_assert(conn->socks_request);
1860 socks = conn->socks_request;
1862 log_debug(LD_APP,"entered.");
1864 sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
1865 options->TestSocks, options->SafeSocks);
1866 if (sockshere == 0) {
1867 if (socks->replylen) {
1868 connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
1869 /* zero it out so we can do another round of negotiation */
1870 socks->replylen = 0;
1871 } else {
1872 log_debug(LD_APP,"socks handshake not all here yet.");
1874 return 0;
1875 } else if (sockshere == -1) {
1876 if (socks->replylen) { /* we should send reply back */
1877 log_debug(LD_APP,"reply is already set for us. Using it.");
1878 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1879 END_STREAM_REASON_SOCKSPROTOCOL);
1881 } else {
1882 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
1883 connection_ap_handshake_socks_reply(conn, NULL, 0,
1884 END_STREAM_REASON_SOCKSPROTOCOL);
1886 connection_mark_unattached_ap(conn,
1887 END_STREAM_REASON_SOCKSPROTOCOL |
1888 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1889 return -1;
1890 } /* else socks handshake is done, continue processing */
1892 if (hostname_is_noconnect_address(socks->address))
1894 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1895 control_event_stream_status(conn, STREAM_EVENT_CLOSED, 0);
1896 connection_mark_unattached_ap(conn, END_STREAM_REASON_DONE);
1897 return -1;
1900 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
1901 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1902 else
1903 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
1905 if (options->LeaveStreamsUnattached) {
1906 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1907 return 0;
1909 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1912 /** connection_init_accepted_conn() found a new trans AP conn.
1913 * Get the original destination and send it to
1914 * connection_ap_handshake_rewrite_and_attach().
1916 * Return -1 if an unexpected error with conn (and it should be marked
1917 * for close), else return 0.
1920 connection_ap_process_transparent(edge_connection_t *conn)
1922 socks_request_t *socks;
1923 or_options_t *options = get_options();
1925 tor_assert(conn);
1926 tor_assert(conn->_base.type == CONN_TYPE_AP);
1927 tor_assert(conn->socks_request);
1928 socks = conn->socks_request;
1930 /* pretend that a socks handshake completed so we don't try to
1931 * send a socks reply down a transparent conn */
1932 socks->command = SOCKS_COMMAND_CONNECT;
1933 socks->has_finished = 1;
1935 log_debug(LD_APP,"entered.");
1937 if (connection_ap_get_original_destination(conn, socks) < 0) {
1938 log_warn(LD_APP,"Fetching original destination failed. Closing.");
1939 connection_mark_unattached_ap(conn,
1940 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
1941 return -1;
1943 /* we have the original destination */
1945 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1947 if (options->LeaveStreamsUnattached) {
1948 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1949 return 0;
1951 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1954 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1955 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1956 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1957 * form of the original destination.
1959 * If the original destination is complete, send it to
1960 * connection_ap_handshake_rewrite_and_attach().
1962 * Return -1 if an unexpected error with conn (and it should be marked
1963 * for close), else return 0.
1965 static int
1966 connection_ap_process_natd(edge_connection_t *conn)
1968 char tmp_buf[36], *tbuf, *daddr;
1969 size_t tlen = 30;
1970 int err, port_ok;
1971 socks_request_t *socks;
1972 or_options_t *options = get_options();
1974 tor_assert(conn);
1975 tor_assert(conn->_base.type == CONN_TYPE_AP);
1976 tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
1977 tor_assert(conn->socks_request);
1978 socks = conn->socks_request;
1980 log_debug(LD_APP,"entered.");
1982 /* look for LF-terminated "[DEST ip_addr port]"
1983 * where ip_addr is a dotted-quad and port is in string form */
1984 err = fetch_from_buf_line(conn->_base.inbuf, tmp_buf, &tlen);
1985 if (err == 0)
1986 return 0;
1987 if (err < 0) {
1988 log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
1989 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1990 return -1;
1993 if (strcmpstart(tmp_buf, "[DEST ")) {
1994 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1995 "said: %s",
1996 escaped(tmp_buf));
1997 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1998 return -1;
2001 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2002 if (!(tbuf = strchr(tbuf, ' '))) {
2003 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
2004 "said: %s",
2005 escaped(tmp_buf));
2006 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2007 return -1;
2009 *tbuf++ = '\0';
2011 /* pretend that a socks handshake completed so we don't try to
2012 * send a socks reply down a natd conn */
2013 strlcpy(socks->address, daddr, sizeof(socks->address));
2014 socks->port = (uint16_t)
2015 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2016 if (!port_ok) {
2017 log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
2018 "of range.", escaped(tbuf));
2019 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2020 return -1;
2023 socks->command = SOCKS_COMMAND_CONNECT;
2024 socks->has_finished = 1;
2026 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2028 if (options->LeaveStreamsUnattached) {
2029 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2030 return 0;
2032 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2034 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
2037 /** Iterate over the two bytes of stream_id until we get one that is not
2038 * already in use; return it. Return 0 if can't get a unique stream_id.
2040 static streamid_t
2041 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2043 edge_connection_t *tmpconn;
2044 streamid_t test_stream_id;
2045 uint32_t attempts=0;
2047 again:
2048 test_stream_id = circ->next_stream_id++;
2049 if (++attempts > 1<<16) {
2050 /* Make sure we don't loop forever if all stream_id's are used. */
2051 log_warn(LD_APP,"No unused stream IDs. Failing.");
2052 return 0;
2054 if (test_stream_id == 0)
2055 goto again;
2056 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2057 if (tmpconn->stream_id == test_stream_id)
2058 goto again;
2059 return test_stream_id;
2062 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2063 * socks_request field, and send it down circ.
2065 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2068 connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
2070 char payload[CELL_PAYLOAD_SIZE];
2071 int payload_len;
2072 int begin_type;
2073 origin_circuit_t *circ;
2074 tor_assert(ap_conn->on_circuit);
2075 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2077 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2078 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2079 tor_assert(ap_conn->socks_request);
2080 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2082 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2083 if (ap_conn->stream_id==0) {
2084 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2085 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2086 return -1;
2089 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2090 (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2091 ap_conn->socks_request->address : "",
2092 ap_conn->socks_request->port);
2093 payload_len = (int)strlen(payload)+1;
2095 log_debug(LD_APP,
2096 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2098 begin_type = ap_conn->use_begindir ?
2099 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2100 if (begin_type == RELAY_COMMAND_BEGIN) {
2101 tor_assert(circ->build_state->onehop_tunnel == 0);
2104 if (connection_edge_send_command(ap_conn, begin_type,
2105 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2106 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2107 return -1; /* circuit is closed, don't continue */
2109 ap_conn->package_window = STREAMWINDOW_START;
2110 ap_conn->deliver_window = STREAMWINDOW_START;
2111 ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
2112 log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
2113 ap_conn->_base.s, circ->_base.n_circ_id);
2114 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2115 return 0;
2118 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2119 * socks_request field, and send it down circ.
2121 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2124 connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
2126 int payload_len, command;
2127 const char *string_addr;
2128 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2129 origin_circuit_t *circ;
2130 tor_assert(ap_conn->on_circuit);
2131 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2133 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2134 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2135 tor_assert(ap_conn->socks_request);
2136 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2138 command = ap_conn->socks_request->command;
2139 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2141 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2142 if (ap_conn->stream_id==0) {
2143 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2144 /*XXXX022 _close_ the circuit because it's full? That sounds dumb. */
2145 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2146 return -1;
2149 if (command == SOCKS_COMMAND_RESOLVE) {
2150 string_addr = ap_conn->socks_request->address;
2151 payload_len = (int)strlen(string_addr)+1;
2152 } else {
2153 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2154 const char *a = ap_conn->socks_request->address;
2155 tor_addr_t addr;
2156 int r;
2158 /* We're doing a reverse lookup. The input could be an IP address, or
2159 * could be an .in-addr.arpa or .ip6.arpa address */
2160 r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
2161 if (r <= 0) {
2162 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2163 safe_str(a));
2164 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2165 return -1;
2168 r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2169 if (r < 0) {
2170 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2171 safe_str(a));
2172 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2173 return -1;
2176 string_addr = inaddr_buf;
2177 payload_len = (int)strlen(inaddr_buf)+1;
2178 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
2181 if (payload_len > RELAY_PAYLOAD_SIZE) {
2182 /* This should be impossible: we don't accept addresses this big. */
2183 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2184 return -1;
2187 log_debug(LD_APP,
2188 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2190 if (connection_edge_send_command(ap_conn,
2191 RELAY_COMMAND_RESOLVE,
2192 string_addr, payload_len) < 0)
2193 return -1; /* circuit is closed, don't continue */
2195 tor_free(ap_conn->_base.address); /* Maybe already set by dnsserv. */
2196 ap_conn->_base.address = tor_strdup("(Tor_internal)");
2197 ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
2198 log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
2199 ap_conn->_base.s, circ->_base.n_circ_id);
2200 control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
2201 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2202 return 0;
2205 /** Make an AP connection_t, make a new linked connection pair, and attach
2206 * one side to the conn, connection_add it, initialize it to circuit_wait,
2207 * and call connection_ap_handshake_attach_circuit(conn) on it.
2209 * Return the other end of the linked connection pair, or -1 if error.
2211 edge_connection_t *
2212 connection_ap_make_link(char *address, uint16_t port,
2213 const char *digest, int use_begindir, int want_onehop)
2215 edge_connection_t *conn;
2217 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2218 want_onehop ? "direct" : "anonymized" , safe_str(address),port);
2220 conn = edge_connection_new(CONN_TYPE_AP, AF_INET);
2221 conn->_base.linked = 1; /* so that we can add it safely below. */
2223 /* populate conn->socks_request */
2225 /* leave version at zero, so the socks_reply is empty */
2226 conn->socks_request->socks_version = 0;
2227 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2228 strlcpy(conn->socks_request->address, address,
2229 sizeof(conn->socks_request->address));
2230 conn->socks_request->port = port;
2231 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2232 conn->want_onehop = want_onehop;
2233 conn->use_begindir = use_begindir;
2234 if (use_begindir) {
2235 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2236 conn->chosen_exit_name[0] = '$';
2237 tor_assert(digest);
2238 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2239 digest, DIGEST_LEN);
2242 conn->_base.address = tor_strdup("(Tor_internal)");
2243 tor_addr_make_unspec(&conn->_base.addr);
2244 conn->_base.port = 0;
2246 if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
2247 connection_free(TO_CONN(conn));
2248 return NULL;
2251 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2253 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2255 /* attaching to a dirty circuit is fine */
2256 if (connection_ap_handshake_attach_circuit(conn) < 0) {
2257 if (!conn->_base.marked_for_close)
2258 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2259 return NULL;
2262 log_info(LD_APP,"... application connection created and linked.");
2263 return conn;
2266 /** Notify any interested controller connections about a new hostname resolve
2267 * or resolve error. Takes the same arguments as does
2268 * connection_ap_handshake_socks_resolved(). */
2269 static void
2270 tell_controller_about_resolved_result(edge_connection_t *conn,
2271 int answer_type,
2272 size_t answer_len,
2273 const char *answer,
2274 int ttl,
2275 time_t expires)
2278 if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
2279 answer_type == RESOLVED_TYPE_HOSTNAME)) {
2280 return; /* we already told the controller. */
2281 } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2282 struct in_addr in;
2283 char buf[INET_NTOA_BUF_LEN];
2284 in.s_addr = get_uint32(answer);
2285 tor_inet_ntoa(&in, buf, sizeof(buf));
2286 control_event_address_mapped(conn->socks_request->address,
2287 buf, expires, NULL);
2288 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len <256) {
2289 char *cp = tor_strndup(answer, answer_len);
2290 control_event_address_mapped(conn->socks_request->address,
2291 cp, expires, NULL);
2292 tor_free(cp);
2293 } else {
2294 control_event_address_mapped(conn->socks_request->address,
2295 "<error>",
2296 time(NULL)+ttl,
2297 "error=yes");
2301 /** Send an answer to an AP connection that has requested a DNS lookup via
2302 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2303 * for unreachable; the answer should be in the format specified in the socks
2304 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2305 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2306 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2308 /* XXXX022 the use of the ttl and expires fields is nutty. Let's make this
2309 * interface and those that use it less ugly. */
2310 void
2311 connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2312 int answer_type,
2313 size_t answer_len,
2314 const char *answer,
2315 int ttl,
2316 time_t expires)
2318 char buf[384];
2319 size_t replylen;
2321 if (ttl >= 0) {
2322 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2323 uint32_t a = ntohl(get_uint32(answer));
2324 if (a)
2325 client_dns_set_addressmap(conn->socks_request->address, a,
2326 conn->chosen_exit_name, ttl);
2327 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2328 char *cp = tor_strndup(answer, answer_len);
2329 client_dns_set_reverse_addressmap(conn->socks_request->address,
2331 conn->chosen_exit_name, ttl);
2332 tor_free(cp);
2336 if (conn->is_dns_request) {
2337 if (conn->dns_server_request) {
2338 /* We had a request on our DNS port: answer it. */
2339 dnsserv_resolved(conn, answer_type, answer_len, answer, ttl);
2340 conn->socks_request->has_finished = 1;
2341 return;
2342 } else {
2343 /* This must be a request from the controller. We already sent
2344 * a mapaddress if there's a ttl. */
2345 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2346 answer, ttl, expires);
2347 conn->socks_request->has_finished = 1;
2348 return;
2350 /* We shouldn't need to free conn here; it gets marked by the caller. */
2353 if (conn->socks_request->socks_version == 4) {
2354 buf[0] = 0x00; /* version */
2355 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2356 buf[1] = SOCKS4_GRANTED;
2357 set_uint16(buf+2, 0);
2358 memcpy(buf+4, answer, 4); /* address */
2359 replylen = SOCKS4_NETWORK_LEN;
2360 } else { /* "error" */
2361 buf[1] = SOCKS4_REJECT;
2362 memset(buf+2, 0, 6);
2363 replylen = SOCKS4_NETWORK_LEN;
2365 } else if (conn->socks_request->socks_version == 5) {
2366 /* SOCKS5 */
2367 buf[0] = 0x05; /* version */
2368 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2369 buf[1] = SOCKS5_SUCCEEDED;
2370 buf[2] = 0; /* reserved */
2371 buf[3] = 0x01; /* IPv4 address type */
2372 memcpy(buf+4, answer, 4); /* address */
2373 set_uint16(buf+8, 0); /* port == 0. */
2374 replylen = 10;
2375 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2376 buf[1] = SOCKS5_SUCCEEDED;
2377 buf[2] = 0; /* reserved */
2378 buf[3] = 0x04; /* IPv6 address type */
2379 memcpy(buf+4, answer, 16); /* address */
2380 set_uint16(buf+20, 0); /* port == 0. */
2381 replylen = 22;
2382 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2383 buf[1] = SOCKS5_SUCCEEDED;
2384 buf[2] = 0; /* reserved */
2385 buf[3] = 0x03; /* Domainname address type */
2386 buf[4] = (char)answer_len;
2387 memcpy(buf+5, answer, answer_len); /* address */
2388 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2389 replylen = 5+answer_len+2;
2390 } else {
2391 buf[1] = SOCKS5_HOST_UNREACHABLE;
2392 memset(buf+2, 0, 8);
2393 replylen = 10;
2395 } else {
2396 /* no socks version info; don't send anything back */
2397 return;
2399 connection_ap_handshake_socks_reply(conn, buf, replylen,
2400 (answer_type == RESOLVED_TYPE_IPV4 ||
2401 answer_type == RESOLVED_TYPE_IPV6) ?
2402 0 : END_STREAM_REASON_RESOLVEFAILED);
2405 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2406 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2407 * handshaking.
2409 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2410 * and return, else reply based on <b>endreason</b> (one of
2411 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2412 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2414 void
2415 connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2416 size_t replylen, int endreason)
2418 char buf[256];
2419 socks5_reply_status_t status =
2420 stream_end_reason_to_socks5_response(endreason);
2422 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2424 control_event_stream_status(conn,
2425 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2426 endreason);
2428 if (conn->socks_request->has_finished) {
2429 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2430 "connection_ap_handshake_socks_reply.");
2431 return;
2433 if (replylen) { /* we already have a reply in mind */
2434 connection_write_to_buf(reply, replylen, TO_CONN(conn));
2435 conn->socks_request->has_finished = 1;
2436 return;
2438 if (conn->socks_request->socks_version == 4) {
2439 memset(buf,0,SOCKS4_NETWORK_LEN);
2440 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2441 /* leave version, destport, destip zero */
2442 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
2443 } else if (conn->socks_request->socks_version == 5) {
2444 buf[0] = 5; /* version 5 */
2445 buf[1] = (char)status;
2446 buf[2] = 0;
2447 buf[3] = 1; /* ipv4 addr */
2448 memset(buf+4,0,6); /* Set external addr/port to 0.
2449 The spec doesn't seem to say what to do here. -RD */
2450 connection_write_to_buf(buf,10,TO_CONN(conn));
2452 /* If socks_version isn't 4 or 5, don't send anything.
2453 * This can happen in the case of AP bridges. */
2454 conn->socks_request->has_finished = 1;
2455 return;
2458 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2459 * an exit hop for the circuit, or we are the origin and it is a
2460 * rendezvous begin.
2462 * Launch a new exit connection and initialize things appropriately.
2464 * If it's a rendezvous stream, call connection_exit_connect() on
2465 * it.
2467 * For general streams, call dns_resolve() on it first, and only call
2468 * connection_exit_connect() if the dns answer is already known.
2470 * Note that we don't call connection_add() on the new stream! We wait
2471 * for connection_exit_connect() to do that.
2473 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2474 * Else return 0.
2477 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2479 edge_connection_t *n_stream;
2480 relay_header_t rh;
2481 char *address=NULL;
2482 uint16_t port;
2483 or_circuit_t *or_circ = NULL;
2485 assert_circuit_ok(circ);
2486 if (!CIRCUIT_IS_ORIGIN(circ))
2487 or_circ = TO_OR_CIRCUIT(circ);
2489 relay_header_unpack(&rh, cell->payload);
2491 /* Note: we have to use relay_send_command_from_edge here, not
2492 * connection_edge_end or connection_edge_send_command, since those require
2493 * that we have a stream connected to a circuit, and we don't connect to a
2494 * circuit until we have a pending/successful resolve. */
2496 if (!server_mode(get_options()) &&
2497 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2498 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2499 "Relay begin cell at non-server. Closing.");
2500 relay_send_end_cell_from_edge(rh.stream_id, circ,
2501 END_STREAM_REASON_EXITPOLICY, NULL);
2502 return 0;
2505 if (rh.command == RELAY_COMMAND_BEGIN) {
2506 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
2507 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2508 "Relay begin cell has no \\0. Closing.");
2509 relay_send_end_cell_from_edge(rh.stream_id, circ,
2510 END_STREAM_REASON_TORPROTOCOL, NULL);
2511 return 0;
2513 if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
2514 &address,NULL,&port)<0) {
2515 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2516 "Unable to parse addr:port in relay begin cell. Closing.");
2517 relay_send_end_cell_from_edge(rh.stream_id, circ,
2518 END_STREAM_REASON_TORPROTOCOL, NULL);
2519 return 0;
2521 if (port==0) {
2522 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2523 "Missing port in relay begin cell. Closing.");
2524 relay_send_end_cell_from_edge(rh.stream_id, circ,
2525 END_STREAM_REASON_TORPROTOCOL, NULL);
2526 tor_free(address);
2527 return 0;
2529 if (or_circ && or_circ->is_first_hop &&
2530 !get_options()->AllowSingleHopExits) {
2531 /* Don't let clients use us as a single-hop proxy, unless the user
2532 * has explicitly allowed that in the config. It attracts attackers
2533 * and users who'd be better off with, well, single-hop proxies.
2535 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2536 "Attempt to open a stream on first hop of circuit. Closing.");
2537 relay_send_end_cell_from_edge(rh.stream_id, circ,
2538 END_STREAM_REASON_TORPROTOCOL, NULL);
2539 tor_free(address);
2540 return 0;
2542 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2543 if (!directory_permits_begindir_requests(get_options()) ||
2544 circ->purpose != CIRCUIT_PURPOSE_OR) {
2545 relay_send_end_cell_from_edge(rh.stream_id, circ,
2546 END_STREAM_REASON_NOTDIRECTORY, NULL);
2547 return 0;
2549 /* Make sure to get the 'real' address of the previous hop: the
2550 * caller might want to know whether his IP address has changed, and
2551 * we might already have corrected _base.addr[ess] for the relay's
2552 * canonical IP address. */
2553 if (or_circ && or_circ->p_conn)
2554 address = tor_dup_addr(&or_circ->p_conn->real_addr);
2555 else
2556 address = tor_strdup("127.0.0.1");
2557 port = 1; /* XXXX This value is never actually used anywhere, and there
2558 * isn't "really" a connection here. But we
2559 * need to set it to something nonzero. */
2560 } else {
2561 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2562 relay_send_end_cell_from_edge(rh.stream_id, circ,
2563 END_STREAM_REASON_INTERNAL, NULL);
2564 return 0;
2567 log_debug(LD_EXIT,"Creating new exit connection.");
2568 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2569 n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
2571 n_stream->stream_id = rh.stream_id;
2572 n_stream->_base.port = port;
2573 /* leave n_stream->s at -1, because it's not yet valid */
2574 n_stream->package_window = STREAMWINDOW_START;
2575 n_stream->deliver_window = STREAMWINDOW_START;
2577 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
2578 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2579 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
2580 n_stream->_base.address = tor_strdup("(rendezvous)");
2581 n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
2582 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
2583 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
2584 assert_circuit_ok(circ);
2585 if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
2586 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
2587 n_stream->_base.port);
2588 relay_send_end_cell_from_edge(rh.stream_id, circ,
2589 END_STREAM_REASON_EXITPOLICY,
2590 origin_circ->cpath->prev);
2591 connection_free(TO_CONN(n_stream));
2592 tor_free(address);
2593 return 0;
2595 assert_circuit_ok(circ);
2596 log_debug(LD_REND,"Finished assigning addr/port");
2597 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
2599 /* add it into the linked list of n_streams on this circuit */
2600 n_stream->next_stream = origin_circ->p_streams;
2601 n_stream->on_circuit = circ;
2602 origin_circ->p_streams = n_stream;
2603 assert_circuit_ok(circ);
2605 connection_exit_connect(n_stream);
2606 tor_free(address);
2607 return 0;
2609 tor_strlower(address);
2610 n_stream->_base.address = address;
2611 n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2612 /* default to failed, change in dns_resolve if it turns out not to fail */
2614 if (we_are_hibernating()) {
2615 relay_send_end_cell_from_edge(rh.stream_id, circ,
2616 END_STREAM_REASON_HIBERNATING, NULL);
2617 connection_free(TO_CONN(n_stream));
2618 return 0;
2621 n_stream->on_circuit = circ;
2623 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2624 tor_assert(or_circ);
2625 if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->real_addr))
2626 tor_addr_assign(&n_stream->_base.addr, &or_circ->p_conn->real_addr);
2627 return connection_exit_connect_dir(n_stream);
2630 log_debug(LD_EXIT,"about to start the dns_resolve().");
2632 /* send it off to the gethostbyname farm */
2633 switch (dns_resolve(n_stream)) {
2634 case 1: /* resolve worked; now n_stream is attached to circ. */
2635 assert_circuit_ok(circ);
2636 log_debug(LD_EXIT,"about to call connection_exit_connect().");
2637 connection_exit_connect(n_stream);
2638 return 0;
2639 case -1: /* resolve failed */
2640 relay_send_end_cell_from_edge(rh.stream_id, circ,
2641 END_STREAM_REASON_RESOLVEFAILED, NULL);
2642 /* n_stream got freed. don't touch it. */
2643 break;
2644 case 0: /* resolve added to pending list */
2645 assert_circuit_ok(circ);
2646 break;
2648 return 0;
2652 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2653 * circuit <b>circ</b>;
2654 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2657 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
2659 edge_connection_t *dummy_conn;
2660 relay_header_t rh;
2662 assert_circuit_ok(TO_CIRCUIT(circ));
2663 relay_header_unpack(&rh, cell->payload);
2665 /* This 'dummy_conn' only exists to remember the stream ID
2666 * associated with the resolve request; and to make the
2667 * implementation of dns.c more uniform. (We really only need to
2668 * remember the circuit, the stream ID, and the hostname to be
2669 * resolved; but if we didn't store them in a connection like this,
2670 * the housekeeping in dns.c would get way more complicated.)
2672 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2673 dummy_conn->stream_id = rh.stream_id;
2674 dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
2675 rh.length);
2676 dummy_conn->_base.port = 0;
2677 dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2678 dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
2680 dummy_conn->on_circuit = TO_CIRCUIT(circ);
2682 /* send it off to the gethostbyname farm */
2683 switch (dns_resolve(dummy_conn)) {
2684 case -1: /* Impossible to resolve; a resolved cell was sent. */
2685 /* Connection freed; don't touch it. */
2686 return 0;
2687 case 1: /* The result was cached; a resolved cell was sent. */
2688 if (!dummy_conn->_base.marked_for_close)
2689 connection_free(TO_CONN(dummy_conn));
2690 return 0;
2691 case 0: /* resolve added to pending list */
2692 assert_circuit_ok(TO_CIRCUIT(circ));
2693 break;
2695 return 0;
2698 /** Connect to conn's specified addr and port. If it worked, conn
2699 * has now been added to the connection_array.
2701 * Send back a connected cell. Include the resolved IP of the destination
2702 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2703 * streams must not reveal what IP they connected to.)
2705 void
2706 connection_exit_connect(edge_connection_t *edge_conn)
2708 const tor_addr_t *addr;
2709 uint16_t port;
2710 connection_t *conn = TO_CONN(edge_conn);
2711 int socket_error = 0;
2713 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
2714 router_compare_to_my_exit_policy(edge_conn)) {
2715 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
2716 escaped_safe_str(conn->address), conn->port);
2717 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
2718 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2719 connection_free(conn);
2720 return;
2723 addr = &conn->addr;
2724 port = conn->port;
2726 log_debug(LD_EXIT,"about to try connecting");
2727 switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
2728 case -1:
2729 /* XXX021 use socket_error below rather than trying to piece things
2730 * together from the current errno, which may have been clobbered. */
2731 connection_edge_end_errno(edge_conn);
2732 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2733 connection_free(conn);
2734 return;
2735 case 0:
2736 conn->state = EXIT_CONN_STATE_CONNECTING;
2738 connection_watch_events(conn, EV_WRITE | EV_READ);
2739 /* writable indicates finish;
2740 * readable/error indicates broken link in windows-land. */
2741 return;
2742 /* case 1: fall through */
2745 conn->state = EXIT_CONN_STATE_OPEN;
2746 if (connection_wants_to_flush(conn)) {
2747 /* in case there are any queued data cells */
2748 log_warn(LD_BUG,"newly connected conn had data waiting!");
2749 // connection_start_writing(conn);
2751 connection_watch_events(conn, EV_READ);
2753 /* also, deliver a 'connected' cell back through the circuit. */
2754 if (connection_edge_is_rendezvous_stream(edge_conn)) {
2755 /* rendezvous stream */
2756 /* don't send an address back! */
2757 connection_edge_send_command(edge_conn,
2758 RELAY_COMMAND_CONNECTED,
2759 NULL, 0);
2760 } else { /* normal stream */
2761 char connected_payload[20];
2762 int connected_payload_len;
2763 if (tor_addr_family(&conn->addr) == AF_INET) {
2764 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
2765 connected_payload_len = 4;
2766 } else {
2767 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
2768 connected_payload_len = 16;
2770 set_uint32(connected_payload+connected_payload_len,
2771 htonl(dns_clip_ttl(edge_conn->address_ttl)));
2772 connected_payload_len += 4;
2773 connection_edge_send_command(edge_conn,
2774 RELAY_COMMAND_CONNECTED,
2775 connected_payload, connected_payload_len);
2779 /** Given an exit conn that should attach to us as a directory server, open a
2780 * bridge connection with a linked connection pair, create a new directory
2781 * conn, and join them together. Return 0 on success (or if there was an
2782 * error we could send back an end cell for). Return -(some circuit end
2783 * reason) if the circuit needs to be torn down. Either connects
2784 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2786 static int
2787 connection_exit_connect_dir(edge_connection_t *exitconn)
2789 dir_connection_t *dirconn = NULL;
2790 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
2792 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
2794 exitconn->_base.state = EXIT_CONN_STATE_OPEN;
2796 dirconn = dir_connection_new(AF_INET);
2798 tor_addr_assign(&dirconn->_base.addr, &exitconn->_base.addr);
2799 dirconn->_base.port = 0;
2800 dirconn->_base.address = tor_strdup(exitconn->_base.address);
2801 dirconn->_base.type = CONN_TYPE_DIR;
2802 dirconn->_base.purpose = DIR_PURPOSE_SERVER;
2803 dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2805 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
2807 if (connection_add(TO_CONN(exitconn))<0) {
2808 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2809 connection_free(TO_CONN(exitconn));
2810 connection_free(TO_CONN(dirconn));
2811 return 0;
2814 /* link exitconn to circ, now that we know we can use it. */
2815 exitconn->next_stream = circ->n_streams;
2816 circ->n_streams = exitconn;
2818 if (connection_add(TO_CONN(dirconn))<0) {
2819 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2820 connection_close_immediate(TO_CONN(exitconn));
2821 connection_mark_for_close(TO_CONN(exitconn));
2822 connection_free(TO_CONN(dirconn));
2823 return 0;
2826 connection_start_reading(TO_CONN(dirconn));
2827 connection_start_reading(TO_CONN(exitconn));
2829 if (connection_edge_send_command(exitconn,
2830 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
2831 connection_mark_for_close(TO_CONN(exitconn));
2832 connection_mark_for_close(TO_CONN(dirconn));
2833 return 0;
2836 return 0;
2839 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2840 * it is a general stream.
2843 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
2845 tor_assert(conn);
2846 if (conn->rend_data)
2847 return 1;
2848 return 0;
2851 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2852 * to exit from it, or 0 if it probably will not allow it.
2853 * (We might be uncertain if conn's destination address has not yet been
2854 * resolved.)
2857 connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit)
2859 tor_assert(conn);
2860 tor_assert(conn->_base.type == CONN_TYPE_AP);
2861 tor_assert(conn->socks_request);
2862 tor_assert(exit);
2864 /* If a particular exit node has been requested for the new connection,
2865 * make sure the exit node of the existing circuit matches exactly.
2867 if (conn->chosen_exit_name) {
2868 routerinfo_t *chosen_exit =
2869 router_get_by_nickname(conn->chosen_exit_name, 1);
2870 if (!chosen_exit || memcmp(chosen_exit->cache_info.identity_digest,
2871 exit->cache_info.identity_digest, DIGEST_LEN)) {
2872 /* doesn't match */
2873 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2874 // conn->chosen_exit_name, exit->nickname);
2875 return 0;
2879 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2880 !conn->use_begindir) {
2881 struct in_addr in;
2882 uint32_t addr = 0;
2883 addr_policy_result_t r;
2884 if (tor_inet_aton(conn->socks_request->address, &in))
2885 addr = ntohl(in.s_addr);
2886 r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
2887 exit->exit_policy);
2888 if (r == ADDR_POLICY_REJECTED)
2889 return 0; /* We know the address, and the exit policy rejects it. */
2890 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
2891 return 0; /* We don't know the addr, but the exit policy rejects most
2892 * addresses with this port. Since the user didn't ask for
2893 * this node, err on the side of caution. */
2894 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2895 /* Can't support reverse lookups without eventdns. */
2896 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
2897 exit->has_old_dnsworkers)
2898 return 0;
2900 /* Don't send DNS requests to non-exit servers by default. */
2901 if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
2902 return 0;
2904 return 1;
2907 /** If address is of the form "y.onion" with a well-formed handle y:
2908 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2910 * If address is of the form "y.exit":
2911 * Put a NUL after y and return EXIT_HOSTNAME.
2913 * Otherwise:
2914 * Return NORMAL_HOSTNAME and change nothing.
2916 hostname_type_t
2917 parse_extended_hostname(char *address)
2919 char *s;
2920 char query[REND_SERVICE_ID_LEN_BASE32+1];
2922 s = strrchr(address,'.');
2923 if (!s)
2924 return NORMAL_HOSTNAME; /* no dot, thus normal */
2925 if (!strcmp(s+1,"exit")) {
2926 *s = 0; /* NUL-terminate it */
2927 return EXIT_HOSTNAME; /* .exit */
2929 if (strcmp(s+1,"onion"))
2930 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
2932 /* so it is .onion */
2933 *s = 0; /* NUL-terminate it */
2934 if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
2935 REND_SERVICE_ID_LEN_BASE32+1)
2936 goto failed;
2937 if (rend_valid_service_id(query)) {
2938 return ONION_HOSTNAME; /* success */
2940 failed:
2941 /* otherwise, return to previous state and return 0 */
2942 *s = '.';
2943 return BAD_HOSTNAME;
2946 /** Check if the address is of the form "y.noconnect"
2949 hostname_is_noconnect_address(const char *address)
2951 return ! strcasecmpend(address, ".noconnect");