Clean up proposal 166 and its implementation.
[tor/rransom.git] / src / or / connection_edge.c
blob1df576d636a3ea89c1fe86e9e18ee7b059733277
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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_edge.c
9 * \brief Handle edge streams.
10 **/
12 #include "or.h"
14 #ifdef HAVE_LINUX_TYPES_H
15 #include <linux/types.h>
16 #endif
17 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
18 #include <linux/netfilter_ipv4.h>
19 #define TRANS_NETFILTER
20 #endif
22 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
23 #include <net/if.h>
24 #include <net/pfvar.h>
25 #define TRANS_PF
26 #endif
28 #define SOCKS4_GRANTED 90
29 #define SOCKS4_REJECT 91
31 static int connection_ap_handshake_process_socks(edge_connection_t *conn);
32 static int connection_ap_process_natd(edge_connection_t *conn);
33 static int connection_exit_connect_dir(edge_connection_t *exitconn);
34 static int address_is_in_virtual_range(const char *addr);
35 static int consider_plaintext_ports(edge_connection_t *conn, uint16_t port);
36 static void clear_trackexithost_mappings(const char *exitname);
38 /** An AP stream has failed/finished. If it hasn't already sent back
39 * a socks reply, send one now (based on endreason). Also set
40 * has_sent_end to 1, and mark the conn.
42 void
43 _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
44 int line, const char *file)
46 tor_assert(conn->_base.type == CONN_TYPE_AP);
47 conn->edge_has_sent_end = 1; /* no circ yet */
49 if (conn->_base.marked_for_close) {
50 /* This call will warn as appropriate. */
51 _connection_mark_for_close(TO_CONN(conn), line, file);
52 return;
55 if (!conn->socks_request->has_finished) {
56 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
57 log_warn(LD_BUG,
58 "stream (marked at %s:%d) sending two socks replies?",
59 file, line);
61 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
62 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
63 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
64 connection_ap_handshake_socks_resolved(conn,
65 RESOLVED_TYPE_ERROR_TRANSIENT,
66 0, NULL, -1, -1);
67 else /* unknown or no handshake at all. send no response. */
68 conn->socks_request->has_finished = 1;
71 _connection_mark_for_close(TO_CONN(conn), line, file);
72 conn->_base.hold_open_until_flushed = 1;
73 conn->end_reason = endreason;
76 /** There was an EOF. Send an end and mark the connection for close.
78 int
79 connection_edge_reached_eof(edge_connection_t *conn)
81 if (buf_datalen(conn->_base.inbuf) &&
82 connection_state_is_open(TO_CONN(conn))) {
83 /* it still has stuff to process. don't let it die yet. */
84 return 0;
86 log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
87 if (!conn->_base.marked_for_close) {
88 /* only mark it if not already marked. it's possible to
89 * get the 'end' right around when the client hangs up on us. */
90 connection_edge_end(conn, END_STREAM_REASON_DONE);
91 if (conn->socks_request) /* eof, so don't send a socks reply back */
92 conn->socks_request->has_finished = 1;
93 connection_mark_for_close(TO_CONN(conn));
95 return 0;
98 /** Handle new bytes on conn->inbuf based on state:
99 * - If it's waiting for socks info, try to read another step of the
100 * socks handshake out of conn->inbuf.
101 * - If it's waiting for the original destination, fetch it.
102 * - If it's open, then package more relay cells from the stream.
103 * - Else, leave the bytes on inbuf alone for now.
105 * Mark and return -1 if there was an unexpected error with the conn,
106 * else return 0.
109 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
111 tor_assert(conn);
113 switch (conn->_base.state) {
114 case AP_CONN_STATE_SOCKS_WAIT:
115 if (connection_ap_handshake_process_socks(conn) < 0) {
116 /* already marked */
117 return -1;
119 return 0;
120 case AP_CONN_STATE_NATD_WAIT:
121 if (connection_ap_process_natd(conn) < 0) {
122 /* already marked */
123 return -1;
125 return 0;
126 case AP_CONN_STATE_OPEN:
127 case EXIT_CONN_STATE_OPEN:
128 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
129 /* (We already sent an end cell if possible) */
130 connection_mark_for_close(TO_CONN(conn));
131 return -1;
133 return 0;
134 case EXIT_CONN_STATE_CONNECTING:
135 case AP_CONN_STATE_RENDDESC_WAIT:
136 case AP_CONN_STATE_CIRCUIT_WAIT:
137 case AP_CONN_STATE_CONNECT_WAIT:
138 case AP_CONN_STATE_RESOLVE_WAIT:
139 case AP_CONN_STATE_CONTROLLER_WAIT:
140 log_info(LD_EDGE,
141 "data from edge while in '%s' state. Leaving it on buffer.",
142 conn_state_to_string(conn->_base.type, conn->_base.state));
143 return 0;
145 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
146 tor_fragile_assert();
147 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
148 connection_mark_for_close(TO_CONN(conn));
149 return -1;
152 /** This edge needs to be closed, because its circuit has closed.
153 * Mark it for close and return 0.
156 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
158 if (!conn->_base.marked_for_close) {
159 log_info(LD_EDGE,
160 "CircID %d: At an edge. Marking connection for close.", circ_id);
161 if (conn->_base.type == CONN_TYPE_AP) {
162 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
163 control_event_stream_bandwidth(conn);
164 control_event_stream_status(conn, STREAM_EVENT_CLOSED,
165 END_STREAM_REASON_DESTROY);
166 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
167 } else {
168 /* closing the circuit, nothing to send an END to */
169 conn->edge_has_sent_end = 1;
170 conn->end_reason = END_STREAM_REASON_DESTROY;
171 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
172 connection_mark_for_close(TO_CONN(conn));
173 conn->_base.hold_open_until_flushed = 1;
176 conn->cpath_layer = NULL;
177 conn->on_circuit = NULL;
178 return 0;
181 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
182 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
183 * is not a client connection, set the relay end cell's reason for closing
184 * as <b>reason</b> */
185 static int
186 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
187 uint8_t reason, crypt_path_t *cpath_layer)
189 char payload[1];
191 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
192 /* Never send the server an informative reason code; it doesn't need to
193 * know why the client stream is failing. */
194 reason = END_STREAM_REASON_MISC;
197 payload[0] = (char) reason;
199 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
200 payload, 1, cpath_layer);
203 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
204 * remember that we've done so. If this is not a client connection, set the
205 * relay end cell's reason for closing as <b>reason</b>.
207 * Return -1 if this function has already been called on this conn,
208 * else return 0.
211 connection_edge_end(edge_connection_t *conn, uint8_t reason)
213 char payload[RELAY_PAYLOAD_SIZE];
214 size_t payload_len=1;
215 circuit_t *circ;
216 uint8_t control_reason = reason;
218 if (conn->edge_has_sent_end) {
219 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
220 "on an already ended stream?", reason);
221 tor_fragile_assert();
222 return -1;
225 if (conn->_base.marked_for_close) {
226 log_warn(LD_BUG,
227 "called on conn that's already marked for close at %s:%d.",
228 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
229 return 0;
232 circ = circuit_get_by_edge_conn(conn);
233 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
234 /* If this is a client circuit, don't send the server an informative
235 * reason code; it doesn't need to know why the client stream is
236 * failing. */
237 reason = END_STREAM_REASON_MISC;
240 payload[0] = (char)reason;
241 if (reason == END_STREAM_REASON_EXITPOLICY &&
242 !connection_edge_is_rendezvous_stream(conn)) {
243 int addrlen;
244 if (tor_addr_family(&conn->_base.addr) == AF_INET) {
245 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
246 addrlen = 4;
247 } else {
248 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
249 addrlen = 16;
251 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
252 payload_len += 4+addrlen;
255 if (circ && !circ->marked_for_close) {
256 log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
257 connection_edge_send_command(conn, RELAY_COMMAND_END,
258 payload, payload_len);
259 } else {
260 log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
261 conn->_base.s);
264 conn->edge_has_sent_end = 1;
265 conn->end_reason = control_reason;
266 return 0;
269 /** An error has just occurred on an operation on an edge connection
270 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
271 * appropriate relay end cell to the other end of the connection's circuit.
274 connection_edge_end_errno(edge_connection_t *conn)
276 uint8_t reason;
277 tor_assert(conn);
278 reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
279 return connection_edge_end(conn, reason);
282 /** Connection <b>conn</b> has finished writing and has no bytes left on
283 * its outbuf.
285 * If it's in state 'open', stop writing, consider responding with a
286 * sendme, and return.
287 * Otherwise, stop writing and return.
289 * If <b>conn</b> is broken, mark it for close and return -1, else
290 * return 0.
293 connection_edge_finished_flushing(edge_connection_t *conn)
295 tor_assert(conn);
297 switch (conn->_base.state) {
298 case AP_CONN_STATE_OPEN:
299 case EXIT_CONN_STATE_OPEN:
300 connection_stop_writing(TO_CONN(conn));
301 connection_edge_consider_sending_sendme(conn);
302 return 0;
303 case AP_CONN_STATE_SOCKS_WAIT:
304 case AP_CONN_STATE_NATD_WAIT:
305 case AP_CONN_STATE_RENDDESC_WAIT:
306 case AP_CONN_STATE_CIRCUIT_WAIT:
307 case AP_CONN_STATE_CONNECT_WAIT:
308 case AP_CONN_STATE_CONTROLLER_WAIT:
309 connection_stop_writing(TO_CONN(conn));
310 return 0;
311 default:
312 log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
313 tor_fragile_assert();
314 return -1;
316 return 0;
319 /** Connected handler for exit connections: start writing pending
320 * data, deliver 'CONNECTED' relay cells as appropriate, and check
321 * any pending data that may have been received. */
323 connection_edge_finished_connecting(edge_connection_t *edge_conn)
325 connection_t *conn;
327 tor_assert(edge_conn);
328 tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
329 conn = TO_CONN(edge_conn);
330 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
332 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
333 escaped_safe_str(conn->address),conn->port,
334 safe_str(fmt_addr(&conn->addr)));
336 rep_hist_note_exit_stream_opened(conn->port, approx_time());
338 conn->state = EXIT_CONN_STATE_OPEN;
339 connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
340 if (connection_wants_to_flush(conn)) /* in case there are any queued relay
341 * cells */
342 connection_start_writing(conn);
343 /* deliver a 'connected' relay cell back through the circuit. */
344 if (connection_edge_is_rendezvous_stream(edge_conn)) {
345 if (connection_edge_send_command(edge_conn,
346 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
347 return 0; /* circuit is closed, don't continue */
348 } else {
349 char connected_payload[20];
350 int connected_payload_len;
351 if (tor_addr_family(&conn->addr) == AF_INET) {
352 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
353 set_uint32(connected_payload+4,
354 htonl(dns_clip_ttl(edge_conn->address_ttl)));
355 connected_payload_len = 8;
356 } else {
357 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
358 set_uint32(connected_payload+16,
359 htonl(dns_clip_ttl(edge_conn->address_ttl)));
360 connected_payload_len = 20;
362 if (connection_edge_send_command(edge_conn,
363 RELAY_COMMAND_CONNECTED,
364 connected_payload, connected_payload_len) < 0)
365 return 0; /* circuit is closed, don't continue */
367 tor_assert(edge_conn->package_window > 0);
368 /* in case the server has written anything */
369 return connection_edge_process_inbuf(edge_conn, 1);
372 /** Define a schedule for how long to wait between retrying
373 * application connections. Rather than waiting a fixed amount of
374 * time between each retry, we wait 10 seconds each for the first
375 * two tries, and 15 seconds for each retry after
376 * that. Hopefully this will improve the expected user experience. */
377 static int
378 compute_retry_timeout(edge_connection_t *conn)
380 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
381 return 10;
382 return 15;
385 /** Find all general-purpose AP streams waiting for a response that sent their
386 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
387 * mark their current circuit as unsuitable for new streams. Then call
388 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
389 * available) or launch a new one.
391 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
392 * retry attempt).
394 void
395 connection_ap_expire_beginning(void)
397 edge_connection_t *conn;
398 circuit_t *circ;
399 time_t now = time(NULL);
400 or_options_t *options = get_options();
401 int severity;
402 int cutoff;
403 int seconds_idle, seconds_since_born;
404 smartlist_t *conns = get_connection_array();
406 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
407 if (c->type != CONN_TYPE_AP || c->marked_for_close)
408 continue;
409 conn = TO_EDGE_CONN(c);
410 /* if it's an internal linked connection, don't yell its status. */
411 severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
412 ? LOG_INFO : LOG_NOTICE;
413 seconds_idle = (int)( now - conn->_base.timestamp_lastread );
414 seconds_since_born = (int)( now - conn->_base.timestamp_created );
416 if (conn->_base.state == AP_CONN_STATE_OPEN)
417 continue;
419 /* We already consider SocksTimeout in
420 * connection_ap_handshake_attach_circuit(), but we need to consider
421 * it here too because controllers that put streams in controller_wait
422 * state never ask Tor to attach the circuit. */
423 if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
424 if (seconds_since_born >= options->SocksTimeout) {
425 log_fn(severity, LD_APP,
426 "Tried for %d seconds to get a connection to %s:%d. "
427 "Giving up. (%s)",
428 seconds_since_born, safe_str(conn->socks_request->address),
429 conn->socks_request->port,
430 conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
431 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
433 continue;
436 /* We're in state connect_wait or resolve_wait now -- waiting for a
437 * reply to our relay cell. See if we want to retry/give up. */
439 cutoff = compute_retry_timeout(conn);
440 if (seconds_idle < cutoff)
441 continue;
442 circ = circuit_get_by_edge_conn(conn);
443 if (!circ) { /* it's vanished? */
444 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
445 safe_str(conn->socks_request->address));
446 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
447 continue;
449 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
450 if (seconds_idle >= options->SocksTimeout) {
451 log_fn(severity, LD_REND,
452 "Rend stream is %d seconds late. Giving up on address"
453 " '%s.onion'.",
454 seconds_idle,
455 safe_str(conn->socks_request->address));
456 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
457 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
459 continue;
461 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
462 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
463 "We tried for %d seconds to connect to '%s' using exit '%s'."
464 " Retrying on a new circuit.",
465 seconds_idle, safe_str(conn->socks_request->address),
466 conn->cpath_layer ?
467 conn->cpath_layer->extend_info->nickname : "*unnamed*");
468 /* send an end down the circuit */
469 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
470 /* un-mark it as ending, since we're going to reuse it */
471 conn->edge_has_sent_end = 0;
472 conn->end_reason = 0;
473 /* kludge to make us not try this circuit again, yet to allow
474 * current streams on it to survive if they can: make it
475 * unattractive to use for new streams */
476 tor_assert(circ->timestamp_dirty);
477 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
478 /* give our stream another 'cutoff' seconds to try */
479 conn->_base.timestamp_lastread += cutoff;
480 if (conn->num_socks_retries < 250) /* avoid overflow */
481 conn->num_socks_retries++;
482 /* move it back into 'pending' state, and try to attach. */
483 if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
484 END_STREAM_REASON_TIMEOUT)<0) {
485 if (!conn->_base.marked_for_close)
486 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
488 } SMARTLIST_FOREACH_END(conn);
491 /** Tell any AP streams that are waiting for a new circuit to try again,
492 * either attaching to an available circ or launching a new one.
494 void
495 connection_ap_attach_pending(void)
497 edge_connection_t *edge_conn;
498 smartlist_t *conns = get_connection_array();
499 SMARTLIST_FOREACH(conns, connection_t *, conn,
501 if (conn->marked_for_close ||
502 conn->type != CONN_TYPE_AP ||
503 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
504 continue;
505 edge_conn = TO_EDGE_CONN(conn);
506 if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
507 if (!edge_conn->_base.marked_for_close)
508 connection_mark_unattached_ap(edge_conn,
509 END_STREAM_REASON_CANT_ATTACH);
514 /** Tell any AP streams that are waiting for a one-hop tunnel to
515 * <b>failed_digest</b> that they are going to fail. */
516 /* XXX022 We should get rid of this function, and instead attach
517 * one-hop streams to circ->p_streams so they get marked in
518 * circuit_mark_for_close like normal p_streams. */
519 void
520 connection_ap_fail_onehop(const char *failed_digest,
521 cpath_build_state_t *build_state)
523 edge_connection_t *edge_conn;
524 char digest[DIGEST_LEN];
525 smartlist_t *conns = get_connection_array();
526 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
527 if (conn->marked_for_close ||
528 conn->type != CONN_TYPE_AP ||
529 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
530 continue;
531 edge_conn = TO_EDGE_CONN(conn);
532 if (!edge_conn->want_onehop)
533 continue;
534 if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
535 memcmp(digest, failed_digest, DIGEST_LEN))
536 continue;
537 if (tor_digest_is_zero(digest)) {
538 /* we don't know the digest; have to compare addr:port */
539 tor_addr_t addr;
540 if (!build_state || !build_state->chosen_exit ||
541 !edge_conn->socks_request || !edge_conn->socks_request->address)
542 continue;
543 if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
544 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
545 build_state->chosen_exit->port != edge_conn->socks_request->port)
546 continue;
548 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
549 "just failed.", edge_conn->chosen_exit_name,
550 edge_conn->socks_request->address);
551 connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
552 } SMARTLIST_FOREACH_END(conn);
555 /** A circuit failed to finish on its last hop <b>info</b>. If there
556 * are any streams waiting with this exit node in mind, but they
557 * don't absolutely require it, make them give up on it.
559 void
560 circuit_discard_optional_exit_enclaves(extend_info_t *info)
562 edge_connection_t *edge_conn;
563 routerinfo_t *r1, *r2;
565 smartlist_t *conns = get_connection_array();
566 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
567 if (conn->marked_for_close ||
568 conn->type != CONN_TYPE_AP ||
569 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
570 continue;
571 edge_conn = TO_EDGE_CONN(conn);
572 if (!edge_conn->chosen_exit_optional &&
573 !edge_conn->chosen_exit_retries)
574 continue;
575 r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
576 r2 = router_get_by_nickname(info->nickname, 0);
577 if (!r1 || !r2 || r1 != r2)
578 continue;
579 tor_assert(edge_conn->socks_request);
580 if (edge_conn->chosen_exit_optional) {
581 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
582 safe_str(edge_conn->chosen_exit_name),
583 escaped_safe_str(edge_conn->socks_request->address));
584 edge_conn->chosen_exit_optional = 0;
585 tor_free(edge_conn->chosen_exit_name); /* clears it */
586 /* if this port is dangerous, warn or reject it now that we don't
587 * think it'll be using an enclave. */
588 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
590 if (edge_conn->chosen_exit_retries) {
591 if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
592 clear_trackexithost_mappings(edge_conn->chosen_exit_name);
593 tor_free(edge_conn->chosen_exit_name); /* clears it */
594 /* if this port is dangerous, warn or reject it now that we don't
595 * think it'll be using an enclave. */
596 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
599 } SMARTLIST_FOREACH_END(conn);
602 /** The AP connection <b>conn</b> has just failed while attaching or
603 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
604 * might work. Detach the circuit, and either reattach it, launch a
605 * new circuit, tell the controller, or give up as a appropriate.
607 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
610 connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
611 int reason)
613 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
614 conn->_base.timestamp_lastread = time(NULL);
615 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
616 /* If we're attaching streams ourself, or if this connection is
617 * a tunneled directory connection, then just attach it. */
618 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
619 circuit_detach_stream(TO_CIRCUIT(circ),conn);
620 return connection_ap_handshake_attach_circuit(conn);
621 } else {
622 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
623 circuit_detach_stream(TO_CIRCUIT(circ),conn);
624 return 0;
628 /** A client-side struct to remember requests to rewrite addresses
629 * to new addresses. These structs are stored in the hash table
630 * "addressmap" below.
632 * There are 5 ways to set an address mapping:
633 * - A MapAddress command from the controller [permanent]
634 * - An AddressMap directive in the torrc [permanent]
635 * - When a TrackHostExits torrc directive is triggered [temporary]
636 * - When a DNS resolve succeeds [temporary]
637 * - When a DNS resolve fails [temporary]
639 * When an addressmap request is made but one is already registered,
640 * the new one is replaced only if the currently registered one has
641 * no "new_address" (that is, it's in the process of DNS resolve),
642 * or if the new one is permanent (expires==0 or 1).
644 * (We overload the 'expires' field, using "0" for mappings set via
645 * the configuration file, "1" for mappings set from the control
646 * interface, and other values for DNS and TrackHostExit mappings that can
647 * expire.)
649 typedef struct {
650 char *new_address;
651 time_t expires;
652 addressmap_entry_source_t source:3;
653 short num_resolve_failures;
654 } addressmap_entry_t;
656 /** Entry for mapping addresses to which virtual address we mapped them to. */
657 typedef struct {
658 char *ipv4_address;
659 char *hostname_address;
660 } virtaddress_entry_t;
662 /** A hash table to store client-side address rewrite instructions. */
663 static strmap_t *addressmap=NULL;
665 * Table mapping addresses to which virtual address, if any, we
666 * assigned them to.
668 * We maintain the following invariant: if [A,B] is in
669 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
670 * must be in addressmap. We do not require that the converse hold:
671 * if it fails, then we could end up mapping two virtual addresses to
672 * the same address, which is no disaster.
674 static strmap_t *virtaddress_reversemap=NULL;
676 /** Initialize addressmap. */
677 void
678 addressmap_init(void)
680 addressmap = strmap_new();
681 virtaddress_reversemap = strmap_new();
684 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
685 static void
686 addressmap_ent_free(void *_ent)
688 addressmap_entry_t *ent = _ent;
689 tor_free(ent->new_address);
690 tor_free(ent);
693 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
694 static void
695 addressmap_virtaddress_ent_free(void *_ent)
697 virtaddress_entry_t *ent = _ent;
698 tor_free(ent->ipv4_address);
699 tor_free(ent->hostname_address);
700 tor_free(ent);
703 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
704 static void
705 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
707 if (ent && ent->new_address &&
708 address_is_in_virtual_range(ent->new_address)) {
709 virtaddress_entry_t *ve =
710 strmap_get(virtaddress_reversemap, ent->new_address);
711 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
712 if (ve) {
713 if (!strcmp(address, ve->ipv4_address))
714 tor_free(ve->ipv4_address);
715 if (!strcmp(address, ve->hostname_address))
716 tor_free(ve->hostname_address);
717 if (!ve->ipv4_address && !ve->hostname_address) {
718 tor_free(ve);
719 strmap_remove(virtaddress_reversemap, ent->new_address);
725 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
726 * client address maps. */
727 static void
728 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
730 addressmap_virtaddress_remove(address, ent);
731 addressmap_ent_free(ent);
734 /** Unregister all TrackHostExits mappings from any address to
735 * *.exitname.exit. */
736 static void
737 clear_trackexithost_mappings(const char *exitname)
739 char *suffix;
740 size_t suffix_len;
741 if (!addressmap || !exitname)
742 return;
743 suffix_len = strlen(exitname) + 16;
744 suffix = tor_malloc(suffix_len);
745 tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
746 tor_strlower(suffix);
748 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
749 if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
750 addressmap_ent_remove(address, ent);
751 MAP_DEL_CURRENT(address);
753 } STRMAP_FOREACH_END;
755 tor_free(suffix);
758 /** Remove all entries from the addressmap that were set via the
759 * configuration file or the command line. */
760 void
761 addressmap_clear_configured(void)
763 addressmap_get_mappings(NULL, 0, 0, 0);
766 /** Remove all entries from the addressmap that are set to expire, ever. */
767 void
768 addressmap_clear_transient(void)
770 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
773 /** Clean out entries from the addressmap cache that were
774 * added long enough ago that they are no longer valid.
776 void
777 addressmap_clean(time_t now)
779 addressmap_get_mappings(NULL, 2, now, 0);
782 /** Free all the elements in the addressmap, and free the addressmap
783 * itself. */
784 void
785 addressmap_free_all(void)
787 if (addressmap) {
788 strmap_free(addressmap, addressmap_ent_free);
789 addressmap = NULL;
791 if (virtaddress_reversemap) {
792 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
793 virtaddress_reversemap = NULL;
797 /** Look at address, and rewrite it until it doesn't want any
798 * more rewrites; but don't get into an infinite loop.
799 * Don't write more than maxlen chars into address. Return true if the
800 * address changed; false otherwise. Set *<b>expires_out</b> to the
801 * expiry time of the result, or to <b>time_max</b> if the result does
802 * not expire.
805 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
807 addressmap_entry_t *ent;
808 int rewrites;
809 char *cp;
810 time_t expires = TIME_MAX;
812 for (rewrites = 0; rewrites < 16; rewrites++) {
813 ent = strmap_get(addressmap, address);
815 if (!ent || !ent->new_address) {
816 if (expires_out)
817 *expires_out = expires;
818 return (rewrites > 0); /* done, no rewrite needed */
821 cp = tor_strdup(escaped_safe_str(ent->new_address));
822 log_info(LD_APP, "Addressmap: rewriting %s to %s",
823 escaped_safe_str(address), cp);
824 if (ent->expires > 1 && ent->expires < expires)
825 expires = ent->expires;
826 tor_free(cp);
827 strlcpy(address, ent->new_address, maxlen);
829 log_warn(LD_CONFIG,
830 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
831 escaped_safe_str(address));
832 /* it's fine to rewrite a rewrite, but don't loop forever */
833 if (expires_out)
834 *expires_out = TIME_MAX;
835 return 1;
838 /** If we have a cached reverse DNS entry for the address stored in the
839 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
840 * rewrite to the cached value and return 1. Otherwise return 0. Set
841 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
842 * if the result does not expire. */
843 static int
844 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
846 size_t len = maxlen + 16;
847 char *s = tor_malloc(len), *cp;
848 addressmap_entry_t *ent;
849 int r = 0;
850 tor_snprintf(s, len, "REVERSE[%s]", address);
851 ent = strmap_get(addressmap, s);
852 if (ent) {
853 cp = tor_strdup(escaped_safe_str(ent->new_address));
854 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
855 escaped_safe_str(s), cp);
856 tor_free(cp);
857 strlcpy(address, ent->new_address, maxlen);
858 r = 1;
861 if (expires_out)
862 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
864 tor_free(s);
865 return r;
868 /** Return 1 if <b>address</b> is already registered, else return 0. If address
869 * is already registered, and <b>update_expires</b> is non-zero, then update
870 * the expiry time on the mapping with update_expires if it is a
871 * mapping created by TrackHostExits. */
873 addressmap_have_mapping(const char *address, int update_expiry)
875 addressmap_entry_t *ent;
876 if (!(ent=strmap_get_lc(addressmap, address)))
877 return 0;
878 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
879 ent->expires=time(NULL) + update_expiry;
880 return 1;
883 /** Register a request to map <b>address</b> to <b>new_address</b>,
884 * which will expire on <b>expires</b> (or 0 if never expires from
885 * config file, 1 if never expires from controller, 2 if never expires
886 * (virtual address mapping) from the controller.)
888 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
889 * free as appropriate. We will leave address alone.
891 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
892 * any mappings that exist from <b>address</b>.
894 void
895 addressmap_register(const char *address, char *new_address, time_t expires,
896 addressmap_entry_source_t source)
898 addressmap_entry_t *ent;
900 ent = strmap_get(addressmap, address);
901 if (!new_address || !strcasecmp(address,new_address)) {
902 /* Remove the mapping, if any. */
903 tor_free(new_address);
904 if (ent) {
905 addressmap_ent_remove(address,ent);
906 strmap_remove(addressmap, address);
908 return;
910 if (!ent) { /* make a new one and register it */
911 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
912 strmap_set(addressmap, address, ent);
913 } else if (ent->new_address) { /* we need to clean up the old mapping. */
914 if (expires > 1) {
915 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
916 "since it's already mapped to '%s'",
917 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
918 tor_free(new_address);
919 return;
921 if (address_is_in_virtual_range(ent->new_address) &&
922 expires != 2) {
923 /* XXX This isn't the perfect test; we want to avoid removing
924 * mappings set from the control interface _as virtual mapping */
925 addressmap_virtaddress_remove(address, ent);
927 tor_free(ent->new_address);
928 } /* else { we have an in-progress resolve with no mapping. } */
930 ent->new_address = new_address;
931 ent->expires = expires==2 ? 1 : expires;
932 ent->num_resolve_failures = 0;
933 ent->source = source;
935 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
936 safe_str(address), safe_str(ent->new_address));
937 control_event_address_mapped(address, ent->new_address, expires, NULL);
940 /** An attempt to resolve <b>address</b> failed at some OR.
941 * Increment the number of resolve failures we have on record
942 * for it, and then return that number.
945 client_dns_incr_failures(const char *address)
947 addressmap_entry_t *ent = strmap_get(addressmap, address);
948 if (!ent) {
949 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
950 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
951 strmap_set(addressmap,address,ent);
953 if (ent->num_resolve_failures < SHORT_MAX)
954 ++ent->num_resolve_failures; /* don't overflow */
955 log_info(LD_APP, "Address %s now has %d resolve failures.",
956 safe_str(address), ent->num_resolve_failures);
957 return ent->num_resolve_failures;
960 /** If <b>address</b> is in the client DNS addressmap, reset
961 * the number of resolve failures we have on record for it.
962 * This is used when we fail a stream because it won't resolve:
963 * otherwise future attempts on that address will only try once.
965 void
966 client_dns_clear_failures(const char *address)
968 addressmap_entry_t *ent = strmap_get(addressmap, address);
969 if (ent)
970 ent->num_resolve_failures = 0;
973 /** Record the fact that <b>address</b> resolved to <b>name</b>.
974 * We can now use this in subsequent streams via addressmap_rewrite()
975 * so we can more correctly choose an exit that will allow <b>address</b>.
977 * If <b>exitname</b> is defined, then append the addresses with
978 * ".exitname.exit" before registering the mapping.
980 * If <b>ttl</b> is nonnegative, the mapping will be valid for
981 * <b>ttl</b>seconds; otherwise, we use the default.
983 static void
984 client_dns_set_addressmap_impl(const char *address, const char *name,
985 const char *exitname,
986 int ttl)
988 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
989 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
990 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
991 char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
993 tor_assert(address);
994 tor_assert(name);
996 if (ttl<0)
997 ttl = DEFAULT_DNS_TTL;
998 else
999 ttl = dns_clip_ttl(ttl);
1001 if (exitname) {
1002 /* XXXX fails to ever get attempts to get an exit address of
1003 * google.com.digest[=~]nickname.exit; we need a syntax for this that
1004 * won't make strict RFC952-compliant applications (like us) barf. */
1005 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1006 "%s.%s.exit", address, exitname);
1007 tor_snprintf(extendedval, sizeof(extendedval),
1008 "%s.%s.exit", name, exitname);
1009 } else {
1010 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1011 "%s", address);
1012 tor_snprintf(extendedval, sizeof(extendedval),
1013 "%s", name);
1015 addressmap_register(extendedaddress, tor_strdup(extendedval),
1016 time(NULL) + ttl, ADDRMAPSRC_DNS);
1019 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1020 * We can now use this in subsequent streams via addressmap_rewrite()
1021 * so we can more correctly choose an exit that will allow <b>address</b>.
1023 * If <b>exitname</b> is defined, then append the addresses with
1024 * ".exitname.exit" before registering the mapping.
1026 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1027 * <b>ttl</b>seconds; otherwise, we use the default.
1029 void
1030 client_dns_set_addressmap(const char *address, uint32_t val,
1031 const char *exitname,
1032 int ttl)
1034 struct in_addr in;
1035 char valbuf[INET_NTOA_BUF_LEN];
1037 tor_assert(address);
1039 if (tor_inet_aton(address, &in))
1040 return; /* If address was an IP address already, don't add a mapping. */
1041 in.s_addr = htonl(val);
1042 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
1044 client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
1047 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1048 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1050 * If <b>exitname</b> is defined, then append the addresses with
1051 * ".exitname.exit" before registering the mapping.
1053 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1054 * <b>ttl</b>seconds; otherwise, we use the default.
1056 static void
1057 client_dns_set_reverse_addressmap(const char *address, const char *v,
1058 const char *exitname,
1059 int ttl)
1061 size_t len = strlen(address) + 16;
1062 char *s = tor_malloc(len);
1063 tor_snprintf(s, len, "REVERSE[%s]", address);
1064 client_dns_set_addressmap_impl(s, v, exitname, ttl);
1065 tor_free(s);
1068 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1069 * These addresses should map to localhost, so even if the
1070 * application accidentally tried to connect to them directly (not
1071 * via Tor), it wouldn't get too far astray.
1073 * These options are configured by parse_virtual_addr_network().
1075 /** Which network should we use for virtual IPv4 addresses? Only the first
1076 * bits of this value are fixed. */
1077 static uint32_t virtual_addr_network = 0x7fc00000u;
1078 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1079 static maskbits_t virtual_addr_netmask_bits = 10;
1080 /** What's the next virtual address we will hand out? */
1081 static uint32_t next_virtual_addr = 0x7fc00000u;
1083 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1084 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1085 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1086 * string and return -1 on failure. If validate_only is false, sets the
1087 * actual virtual address range to the parsed value. */
1089 parse_virtual_addr_network(const char *val, int validate_only,
1090 char **msg)
1092 uint32_t addr;
1093 uint16_t port_min, port_max;
1094 maskbits_t bits;
1096 if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
1097 if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
1098 return -1;
1101 if (port_min != 1 || port_max != 65535) {
1102 if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
1103 return -1;
1106 if (bits > 16) {
1107 if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
1108 "network or larger");
1109 return -1;
1112 if (validate_only)
1113 return 0;
1115 virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
1116 virtual_addr_netmask_bits = bits;
1118 if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
1119 next_virtual_addr = addr;
1121 return 0;
1125 * Return true iff <b>addr</b> is likely to have been returned by
1126 * client_dns_get_unused_address.
1128 static int
1129 address_is_in_virtual_range(const char *address)
1131 struct in_addr in;
1132 tor_assert(address);
1133 if (!strcasecmpend(address, ".virtual")) {
1134 return 1;
1135 } else if (tor_inet_aton(address, &in)) {
1136 uint32_t addr = ntohl(in.s_addr);
1137 if (!addr_mask_cmp_bits(addr, virtual_addr_network,
1138 virtual_addr_netmask_bits))
1139 return 1;
1141 return 0;
1144 /** Return a newly allocated string holding an address of <b>type</b>
1145 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1146 * and that is very unlikely to be the address of any real host.
1148 static char *
1149 addressmap_get_virtual_address(int type)
1151 char buf[64];
1152 struct in_addr in;
1153 tor_assert(addressmap);
1155 if (type == RESOLVED_TYPE_HOSTNAME) {
1156 char rand[10];
1157 do {
1158 crypto_rand(rand, sizeof(rand));
1159 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
1160 strlcat(buf, ".virtual", sizeof(buf));
1161 } while (strmap_get(addressmap, buf));
1162 return tor_strdup(buf);
1163 } else if (type == RESOLVED_TYPE_IPV4) {
1164 // This is an imperfect estimate of how many addresses are available, but
1165 // that's ok.
1166 uint32_t available = 1u << (32-virtual_addr_netmask_bits);
1167 while (available) {
1168 /* Don't hand out any .0 or .255 address. */
1169 while ((next_virtual_addr & 0xff) == 0 ||
1170 (next_virtual_addr & 0xff) == 0xff) {
1171 ++next_virtual_addr;
1173 in.s_addr = htonl(next_virtual_addr);
1174 tor_inet_ntoa(&in, buf, sizeof(buf));
1175 if (!strmap_get(addressmap, buf)) {
1176 ++next_virtual_addr;
1177 break;
1180 ++next_virtual_addr;
1181 --available;
1182 log_info(LD_CONFIG, "%d addrs available", (int)available);
1183 if (! --available) {
1184 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
1185 return NULL;
1187 if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
1188 virtual_addr_netmask_bits))
1189 next_virtual_addr = virtual_addr_network;
1191 return tor_strdup(buf);
1192 } else {
1193 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
1194 return NULL;
1198 /** A controller has requested that we map some address of type
1199 * <b>type</b> to the address <b>new_address</b>. Choose an address
1200 * that is unlikely to be used, and map it, and return it in a newly
1201 * allocated string. If another address of the same type is already
1202 * mapped to <b>new_address</b>, try to return a copy of that address.
1204 * The string in <b>new_address</b> may be freed, or inserted into a map
1205 * as appropriate.
1207 const char *
1208 addressmap_register_virtual_address(int type, char *new_address)
1210 char **addrp;
1211 virtaddress_entry_t *vent;
1213 tor_assert(new_address);
1214 tor_assert(addressmap);
1215 tor_assert(virtaddress_reversemap);
1217 vent = strmap_get(virtaddress_reversemap, new_address);
1218 if (!vent) {
1219 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
1220 strmap_set(virtaddress_reversemap, new_address, vent);
1223 addrp = (type == RESOLVED_TYPE_IPV4) ?
1224 &vent->ipv4_address : &vent->hostname_address;
1225 if (*addrp) {
1226 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1227 if (ent && ent->new_address &&
1228 !strcasecmp(new_address, ent->new_address)) {
1229 tor_free(new_address);
1230 return tor_strdup(*addrp);
1231 } else
1232 log_warn(LD_BUG,
1233 "Internal confusion: I thought that '%s' was mapped to by "
1234 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1235 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
1236 ent?safe_str(ent->new_address):"(nothing)");
1239 tor_free(*addrp);
1240 *addrp = addressmap_get_virtual_address(type);
1241 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1242 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_CONTROLLER);
1244 #if 0
1246 /* Try to catch possible bugs */
1247 addressmap_entry_t *ent;
1248 ent = strmap_get(addressmap, *addrp);
1249 tor_assert(ent);
1250 tor_assert(!strcasecmp(ent->new_address,new_address));
1251 vent = strmap_get(virtaddress_reversemap, new_address);
1252 tor_assert(vent);
1253 tor_assert(!strcasecmp(*addrp,
1254 (type == RESOLVED_TYPE_IPV4) ?
1255 vent->ipv4_address : vent->hostname_address));
1256 log_info(LD_APP, "Map from %s to %s okay.",
1257 safe_str(*addrp),safe_str(new_address));
1259 #endif
1261 return *addrp;
1264 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1265 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1266 * should be true if we're using this address as a client; false if we're
1267 * using it as a server.
1270 address_is_invalid_destination(const char *address, int client)
1272 if (client) {
1273 if (get_options()->AllowNonRFC953Hostnames)
1274 return 0;
1275 } else {
1276 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1277 return 0;
1280 while (*address) {
1281 if (TOR_ISALNUM(*address) ||
1282 *address == '-' ||
1283 *address == '.' ||
1284 *address == '_') /* Underscore is not allowed, but Windows does it
1285 * sometimes, just to thumb its nose at the IETF. */
1286 ++address;
1287 else
1288 return 1;
1290 return 0;
1293 /** Iterate over all address mappings which have expiry times between
1294 * min_expires and max_expires, inclusive. If sl is provided, add an
1295 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1296 * the expiry time if want_expiry is false. If sl is NULL, remove the
1297 * mappings.
1299 void
1300 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1301 time_t max_expires, int want_expiry)
1303 strmap_iter_t *iter;
1304 const char *key;
1305 void *_val;
1306 addressmap_entry_t *val;
1308 if (!addressmap)
1309 addressmap_init();
1311 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1312 strmap_iter_get(iter, &key, &_val);
1313 val = _val;
1314 if (val->expires >= min_expires && val->expires <= max_expires) {
1315 if (!sl) {
1316 iter = strmap_iter_next_rmv(addressmap,iter);
1317 addressmap_ent_remove(key, val);
1318 continue;
1319 } else if (val->new_address) {
1320 size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
1321 char *line = tor_malloc(len);
1322 if (want_expiry) {
1323 if (val->expires < 3 || val->expires == TIME_MAX)
1324 tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
1325 else {
1326 char time[ISO_TIME_LEN+1];
1327 format_iso_time(time, val->expires);
1328 tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
1329 time);
1331 } else {
1332 tor_snprintf(line, len, "%s %s", key, val->new_address);
1334 smartlist_add(sl, line);
1337 iter = strmap_iter_next(addressmap,iter);
1341 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1342 * reject depending on our config options. */
1343 static int
1344 consider_plaintext_ports(edge_connection_t *conn, uint16_t port)
1346 or_options_t *options = get_options();
1347 int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
1349 if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
1350 log_warn(LD_APP, "Application request to port %d: this port is "
1351 "commonly used for unencrypted protocols. Please make sure "
1352 "you don't send anything you would mind the rest of the "
1353 "Internet reading!%s", port, reject ? " Closing." : "");
1354 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1355 port, reject ? "REJECT" : "WARN");
1358 if (reject) {
1359 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1360 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1361 return -1;
1364 return 0;
1367 /** How many times do we try connecting with an exit configured via
1368 * TrackHostExits before concluding that it won't work any more and trying a
1369 * different one? */
1370 #define TRACKHOSTEXITS_RETRIES 5
1372 /** Connection <b>conn</b> just finished its socks handshake, or the
1373 * controller asked us to take care of it. If <b>circ</b> is defined,
1374 * then that's where we'll want to attach it. Otherwise we have to
1375 * figure it out ourselves.
1377 * First, parse whether it's a .exit address, remap it, and so on. Then
1378 * if it's for a general circuit, try to attach it to a circuit (or launch
1379 * one as needed), else if it's for a rendezvous circuit, fetch a
1380 * rendezvous descriptor first (or attach/launch a circuit if the
1381 * rendezvous descriptor is already here and fresh enough).
1383 * The stream will exit from the hop
1384 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1385 * <b>cpath</b> is NULL.
1388 connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
1389 origin_circuit_t *circ,
1390 crypt_path_t *cpath)
1392 socks_request_t *socks = conn->socks_request;
1393 hostname_type_t addresstype;
1394 or_options_t *options = get_options();
1395 struct in_addr addr_tmp;
1396 int automap = 0;
1397 char orig_address[MAX_SOCKS_ADDR_LEN];
1398 time_t map_expires = TIME_MAX;
1399 int remapped_to_exit = 0;
1400 time_t now = time(NULL);
1402 tor_strlower(socks->address); /* normalize it */
1403 strlcpy(orig_address, socks->address, sizeof(orig_address));
1404 log_debug(LD_APP,"Client asked for %s:%d",
1405 safe_str(socks->address),
1406 socks->port);
1408 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1409 !tor_inet_aton(socks->address, &addr_tmp) &&
1410 options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
1411 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
1412 if (!strcasecmpend(socks->address, cp)) {
1413 automap = 1;
1414 break;
1416 if (automap) {
1417 const char *new_addr;
1418 new_addr = addressmap_register_virtual_address(
1419 RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
1420 tor_assert(new_addr);
1421 log_info(LD_APP, "Automapping %s to %s",
1422 escaped_safe_str(socks->address), safe_str(new_addr));
1423 strlcpy(socks->address, new_addr, sizeof(socks->address));
1427 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1428 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1429 &map_expires)) {
1430 char *result = tor_strdup(socks->address);
1431 /* remember _what_ is supposed to have been resolved. */
1432 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1433 orig_address);
1434 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1435 strlen(result), result, -1,
1436 map_expires);
1437 connection_mark_unattached_ap(conn,
1438 END_STREAM_REASON_DONE |
1439 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1440 return 0;
1442 if (options->ClientDNSRejectInternalAddresses) {
1443 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1444 tor_addr_t addr;
1445 int ok;
1446 ok = tor_addr_parse_reverse_lookup_name(
1447 &addr, socks->address, AF_UNSPEC, 1);
1448 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1449 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1450 0, NULL, -1, TIME_MAX);
1451 connection_mark_unattached_ap(conn,
1452 END_STREAM_REASON_SOCKSPROTOCOL |
1453 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1454 return -1;
1457 } else if (!automap) {
1458 int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
1459 /* For address map controls, remap the address. */
1460 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1461 &map_expires)) {
1462 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1463 REMAP_STREAM_SOURCE_CACHE);
1464 if (started_without_chosen_exit &&
1465 !strcasecmpend(socks->address, ".exit") &&
1466 map_expires < TIME_MAX)
1467 remapped_to_exit = 1;
1471 if (!automap && address_is_in_virtual_range(socks->address)) {
1472 /* This address was probably handed out by client_dns_get_unmapped_address,
1473 * but the mapping was discarded for some reason. We *don't* want to send
1474 * the address through Tor; that's likely to fail, and may leak
1475 * information.
1477 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1478 socks->address); /* don't safe_str() this yet. */
1479 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
1480 return -1;
1483 /* Parse the address provided by SOCKS. Modify it in-place if it
1484 * specifies a hidden-service (.onion) or particular exit node (.exit).
1486 addresstype = parse_extended_hostname(socks->address,
1487 remapped_to_exit || options->AllowDotExit);
1489 if (addresstype == BAD_HOSTNAME) {
1490 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
1491 safe_str(socks->address));
1492 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1493 escaped(socks->address));
1494 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1495 return -1;
1498 if (addresstype == EXIT_HOSTNAME) {
1499 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1500 * node, and conn->address to hold only the address portion. */
1501 char *s = strrchr(socks->address,'.');
1502 tor_assert(!automap);
1503 if (s) {
1504 if (s[1] != '\0') {
1505 conn->chosen_exit_name = tor_strdup(s+1);
1506 if (remapped_to_exit) /* 5 tries before it expires the addressmap */
1507 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1508 *s = 0;
1509 } else {
1510 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1511 safe_str(socks->address));
1512 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1513 escaped(socks->address));
1514 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1515 return -1;
1517 } else {
1518 routerinfo_t *r;
1519 conn->chosen_exit_name = tor_strdup(socks->address);
1520 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1521 *socks->address = 0;
1522 if (r) {
1523 strlcpy(socks->address, r->address, sizeof(socks->address));
1524 } else {
1525 log_warn(LD_APP,
1526 "Unrecognized server in exit address '%s.exit'. Refusing.",
1527 safe_str(socks->address));
1528 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1529 return -1;
1534 if (addresstype != ONION_HOSTNAME) {
1535 /* not a hidden-service request (i.e. normal or .exit) */
1536 if (address_is_invalid_destination(socks->address, 1)) {
1537 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1538 escaped(socks->address));
1539 log_warn(LD_APP,
1540 "Destination '%s' seems to be an invalid hostname. Failing.",
1541 safe_str(socks->address));
1542 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1543 return -1;
1546 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1547 uint32_t answer;
1548 struct in_addr in;
1549 /* Reply to resolves immediately if we can. */
1550 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
1551 log_warn(LD_APP,"Address to be resolved is too large. Failing.");
1552 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1553 escaped(socks->address));
1554 connection_ap_handshake_socks_resolved(conn,
1555 RESOLVED_TYPE_ERROR_TRANSIENT,
1556 0,NULL,-1,TIME_MAX);
1557 connection_mark_unattached_ap(conn,
1558 END_STREAM_REASON_SOCKSPROTOCOL |
1559 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1560 return -1;
1562 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1563 /* leave it in network order */
1564 answer = in.s_addr;
1565 /* remember _what_ is supposed to have been resolved. */
1566 strlcpy(socks->address, orig_address, sizeof(socks->address));
1567 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1568 (char*)&answer,-1,map_expires);
1569 connection_mark_unattached_ap(conn,
1570 END_STREAM_REASON_DONE |
1571 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1572 return 0;
1574 tor_assert(!automap);
1575 rep_hist_note_used_resolve(now); /* help predict this next time */
1576 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1577 tor_assert(!automap);
1578 if (socks->port == 0) {
1579 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1580 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1581 return -1;
1584 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1585 /* see if we can find a suitable enclave exit */
1586 routerinfo_t *r =
1587 router_find_exact_exit_enclave(socks->address, socks->port);
1588 if (r) {
1589 log_info(LD_APP,
1590 "Redirecting address %s to exit at enclave router %s",
1591 safe_str(socks->address), r->nickname);
1592 /* use the hex digest, not nickname, in case there are two
1593 routers with this nickname */
1594 conn->chosen_exit_name =
1595 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1596 conn->chosen_exit_optional = 1;
1600 /* warn or reject if it's using a dangerous port */
1601 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1602 if (consider_plaintext_ports(conn, socks->port) < 0)
1603 return -1;
1605 if (!conn->use_begindir) {
1606 /* help predict this next time */
1607 rep_hist_note_used_port(now, socks->port);
1609 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1610 rep_hist_note_used_resolve(now); /* help predict this next time */
1611 /* no extra processing needed */
1612 } else {
1613 tor_fragile_assert();
1615 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1616 if ((circ && connection_ap_handshake_attach_chosen_circuit(
1617 conn, circ, cpath) < 0) ||
1618 (!circ &&
1619 connection_ap_handshake_attach_circuit(conn) < 0)) {
1620 if (!conn->_base.marked_for_close)
1621 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1622 return -1;
1624 return 0;
1625 } else {
1626 /* it's a hidden-service request */
1627 rend_cache_entry_t *entry;
1628 int r;
1629 rend_service_authorization_t *client_auth;
1630 tor_assert(!automap);
1631 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1632 /* if it's a resolve request, fail it right now, rather than
1633 * building all the circuits and then realizing it won't work. */
1634 log_warn(LD_APP,
1635 "Resolve requests to hidden services not allowed. Failing.");
1636 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1637 0,NULL,-1,TIME_MAX);
1638 connection_mark_unattached_ap(conn,
1639 END_STREAM_REASON_SOCKSPROTOCOL |
1640 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1641 return -1;
1644 if (circ) {
1645 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1646 "supported for .onion addresses currently. Failing.");
1647 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1648 return -1;
1651 conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1652 strlcpy(conn->rend_data->onion_address, socks->address,
1653 sizeof(conn->rend_data->onion_address));
1654 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1655 safe_str(conn->rend_data->onion_address));
1656 /* see if we already have it cached */
1657 r = rend_cache_lookup_entry(conn->rend_data->onion_address, -1, &entry);
1658 if (r<0) {
1659 log_warn(LD_BUG,"Invalid service name '%s'",
1660 safe_str(conn->rend_data->onion_address));
1661 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1662 return -1;
1665 /* Help predict this next time. We're not sure if it will need
1666 * a stable circuit yet, but we know we'll need *something*. */
1667 rep_hist_note_used_internal(now, 0, 1);
1669 /* Look up if we have client authorization for it. */
1670 client_auth = rend_client_lookup_service_authorization(
1671 conn->rend_data->onion_address);
1672 if (client_auth) {
1673 log_info(LD_REND, "Using previously configured client authorization "
1674 "for hidden service request.");
1675 memcpy(conn->rend_data->descriptor_cookie,
1676 client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
1677 conn->rend_data->auth_type = client_auth->auth_type;
1679 if (r==0) {
1680 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1681 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1682 safe_str(conn->rend_data->onion_address));
1683 rend_client_refetch_v2_renddesc(conn->rend_data);
1684 } else { /* r > 0 */
1685 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1686 log_info(LD_REND, "Descriptor is here. Great.");
1687 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1688 if (!conn->_base.marked_for_close)
1689 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1690 return -1;
1693 return 0;
1695 return 0; /* unreached but keeps the compiler happy */
1698 #ifdef TRANS_PF
1699 static int pf_socket = -1;
1701 get_pf_socket(void)
1703 int pf;
1704 /* This should be opened before dropping privileges. */
1705 if (pf_socket >= 0)
1706 return pf_socket;
1708 #ifdef OPENBSD
1709 /* only works on OpenBSD */
1710 pf = open("/dev/pf", O_RDONLY);
1711 #else
1712 /* works on NetBSD and FreeBSD */
1713 pf = open("/dev/pf", O_RDWR);
1714 #endif
1716 if (pf < 0) {
1717 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1718 return -1;
1721 pf_socket = pf;
1722 return pf_socket;
1724 #endif
1726 /** Fetch the original destination address and port from a
1727 * system-specific interface and put them into a
1728 * socks_request_t as if they came from a socks request.
1730 * Return -1 if an error prevents fetching the destination,
1731 * else return 0.
1733 static int
1734 connection_ap_get_original_destination(edge_connection_t *conn,
1735 socks_request_t *req)
1737 #ifdef TRANS_NETFILTER
1738 /* Linux 2.4+ */
1739 struct sockaddr_storage orig_dst;
1740 socklen_t orig_dst_len = sizeof(orig_dst);
1741 tor_addr_t addr;
1743 if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
1744 (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
1745 int e = tor_socket_errno(conn->_base.s);
1746 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1747 return -1;
1750 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1751 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1753 return 0;
1754 #elif defined(TRANS_PF)
1755 struct sockaddr_storage proxy_addr;
1756 socklen_t proxy_addr_len = sizeof(proxy_addr);
1757 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1758 struct pfioc_natlook pnl;
1759 tor_addr_t addr;
1760 int pf = -1;
1762 if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
1763 &proxy_addr_len) < 0) {
1764 int e = tor_socket_errno(conn->_base.s);
1765 log_warn(LD_NET, "getsockname() to determine transocks destination "
1766 "failed: %s", tor_socket_strerror(e));
1767 return -1;
1770 memset(&pnl, 0, sizeof(pnl));
1771 pnl.proto = IPPROTO_TCP;
1772 pnl.direction = PF_OUT;
1773 if (proxy_sa->sa_family == AF_INET) {
1774 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1775 pnl.af = AF_INET;
1776 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&conn->_base.addr);
1777 pnl.sport = htons(conn->_base.port);
1778 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1779 pnl.dport = sin->sin_port;
1780 } else if (proxy_sa->sa_family == AF_INET6) {
1781 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1782 pnl.af = AF_INET6;
1783 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&conn->_base.addr),
1784 sizeof(struct in6_addr));
1785 pnl.sport = htons(conn->_base.port);
1786 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1787 pnl.dport = sin6->sin6_port;
1788 } else {
1789 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1790 (int)proxy_sa->sa_family);
1791 return -1;
1794 pf = get_pf_socket();
1795 if (pf<0)
1796 return -1;
1798 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1799 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1800 return -1;
1803 if (pnl.af == AF_INET) {
1804 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1805 } else if (pnl.af == AF_INET6) {
1806 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1807 } else {
1808 tor_fragile_assert();
1809 return -1;
1812 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1813 req->port = ntohs(pnl.rdport);
1815 return 0;
1816 #else
1817 (void)conn;
1818 (void)req;
1819 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1820 "transparent proxy method was configured.");
1821 return -1;
1822 #endif
1825 /** connection_edge_process_inbuf() found a conn in state
1826 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1827 * the socks handshake.
1829 * If the handshake is complete, send it to
1830 * connection_ap_handshake_rewrite_and_attach().
1832 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1833 * else return 0.
1835 static int
1836 connection_ap_handshake_process_socks(edge_connection_t *conn)
1838 socks_request_t *socks;
1839 int sockshere;
1840 or_options_t *options = get_options();
1842 tor_assert(conn);
1843 tor_assert(conn->_base.type == CONN_TYPE_AP);
1844 tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
1845 tor_assert(conn->socks_request);
1846 socks = conn->socks_request;
1848 log_debug(LD_APP,"entered.");
1850 sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
1851 options->TestSocks, options->SafeSocks);
1852 if (sockshere == 0) {
1853 if (socks->replylen) {
1854 connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
1855 /* zero it out so we can do another round of negotiation */
1856 socks->replylen = 0;
1857 } else {
1858 log_debug(LD_APP,"socks handshake not all here yet.");
1860 return 0;
1861 } else if (sockshere == -1) {
1862 if (socks->replylen) { /* we should send reply back */
1863 log_debug(LD_APP,"reply is already set for us. Using it.");
1864 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1865 END_STREAM_REASON_SOCKSPROTOCOL);
1867 } else {
1868 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
1869 connection_ap_handshake_socks_reply(conn, NULL, 0,
1870 END_STREAM_REASON_SOCKSPROTOCOL);
1872 connection_mark_unattached_ap(conn,
1873 END_STREAM_REASON_SOCKSPROTOCOL |
1874 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1875 return -1;
1876 } /* else socks handshake is done, continue processing */
1878 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
1879 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1880 else
1881 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
1883 if (options->LeaveStreamsUnattached) {
1884 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1885 return 0;
1887 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1890 /** connection_init_accepted_conn() found a new trans AP conn.
1891 * Get the original destination and send it to
1892 * connection_ap_handshake_rewrite_and_attach().
1894 * Return -1 if an unexpected error with conn (and it should be marked
1895 * for close), else return 0.
1898 connection_ap_process_transparent(edge_connection_t *conn)
1900 socks_request_t *socks;
1901 or_options_t *options = get_options();
1903 tor_assert(conn);
1904 tor_assert(conn->_base.type == CONN_TYPE_AP);
1905 tor_assert(conn->socks_request);
1906 socks = conn->socks_request;
1908 /* pretend that a socks handshake completed so we don't try to
1909 * send a socks reply down a transparent conn */
1910 socks->command = SOCKS_COMMAND_CONNECT;
1911 socks->has_finished = 1;
1913 log_debug(LD_APP,"entered.");
1915 if (connection_ap_get_original_destination(conn, socks) < 0) {
1916 log_warn(LD_APP,"Fetching original destination failed. Closing.");
1917 connection_mark_unattached_ap(conn,
1918 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
1919 return -1;
1921 /* we have the original destination */
1923 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1925 if (options->LeaveStreamsUnattached) {
1926 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1927 return 0;
1929 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1932 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1933 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1934 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1935 * form of the original destination.
1937 * If the original destination is complete, send it to
1938 * connection_ap_handshake_rewrite_and_attach().
1940 * Return -1 if an unexpected error with conn (and it should be marked
1941 * for close), else return 0.
1943 static int
1944 connection_ap_process_natd(edge_connection_t *conn)
1946 char tmp_buf[36], *tbuf, *daddr;
1947 size_t tlen = 30;
1948 int err, port_ok;
1949 socks_request_t *socks;
1950 or_options_t *options = get_options();
1952 tor_assert(conn);
1953 tor_assert(conn->_base.type == CONN_TYPE_AP);
1954 tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
1955 tor_assert(conn->socks_request);
1956 socks = conn->socks_request;
1958 log_debug(LD_APP,"entered.");
1960 /* look for LF-terminated "[DEST ip_addr port]"
1961 * where ip_addr is a dotted-quad and port is in string form */
1962 err = fetch_from_buf_line(conn->_base.inbuf, tmp_buf, &tlen);
1963 if (err == 0)
1964 return 0;
1965 if (err < 0) {
1966 log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
1967 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1968 return -1;
1971 if (strcmpstart(tmp_buf, "[DEST ")) {
1972 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1973 "said: %s",
1974 escaped(tmp_buf));
1975 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1976 return -1;
1979 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
1980 if (!(tbuf = strchr(tbuf, ' '))) {
1981 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1982 "said: %s",
1983 escaped(tmp_buf));
1984 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1985 return -1;
1987 *tbuf++ = '\0';
1989 /* pretend that a socks handshake completed so we don't try to
1990 * send a socks reply down a natd conn */
1991 strlcpy(socks->address, daddr, sizeof(socks->address));
1992 socks->port = (uint16_t)
1993 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
1994 if (!port_ok) {
1995 log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
1996 "of range.", escaped(tbuf));
1997 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1998 return -1;
2001 socks->command = SOCKS_COMMAND_CONNECT;
2002 socks->has_finished = 1;
2004 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2006 if (options->LeaveStreamsUnattached) {
2007 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2008 return 0;
2010 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2012 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
2015 /** Iterate over the two bytes of stream_id until we get one that is not
2016 * already in use; return it. Return 0 if can't get a unique stream_id.
2018 static streamid_t
2019 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2021 edge_connection_t *tmpconn;
2022 streamid_t test_stream_id;
2023 uint32_t attempts=0;
2025 again:
2026 test_stream_id = circ->next_stream_id++;
2027 if (++attempts > 1<<16) {
2028 /* Make sure we don't loop forever if all stream_id's are used. */
2029 log_warn(LD_APP,"No unused stream IDs. Failing.");
2030 return 0;
2032 if (test_stream_id == 0)
2033 goto again;
2034 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2035 if (tmpconn->stream_id == test_stream_id)
2036 goto again;
2037 return test_stream_id;
2040 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2041 * socks_request field, and send it down circ.
2043 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2046 connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
2048 char payload[CELL_PAYLOAD_SIZE];
2049 int payload_len;
2050 int begin_type;
2051 origin_circuit_t *circ;
2052 tor_assert(ap_conn->on_circuit);
2053 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2055 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2056 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2057 tor_assert(ap_conn->socks_request);
2058 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2060 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2061 if (ap_conn->stream_id==0) {
2062 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2063 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2064 return -1;
2067 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2068 (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2069 ap_conn->socks_request->address : "",
2070 ap_conn->socks_request->port);
2071 payload_len = (int)strlen(payload)+1;
2073 log_debug(LD_APP,
2074 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2076 begin_type = ap_conn->use_begindir ?
2077 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2078 if (begin_type == RELAY_COMMAND_BEGIN) {
2079 tor_assert(circ->build_state->onehop_tunnel == 0);
2082 if (connection_edge_send_command(ap_conn, begin_type,
2083 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2084 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2085 return -1; /* circuit is closed, don't continue */
2087 ap_conn->package_window = STREAMWINDOW_START;
2088 ap_conn->deliver_window = STREAMWINDOW_START;
2089 ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
2090 log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
2091 ap_conn->_base.s, circ->_base.n_circ_id);
2092 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2093 return 0;
2096 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2097 * socks_request field, and send it down circ.
2099 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2102 connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
2104 int payload_len, command;
2105 const char *string_addr;
2106 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2107 origin_circuit_t *circ;
2108 tor_assert(ap_conn->on_circuit);
2109 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2111 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2112 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2113 tor_assert(ap_conn->socks_request);
2114 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2116 command = ap_conn->socks_request->command;
2117 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2119 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2120 if (ap_conn->stream_id==0) {
2121 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2122 /*XXXX022 _close_ the circuit because it's full? That sounds dumb. */
2123 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2124 return -1;
2127 if (command == SOCKS_COMMAND_RESOLVE) {
2128 string_addr = ap_conn->socks_request->address;
2129 payload_len = (int)strlen(string_addr)+1;
2130 } else {
2131 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2132 const char *a = ap_conn->socks_request->address;
2133 tor_addr_t addr;
2134 int r;
2136 /* We're doing a reverse lookup. The input could be an IP address, or
2137 * could be an .in-addr.arpa or .ip6.arpa address */
2138 r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
2139 if (r <= 0) {
2140 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2141 safe_str(a));
2142 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2143 return -1;
2146 r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2147 if (r < 0) {
2148 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2149 safe_str(a));
2150 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2151 return -1;
2154 string_addr = inaddr_buf;
2155 payload_len = (int)strlen(inaddr_buf)+1;
2156 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
2159 if (payload_len > RELAY_PAYLOAD_SIZE) {
2160 /* This should be impossible: we don't accept addresses this big. */
2161 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2162 return -1;
2165 log_debug(LD_APP,
2166 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2168 if (connection_edge_send_command(ap_conn,
2169 RELAY_COMMAND_RESOLVE,
2170 string_addr, payload_len) < 0)
2171 return -1; /* circuit is closed, don't continue */
2173 tor_free(ap_conn->_base.address); /* Maybe already set by dnsserv. */
2174 ap_conn->_base.address = tor_strdup("(Tor_internal)");
2175 ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
2176 log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
2177 ap_conn->_base.s, circ->_base.n_circ_id);
2178 control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
2179 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2180 return 0;
2183 /** Make an AP connection_t, make a new linked connection pair, and attach
2184 * one side to the conn, connection_add it, initialize it to circuit_wait,
2185 * and call connection_ap_handshake_attach_circuit(conn) on it.
2187 * Return the other end of the linked connection pair, or -1 if error.
2189 edge_connection_t *
2190 connection_ap_make_link(char *address, uint16_t port,
2191 const char *digest, int use_begindir, int want_onehop)
2193 edge_connection_t *conn;
2195 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2196 want_onehop ? "direct" : "anonymized" , safe_str(address),port);
2198 conn = edge_connection_new(CONN_TYPE_AP, AF_INET);
2199 conn->_base.linked = 1; /* so that we can add it safely below. */
2201 /* populate conn->socks_request */
2203 /* leave version at zero, so the socks_reply is empty */
2204 conn->socks_request->socks_version = 0;
2205 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2206 strlcpy(conn->socks_request->address, address,
2207 sizeof(conn->socks_request->address));
2208 conn->socks_request->port = port;
2209 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2210 conn->want_onehop = want_onehop;
2211 conn->use_begindir = use_begindir;
2212 if (use_begindir) {
2213 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2214 conn->chosen_exit_name[0] = '$';
2215 tor_assert(digest);
2216 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2217 digest, DIGEST_LEN);
2220 conn->_base.address = tor_strdup("(Tor_internal)");
2221 tor_addr_make_unspec(&conn->_base.addr);
2222 conn->_base.port = 0;
2224 if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
2225 connection_free(TO_CONN(conn));
2226 return NULL;
2229 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2231 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2233 /* attaching to a dirty circuit is fine */
2234 if (connection_ap_handshake_attach_circuit(conn) < 0) {
2235 if (!conn->_base.marked_for_close)
2236 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2237 return NULL;
2240 log_info(LD_APP,"... application connection created and linked.");
2241 return conn;
2244 /** Notify any interested controller connections about a new hostname resolve
2245 * or resolve error. Takes the same arguments as does
2246 * connection_ap_handshake_socks_resolved(). */
2247 static void
2248 tell_controller_about_resolved_result(edge_connection_t *conn,
2249 int answer_type,
2250 size_t answer_len,
2251 const char *answer,
2252 int ttl,
2253 time_t expires)
2256 if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
2257 answer_type == RESOLVED_TYPE_HOSTNAME)) {
2258 return; /* we already told the controller. */
2259 } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2260 struct in_addr in;
2261 char buf[INET_NTOA_BUF_LEN];
2262 in.s_addr = get_uint32(answer);
2263 tor_inet_ntoa(&in, buf, sizeof(buf));
2264 control_event_address_mapped(conn->socks_request->address,
2265 buf, expires, NULL);
2266 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len <256) {
2267 char *cp = tor_strndup(answer, answer_len);
2268 control_event_address_mapped(conn->socks_request->address,
2269 cp, expires, NULL);
2270 tor_free(cp);
2271 } else {
2272 control_event_address_mapped(conn->socks_request->address,
2273 "<error>",
2274 time(NULL)+ttl,
2275 "error=yes");
2279 /** Send an answer to an AP connection that has requested a DNS lookup via
2280 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2281 * for unreachable; the answer should be in the format specified in the socks
2282 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2283 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2284 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2286 /* XXXX022 the use of the ttl and expires fields is nutty. Let's make this
2287 * interface and those that use it less ugly. */
2288 void
2289 connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2290 int answer_type,
2291 size_t answer_len,
2292 const char *answer,
2293 int ttl,
2294 time_t expires)
2296 char buf[384];
2297 size_t replylen;
2299 if (ttl >= 0) {
2300 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2301 uint32_t a = ntohl(get_uint32(answer));
2302 if (a)
2303 client_dns_set_addressmap(conn->socks_request->address, a,
2304 conn->chosen_exit_name, ttl);
2305 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2306 char *cp = tor_strndup(answer, answer_len);
2307 client_dns_set_reverse_addressmap(conn->socks_request->address,
2309 conn->chosen_exit_name, ttl);
2310 tor_free(cp);
2314 if (conn->is_dns_request) {
2315 if (conn->dns_server_request) {
2316 /* We had a request on our DNS port: answer it. */
2317 dnsserv_resolved(conn, answer_type, answer_len, answer, ttl);
2318 conn->socks_request->has_finished = 1;
2319 return;
2320 } else {
2321 /* This must be a request from the controller. We already sent
2322 * a mapaddress if there's a ttl. */
2323 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2324 answer, ttl, expires);
2325 conn->socks_request->has_finished = 1;
2326 return;
2328 /* We shouldn't need to free conn here; it gets marked by the caller. */
2331 if (conn->socks_request->socks_version == 4) {
2332 buf[0] = 0x00; /* version */
2333 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2334 buf[1] = SOCKS4_GRANTED;
2335 set_uint16(buf+2, 0);
2336 memcpy(buf+4, answer, 4); /* address */
2337 replylen = SOCKS4_NETWORK_LEN;
2338 } else { /* "error" */
2339 buf[1] = SOCKS4_REJECT;
2340 memset(buf+2, 0, 6);
2341 replylen = SOCKS4_NETWORK_LEN;
2343 } else if (conn->socks_request->socks_version == 5) {
2344 /* SOCKS5 */
2345 buf[0] = 0x05; /* version */
2346 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2347 buf[1] = SOCKS5_SUCCEEDED;
2348 buf[2] = 0; /* reserved */
2349 buf[3] = 0x01; /* IPv4 address type */
2350 memcpy(buf+4, answer, 4); /* address */
2351 set_uint16(buf+8, 0); /* port == 0. */
2352 replylen = 10;
2353 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2354 buf[1] = SOCKS5_SUCCEEDED;
2355 buf[2] = 0; /* reserved */
2356 buf[3] = 0x04; /* IPv6 address type */
2357 memcpy(buf+4, answer, 16); /* address */
2358 set_uint16(buf+20, 0); /* port == 0. */
2359 replylen = 22;
2360 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2361 buf[1] = SOCKS5_SUCCEEDED;
2362 buf[2] = 0; /* reserved */
2363 buf[3] = 0x03; /* Domainname address type */
2364 buf[4] = (char)answer_len;
2365 memcpy(buf+5, answer, answer_len); /* address */
2366 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2367 replylen = 5+answer_len+2;
2368 } else {
2369 buf[1] = SOCKS5_HOST_UNREACHABLE;
2370 memset(buf+2, 0, 8);
2371 replylen = 10;
2373 } else {
2374 /* no socks version info; don't send anything back */
2375 return;
2377 connection_ap_handshake_socks_reply(conn, buf, replylen,
2378 (answer_type == RESOLVED_TYPE_IPV4 ||
2379 answer_type == RESOLVED_TYPE_IPV6) ?
2380 0 : END_STREAM_REASON_RESOLVEFAILED);
2383 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2384 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2385 * handshaking.
2387 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2388 * and return, else reply based on <b>endreason</b> (one of
2389 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2390 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2392 void
2393 connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2394 size_t replylen, int endreason)
2396 char buf[256];
2397 socks5_reply_status_t status =
2398 stream_end_reason_to_socks5_response(endreason);
2400 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2402 control_event_stream_status(conn,
2403 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2404 endreason);
2406 if (conn->socks_request->has_finished) {
2407 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2408 "connection_ap_handshake_socks_reply.");
2409 return;
2411 if (replylen) { /* we already have a reply in mind */
2412 connection_write_to_buf(reply, replylen, TO_CONN(conn));
2413 conn->socks_request->has_finished = 1;
2414 return;
2416 if (conn->socks_request->socks_version == 4) {
2417 memset(buf,0,SOCKS4_NETWORK_LEN);
2418 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2419 /* leave version, destport, destip zero */
2420 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
2421 } else if (conn->socks_request->socks_version == 5) {
2422 buf[0] = 5; /* version 5 */
2423 buf[1] = (char)status;
2424 buf[2] = 0;
2425 buf[3] = 1; /* ipv4 addr */
2426 memset(buf+4,0,6); /* Set external addr/port to 0.
2427 The spec doesn't seem to say what to do here. -RD */
2428 connection_write_to_buf(buf,10,TO_CONN(conn));
2430 /* If socks_version isn't 4 or 5, don't send anything.
2431 * This can happen in the case of AP bridges. */
2432 conn->socks_request->has_finished = 1;
2433 return;
2436 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2437 * an exit hop for the circuit, or we are the origin and it is a
2438 * rendezvous begin.
2440 * Launch a new exit connection and initialize things appropriately.
2442 * If it's a rendezvous stream, call connection_exit_connect() on
2443 * it.
2445 * For general streams, call dns_resolve() on it first, and only call
2446 * connection_exit_connect() if the dns answer is already known.
2448 * Note that we don't call connection_add() on the new stream! We wait
2449 * for connection_exit_connect() to do that.
2451 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2452 * Else return 0.
2455 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2457 edge_connection_t *n_stream;
2458 relay_header_t rh;
2459 char *address=NULL;
2460 uint16_t port;
2461 or_circuit_t *or_circ = NULL;
2463 assert_circuit_ok(circ);
2464 if (!CIRCUIT_IS_ORIGIN(circ))
2465 or_circ = TO_OR_CIRCUIT(circ);
2467 relay_header_unpack(&rh, cell->payload);
2469 /* Note: we have to use relay_send_command_from_edge here, not
2470 * connection_edge_end or connection_edge_send_command, since those require
2471 * that we have a stream connected to a circuit, and we don't connect to a
2472 * circuit until we have a pending/successful resolve. */
2474 if (!server_mode(get_options()) &&
2475 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2476 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2477 "Relay begin cell at non-server. Closing.");
2478 relay_send_end_cell_from_edge(rh.stream_id, circ,
2479 END_STREAM_REASON_EXITPOLICY, NULL);
2480 return 0;
2483 if (rh.command == RELAY_COMMAND_BEGIN) {
2484 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
2485 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2486 "Relay begin cell has no \\0. Closing.");
2487 relay_send_end_cell_from_edge(rh.stream_id, circ,
2488 END_STREAM_REASON_TORPROTOCOL, NULL);
2489 return 0;
2491 if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
2492 &address,NULL,&port)<0) {
2493 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2494 "Unable to parse addr:port in relay begin cell. Closing.");
2495 relay_send_end_cell_from_edge(rh.stream_id, circ,
2496 END_STREAM_REASON_TORPROTOCOL, NULL);
2497 return 0;
2499 if (port==0) {
2500 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2501 "Missing port in relay begin cell. Closing.");
2502 relay_send_end_cell_from_edge(rh.stream_id, circ,
2503 END_STREAM_REASON_TORPROTOCOL, NULL);
2504 tor_free(address);
2505 return 0;
2507 if (or_circ && or_circ->is_first_hop &&
2508 !get_options()->AllowSingleHopExits) {
2509 /* Don't let clients use us as a single-hop proxy, unless the user
2510 * has explicitly allowed that in the config. It attracts attackers
2511 * and users who'd be better off with, well, single-hop proxies.
2513 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2514 "Attempt to open a stream on first hop of circuit. Closing.");
2515 relay_send_end_cell_from_edge(rh.stream_id, circ,
2516 END_STREAM_REASON_TORPROTOCOL, NULL);
2517 tor_free(address);
2518 return 0;
2520 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2521 if (!directory_permits_begindir_requests(get_options()) ||
2522 circ->purpose != CIRCUIT_PURPOSE_OR) {
2523 relay_send_end_cell_from_edge(rh.stream_id, circ,
2524 END_STREAM_REASON_NOTDIRECTORY, NULL);
2525 return 0;
2527 /* Make sure to get the 'real' address of the previous hop: the
2528 * caller might want to know whether his IP address has changed, and
2529 * we might already have corrected _base.addr[ess] for the relay's
2530 * canonical IP address. */
2531 if (or_circ && or_circ->p_conn)
2532 address = tor_dup_addr(&or_circ->p_conn->real_addr);
2533 else
2534 address = tor_strdup("127.0.0.1");
2535 port = 1; /* XXXX This value is never actually used anywhere, and there
2536 * isn't "really" a connection here. But we
2537 * need to set it to something nonzero. */
2538 } else {
2539 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2540 relay_send_end_cell_from_edge(rh.stream_id, circ,
2541 END_STREAM_REASON_INTERNAL, NULL);
2542 return 0;
2545 log_debug(LD_EXIT,"Creating new exit connection.");
2546 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2548 /* Remember the tunneled request ID in the new edge connection, so that
2549 * we can measure download times. */
2550 TO_CONN(n_stream)->dirreq_id = circ->dirreq_id;
2552 n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
2554 n_stream->stream_id = rh.stream_id;
2555 n_stream->_base.port = port;
2556 /* leave n_stream->s at -1, because it's not yet valid */
2557 n_stream->package_window = STREAMWINDOW_START;
2558 n_stream->deliver_window = STREAMWINDOW_START;
2560 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
2561 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2562 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
2563 n_stream->_base.address = tor_strdup("(rendezvous)");
2564 n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
2565 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
2566 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
2567 assert_circuit_ok(circ);
2568 if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
2569 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
2570 n_stream->_base.port);
2571 relay_send_end_cell_from_edge(rh.stream_id, circ,
2572 END_STREAM_REASON_EXITPOLICY,
2573 origin_circ->cpath->prev);
2574 connection_free(TO_CONN(n_stream));
2575 tor_free(address);
2576 return 0;
2578 assert_circuit_ok(circ);
2579 log_debug(LD_REND,"Finished assigning addr/port");
2580 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
2582 /* add it into the linked list of n_streams on this circuit */
2583 n_stream->next_stream = origin_circ->p_streams;
2584 n_stream->on_circuit = circ;
2585 origin_circ->p_streams = n_stream;
2586 assert_circuit_ok(circ);
2588 connection_exit_connect(n_stream);
2589 tor_free(address);
2590 return 0;
2592 tor_strlower(address);
2593 n_stream->_base.address = address;
2594 n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2595 /* default to failed, change in dns_resolve if it turns out not to fail */
2597 if (we_are_hibernating()) {
2598 relay_send_end_cell_from_edge(rh.stream_id, circ,
2599 END_STREAM_REASON_HIBERNATING, NULL);
2600 connection_free(TO_CONN(n_stream));
2601 return 0;
2604 n_stream->on_circuit = circ;
2606 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2607 tor_assert(or_circ);
2608 if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->real_addr))
2609 tor_addr_assign(&n_stream->_base.addr, &or_circ->p_conn->real_addr);
2610 return connection_exit_connect_dir(n_stream);
2613 log_debug(LD_EXIT,"about to start the dns_resolve().");
2615 /* send it off to the gethostbyname farm */
2616 switch (dns_resolve(n_stream)) {
2617 case 1: /* resolve worked; now n_stream is attached to circ. */
2618 assert_circuit_ok(circ);
2619 log_debug(LD_EXIT,"about to call connection_exit_connect().");
2620 connection_exit_connect(n_stream);
2621 return 0;
2622 case -1: /* resolve failed */
2623 relay_send_end_cell_from_edge(rh.stream_id, circ,
2624 END_STREAM_REASON_RESOLVEFAILED, NULL);
2625 /* n_stream got freed. don't touch it. */
2626 break;
2627 case 0: /* resolve added to pending list */
2628 assert_circuit_ok(circ);
2629 break;
2631 return 0;
2635 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2636 * circuit <b>circ</b>;
2637 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2640 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
2642 edge_connection_t *dummy_conn;
2643 relay_header_t rh;
2645 assert_circuit_ok(TO_CIRCUIT(circ));
2646 relay_header_unpack(&rh, cell->payload);
2648 /* This 'dummy_conn' only exists to remember the stream ID
2649 * associated with the resolve request; and to make the
2650 * implementation of dns.c more uniform. (We really only need to
2651 * remember the circuit, the stream ID, and the hostname to be
2652 * resolved; but if we didn't store them in a connection like this,
2653 * the housekeeping in dns.c would get way more complicated.)
2655 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2656 dummy_conn->stream_id = rh.stream_id;
2657 dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
2658 rh.length);
2659 dummy_conn->_base.port = 0;
2660 dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2661 dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
2663 dummy_conn->on_circuit = TO_CIRCUIT(circ);
2665 /* send it off to the gethostbyname farm */
2666 switch (dns_resolve(dummy_conn)) {
2667 case -1: /* Impossible to resolve; a resolved cell was sent. */
2668 /* Connection freed; don't touch it. */
2669 return 0;
2670 case 1: /* The result was cached; a resolved cell was sent. */
2671 if (!dummy_conn->_base.marked_for_close)
2672 connection_free(TO_CONN(dummy_conn));
2673 return 0;
2674 case 0: /* resolve added to pending list */
2675 assert_circuit_ok(TO_CIRCUIT(circ));
2676 break;
2678 return 0;
2681 /** Connect to conn's specified addr and port. If it worked, conn
2682 * has now been added to the connection_array.
2684 * Send back a connected cell. Include the resolved IP of the destination
2685 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2686 * streams must not reveal what IP they connected to.)
2688 void
2689 connection_exit_connect(edge_connection_t *edge_conn)
2691 const tor_addr_t *addr;
2692 uint16_t port;
2693 connection_t *conn = TO_CONN(edge_conn);
2694 int socket_error = 0;
2696 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
2697 router_compare_to_my_exit_policy(edge_conn)) {
2698 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
2699 escaped_safe_str(conn->address), conn->port);
2700 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
2701 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2702 connection_free(conn);
2703 return;
2706 addr = &conn->addr;
2707 port = conn->port;
2709 log_debug(LD_EXIT,"about to try connecting");
2710 switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
2711 case -1:
2712 /* XXX021 use socket_error below rather than trying to piece things
2713 * together from the current errno, which may have been clobbered. */
2714 connection_edge_end_errno(edge_conn);
2715 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2716 connection_free(conn);
2717 return;
2718 case 0:
2719 conn->state = EXIT_CONN_STATE_CONNECTING;
2721 connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
2722 /* writable indicates finish;
2723 * readable/error indicates broken link in windows-land. */
2724 return;
2725 /* case 1: fall through */
2728 conn->state = EXIT_CONN_STATE_OPEN;
2729 if (connection_wants_to_flush(conn)) {
2730 /* in case there are any queued data cells */
2731 log_warn(LD_BUG,"newly connected conn had data waiting!");
2732 // connection_start_writing(conn);
2734 connection_watch_events(conn, READ_EVENT);
2736 /* also, deliver a 'connected' cell back through the circuit. */
2737 if (connection_edge_is_rendezvous_stream(edge_conn)) {
2738 /* rendezvous stream */
2739 /* don't send an address back! */
2740 connection_edge_send_command(edge_conn,
2741 RELAY_COMMAND_CONNECTED,
2742 NULL, 0);
2743 } else { /* normal stream */
2744 char connected_payload[20];
2745 int connected_payload_len;
2746 if (tor_addr_family(&conn->addr) == AF_INET) {
2747 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
2748 connected_payload_len = 4;
2749 } else {
2750 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
2751 connected_payload_len = 16;
2753 set_uint32(connected_payload+connected_payload_len,
2754 htonl(dns_clip_ttl(edge_conn->address_ttl)));
2755 connected_payload_len += 4;
2756 connection_edge_send_command(edge_conn,
2757 RELAY_COMMAND_CONNECTED,
2758 connected_payload, connected_payload_len);
2762 /** Given an exit conn that should attach to us as a directory server, open a
2763 * bridge connection with a linked connection pair, create a new directory
2764 * conn, and join them together. Return 0 on success (or if there was an
2765 * error we could send back an end cell for). Return -(some circuit end
2766 * reason) if the circuit needs to be torn down. Either connects
2767 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2769 static int
2770 connection_exit_connect_dir(edge_connection_t *exitconn)
2772 dir_connection_t *dirconn = NULL;
2773 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
2775 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
2777 exitconn->_base.state = EXIT_CONN_STATE_OPEN;
2779 dirconn = dir_connection_new(AF_INET);
2781 tor_addr_assign(&dirconn->_base.addr, &exitconn->_base.addr);
2782 dirconn->_base.port = 0;
2783 dirconn->_base.address = tor_strdup(exitconn->_base.address);
2784 dirconn->_base.type = CONN_TYPE_DIR;
2785 dirconn->_base.purpose = DIR_PURPOSE_SERVER;
2786 dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2788 /* Note that the new dir conn belongs to the same tunneled request as
2789 * the edge conn, so that we can measure download times. */
2790 TO_CONN(dirconn)->dirreq_id = TO_CONN(exitconn)->dirreq_id;
2792 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
2794 if (connection_add(TO_CONN(exitconn))<0) {
2795 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2796 connection_free(TO_CONN(exitconn));
2797 connection_free(TO_CONN(dirconn));
2798 return 0;
2801 /* link exitconn to circ, now that we know we can use it. */
2802 exitconn->next_stream = circ->n_streams;
2803 circ->n_streams = exitconn;
2805 if (connection_add(TO_CONN(dirconn))<0) {
2806 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2807 connection_close_immediate(TO_CONN(exitconn));
2808 connection_mark_for_close(TO_CONN(exitconn));
2809 connection_free(TO_CONN(dirconn));
2810 return 0;
2813 connection_start_reading(TO_CONN(dirconn));
2814 connection_start_reading(TO_CONN(exitconn));
2816 if (connection_edge_send_command(exitconn,
2817 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
2818 connection_mark_for_close(TO_CONN(exitconn));
2819 connection_mark_for_close(TO_CONN(dirconn));
2820 return 0;
2823 return 0;
2826 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2827 * it is a general stream.
2830 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
2832 tor_assert(conn);
2833 if (conn->rend_data)
2834 return 1;
2835 return 0;
2838 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2839 * to exit from it, or 0 if it probably will not allow it.
2840 * (We might be uncertain if conn's destination address has not yet been
2841 * resolved.)
2844 connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit)
2846 tor_assert(conn);
2847 tor_assert(conn->_base.type == CONN_TYPE_AP);
2848 tor_assert(conn->socks_request);
2849 tor_assert(exit);
2851 /* If a particular exit node has been requested for the new connection,
2852 * make sure the exit node of the existing circuit matches exactly.
2854 if (conn->chosen_exit_name) {
2855 routerinfo_t *chosen_exit =
2856 router_get_by_nickname(conn->chosen_exit_name, 1);
2857 if (!chosen_exit || memcmp(chosen_exit->cache_info.identity_digest,
2858 exit->cache_info.identity_digest, DIGEST_LEN)) {
2859 /* doesn't match */
2860 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2861 // conn->chosen_exit_name, exit->nickname);
2862 return 0;
2866 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2867 !conn->use_begindir) {
2868 struct in_addr in;
2869 uint32_t addr = 0;
2870 addr_policy_result_t r;
2871 if (tor_inet_aton(conn->socks_request->address, &in))
2872 addr = ntohl(in.s_addr);
2873 r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
2874 exit->exit_policy);
2875 if (r == ADDR_POLICY_REJECTED)
2876 return 0; /* We know the address, and the exit policy rejects it. */
2877 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
2878 return 0; /* We don't know the addr, but the exit policy rejects most
2879 * addresses with this port. Since the user didn't ask for
2880 * this node, err on the side of caution. */
2881 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2882 /* Can't support reverse lookups without eventdns. */
2883 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
2884 exit->has_old_dnsworkers)
2885 return 0;
2887 /* Don't send DNS requests to non-exit servers by default. */
2888 if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
2889 return 0;
2891 return 1;
2894 /** If address is of the form "y.onion" with a well-formed handle y:
2895 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2897 * If address is of the form "y.exit" and <b>allowdotexit</b> is true:
2898 * Put a NUL after y and return EXIT_HOSTNAME.
2900 * Otherwise:
2901 * Return NORMAL_HOSTNAME and change nothing.
2903 hostname_type_t
2904 parse_extended_hostname(char *address, int allowdotexit)
2906 char *s;
2907 char query[REND_SERVICE_ID_LEN_BASE32+1];
2909 s = strrchr(address,'.');
2910 if (!s)
2911 return NORMAL_HOSTNAME; /* no dot, thus normal */
2912 if (!strcmp(s+1,"exit")) {
2913 if (allowdotexit) {
2914 *s = 0; /* NUL-terminate it */
2915 return EXIT_HOSTNAME; /* .exit */
2916 } /* else */
2917 log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
2918 "security risks. Set AllowDotExit in your torrc to enable it.");
2919 /* FFFF send a controller event too to notify Vidalia users */
2921 if (strcmp(s+1,"onion"))
2922 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
2924 /* so it is .onion */
2925 *s = 0; /* NUL-terminate it */
2926 if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
2927 REND_SERVICE_ID_LEN_BASE32+1)
2928 goto failed;
2929 if (rend_valid_service_id(query)) {
2930 return ONION_HOSTNAME; /* success */
2932 failed:
2933 /* otherwise, return to previous state and return 0 */
2934 *s = '.';
2935 return BAD_HOSTNAME;