Move in-addr.arpa parsing and generation into address.c, and simplify the code that...
[tor/rransom.git] / src / or / connection_edge.c
blob9b192b5565c3534d3515aaf5b037f34f0cfa7b35
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char connection_edge_c_id[] =
8 "$Id$";
10 /**
11 * \file connection_edge.c
12 * \brief Handle edge streams.
13 **/
15 #include "or.h"
17 #ifdef HAVE_LINUX_TYPES_H
18 #include <linux/types.h>
19 #endif
20 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
21 #include <linux/netfilter_ipv4.h>
22 #define TRANS_NETFILTER
23 #endif
25 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
26 #include <net/if.h>
27 #include <net/pfvar.h>
28 #define TRANS_PF
29 #endif
31 #define SOCKS4_GRANTED 90
32 #define SOCKS4_REJECT 91
34 static int connection_ap_handshake_process_socks(edge_connection_t *conn);
35 static int connection_ap_process_natd(edge_connection_t *conn);
36 static int connection_exit_connect_dir(edge_connection_t *exitconn);
37 static int address_is_in_virtual_range(const char *addr);
38 static int consider_plaintext_ports(edge_connection_t *conn, uint16_t port);
39 static void clear_trackexithost_mappings(const char *exitname);
41 /** An AP stream has failed/finished. If it hasn't already sent back
42 * a socks reply, send one now (based on endreason). Also set
43 * has_sent_end to 1, and mark the conn.
45 void
46 _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
47 int line, const char *file)
49 tor_assert(conn->_base.type == CONN_TYPE_AP);
50 conn->edge_has_sent_end = 1; /* no circ yet */
52 if (conn->_base.marked_for_close) {
53 /* This call will warn as appropriate. */
54 _connection_mark_for_close(TO_CONN(conn), line, file);
55 return;
58 if (!conn->socks_request->has_finished) {
59 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
60 log_warn(LD_BUG,
61 "stream (marked at %s:%d) sending two socks replies?",
62 file, line);
64 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
65 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
66 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
67 connection_ap_handshake_socks_resolved(conn,
68 RESOLVED_TYPE_ERROR_TRANSIENT,
69 0, NULL, -1, -1);
70 else /* unknown or no handshake at all. send no response. */
71 conn->socks_request->has_finished = 1;
74 _connection_mark_for_close(TO_CONN(conn), line, file);
75 conn->_base.hold_open_until_flushed = 1;
76 conn->end_reason = endreason;
79 /** There was an EOF. Send an end and mark the connection for close.
81 int
82 connection_edge_reached_eof(edge_connection_t *conn)
84 if (buf_datalen(conn->_base.inbuf) &&
85 connection_state_is_open(TO_CONN(conn))) {
86 /* it still has stuff to process. don't let it die yet. */
87 return 0;
89 log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
90 if (!conn->_base.marked_for_close) {
91 /* only mark it if not already marked. it's possible to
92 * get the 'end' right around when the client hangs up on us. */
93 connection_edge_end(conn, END_STREAM_REASON_DONE);
94 if (conn->socks_request) /* eof, so don't send a socks reply back */
95 conn->socks_request->has_finished = 1;
96 connection_mark_for_close(TO_CONN(conn));
98 return 0;
101 /** Handle new bytes on conn->inbuf based on state:
102 * - If it's waiting for socks info, try to read another step of the
103 * socks handshake out of conn->inbuf.
104 * - If it's waiting for the original destination, fetch it.
105 * - If it's open, then package more relay cells from the stream.
106 * - Else, leave the bytes on inbuf alone for now.
108 * Mark and return -1 if there was an unexpected error with the conn,
109 * else return 0.
112 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
114 tor_assert(conn);
116 switch (conn->_base.state) {
117 case AP_CONN_STATE_SOCKS_WAIT:
118 if (connection_ap_handshake_process_socks(conn) < 0) {
119 /* already marked */
120 return -1;
122 return 0;
123 case AP_CONN_STATE_NATD_WAIT:
124 if (connection_ap_process_natd(conn) < 0) {
125 /* already marked */
126 return -1;
128 return 0;
129 case AP_CONN_STATE_OPEN:
130 case EXIT_CONN_STATE_OPEN:
131 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
132 /* (We already sent an end cell if possible) */
133 connection_mark_for_close(TO_CONN(conn));
134 return -1;
136 return 0;
137 case EXIT_CONN_STATE_CONNECTING:
138 case AP_CONN_STATE_RENDDESC_WAIT:
139 case AP_CONN_STATE_CIRCUIT_WAIT:
140 case AP_CONN_STATE_CONNECT_WAIT:
141 case AP_CONN_STATE_RESOLVE_WAIT:
142 case AP_CONN_STATE_CONTROLLER_WAIT:
143 log_info(LD_EDGE,
144 "data from edge while in '%s' state. Leaving it on buffer.",
145 conn_state_to_string(conn->_base.type, conn->_base.state));
146 return 0;
148 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
149 tor_fragile_assert();
150 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
151 connection_mark_for_close(TO_CONN(conn));
152 return -1;
155 /** This edge needs to be closed, because its circuit has closed.
156 * Mark it for close and return 0.
159 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
161 if (!conn->_base.marked_for_close) {
162 log_info(LD_EDGE,
163 "CircID %d: At an edge. Marking connection for close.", circ_id);
164 if (conn->_base.type == CONN_TYPE_AP) {
165 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
166 control_event_stream_status(conn, STREAM_EVENT_CLOSED,
167 END_STREAM_REASON_DESTROY);
168 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
169 } else {
170 /* closing the circuit, nothing to send an END to */
171 conn->edge_has_sent_end = 1;
172 conn->end_reason = END_STREAM_REASON_DESTROY;
173 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
174 connection_mark_for_close(TO_CONN(conn));
175 conn->_base.hold_open_until_flushed = 1;
178 conn->cpath_layer = NULL;
179 conn->on_circuit = NULL;
180 return 0;
183 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
184 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
185 * is not a client connection, set the relay end cell's reason for closing
186 * as <b>reason</b> */
187 static int
188 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
189 uint8_t reason, crypt_path_t *cpath_layer)
191 char payload[1];
193 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
194 /* Never send the server an informative reason code; it doesn't need to
195 * know why the client stream is failing. */
196 reason = END_STREAM_REASON_MISC;
199 payload[0] = (char) reason;
201 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
202 payload, 1, cpath_layer);
205 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
206 * remember that we've done so. If this is not a client connection, set the
207 * relay end cell's reason for closing as <b>reason</b>.
209 * Return -1 if this function has already been called on this conn,
210 * else return 0.
213 connection_edge_end(edge_connection_t *conn, uint8_t reason)
215 char payload[RELAY_PAYLOAD_SIZE];
216 size_t payload_len=1;
217 circuit_t *circ;
219 if (conn->edge_has_sent_end) {
220 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
221 "on an already ended stream?", reason);
222 tor_fragile_assert();
223 return -1;
226 if (conn->_base.marked_for_close) {
227 log_warn(LD_BUG,
228 "called on conn that's already marked for close at %s:%d.",
229 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
230 return 0;
233 circ = circuit_get_by_edge_conn(conn);
234 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
235 /* If this is a client circuit, don't send the server an informative
236 * reason code; it doesn't need to know why the client stream is
237 * failing. */
238 reason = END_STREAM_REASON_MISC;
241 payload[0] = (char)reason;
242 if (reason == END_STREAM_REASON_EXITPOLICY &&
243 !connection_edge_is_rendezvous_stream(conn)) {
244 int addrlen;
245 if (tor_addr_family(&conn->_base.addr) == AF_INET) {
246 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
247 addrlen = 4;
248 } else {
249 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
250 addrlen = 16;
252 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
253 payload_len += 4+addrlen;
256 if (circ && !circ->marked_for_close) {
257 log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
258 connection_edge_send_command(conn, RELAY_COMMAND_END,
259 payload, payload_len);
260 } else {
261 log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
262 conn->_base.s);
265 conn->edge_has_sent_end = 1;
266 conn->end_reason = reason;
267 return 0;
270 /** An error has just occured on an operation on an edge connection
271 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
272 * appropriate relay end cell to the other end of the connection's circuit.
275 connection_edge_end_errno(edge_connection_t *conn)
277 uint8_t reason;
278 tor_assert(conn);
279 reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
280 return connection_edge_end(conn, reason);
283 /** Connection <b>conn</b> has finished writing and has no bytes left on
284 * its outbuf.
286 * If it's in state 'open', stop writing, consider responding with a
287 * sendme, and return.
288 * Otherwise, stop writing and return.
290 * If <b>conn</b> is broken, mark it for close and return -1, else
291 * return 0.
294 connection_edge_finished_flushing(edge_connection_t *conn)
296 tor_assert(conn);
298 switch (conn->_base.state) {
299 case AP_CONN_STATE_OPEN:
300 case EXIT_CONN_STATE_OPEN:
301 connection_stop_writing(TO_CONN(conn));
302 connection_edge_consider_sending_sendme(conn);
303 return 0;
304 case AP_CONN_STATE_SOCKS_WAIT:
305 case AP_CONN_STATE_NATD_WAIT:
306 case AP_CONN_STATE_RENDDESC_WAIT:
307 case AP_CONN_STATE_CIRCUIT_WAIT:
308 case AP_CONN_STATE_CONNECT_WAIT:
309 case AP_CONN_STATE_CONTROLLER_WAIT:
310 connection_stop_writing(TO_CONN(conn));
311 return 0;
312 default:
313 log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
314 tor_fragile_assert();
315 return -1;
317 return 0;
320 /** Connected handler for exit connections: start writing pending
321 * data, deliver 'CONNECTED' relay cells as appropriate, and check
322 * any pending data that may have been received. */
324 connection_edge_finished_connecting(edge_connection_t *edge_conn)
326 connection_t *conn;
328 tor_assert(edge_conn);
329 tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
330 conn = TO_CONN(edge_conn);
331 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
333 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
334 escaped_safe_str(conn->address),conn->port,
335 fmt_addr(&conn->addr));
337 conn->state = EXIT_CONN_STATE_OPEN;
338 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
339 if (connection_wants_to_flush(conn)) /* in case there are any queued relay
340 * cells */
341 connection_start_writing(conn);
342 /* deliver a 'connected' relay cell back through the circuit. */
343 if (connection_edge_is_rendezvous_stream(edge_conn)) {
344 if (connection_edge_send_command(edge_conn,
345 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
346 return 0; /* circuit is closed, don't continue */
347 } else {
348 char connected_payload[20];
349 int connected_payload_len;
350 if (tor_addr_family(&conn->addr) == AF_INET) {
351 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
352 set_uint32(connected_payload+4,
353 htonl(dns_clip_ttl(edge_conn->address_ttl)));
354 connected_payload_len = 8;
355 } else {
356 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
357 set_uint32(connected_payload+16,
358 htonl(dns_clip_ttl(edge_conn->address_ttl)));
359 connected_payload_len = 20;
361 if (connection_edge_send_command(edge_conn,
362 RELAY_COMMAND_CONNECTED,
363 connected_payload, connected_payload_len) < 0)
364 return 0; /* circuit is closed, don't continue */
366 tor_assert(edge_conn->package_window > 0);
367 /* in case the server has written anything */
368 return connection_edge_process_inbuf(edge_conn, 1);
371 /** Define a schedule for how long to wait between retrying
372 * application connections. Rather than waiting a fixed amount of
373 * time between each retry, we wait 10 seconds each for the first
374 * two tries, and 15 seconds for each retry after
375 * that. Hopefully this will improve the expected user experience. */
376 static int
377 compute_retry_timeout(edge_connection_t *conn)
379 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
380 return 10;
381 return 15;
384 /** Find all general-purpose AP streams waiting for a response that sent their
385 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
386 * mark their current circuit as unsuitable for new streams. Then call
387 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
388 * available) or launch a new one.
390 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
391 * retry attempt).
393 void
394 connection_ap_expire_beginning(void)
396 edge_connection_t *conn;
397 circuit_t *circ;
398 time_t now = time(NULL);
399 or_options_t *options = get_options();
400 int severity;
401 int cutoff;
402 int seconds_idle;
403 smartlist_t *conns = get_connection_array();
405 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
406 if (c->type != CONN_TYPE_AP)
407 continue;
408 conn = TO_EDGE_CONN(c);
409 /* if it's an internal linked connection, don't yell its status. */
410 severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
411 ? LOG_INFO : LOG_NOTICE;
412 seconds_idle = (int)( now - conn->_base.timestamp_lastread );
414 if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
415 if (seconds_idle >= options->SocksTimeout) {
416 log_fn(severity, LD_APP,
417 "Tried for %d seconds to get a connection to %s:%d. "
418 "Giving up. (%s)",
419 seconds_idle, safe_str(conn->socks_request->address),
420 conn->socks_request->port,
421 conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
422 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
424 continue;
427 if (conn->_base.state == AP_CONN_STATE_OPEN)
428 continue;
430 /* We're in state connect_wait or resolve_wait now -- waiting for a
431 * reply to our relay cell. See if we want to retry/give up. */
433 cutoff = compute_retry_timeout(conn);
434 if (seconds_idle < cutoff)
435 continue;
436 circ = circuit_get_by_edge_conn(conn);
437 if (!circ) { /* it's vanished? */
438 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
439 safe_str(conn->socks_request->address));
440 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
441 continue;
443 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
444 if (seconds_idle >= options->SocksTimeout) {
445 log_fn(severity, LD_REND,
446 "Rend stream is %d seconds late. Giving up on address"
447 " '%s.onion'.",
448 seconds_idle,
449 safe_str(conn->socks_request->address));
450 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
451 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
453 continue;
455 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
456 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
457 "We tried for %d seconds to connect to '%s' using exit '%s'."
458 " Retrying on a new circuit.",
459 seconds_idle, safe_str(conn->socks_request->address),
460 conn->cpath_layer ?
461 conn->cpath_layer->extend_info->nickname : "*unnamed*");
462 /* send an end down the circuit */
463 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
464 /* un-mark it as ending, since we're going to reuse it */
465 conn->edge_has_sent_end = 0;
466 conn->end_reason = 0;
467 /* kludge to make us not try this circuit again, yet to allow
468 * current streams on it to survive if they can: make it
469 * unattractive to use for new streams */
470 tor_assert(circ->timestamp_dirty);
471 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
472 /* give our stream another 'cutoff' seconds to try */
473 conn->_base.timestamp_lastread += cutoff;
474 if (conn->num_socks_retries < 250) /* avoid overflow */
475 conn->num_socks_retries++;
476 /* move it back into 'pending' state, and try to attach. */
477 if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
478 END_STREAM_REASON_TIMEOUT)<0) {
479 if (!conn->_base.marked_for_close)
480 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
482 } SMARTLIST_FOREACH_END(conn);
485 /** Tell any AP streams that are waiting for a new circuit to try again,
486 * either attaching to an available circ or launching a new one.
488 void
489 connection_ap_attach_pending(void)
491 edge_connection_t *edge_conn;
492 smartlist_t *conns = get_connection_array();
493 SMARTLIST_FOREACH(conns, connection_t *, conn,
495 if (conn->marked_for_close ||
496 conn->type != CONN_TYPE_AP ||
497 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
498 continue;
499 edge_conn = TO_EDGE_CONN(conn);
500 if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
501 if (!edge_conn->_base.marked_for_close)
502 connection_mark_unattached_ap(edge_conn,
503 END_STREAM_REASON_CANT_ATTACH);
508 /** Tell any AP streams that are waiting for a onehop tunnel to
509 * <b>failed_digest</b> that they are going to fail. */
510 /* XXX021 We should get rid of this function, and instead attach
511 * onehop streams to circ->p_streams so they get marked in
512 * circuit_mark_for_close like normal p_streams. */
513 void
514 connection_ap_fail_onehop(const char *failed_digest,
515 cpath_build_state_t *build_state)
517 edge_connection_t *edge_conn;
518 char digest[DIGEST_LEN];
519 smartlist_t *conns = get_connection_array();
520 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
521 if (conn->marked_for_close ||
522 conn->type != CONN_TYPE_AP ||
523 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
524 continue;
525 edge_conn = TO_EDGE_CONN(conn);
526 if (!edge_conn->want_onehop)
527 continue;
528 if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
529 memcmp(digest, failed_digest, DIGEST_LEN))
530 continue;
531 if (tor_digest_is_zero(digest)) {
532 /* we don't know the digest; have to compare addr:port */
533 tor_addr_t addr;
534 if (!build_state || !build_state->chosen_exit ||
535 !edge_conn->socks_request || !edge_conn->socks_request->address)
536 continue;
537 if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
538 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
539 build_state->chosen_exit->port != edge_conn->socks_request->port)
540 continue;
542 log_info(LD_APP, "Closing onehop stream to '%s/%s' because the OR conn "
543 "just failed.", edge_conn->chosen_exit_name,
544 edge_conn->socks_request->address);
545 connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
546 } SMARTLIST_FOREACH_END(conn);
549 /** A circuit failed to finish on its last hop <b>info</b>. If there
550 * are any streams waiting with this exit node in mind, but they
551 * don't absolutely require it, make them give up on it.
553 void
554 circuit_discard_optional_exit_enclaves(extend_info_t *info)
556 edge_connection_t *edge_conn;
557 routerinfo_t *r1, *r2;
559 smartlist_t *conns = get_connection_array();
560 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
561 if (conn->marked_for_close ||
562 conn->type != CONN_TYPE_AP ||
563 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
564 continue;
565 edge_conn = TO_EDGE_CONN(conn);
566 if (!edge_conn->chosen_exit_optional &&
567 !edge_conn->chosen_exit_retries)
568 continue;
569 r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
570 r2 = router_get_by_nickname(info->nickname, 0);
571 if (!r1 || !r2 || r1 != r2)
572 continue;
573 tor_assert(edge_conn->socks_request);
574 if (edge_conn->chosen_exit_optional) {
575 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
576 safe_str(edge_conn->chosen_exit_name),
577 escaped_safe_str(edge_conn->socks_request->address));
578 edge_conn->chosen_exit_optional = 0;
579 tor_free(edge_conn->chosen_exit_name); /* clears it */
580 /* if this port is dangerous, warn or reject it now that we don't
581 * think it'll be using an enclave. */
582 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
584 if (edge_conn->chosen_exit_retries) {
585 if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
586 clear_trackexithost_mappings(edge_conn->chosen_exit_name);
587 tor_free(edge_conn->chosen_exit_name); /* clears it */
588 /* if this port is dangerous, warn or reject it now that we don't
589 * think it'll be using an enclave. */
590 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
593 } SMARTLIST_FOREACH_END(conn);
596 /** The AP connection <b>conn</b> has just failed while attaching or
597 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
598 * might work. Detach the circuit, and either reattach it, launch a
599 * new circuit, tell the controller, or give up as a appropriate.
601 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
604 connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
605 int reason)
607 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
608 conn->_base.timestamp_lastread = time(NULL);
609 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
610 /* If we're attaching streams ourself, or if this connection is
611 * a tunneled directory connection, then just attach it. */
612 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
613 circuit_detach_stream(TO_CIRCUIT(circ),conn);
614 return connection_ap_handshake_attach_circuit(conn);
615 } else {
616 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
617 circuit_detach_stream(TO_CIRCUIT(circ),conn);
618 return 0;
622 /** A client-side struct to remember requests to rewrite addresses
623 * to new addresses. These structs are stored in the hash table
624 * "addressmap" below.
626 * There are 5 ways to set an address mapping:
627 * - A MapAddress command from the controller [permanent]
628 * - An AddressMap directive in the torrc [permanent]
629 * - When a TrackHostExits torrc directive is triggered [temporary]
630 * - When a dns resolve succeeds [temporary]
631 * - When a dns resolve fails [temporary]
633 * When an addressmap request is made but one is already registered,
634 * the new one is replaced only if the currently registered one has
635 * no "new_address" (that is, it's in the process of dns resolve),
636 * or if the new one is permanent (expires==0 or 1).
638 * (We overload the 'expires' field, using "0" for mappings set via
639 * the configuration file, "1" for mappings set from the control
640 * interface, and other values for DNS and TrackHostExit mappings that can
641 * expire.)
643 typedef struct {
644 char *new_address;
645 time_t expires;
646 addressmap_entry_source_t source:3;
647 short num_resolve_failures;
648 } addressmap_entry_t;
650 /** Entry for mapping addresses to which virtual address we mapped them to. */
651 typedef struct {
652 char *ipv4_address;
653 char *hostname_address;
654 } virtaddress_entry_t;
656 /** A hash table to store client-side address rewrite instructions. */
657 static strmap_t *addressmap=NULL;
659 * Table mapping addresses to which virtual address, if any, we
660 * assigned them to.
662 * We maintain the following invariant: if [A,B] is in
663 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
664 * must be in addressmap. We do not require that the converse hold:
665 * if it fails, then we could end up mapping two virtual addresses to
666 * the same address, which is no disaster.
668 static strmap_t *virtaddress_reversemap=NULL;
670 /** Initialize addressmap. */
671 void
672 addressmap_init(void)
674 addressmap = strmap_new();
675 virtaddress_reversemap = strmap_new();
678 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
679 static void
680 addressmap_ent_free(void *_ent)
682 addressmap_entry_t *ent = _ent;
683 tor_free(ent->new_address);
684 tor_free(ent);
687 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
688 static void
689 addressmap_virtaddress_ent_free(void *_ent)
691 virtaddress_entry_t *ent = _ent;
692 tor_free(ent->ipv4_address);
693 tor_free(ent->hostname_address);
694 tor_free(ent);
697 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
698 static void
699 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
701 if (ent && ent->new_address &&
702 address_is_in_virtual_range(ent->new_address)) {
703 virtaddress_entry_t *ve =
704 strmap_get(virtaddress_reversemap, ent->new_address);
705 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
706 if (ve) {
707 if (!strcmp(address, ve->ipv4_address))
708 tor_free(ve->ipv4_address);
709 if (!strcmp(address, ve->hostname_address))
710 tor_free(ve->hostname_address);
711 if (!ve->ipv4_address && !ve->hostname_address) {
712 tor_free(ve);
713 strmap_remove(virtaddress_reversemap, ent->new_address);
719 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
720 * client address maps. */
721 static void
722 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
724 addressmap_virtaddress_remove(address, ent);
725 addressmap_ent_free(ent);
728 /** Unregister all TrackHostExits mappings from any address to
729 * *.exitname.exit. */
730 static void
731 clear_trackexithost_mappings(const char *exitname)
733 char *suffix;
734 size_t suffix_len;
735 if (!addressmap || !exitname)
736 return;
737 suffix_len = strlen(exitname) + 16;
738 suffix = tor_malloc(suffix_len);
739 tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
740 tor_strlower(suffix);
742 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
743 if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
744 addressmap_ent_remove(address, ent);
745 MAP_DEL_CURRENT(address);
747 } STRMAP_FOREACH_END;
749 tor_free(suffix);
752 /** Remove all entries from the addressmap that were set via the
753 * configuration file or the command line. */
754 void
755 addressmap_clear_configured(void)
757 addressmap_get_mappings(NULL, 0, 0, 0);
760 /** Remove all entries from the addressmap that are set to expire, ever. */
761 void
762 addressmap_clear_transient(void)
764 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
767 /** Clean out entries from the addressmap cache that were
768 * added long enough ago that they are no longer valid.
770 void
771 addressmap_clean(time_t now)
773 addressmap_get_mappings(NULL, 2, now, 0);
776 /** Free all the elements in the addressmap, and free the addressmap
777 * itself. */
778 void
779 addressmap_free_all(void)
781 if (addressmap) {
782 strmap_free(addressmap, addressmap_ent_free);
783 addressmap = NULL;
785 if (virtaddress_reversemap) {
786 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
787 virtaddress_reversemap = NULL;
791 /** Look at address, and rewrite it until it doesn't want any
792 * more rewrites; but don't get into an infinite loop.
793 * Don't write more than maxlen chars into address. Return true if the
794 * address changed; false otherwise. Set *<b>expires_out</b> to the
795 * expiry time of the result, or to <b>time_max</b> if the result does
796 * not expire.
799 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
801 addressmap_entry_t *ent;
802 int rewrites;
803 char *cp;
804 time_t expires = TIME_MAX;
806 for (rewrites = 0; rewrites < 16; rewrites++) {
807 ent = strmap_get(addressmap, address);
809 if (!ent || !ent->new_address) {
810 if (expires_out)
811 *expires_out = expires;
812 return (rewrites > 0); /* done, no rewrite needed */
815 cp = tor_strdup(escaped_safe_str(ent->new_address));
816 log_info(LD_APP, "Addressmap: rewriting %s to %s",
817 escaped_safe_str(address), cp);
818 if (ent->expires > 1 && ent->expires < expires)
819 expires = ent->expires;
820 tor_free(cp);
821 strlcpy(address, ent->new_address, maxlen);
823 log_warn(LD_CONFIG,
824 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
825 escaped_safe_str(address));
826 /* it's fine to rewrite a rewrite, but don't loop forever */
827 if (expires_out)
828 *expires_out = TIME_MAX;
829 return 1;
832 /** If we have a cached reverse DNS entry for the address stored in the
833 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
834 * rewrite to the cached value and return 1. Otherwise return 0. Set
835 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
836 * if the result does not expire. */
837 static int
838 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
840 size_t len = maxlen + 16;
841 char *s = tor_malloc(len), *cp;
842 addressmap_entry_t *ent;
843 int r = 0;
844 tor_snprintf(s, len, "REVERSE[%s]", address);
845 ent = strmap_get(addressmap, s);
846 if (ent) {
847 cp = tor_strdup(escaped_safe_str(ent->new_address));
848 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
849 escaped_safe_str(s), cp);
850 tor_free(cp);
851 strlcpy(address, ent->new_address, maxlen);
852 r = 1;
855 if (expires_out)
856 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
858 tor_free(s);
859 return r;
862 /** Return 1 if <b>address</b> is already registered, else return 0. If address
863 * is already registered, and <b>update_expires</b> is non-zero, then update
864 * the expiry time on the mapping with update_expires if it is a
865 * mapping created by TrackHostExits. */
867 addressmap_have_mapping(const char *address, int update_expiry)
869 addressmap_entry_t *ent;
870 if (!(ent=strmap_get_lc(addressmap, address)))
871 return 0;
872 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
873 ent->expires=time(NULL) + update_expiry;
874 return 1;
877 /** Register a request to map <b>address</b> to <b>new_address</b>,
878 * which will expire on <b>expires</b> (or 0 if never expires from
879 * config file, 1 if never expires from controller, 2 if never expires
880 * (virtual address mapping) from the controller.)
882 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
883 * free as appropriate. We will leave address alone.
885 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
886 * any mappings that exist from <b>address</b>.
888 void
889 addressmap_register(const char *address, char *new_address, time_t expires,
890 addressmap_entry_source_t source)
892 addressmap_entry_t *ent;
894 ent = strmap_get(addressmap, address);
895 if (!new_address || !strcasecmp(address,new_address)) {
896 /* Remove the mapping, if any. */
897 tor_free(new_address);
898 if (ent) {
899 addressmap_ent_remove(address,ent);
900 strmap_remove(addressmap, address);
902 return;
904 if (!ent) { /* make a new one and register it */
905 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
906 strmap_set(addressmap, address, ent);
907 } else if (ent->new_address) { /* we need to clean up the old mapping. */
908 if (expires > 1) {
909 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
910 "since it's already mapped to '%s'",
911 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
912 tor_free(new_address);
913 return;
915 if (address_is_in_virtual_range(ent->new_address) &&
916 expires != 2) {
917 /* XXX This isn't the perfect test; we want to avoid removing
918 * mappings set from the control interface _as virtual mapping */
919 addressmap_virtaddress_remove(address, ent);
921 tor_free(ent->new_address);
922 } /* else { we have an in-progress resolve with no mapping. } */
924 ent->new_address = new_address;
925 ent->expires = expires==2 ? 1 : expires;
926 ent->num_resolve_failures = 0;
927 ent->source = source;
929 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
930 safe_str(address), safe_str(ent->new_address));
931 control_event_address_mapped(address, ent->new_address, expires, NULL);
934 /** An attempt to resolve <b>address</b> failed at some OR.
935 * Increment the number of resolve failures we have on record
936 * for it, and then return that number.
939 client_dns_incr_failures(const char *address)
941 addressmap_entry_t *ent = strmap_get(addressmap, address);
942 if (!ent) {
943 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
944 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
945 strmap_set(addressmap,address,ent);
947 if (ent->num_resolve_failures < SHORT_MAX)
948 ++ent->num_resolve_failures; /* don't overflow */
949 log_info(LD_APP, "Address %s now has %d resolve failures.",
950 safe_str(address), ent->num_resolve_failures);
951 return ent->num_resolve_failures;
954 /** If <b>address</b> is in the client dns addressmap, reset
955 * the number of resolve failures we have on record for it.
956 * This is used when we fail a stream because it won't resolve:
957 * otherwise future attempts on that address will only try once.
959 void
960 client_dns_clear_failures(const char *address)
962 addressmap_entry_t *ent = strmap_get(addressmap, address);
963 if (ent)
964 ent->num_resolve_failures = 0;
967 /** Record the fact that <b>address</b> resolved to <b>name</b>.
968 * We can now use this in subsequent streams via addressmap_rewrite()
969 * so we can more correctly choose an exit that will allow <b>address</b>.
971 * If <b>exitname</b> is defined, then append the addresses with
972 * ".exitname.exit" before registering the mapping.
974 * If <b>ttl</b> is nonnegative, the mapping will be valid for
975 * <b>ttl</b>seconds; otherwise, we use the default.
977 static void
978 client_dns_set_addressmap_impl(const char *address, const char *name,
979 const char *exitname,
980 int ttl)
982 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
983 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
984 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
985 char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
987 tor_assert(address);
988 tor_assert(name);
990 if (ttl<0)
991 ttl = DEFAULT_DNS_TTL;
992 else
993 ttl = dns_clip_ttl(ttl);
995 if (exitname) {
996 /* XXXX fails to ever get attempts to get an exit address of
997 * google.com.digest[=~]nickname.exit; we need a syntax for this that
998 * won't make strict RFC952-compliant applications (like us) barf. */
999 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1000 "%s.%s.exit", address, exitname);
1001 tor_snprintf(extendedval, sizeof(extendedval),
1002 "%s.%s.exit", name, exitname);
1003 } else {
1004 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1005 "%s", address);
1006 tor_snprintf(extendedval, sizeof(extendedval),
1007 "%s", name);
1009 addressmap_register(extendedaddress, tor_strdup(extendedval),
1010 time(NULL) + ttl, ADDRMAPSRC_DNS);
1013 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1014 * We can now use this in subsequent streams via addressmap_rewrite()
1015 * so we can more correctly choose an exit that will allow <b>address</b>.
1017 * If <b>exitname</b> is defined, then append the addresses with
1018 * ".exitname.exit" before registering the mapping.
1020 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1021 * <b>ttl</b>seconds; otherwise, we use the default.
1023 void
1024 client_dns_set_addressmap(const char *address, uint32_t val,
1025 const char *exitname,
1026 int ttl)
1028 struct in_addr in;
1029 char valbuf[INET_NTOA_BUF_LEN];
1031 tor_assert(address);
1033 if (tor_inet_aton(address, &in))
1034 return; /* If address was an IP address already, don't add a mapping. */
1035 in.s_addr = htonl(val);
1036 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
1038 client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
1041 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1042 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1044 * If <b>exitname</b> is defined, then append the addresses with
1045 * ".exitname.exit" before registering the mapping.
1047 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1048 * <b>ttl</b>seconds; otherwise, we use the default.
1050 static void
1051 client_dns_set_reverse_addressmap(const char *address, const char *v,
1052 const char *exitname,
1053 int ttl)
1055 size_t len = strlen(address) + 16;
1056 char *s = tor_malloc(len);
1057 tor_snprintf(s, len, "REVERSE[%s]", address);
1058 client_dns_set_addressmap_impl(s, v, exitname, ttl);
1059 tor_free(s);
1062 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1063 * These addresses should map to localhost, so even if the
1064 * application accidentally tried to connect to them directly (not
1065 * via Tor), it wouldn't get too far astray.
1067 * These options are configured by parse_virtual_addr_network().
1069 /** Which network should we use for virtual IPv4 addresses? Only the first
1070 * bits of this value are fixed. */
1071 static uint32_t virtual_addr_network = 0x7fc00000u;
1072 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1073 static maskbits_t virtual_addr_netmask_bits = 10;
1074 /** What's the next virtual address we will hand out? */
1075 static uint32_t next_virtual_addr = 0x7fc00000u;
1077 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1078 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1079 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1080 * string and return -1 on failure. If validate_only is false, sets the
1081 * actual virtual address range to the parsed value. */
1083 parse_virtual_addr_network(const char *val, int validate_only,
1084 char **msg)
1086 uint32_t addr;
1087 uint16_t port_min, port_max;
1088 maskbits_t bits;
1090 if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
1091 if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
1092 return -1;
1095 if (port_min != 1 || port_max != 65535) {
1096 if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
1097 return -1;
1100 if (bits > 16) {
1101 if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
1102 "network or larger");
1103 return -1;
1106 if (validate_only)
1107 return 0;
1109 virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
1110 virtual_addr_netmask_bits = bits;
1112 if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
1113 next_virtual_addr = addr;
1115 return 0;
1119 * Return true iff <b>addr</b> is likely to have been returned by
1120 * client_dns_get_unused_address.
1122 static int
1123 address_is_in_virtual_range(const char *address)
1125 struct in_addr in;
1126 tor_assert(address);
1127 if (!strcasecmpend(address, ".virtual")) {
1128 return 1;
1129 } else if (tor_inet_aton(address, &in)) {
1130 uint32_t addr = ntohl(in.s_addr);
1131 if (!addr_mask_cmp_bits(addr, virtual_addr_network,
1132 virtual_addr_netmask_bits))
1133 return 1;
1135 return 0;
1138 /** Return a newly allocated string holding an address of <b>type</b>
1139 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1140 * and that is very unlikely to be the address of any real host.
1142 static char *
1143 addressmap_get_virtual_address(int type)
1145 char buf[64];
1146 struct in_addr in;
1147 tor_assert(addressmap);
1149 if (type == RESOLVED_TYPE_HOSTNAME) {
1150 char rand[10];
1151 do {
1152 crypto_rand(rand, sizeof(rand));
1153 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
1154 strlcat(buf, ".virtual", sizeof(buf));
1155 } while (strmap_get(addressmap, buf));
1156 return tor_strdup(buf);
1157 } else if (type == RESOLVED_TYPE_IPV4) {
1158 // This is an imperfect estimate of how many addresses are available, but
1159 // that's ok.
1160 uint32_t available = 1u << (32-virtual_addr_netmask_bits);
1161 while (available) {
1162 /* Don't hand out any .0 or .255 address. */
1163 while ((next_virtual_addr & 0xff) == 0 ||
1164 (next_virtual_addr & 0xff) == 0xff) {
1165 ++next_virtual_addr;
1167 in.s_addr = htonl(next_virtual_addr);
1168 tor_inet_ntoa(&in, buf, sizeof(buf));
1169 if (!strmap_get(addressmap, buf)) {
1170 ++next_virtual_addr;
1171 break;
1174 ++next_virtual_addr;
1175 --available;
1176 log_info(LD_CONFIG, "%d addrs available", (int)available);
1177 if (! --available) {
1178 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
1179 return NULL;
1181 if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
1182 virtual_addr_netmask_bits))
1183 next_virtual_addr = virtual_addr_network;
1185 return tor_strdup(buf);
1186 } else {
1187 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
1188 return NULL;
1192 /** A controller has requested that we map some address of type
1193 * <b>type</b> to the address <b>new_address</b>. Choose an address
1194 * that is unlikely to be used, and map it, and return it in a newly
1195 * allocated string. If another address of the same type is already
1196 * mapped to <b>new_address</b>, try to return a copy of that address.
1198 * The string in <b>new_address</b> may be freed, or inserted into a map
1199 * as appropriate.
1201 const char *
1202 addressmap_register_virtual_address(int type, char *new_address)
1204 char **addrp;
1205 virtaddress_entry_t *vent;
1207 tor_assert(new_address);
1208 tor_assert(addressmap);
1209 tor_assert(virtaddress_reversemap);
1211 vent = strmap_get(virtaddress_reversemap, new_address);
1212 if (!vent) {
1213 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
1214 strmap_set(virtaddress_reversemap, new_address, vent);
1217 addrp = (type == RESOLVED_TYPE_IPV4) ?
1218 &vent->ipv4_address : &vent->hostname_address;
1219 if (*addrp) {
1220 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1221 if (ent && ent->new_address &&
1222 !strcasecmp(new_address, ent->new_address)) {
1223 tor_free(new_address);
1224 return tor_strdup(*addrp);
1225 } else
1226 log_warn(LD_BUG,
1227 "Internal confusion: I thought that '%s' was mapped to by "
1228 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1229 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
1230 ent?safe_str(ent->new_address):"(nothing)");
1233 tor_free(*addrp);
1234 *addrp = addressmap_get_virtual_address(type);
1235 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1236 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_CONTROLLER);
1238 #if 0
1240 /* Try to catch possible bugs */
1241 addressmap_entry_t *ent;
1242 ent = strmap_get(addressmap, *addrp);
1243 tor_assert(ent);
1244 tor_assert(!strcasecmp(ent->new_address,new_address));
1245 vent = strmap_get(virtaddress_reversemap, new_address);
1246 tor_assert(vent);
1247 tor_assert(!strcasecmp(*addrp,
1248 (type == RESOLVED_TYPE_IPV4) ?
1249 vent->ipv4_address : vent->hostname_address));
1250 log_info(LD_APP, "Map from %s to %s okay.",
1251 safe_str(*addrp),safe_str(new_address));
1253 #endif
1255 return *addrp;
1258 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1259 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1260 * should be true if we're using this address as a client; false if we're
1261 * using it as a server.
1264 address_is_invalid_destination(const char *address, int client)
1266 if (client) {
1267 if (get_options()->AllowNonRFC953Hostnames)
1268 return 0;
1269 } else {
1270 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1271 return 0;
1274 while (*address) {
1275 if (TOR_ISALNUM(*address) ||
1276 *address == '-' ||
1277 *address == '.' ||
1278 *address == '_') /* Underscore is not allowed, but Windows does it
1279 * sometimes, just to thumb its nose at the IETF. */
1280 ++address;
1281 else
1282 return 1;
1284 return 0;
1287 /** Iterate over all address mappings which have expiry times between
1288 * min_expires and max_expires, inclusive. If sl is provided, add an
1289 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1290 * the expiry time if want_expiry is false. If sl is NULL, remove the
1291 * mappings.
1293 void
1294 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1295 time_t max_expires, int want_expiry)
1297 strmap_iter_t *iter;
1298 const char *key;
1299 void *_val;
1300 addressmap_entry_t *val;
1302 if (!addressmap)
1303 addressmap_init();
1305 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1306 strmap_iter_get(iter, &key, &_val);
1307 val = _val;
1308 if (val->expires >= min_expires && val->expires <= max_expires) {
1309 if (!sl) {
1310 iter = strmap_iter_next_rmv(addressmap,iter);
1311 addressmap_ent_remove(key, val);
1312 continue;
1313 } else if (val->new_address) {
1314 size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
1315 char *line = tor_malloc(len);
1316 if (want_expiry) {
1317 if (val->expires < 3 || val->expires == TIME_MAX)
1318 tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
1319 else {
1320 char time[ISO_TIME_LEN+1];
1321 format_iso_time(time, val->expires);
1322 tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
1323 time);
1325 } else {
1326 tor_snprintf(line, len, "%s %s", key, val->new_address);
1328 smartlist_add(sl, line);
1331 iter = strmap_iter_next(addressmap,iter);
1335 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1336 * reject depending on our config options. */
1337 static int
1338 consider_plaintext_ports(edge_connection_t *conn, uint16_t port)
1340 or_options_t *options = get_options();
1341 int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
1343 if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
1344 log_warn(LD_APP, "Application request to port %d: this port is "
1345 "commonly used for unencrypted protocols. Please make sure "
1346 "you don't send anything you would mind the rest of the "
1347 "Internet reading!%s", port, reject ? " Closing." : "");
1348 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1349 port, reject ? "REJECT" : "WARN");
1352 if (reject) {
1353 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1354 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1355 return -1;
1358 return 0;
1361 /** How many times do we try connecting with an exit configured via
1362 * TrackHostExits before concluding that it won't work any more and trying a
1363 * different one? */
1364 #define TRACKHOSTEXITS_RETRIES 5
1366 /** Connection <b>conn</b> just finished its socks handshake, or the
1367 * controller asked us to take care of it. If <b>circ</b> is defined,
1368 * then that's where we'll want to attach it. Otherwise we have to
1369 * figure it out ourselves.
1371 * First, parse whether it's a .exit address, remap it, and so on. Then
1372 * if it's for a general circuit, try to attach it to a circuit (or launch
1373 * one as needed), else if it's for a rendezvous circuit, fetch a
1374 * rendezvous descriptor first (or attach/launch a circuit if the
1375 * rendezvous descriptor is already here and fresh enough).
1377 * The stream will exit from the hop
1378 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1379 * <b>cpath</b> is NULL.
1382 connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
1383 origin_circuit_t *circ,
1384 crypt_path_t *cpath)
1386 socks_request_t *socks = conn->socks_request;
1387 hostname_type_t addresstype;
1388 or_options_t *options = get_options();
1389 struct in_addr addr_tmp;
1390 int automap = 0;
1391 char orig_address[MAX_SOCKS_ADDR_LEN];
1392 time_t map_expires = TIME_MAX;
1393 int remapped_to_exit = 0;
1394 time_t now = time(NULL);
1396 tor_strlower(socks->address); /* normalize it */
1397 strlcpy(orig_address, socks->address, sizeof(orig_address));
1398 log_debug(LD_APP,"Client asked for %s:%d",
1399 safe_str(socks->address),
1400 socks->port);
1402 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1403 !tor_inet_aton(socks->address, &addr_tmp) &&
1404 options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
1405 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
1406 if (!strcasecmpend(socks->address, cp)) {
1407 automap = 1;
1408 break;
1410 if (automap) {
1411 const char *new_addr;
1412 new_addr = addressmap_register_virtual_address(
1413 RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
1414 tor_assert(new_addr);
1415 log_info(LD_APP, "Automapping %s to %s",
1416 escaped_safe_str(socks->address), safe_str(new_addr));
1417 strlcpy(socks->address, new_addr, sizeof(socks->address));
1421 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1422 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1423 &map_expires)) {
1424 char *result = tor_strdup(socks->address);
1425 /* remember _what_ is supposed to have been resolved. */
1426 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1427 orig_address);
1428 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1429 strlen(result), result, -1,
1430 map_expires);
1431 connection_mark_unattached_ap(conn,
1432 END_STREAM_REASON_DONE |
1433 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1434 return 0;
1436 if (options->ClientDNSRejectInternalAddresses) {
1437 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1438 tor_addr_t addr;
1439 int ok;
1440 ok = tor_addr_parse_reverse_lookup_name(
1441 &addr, socks->address, AF_UNSPEC, 1);
1442 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1443 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1444 0, NULL, -1, TIME_MAX);
1445 connection_mark_unattached_ap(conn,
1446 END_STREAM_REASON_SOCKSPROTOCOL |
1447 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1448 return -1;
1451 } else if (!automap) {
1452 int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
1453 /* For address map controls, remap the address. */
1454 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1455 &map_expires)) {
1456 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1457 REMAP_STREAM_SOURCE_CACHE);
1458 if (started_without_chosen_exit &&
1459 !strcasecmpend(socks->address, ".exit") &&
1460 map_expires < TIME_MAX)
1461 remapped_to_exit = 1;
1465 if (!automap && address_is_in_virtual_range(socks->address)) {
1466 /* This address was probably handed out by client_dns_get_unmapped_address,
1467 * but the mapping was discarded for some reason. We *don't* want to send
1468 * the address through Tor; that's likely to fail, and may leak
1469 * information.
1471 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1472 socks->address); /* don't safe_str() this yet. */
1473 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
1474 return -1;
1477 /* Parse the address provided by SOCKS. Modify it in-place if it
1478 * specifies a hidden-service (.onion) or particular exit node (.exit).
1480 addresstype = parse_extended_hostname(socks->address);
1482 if (addresstype == BAD_HOSTNAME) {
1483 log_warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
1484 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1485 escaped(socks->address));
1486 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1487 return -1;
1490 if (addresstype == EXIT_HOSTNAME) {
1491 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1492 * node, and conn->address to hold only the address portion.*/
1493 char *s = strrchr(socks->address,'.');
1494 tor_assert(!automap);
1495 if (s) {
1496 if (s[1] != '\0') {
1497 conn->chosen_exit_name = tor_strdup(s+1);
1498 if (remapped_to_exit) /* 5 tries before it expires the addressmap */
1499 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1500 *s = 0;
1501 } else {
1502 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1503 safe_str(socks->address));
1504 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1505 escaped(socks->address));
1506 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1507 return -1;
1509 } else {
1510 routerinfo_t *r;
1511 conn->chosen_exit_name = tor_strdup(socks->address);
1512 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1513 *socks->address = 0;
1514 if (r) {
1515 strlcpy(socks->address, r->address, sizeof(socks->address));
1516 } else {
1517 log_warn(LD_APP,
1518 "Unrecognized server in exit address '%s.exit'. Refusing.",
1519 safe_str(socks->address));
1520 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1521 return -1;
1526 if (addresstype != ONION_HOSTNAME) {
1527 /* not a hidden-service request (i.e. normal or .exit) */
1528 if (address_is_invalid_destination(socks->address, 1)) {
1529 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1530 escaped(socks->address));
1531 log_warn(LD_APP,
1532 "Destination '%s' seems to be an invalid hostname. Failing.",
1533 safe_str(socks->address));
1534 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1535 return -1;
1538 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1539 uint32_t answer;
1540 struct in_addr in;
1541 /* Reply to resolves immediately if we can. */
1542 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
1543 log_warn(LD_APP,"Address to be resolved is too large. Failing.");
1544 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1545 escaped(socks->address));
1546 connection_ap_handshake_socks_resolved(conn,
1547 RESOLVED_TYPE_ERROR_TRANSIENT,
1548 0,NULL,-1,TIME_MAX);
1549 connection_mark_unattached_ap(conn,
1550 END_STREAM_REASON_SOCKSPROTOCOL |
1551 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1552 return -1;
1554 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1555 /* leave it in network order */
1556 answer = in.s_addr;
1557 /* remember _what_ is supposed to have been resolved. */
1558 strlcpy(socks->address, orig_address, sizeof(socks->address));
1559 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1560 (char*)&answer,-1,map_expires);
1561 connection_mark_unattached_ap(conn,
1562 END_STREAM_REASON_DONE |
1563 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1564 return 0;
1566 tor_assert(!automap);
1567 rep_hist_note_used_resolve(now); /* help predict this next time */
1568 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1569 tor_assert(!automap);
1570 if (socks->port == 0) {
1571 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1572 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1573 return -1;
1576 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1577 /* see if we can find a suitable enclave exit */
1578 routerinfo_t *r =
1579 router_find_exact_exit_enclave(socks->address, socks->port);
1580 if (r) {
1581 log_info(LD_APP,
1582 "Redirecting address %s to exit at enclave router %s",
1583 safe_str(socks->address), r->nickname);
1584 /* use the hex digest, not nickname, in case there are two
1585 routers with this nickname */
1586 conn->chosen_exit_name =
1587 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1588 conn->chosen_exit_optional = 1;
1592 /* warn or reject if it's using a dangerous port */
1593 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1594 if (consider_plaintext_ports(conn, socks->port) < 0)
1595 return -1;
1597 if (!conn->use_begindir) {
1598 /* help predict this next time */
1599 rep_hist_note_used_port(now, socks->port);
1601 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1602 rep_hist_note_used_resolve(now); /* help predict this next time */
1603 /* no extra processing needed */
1604 } else {
1605 tor_fragile_assert();
1607 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1608 if ((circ && connection_ap_handshake_attach_chosen_circuit(
1609 conn, circ, cpath) < 0) ||
1610 (!circ &&
1611 connection_ap_handshake_attach_circuit(conn) < 0)) {
1612 if (!conn->_base.marked_for_close)
1613 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1614 return -1;
1616 return 0;
1617 } else {
1618 /* it's a hidden-service request */
1619 rend_cache_entry_t *entry;
1620 int r;
1621 rend_service_authorization_t *client_auth;
1622 tor_assert(!automap);
1623 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1624 /* if it's a resolve request, fail it right now, rather than
1625 * building all the circuits and then realizing it won't work. */
1626 log_warn(LD_APP,
1627 "Resolve requests to hidden services not allowed. Failing.");
1628 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1629 0,NULL,-1,TIME_MAX);
1630 connection_mark_unattached_ap(conn,
1631 END_STREAM_REASON_SOCKSPROTOCOL |
1632 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1633 return -1;
1636 if (circ) {
1637 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1638 "supported for .onion addresses currently. Failing.");
1639 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1640 return -1;
1643 conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1644 strlcpy(conn->rend_data->onion_address, socks->address,
1645 sizeof(conn->rend_data->onion_address));
1646 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1647 safe_str(conn->rend_data->onion_address));
1648 /* see if we already have it cached */
1649 r = rend_cache_lookup_entry(conn->rend_data->onion_address, -1, &entry);
1650 if (r<0) {
1651 log_warn(LD_BUG,"Invalid service name '%s'",
1652 safe_str(conn->rend_data->onion_address));
1653 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1654 return -1;
1657 /* Help predict this next time. We're not sure if it will need
1658 * a stable circuit yet, but we know we'll need *something*. */
1659 rep_hist_note_used_internal(now, 0, 1);
1661 /* Look up if we have client authorization for it. */
1662 client_auth = rend_client_lookup_service_authorization(
1663 conn->rend_data->onion_address);
1664 if (client_auth) {
1665 log_info(LD_REND, "Using previously configured client authorization "
1666 "for hidden service request.");
1667 memcpy(conn->rend_data->descriptor_cookie,
1668 client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
1669 conn->rend_data->auth_type = client_auth->auth_type;
1671 if (r==0) {
1672 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1673 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1674 safe_str(conn->rend_data->onion_address));
1675 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1676 * arrives first. Exception: When using client authorization, only
1677 * fetch v2 descriptors.*/
1678 rend_client_refetch_v2_renddesc(conn->rend_data);
1679 if (conn->rend_data->auth_type == REND_NO_AUTH)
1680 rend_client_refetch_renddesc(conn->rend_data->onion_address);
1681 } else { /* r > 0 */
1682 /** How long after we receive a hidden service descriptor do we consider
1683 * it valid? */
1684 #define NUM_SECONDS_BEFORE_HS_REFETCH (60*15)
1685 if (now - entry->received < NUM_SECONDS_BEFORE_HS_REFETCH) {
1686 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1687 log_info(LD_REND, "Descriptor is here and fresh enough. Great.");
1688 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1689 if (!conn->_base.marked_for_close)
1690 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1691 return -1;
1693 } else {
1694 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1695 log_info(LD_REND, "Stale descriptor %s. Refetching.",
1696 safe_str(conn->rend_data->onion_address));
1697 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1698 * arrives first. Exception: When using client authorization, only
1699 * fetch v2 descriptors.*/
1700 rend_client_refetch_v2_renddesc(conn->rend_data);
1701 if (conn->rend_data->auth_type == REND_NO_AUTH)
1702 rend_client_refetch_renddesc(conn->rend_data->onion_address);
1705 return 0;
1707 return 0; /* unreached but keeps the compiler happy */
1710 #ifdef TRANS_PF
1711 static int pf_socket = -1;
1713 get_pf_socket(void)
1715 int pf;
1716 /* This should be opened before dropping privs. */
1717 if (pf_socket >= 0)
1718 return pf_socket;
1720 #ifdef OPENBSD
1721 /* only works on OpenBSD */
1722 pf = open("/dev/pf", O_RDONLY);
1723 #else
1724 /* works on NetBSD and FreeBSD */
1725 pf = open("/dev/pf", O_RDWR);
1726 #endif
1728 if (pf < 0) {
1729 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1730 return -1;
1733 pf_socket = pf;
1734 return pf_socket;
1736 #endif
1738 /** Fetch the original destination address and port from a
1739 * system-specific interface and put them into a
1740 * socks_request_t as if they came from a socks request.
1742 * Return -1 if an error prevents fetching the destination,
1743 * else return 0.
1745 static int
1746 connection_ap_get_original_destination(edge_connection_t *conn,
1747 socks_request_t *req)
1749 #ifdef TRANS_NETFILTER
1750 /* Linux 2.4+ */
1751 struct sockaddr_storage orig_dst;
1752 socklen_t orig_dst_len = sizeof(orig_dst);
1753 tor_addr_t addr;
1755 if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
1756 (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
1757 int e = tor_socket_errno(conn->_base.s);
1758 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1759 return -1;
1762 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1763 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1765 return 0;
1766 #elif defined(TRANS_PF)
1767 struct sockaddr_storage proxy_addr;
1768 socklen_t proxy_addr_len = sizeof(proxy_addr);
1769 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1770 struct pfioc_natlook pnl;
1771 tor_addr_t addr;
1772 int pf = -1;
1774 if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
1775 &proxy_addr_len) < 0) {
1776 int e = tor_socket_errno(conn->_base.s);
1777 log_warn(LD_NET, "getsockname() to determine transocks destination "
1778 "failed: %s", tor_socket_strerror(e));
1779 return -1;
1782 memset(&pnl, 0, sizeof(pnl));
1783 pnl.proto = IPPROTO_TCP;
1784 pnl.direction = PF_OUT;
1785 if (proxy_sa->sa_family == AF_INET) {
1786 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1787 pnl.af = AF_INET;
1788 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&conn->_base.addr);
1789 pnl.sport = htons(conn->_base.port);
1790 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1791 pnl.dport = sin->sin_port;
1792 } else if (proxy_sa->sa_family == AF_INET6) {
1793 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1794 pnl.af = AF_INET6;
1795 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&conn->_base.addr),
1796 sizeof(struct in6_addr));
1797 pnl.sport = htons(conn->_base.port);
1798 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1799 pnl.dport = sin6->sin6_port;
1800 } else {
1801 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1802 (int)proxy_sa->sa_family);
1803 return -1;
1806 pf = get_pf_socket();
1807 if (pf<0)
1808 return -1;
1810 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1811 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1812 return -1;
1815 if (pnl.af == AF_INET) {
1816 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1817 } else if (pnl.af == AF_INET6) {
1818 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1819 } else {
1820 tor_fragile_assert();
1821 return -1;
1824 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1825 req->port = ntohs(pnl.rdport);
1827 return 0;
1828 #else
1829 (void)conn;
1830 (void)req;
1831 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1832 "transparent proxy method was configured.");
1833 return -1;
1834 #endif
1837 /** connection_edge_process_inbuf() found a conn in state
1838 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1839 * the socks handshake.
1841 * If the handshake is complete, send it to
1842 * connection_ap_handshake_rewrite_and_attach().
1844 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1845 * else return 0.
1847 static int
1848 connection_ap_handshake_process_socks(edge_connection_t *conn)
1850 socks_request_t *socks;
1851 int sockshere;
1852 or_options_t *options = get_options();
1854 tor_assert(conn);
1855 tor_assert(conn->_base.type == CONN_TYPE_AP);
1856 tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
1857 tor_assert(conn->socks_request);
1858 socks = conn->socks_request;
1860 log_debug(LD_APP,"entered.");
1862 sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
1863 options->TestSocks, options->SafeSocks);
1864 if (sockshere == 0) {
1865 if (socks->replylen) {
1866 connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
1867 /* zero it out so we can do another round of negotiation */
1868 socks->replylen = 0;
1869 } else {
1870 log_debug(LD_APP,"socks handshake not all here yet.");
1872 return 0;
1873 } else if (sockshere == -1) {
1874 if (socks->replylen) { /* we should send reply back */
1875 log_debug(LD_APP,"reply is already set for us. Using it.");
1876 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1877 END_STREAM_REASON_SOCKSPROTOCOL);
1879 } else {
1880 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
1881 connection_ap_handshake_socks_reply(conn, NULL, 0,
1882 END_STREAM_REASON_SOCKSPROTOCOL);
1884 connection_mark_unattached_ap(conn,
1885 END_STREAM_REASON_SOCKSPROTOCOL |
1886 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1887 return -1;
1888 } /* else socks handshake is done, continue processing */
1890 if (hostname_is_noconnect_address(socks->address))
1892 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1893 control_event_stream_status(conn, STREAM_EVENT_CLOSED, 0);
1894 connection_mark_unattached_ap(conn, END_STREAM_REASON_DONE);
1895 return -1;
1898 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
1899 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1900 else
1901 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
1903 if (options->LeaveStreamsUnattached) {
1904 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1905 return 0;
1907 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1910 /** connection_init_accepted_conn() found a new trans AP conn.
1911 * Get the original destination and send it to
1912 * connection_ap_handshake_rewrite_and_attach().
1914 * Return -1 if an unexpected error with conn (and it should be marked
1915 * for close), else return 0.
1918 connection_ap_process_transparent(edge_connection_t *conn)
1920 socks_request_t *socks;
1921 or_options_t *options = get_options();
1923 tor_assert(conn);
1924 tor_assert(conn->_base.type == CONN_TYPE_AP);
1925 tor_assert(conn->socks_request);
1926 socks = conn->socks_request;
1928 /* pretend that a socks handshake completed so we don't try to
1929 * send a socks reply down a transparent conn */
1930 socks->command = SOCKS_COMMAND_CONNECT;
1931 socks->has_finished = 1;
1933 log_debug(LD_APP,"entered.");
1935 if (connection_ap_get_original_destination(conn, socks) < 0) {
1936 log_warn(LD_APP,"Fetching original destination failed. Closing.");
1937 connection_mark_unattached_ap(conn,
1938 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
1939 return -1;
1941 /* we have the original destination */
1943 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1945 if (options->LeaveStreamsUnattached) {
1946 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1947 return 0;
1949 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1952 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1953 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1954 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1955 * form of the original destination.
1957 * If the original destination is complete, send it to
1958 * connection_ap_handshake_rewrite_and_attach().
1960 * Return -1 if an unexpected error with conn (and it should be marked
1961 * for close), else return 0.
1963 static int
1964 connection_ap_process_natd(edge_connection_t *conn)
1966 char tmp_buf[36], *tbuf, *daddr;
1967 size_t tlen = 30;
1968 int err, port_ok;
1969 socks_request_t *socks;
1970 or_options_t *options = get_options();
1972 tor_assert(conn);
1973 tor_assert(conn->_base.type == CONN_TYPE_AP);
1974 tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
1975 tor_assert(conn->socks_request);
1976 socks = conn->socks_request;
1978 log_debug(LD_APP,"entered.");
1980 /* look for LF-terminated "[DEST ip_addr port]"
1981 * where ip_addr is a dotted-quad and port is in string form */
1982 err = fetch_from_buf_line(conn->_base.inbuf, tmp_buf, &tlen);
1983 if (err == 0)
1984 return 0;
1985 if (err < 0) {
1986 log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
1987 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1988 return -1;
1991 if (strcmpstart(tmp_buf, "[DEST ")) {
1992 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1993 "said: %s",
1994 escaped(tmp_buf));
1995 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1996 return -1;
1999 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2000 if (!(tbuf = strchr(tbuf, ' '))) {
2001 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
2002 "said: %s",
2003 escaped(tmp_buf));
2004 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2005 return -1;
2007 *tbuf++ = '\0';
2009 /* pretend that a socks handshake completed so we don't try to
2010 * send a socks reply down a natd conn */
2011 strlcpy(socks->address, daddr, sizeof(socks->address));
2012 socks->port = (uint16_t)
2013 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2014 if (!port_ok) {
2015 log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
2016 "of range.", escaped(tbuf));
2017 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2018 return -1;
2021 socks->command = SOCKS_COMMAND_CONNECT;
2022 socks->has_finished = 1;
2024 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2026 if (options->LeaveStreamsUnattached) {
2027 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2028 return 0;
2030 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2032 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
2035 /** Iterate over the two bytes of stream_id until we get one that is not
2036 * already in use; return it. Return 0 if can't get a unique stream_id.
2038 static streamid_t
2039 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2041 edge_connection_t *tmpconn;
2042 streamid_t test_stream_id;
2043 uint32_t attempts=0;
2045 again:
2046 test_stream_id = circ->next_stream_id++;
2047 if (++attempts > 1<<16) {
2048 /* Make sure we don't loop forever if all stream_id's are used. */
2049 log_warn(LD_APP,"No unused stream IDs. Failing.");
2050 return 0;
2052 if (test_stream_id == 0)
2053 goto again;
2054 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2055 if (tmpconn->stream_id == test_stream_id)
2056 goto again;
2057 return test_stream_id;
2060 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2061 * socks_request field, and send it down circ.
2063 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2066 connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
2068 char payload[CELL_PAYLOAD_SIZE];
2069 int payload_len;
2070 int begin_type;
2071 origin_circuit_t *circ;
2072 tor_assert(ap_conn->on_circuit);
2073 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2075 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2076 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2077 tor_assert(ap_conn->socks_request);
2078 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2080 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2081 if (ap_conn->stream_id==0) {
2082 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2083 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2084 return -1;
2087 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2088 (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2089 ap_conn->socks_request->address : "",
2090 ap_conn->socks_request->port);
2091 payload_len = (int)strlen(payload)+1;
2093 log_debug(LD_APP,
2094 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2096 begin_type = ap_conn->use_begindir ?
2097 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2098 if (begin_type == RELAY_COMMAND_BEGIN) {
2099 tor_assert(circ->build_state->onehop_tunnel == 0);
2102 if (connection_edge_send_command(ap_conn, begin_type,
2103 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2104 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2105 return -1; /* circuit is closed, don't continue */
2107 ap_conn->package_window = STREAMWINDOW_START;
2108 ap_conn->deliver_window = STREAMWINDOW_START;
2109 ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
2110 log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
2111 ap_conn->_base.s, circ->_base.n_circ_id);
2112 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2113 return 0;
2116 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2117 * socks_request field, and send it down circ.
2119 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2122 connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
2124 int payload_len, command;
2125 const char *string_addr;
2126 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2127 origin_circuit_t *circ;
2128 tor_assert(ap_conn->on_circuit);
2129 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2131 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2132 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2133 tor_assert(ap_conn->socks_request);
2134 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2136 command = ap_conn->socks_request->command;
2137 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2139 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2140 if (ap_conn->stream_id==0) {
2141 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2142 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2143 return -1;
2146 if (command == SOCKS_COMMAND_RESOLVE) {
2147 string_addr = ap_conn->socks_request->address;
2148 payload_len = (int)strlen(string_addr)+1;
2149 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
2150 } else {
2151 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2152 const char *a = ap_conn->socks_request->address;
2153 tor_addr_t addr;
2154 int r;
2156 /* We're doing a reverse lookup. The input could be an IP address, or
2157 * could be an .in-addr.arpa or .ip6.arpa address */
2158 r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
2159 if (r <= 0) {
2160 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2161 safe_str(a));
2162 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2163 return -1;
2166 r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2167 if (r < 0) {
2168 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2169 safe_str(a));
2170 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2171 return -1;
2174 string_addr = inaddr_buf;
2175 payload_len = (int)strlen(inaddr_buf)+1;
2176 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
2179 log_debug(LD_APP,
2180 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2182 if (connection_edge_send_command(ap_conn,
2183 RELAY_COMMAND_RESOLVE,
2184 string_addr, payload_len) < 0)
2185 return -1; /* circuit is closed, don't continue */
2187 tor_free(ap_conn->_base.address); /* Maybe already set by dnsserv. */
2188 ap_conn->_base.address = tor_strdup("(Tor_internal)");
2189 ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
2190 log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
2191 ap_conn->_base.s, circ->_base.n_circ_id);
2192 control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
2193 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2194 return 0;
2197 /** Make an AP connection_t, make a new linked connection pair, and attach
2198 * one side to the conn, connection_add it, initialize it to circuit_wait,
2199 * and call connection_ap_handshake_attach_circuit(conn) on it.
2201 * Return the other end of the linked connection pair, or -1 if error.
2203 edge_connection_t *
2204 connection_ap_make_link(char *address, uint16_t port,
2205 const char *digest, int use_begindir, int want_onehop)
2207 edge_connection_t *conn;
2209 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2210 want_onehop ? "direct" : "anonymized" , safe_str(address),port);
2212 conn = edge_connection_new(CONN_TYPE_AP, AF_INET);
2213 conn->_base.linked = 1; /* so that we can add it safely below. */
2215 /* populate conn->socks_request */
2217 /* leave version at zero, so the socks_reply is empty */
2218 conn->socks_request->socks_version = 0;
2219 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2220 strlcpy(conn->socks_request->address, address,
2221 sizeof(conn->socks_request->address));
2222 conn->socks_request->port = port;
2223 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2224 conn->want_onehop = want_onehop;
2225 conn->use_begindir = use_begindir;
2226 if (use_begindir) {
2227 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2228 conn->chosen_exit_name[0] = '$';
2229 tor_assert(digest);
2230 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2231 digest, DIGEST_LEN);
2234 conn->_base.address = tor_strdup("(Tor_internal)");
2235 tor_addr_make_unspec(&conn->_base.addr);
2236 conn->_base.port = 0;
2238 if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
2239 connection_free(TO_CONN(conn));
2240 return NULL;
2243 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2245 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2247 /* attaching to a dirty circuit is fine */
2248 if (connection_ap_handshake_attach_circuit(conn) < 0) {
2249 if (!conn->_base.marked_for_close)
2250 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2251 return NULL;
2254 log_info(LD_APP,"... application connection created and linked.");
2255 return conn;
2258 /** Notify any interested controller connections about a new hostname resolve
2259 * or resolve error. Takes the same arguments as does
2260 * connection_ap_handshake_socks_resolved(). */
2261 static void
2262 tell_controller_about_resolved_result(edge_connection_t *conn,
2263 int answer_type,
2264 size_t answer_len,
2265 const char *answer,
2266 int ttl,
2267 time_t expires)
2270 if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
2271 answer_type == RESOLVED_TYPE_HOSTNAME)) {
2272 return; /* we already told the controller. */
2273 } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2274 struct in_addr in;
2275 char buf[INET_NTOA_BUF_LEN];
2276 in.s_addr = get_uint32(answer);
2277 tor_inet_ntoa(&in, buf, sizeof(buf));
2278 control_event_address_mapped(conn->socks_request->address,
2279 buf, expires, NULL);
2280 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len <256) {
2281 char *cp = tor_strndup(answer, answer_len);
2282 control_event_address_mapped(conn->socks_request->address,
2283 cp, expires, NULL);
2284 tor_free(cp);
2285 } else {
2286 control_event_address_mapped(conn->socks_request->address,
2287 "<error>",
2288 time(NULL)+ttl,
2289 "error=yes");
2293 /** Send an answer to an AP connection that has requested a DNS lookup via
2294 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2295 * for unreachable; the answer should be in the format specified in the socks
2296 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2297 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2298 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2300 /* XXXX021 the use of the ttl and expires fields is nutty. Let's make this
2301 * interface and those that use it less ugly. */
2302 void
2303 connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2304 int answer_type,
2305 size_t answer_len,
2306 const char *answer,
2307 int ttl,
2308 time_t expires)
2310 char buf[384];
2311 size_t replylen;
2313 if (ttl >= 0) {
2314 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2315 uint32_t a = ntohl(get_uint32(answer));
2316 if (a)
2317 client_dns_set_addressmap(conn->socks_request->address, a,
2318 conn->chosen_exit_name, ttl);
2319 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2320 char *cp = tor_strndup(answer, answer_len);
2321 client_dns_set_reverse_addressmap(conn->socks_request->address,
2323 conn->chosen_exit_name, ttl);
2324 tor_free(cp);
2328 if (conn->is_dns_request) {
2329 if (conn->dns_server_request) {
2330 /* We had a request on our DNS port: answer it. */
2331 dnsserv_resolved(conn, answer_type, answer_len, answer, ttl);
2332 conn->socks_request->has_finished = 1;
2333 return;
2334 } else {
2335 /* This must be a request from the controller. We already sent
2336 * a mapaddress if there's a ttl. */
2337 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2338 answer, ttl, expires);
2339 conn->socks_request->has_finished = 1;
2340 return;
2342 /* We shouldn't need to free conn here; it gets marked by the caller. */
2345 if (conn->socks_request->socks_version == 4) {
2346 buf[0] = 0x00; /* version */
2347 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2348 buf[1] = SOCKS4_GRANTED;
2349 set_uint16(buf+2, 0);
2350 memcpy(buf+4, answer, 4); /* address */
2351 replylen = SOCKS4_NETWORK_LEN;
2352 } else { /* "error" */
2353 buf[1] = SOCKS4_REJECT;
2354 memset(buf+2, 0, 6);
2355 replylen = SOCKS4_NETWORK_LEN;
2357 } else if (conn->socks_request->socks_version == 5) {
2358 /* SOCKS5 */
2359 buf[0] = 0x05; /* version */
2360 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2361 buf[1] = SOCKS5_SUCCEEDED;
2362 buf[2] = 0; /* reserved */
2363 buf[3] = 0x01; /* IPv4 address type */
2364 memcpy(buf+4, answer, 4); /* address */
2365 set_uint16(buf+8, 0); /* port == 0. */
2366 replylen = 10;
2367 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2368 buf[1] = SOCKS5_SUCCEEDED;
2369 buf[2] = 0; /* reserved */
2370 buf[3] = 0x04; /* IPv6 address type */
2371 memcpy(buf+4, answer, 16); /* address */
2372 set_uint16(buf+20, 0); /* port == 0. */
2373 replylen = 22;
2374 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2375 buf[1] = SOCKS5_SUCCEEDED;
2376 buf[2] = 0; /* reserved */
2377 buf[3] = 0x03; /* Domainname address type */
2378 buf[4] = (char)answer_len;
2379 memcpy(buf+5, answer, answer_len); /* address */
2380 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2381 replylen = 5+answer_len+2;
2382 } else {
2383 buf[1] = SOCKS5_HOST_UNREACHABLE;
2384 memset(buf+2, 0, 8);
2385 replylen = 10;
2387 } else {
2388 /* no socks version info; don't send anything back */
2389 return;
2391 connection_ap_handshake_socks_reply(conn, buf, replylen,
2392 (answer_type == RESOLVED_TYPE_IPV4 ||
2393 answer_type == RESOLVED_TYPE_IPV6) ?
2394 0 : END_STREAM_REASON_RESOLVEFAILED);
2397 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2398 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2399 * handshaking.
2401 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2402 * and return, else reply based on <b>endreason</b> (one of
2403 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2404 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2406 void
2407 connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2408 size_t replylen, int endreason)
2410 char buf[256];
2411 socks5_reply_status_t status =
2412 stream_end_reason_to_socks5_response(endreason);
2414 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2416 control_event_stream_status(conn,
2417 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2418 endreason);
2420 if (conn->socks_request->has_finished) {
2421 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2422 "connection_ap_handshake_socks_reply.");
2423 return;
2425 if (replylen) { /* we already have a reply in mind */
2426 connection_write_to_buf(reply, replylen, TO_CONN(conn));
2427 conn->socks_request->has_finished = 1;
2428 return;
2430 if (conn->socks_request->socks_version == 4) {
2431 memset(buf,0,SOCKS4_NETWORK_LEN);
2432 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2433 /* leave version, destport, destip zero */
2434 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
2435 } else if (conn->socks_request->socks_version == 5) {
2436 buf[0] = 5; /* version 5 */
2437 buf[1] = (char)status;
2438 buf[2] = 0;
2439 buf[3] = 1; /* ipv4 addr */
2440 memset(buf+4,0,6); /* Set external addr/port to 0.
2441 The spec doesn't seem to say what to do here. -RD */
2442 connection_write_to_buf(buf,10,TO_CONN(conn));
2444 /* If socks_version isn't 4 or 5, don't send anything.
2445 * This can happen in the case of AP bridges. */
2446 conn->socks_request->has_finished = 1;
2447 return;
2450 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2451 * an exit hop for the circuit, or we are the origin and it is a
2452 * rendezvous begin.
2454 * Launch a new exit connection and initialize things appropriately.
2456 * If it's a rendezvous stream, call connection_exit_connect() on
2457 * it.
2459 * For general streams, call dns_resolve() on it first, and only call
2460 * connection_exit_connect() if the dns answer is already known.
2462 * Note that we don't call connection_add() on the new stream! We wait
2463 * for connection_exit_connect() to do that.
2465 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2466 * Else return 0.
2469 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2471 edge_connection_t *n_stream;
2472 relay_header_t rh;
2473 char *address=NULL;
2474 uint16_t port;
2475 or_circuit_t *or_circ = NULL;
2477 assert_circuit_ok(circ);
2478 if (!CIRCUIT_IS_ORIGIN(circ))
2479 or_circ = TO_OR_CIRCUIT(circ);
2481 relay_header_unpack(&rh, cell->payload);
2483 /* Note: we have to use relay_send_command_from_edge here, not
2484 * connection_edge_end or connection_edge_send_command, since those require
2485 * that we have a stream connected to a circuit, and we don't connect to a
2486 * circuit until we have a pending/successful resolve. */
2488 if (!server_mode(get_options()) &&
2489 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2490 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2491 "Relay begin cell at non-server. Closing.");
2492 relay_send_end_cell_from_edge(rh.stream_id, circ,
2493 END_STREAM_REASON_EXITPOLICY, NULL);
2494 return 0;
2497 if (rh.command == RELAY_COMMAND_BEGIN) {
2498 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
2499 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2500 "Relay begin cell has no \\0. Closing.");
2501 relay_send_end_cell_from_edge(rh.stream_id, circ,
2502 END_STREAM_REASON_TORPROTOCOL, NULL);
2503 return 0;
2505 if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
2506 &address,NULL,&port)<0) {
2507 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2508 "Unable to parse addr:port in relay begin cell. Closing.");
2509 relay_send_end_cell_from_edge(rh.stream_id, circ,
2510 END_STREAM_REASON_TORPROTOCOL, NULL);
2511 return 0;
2513 if (port==0) {
2514 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2515 "Missing port in relay begin cell. Closing.");
2516 relay_send_end_cell_from_edge(rh.stream_id, circ,
2517 END_STREAM_REASON_TORPROTOCOL, NULL);
2518 tor_free(address);
2519 return 0;
2521 if (or_circ && or_circ->is_first_hop &&
2522 !get_options()->AllowSingleHopExits) {
2523 /* Don't let clients use us as a single-hop proxy, unless the user
2524 * has explicitly allowed that in the config. It attracts attackers
2525 * and users who'd be better off with, well, single-hop proxies.
2527 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2528 "Attempt to open a stream on first hop of circuit. Closing.");
2529 relay_send_end_cell_from_edge(rh.stream_id, circ,
2530 END_STREAM_REASON_TORPROTOCOL, NULL);
2531 tor_free(address);
2532 return 0;
2534 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2535 if (!directory_permits_begindir_requests(get_options()) ||
2536 circ->purpose != CIRCUIT_PURPOSE_OR) {
2537 relay_send_end_cell_from_edge(rh.stream_id, circ,
2538 END_STREAM_REASON_NOTDIRECTORY, NULL);
2539 return 0;
2541 if (or_circ && or_circ->p_conn && or_circ->p_conn->_base.address)
2542 address = tor_strdup(or_circ->p_conn->_base.address);
2543 else
2544 address = tor_strdup("127.0.0.1");
2545 port = 1; /* XXXX This value is never actually used anywhere, and there
2546 * isn't "really" a connection here. But we
2547 * need to set it to something nonzero. */
2548 } else {
2549 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2550 relay_send_end_cell_from_edge(rh.stream_id, circ,
2551 END_STREAM_REASON_INTERNAL, NULL);
2552 return 0;
2555 log_debug(LD_EXIT,"Creating new exit connection.");
2556 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2557 n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
2559 n_stream->stream_id = rh.stream_id;
2560 n_stream->_base.port = port;
2561 /* leave n_stream->s at -1, because it's not yet valid */
2562 n_stream->package_window = STREAMWINDOW_START;
2563 n_stream->deliver_window = STREAMWINDOW_START;
2565 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
2566 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2567 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
2568 n_stream->_base.address = tor_strdup("(rendezvous)");
2569 n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
2570 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
2571 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
2572 assert_circuit_ok(circ);
2573 if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
2574 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
2575 n_stream->_base.port);
2576 relay_send_end_cell_from_edge(rh.stream_id, circ,
2577 END_STREAM_REASON_EXITPOLICY,
2578 origin_circ->cpath->prev);
2579 connection_free(TO_CONN(n_stream));
2580 tor_free(address);
2581 return 0;
2583 assert_circuit_ok(circ);
2584 log_debug(LD_REND,"Finished assigning addr/port");
2585 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
2587 /* add it into the linked list of n_streams on this circuit */
2588 n_stream->next_stream = origin_circ->p_streams;
2589 n_stream->on_circuit = circ;
2590 origin_circ->p_streams = n_stream;
2591 assert_circuit_ok(circ);
2593 connection_exit_connect(n_stream);
2594 tor_free(address);
2595 return 0;
2597 tor_strlower(address);
2598 n_stream->_base.address = address;
2599 n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2600 /* default to failed, change in dns_resolve if it turns out not to fail */
2602 if (we_are_hibernating()) {
2603 relay_send_end_cell_from_edge(rh.stream_id, circ,
2604 END_STREAM_REASON_HIBERNATING, NULL);
2605 connection_free(TO_CONN(n_stream));
2606 return 0;
2609 n_stream->on_circuit = circ;
2611 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2612 tor_assert(or_circ);
2613 if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->_base.addr))
2614 n_stream->_base.addr = or_circ->p_conn->_base.addr;
2615 return connection_exit_connect_dir(n_stream);
2618 log_debug(LD_EXIT,"about to start the dns_resolve().");
2620 /* send it off to the gethostbyname farm */
2621 switch (dns_resolve(n_stream)) {
2622 case 1: /* resolve worked; now n_stream is attached to circ. */
2623 assert_circuit_ok(circ);
2624 log_debug(LD_EXIT,"about to call connection_exit_connect().");
2625 connection_exit_connect(n_stream);
2626 return 0;
2627 case -1: /* resolve failed */
2628 relay_send_end_cell_from_edge(rh.stream_id, circ,
2629 END_STREAM_REASON_RESOLVEFAILED, NULL);
2630 /* n_stream got freed. don't touch it. */
2631 break;
2632 case 0: /* resolve added to pending list */
2633 assert_circuit_ok(circ);
2634 break;
2636 return 0;
2640 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2641 * circuit <b>circ</b>;
2642 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2645 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
2647 edge_connection_t *dummy_conn;
2648 relay_header_t rh;
2650 assert_circuit_ok(TO_CIRCUIT(circ));
2651 relay_header_unpack(&rh, cell->payload);
2653 /* This 'dummy_conn' only exists to remember the stream ID
2654 * associated with the resolve request; and to make the
2655 * implementation of dns.c more uniform. (We really only need to
2656 * remember the circuit, the stream ID, and the hostname to be
2657 * resolved; but if we didn't store them in a connection like this,
2658 * the housekeeping in dns.c would get way more complicated.)
2660 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2661 dummy_conn->stream_id = rh.stream_id;
2662 dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
2663 rh.length);
2664 dummy_conn->_base.port = 0;
2665 dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2666 dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
2668 dummy_conn->on_circuit = TO_CIRCUIT(circ);
2670 /* send it off to the gethostbyname farm */
2671 switch (dns_resolve(dummy_conn)) {
2672 case -1: /* Impossible to resolve; a resolved cell was sent. */
2673 /* Connection freed; don't touch it. */
2674 return 0;
2675 case 1: /* The result was cached; a resolved cell was sent. */
2676 if (!dummy_conn->_base.marked_for_close)
2677 connection_free(TO_CONN(dummy_conn));
2678 return 0;
2679 case 0: /* resolve added to pending list */
2680 assert_circuit_ok(TO_CIRCUIT(circ));
2681 break;
2683 return 0;
2686 /** Connect to conn's specified addr and port. If it worked, conn
2687 * has now been added to the connection_array.
2689 * Send back a connected cell. Include the resolved IP of the destination
2690 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2691 * streams must not reveal what IP they connected to.)
2693 void
2694 connection_exit_connect(edge_connection_t *edge_conn)
2696 const tor_addr_t *addr;
2697 uint16_t port;
2698 connection_t *conn = TO_CONN(edge_conn);
2699 int socket_error = 0;
2701 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
2702 router_compare_to_my_exit_policy(edge_conn)) {
2703 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
2704 escaped_safe_str(conn->address), conn->port);
2705 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
2706 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2707 connection_free(conn);
2708 return;
2711 addr = &conn->addr;
2712 port = conn->port;
2714 log_debug(LD_EXIT,"about to try connecting");
2715 switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
2716 case -1:
2717 /* XXX021 use socket_error below rather than trying to piece things
2718 * together from the current errno, which may have been clobbered. */
2719 connection_edge_end_errno(edge_conn);
2720 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2721 connection_free(conn);
2722 return;
2723 case 0:
2724 conn->state = EXIT_CONN_STATE_CONNECTING;
2726 connection_watch_events(conn, EV_WRITE | EV_READ);
2727 /* writable indicates finish;
2728 * readable/error indicates broken link in windowsland. */
2729 return;
2730 /* case 1: fall through */
2733 conn->state = EXIT_CONN_STATE_OPEN;
2734 if (connection_wants_to_flush(conn)) {
2735 /* in case there are any queued data cells */
2736 log_warn(LD_BUG,"newly connected conn had data waiting!");
2737 // connection_start_writing(conn);
2739 connection_watch_events(conn, EV_READ);
2741 /* also, deliver a 'connected' cell back through the circuit. */
2742 if (connection_edge_is_rendezvous_stream(edge_conn)) {
2743 /* rendezvous stream */
2744 /* don't send an address back! */
2745 connection_edge_send_command(edge_conn,
2746 RELAY_COMMAND_CONNECTED,
2747 NULL, 0);
2748 } else { /* normal stream */
2749 char connected_payload[20];
2750 int connected_payload_len;
2751 if (tor_addr_family(&conn->addr) == AF_INET) {
2752 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
2753 connected_payload_len = 4;
2754 } else {
2755 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
2756 connected_payload_len = 16;
2758 set_uint32(connected_payload+connected_payload_len,
2759 htonl(dns_clip_ttl(edge_conn->address_ttl)));
2760 connected_payload_len += 4;
2761 connection_edge_send_command(edge_conn,
2762 RELAY_COMMAND_CONNECTED,
2763 connected_payload, connected_payload_len);
2767 /** Given an exit conn that should attach to us as a directory server, open a
2768 * bridge connection with a linked connection pair, create a new directory
2769 * conn, and join them together. Return 0 on success (or if there was an
2770 * error we could send back an end cell for). Return -(some circuit end
2771 * reason) if the circuit needs to be torn down. Either connects
2772 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2774 static int
2775 connection_exit_connect_dir(edge_connection_t *exitconn)
2777 dir_connection_t *dirconn = NULL;
2778 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
2780 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
2782 exitconn->_base.state = EXIT_CONN_STATE_OPEN;
2784 dirconn = dir_connection_new(AF_INET);
2786 dirconn->_base.addr = exitconn->_base.addr;
2787 dirconn->_base.port = 0;
2788 dirconn->_base.address = tor_strdup(circ->p_conn->_base.address);
2789 dirconn->_base.type = CONN_TYPE_DIR;
2790 dirconn->_base.purpose = DIR_PURPOSE_SERVER;
2791 dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2793 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
2795 if (connection_add(TO_CONN(exitconn))<0) {
2796 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2797 connection_free(TO_CONN(exitconn));
2798 connection_free(TO_CONN(dirconn));
2799 return 0;
2802 /* link exitconn to circ, now that we know we can use it. */
2803 exitconn->next_stream = circ->n_streams;
2804 circ->n_streams = exitconn;
2806 if (connection_add(TO_CONN(dirconn))<0) {
2807 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2808 connection_close_immediate(TO_CONN(exitconn));
2809 connection_mark_for_close(TO_CONN(exitconn));
2810 connection_free(TO_CONN(dirconn));
2811 return 0;
2814 connection_start_reading(TO_CONN(dirconn));
2815 connection_start_reading(TO_CONN(exitconn));
2817 if (connection_edge_send_command(exitconn,
2818 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
2819 connection_mark_for_close(TO_CONN(exitconn));
2820 connection_mark_for_close(TO_CONN(dirconn));
2821 return 0;
2824 return 0;
2827 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2828 * it is a general stream.
2831 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
2833 tor_assert(conn);
2834 if (conn->rend_data) /* XXX */ /* XXXX Why is this XXX? -NM */
2835 return 1;
2836 return 0;
2839 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2840 * to exit from it, or 0 if it probably will not allow it.
2841 * (We might be uncertain if conn's destination address has not yet been
2842 * resolved.)
2845 connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit)
2847 tor_assert(conn);
2848 tor_assert(conn->_base.type == CONN_TYPE_AP);
2849 tor_assert(conn->socks_request);
2850 tor_assert(exit);
2852 /* If a particular exit node has been requested for the new connection,
2853 * make sure the exit node of the existing circuit matches exactly.
2855 if (conn->chosen_exit_name) {
2856 routerinfo_t *chosen_exit =
2857 router_get_by_nickname(conn->chosen_exit_name, 1);
2858 if (!chosen_exit || memcmp(chosen_exit->cache_info.identity_digest,
2859 exit->cache_info.identity_digest, DIGEST_LEN)) {
2860 /* doesn't match */
2861 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2862 // conn->chosen_exit_name, exit->nickname);
2863 return 0;
2867 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2868 !conn->use_begindir) {
2869 struct in_addr in;
2870 uint32_t addr = 0;
2871 addr_policy_result_t r;
2872 if (tor_inet_aton(conn->socks_request->address, &in))
2873 addr = ntohl(in.s_addr);
2874 r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
2875 exit->exit_policy);
2876 if (r == ADDR_POLICY_REJECTED)
2877 return 0; /* We know the address, and the exit policy rejects it. */
2878 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
2879 return 0; /* We don't know the addr, but the exit policy rejects most
2880 * addresses with this port. Since the user didn't ask for
2881 * this node, err on the side of caution. */
2882 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2883 /* Can't support reverse lookups without eventdns. */
2884 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
2885 exit->has_old_dnsworkers)
2886 return 0;
2888 /* Don't send DNS requests to non-exit servers by default. */
2889 if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
2890 return 0;
2892 return 1;
2895 /** If address is of the form "y.onion" with a well-formed handle y:
2896 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2898 * If address is of the form "y.exit":
2899 * Put a NUL after y and return EXIT_HOSTNAME.
2901 * Otherwise:
2902 * Return NORMAL_HOSTNAME and change nothing.
2904 hostname_type_t
2905 parse_extended_hostname(char *address)
2907 char *s;
2908 char query[REND_SERVICE_ID_LEN_BASE32+1];
2910 s = strrchr(address,'.');
2911 if (!s)
2912 return NORMAL_HOSTNAME; /* no dot, thus normal */
2913 if (!strcmp(s+1,"exit")) {
2914 *s = 0; /* nul-terminate it */
2915 return EXIT_HOSTNAME; /* .exit */
2917 if (strcmp(s+1,"onion"))
2918 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
2920 /* so it is .onion */
2921 *s = 0; /* nul-terminate it */
2922 if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
2923 REND_SERVICE_ID_LEN_BASE32+1)
2924 goto failed;
2925 if (rend_valid_service_id(query)) {
2926 return ONION_HOSTNAME; /* success */
2928 failed:
2929 /* otherwise, return to previous state and return 0 */
2930 *s = '.';
2931 return BAD_HOSTNAME;
2934 /** Check if the address is of the form "y.noconnect"
2937 hostname_is_noconnect_address(const char *address)
2939 return ! strcasecmpend(address, ".noconnect");