fix compile
[tor/rransom.git] / src / or / connection_edge.c
blobd7e8394614aa5b8127c8058c3450a2986a161b17
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);
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 int timeout = get_options()->CircuitStreamTimeout;
381 if (timeout) /* if our config options override the default, use them */
382 return timeout;
383 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
384 return 10;
385 return 15;
388 /** Find all general-purpose AP streams waiting for a response that sent their
389 * begin/resolve cell too long ago. Detach from their current circuit, and
390 * mark their current circuit as unsuitable for new streams. Then call
391 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
392 * available) or launch a new one.
394 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
395 * retry attempt).
397 void
398 connection_ap_expire_beginning(void)
400 edge_connection_t *conn;
401 circuit_t *circ;
402 time_t now = time(NULL);
403 or_options_t *options = get_options();
404 int severity;
405 int cutoff;
406 int seconds_idle, seconds_since_born;
407 smartlist_t *conns = get_connection_array();
409 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
410 if (c->type != CONN_TYPE_AP || c->marked_for_close)
411 continue;
412 conn = TO_EDGE_CONN(c);
413 /* if it's an internal linked connection, don't yell its status. */
414 severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
415 ? LOG_INFO : LOG_NOTICE;
416 seconds_idle = (int)( now - conn->_base.timestamp_lastread );
417 seconds_since_born = (int)( now - conn->_base.timestamp_created );
419 if (conn->_base.state == AP_CONN_STATE_OPEN)
420 continue;
422 /* We already consider SocksTimeout in
423 * connection_ap_handshake_attach_circuit(), but we need to consider
424 * it here too because controllers that put streams in controller_wait
425 * state never ask Tor to attach the circuit. */
426 if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
427 if (seconds_since_born >= options->SocksTimeout) {
428 log_fn(severity, LD_APP,
429 "Tried for %d seconds to get a connection to %s:%d. "
430 "Giving up. (%s)",
431 seconds_since_born,
432 safe_str_client(conn->socks_request->address),
433 conn->socks_request->port,
434 conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
435 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
437 continue;
440 /* We're in state connect_wait or resolve_wait now -- waiting for a
441 * reply to our relay cell. See if we want to retry/give up. */
443 cutoff = compute_retry_timeout(conn);
444 if (seconds_idle < cutoff)
445 continue;
446 circ = circuit_get_by_edge_conn(conn);
447 if (!circ) { /* it's vanished? */
448 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
449 safe_str_client(conn->socks_request->address));
450 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
451 continue;
453 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
454 if (seconds_idle >= options->SocksTimeout) {
455 log_fn(severity, LD_REND,
456 "Rend stream is %d seconds late. Giving up on address"
457 " '%s.onion'.",
458 seconds_idle,
459 safe_str_client(conn->socks_request->address));
460 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
461 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
463 continue;
465 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
466 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
467 "We tried for %d seconds to connect to '%s' using exit '%s'."
468 " Retrying on a new circuit.",
469 seconds_idle,
470 safe_str_client(conn->socks_request->address),
471 conn->cpath_layer ?
472 conn->cpath_layer->extend_info->nickname : "*unnamed*");
473 /* send an end down the circuit */
474 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
475 /* un-mark it as ending, since we're going to reuse it */
476 conn->edge_has_sent_end = 0;
477 conn->end_reason = 0;
478 /* kludge to make us not try this circuit again, yet to allow
479 * current streams on it to survive if they can: make it
480 * unattractive to use for new streams */
481 tor_assert(circ->timestamp_dirty);
482 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
483 /* give our stream another 'cutoff' seconds to try */
484 conn->_base.timestamp_lastread += cutoff;
485 if (conn->num_socks_retries < 250) /* avoid overflow */
486 conn->num_socks_retries++;
487 /* move it back into 'pending' state, and try to attach. */
488 if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
489 END_STREAM_REASON_TIMEOUT)<0) {
490 if (!conn->_base.marked_for_close)
491 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
493 } SMARTLIST_FOREACH_END(conn);
496 /** Tell any AP streams that are waiting for a new circuit to try again,
497 * either attaching to an available circ or launching a new one.
499 void
500 connection_ap_attach_pending(void)
502 edge_connection_t *edge_conn;
503 smartlist_t *conns = get_connection_array();
504 SMARTLIST_FOREACH(conns, connection_t *, conn,
506 if (conn->marked_for_close ||
507 conn->type != CONN_TYPE_AP ||
508 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
509 continue;
510 edge_conn = TO_EDGE_CONN(conn);
511 if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
512 if (!edge_conn->_base.marked_for_close)
513 connection_mark_unattached_ap(edge_conn,
514 END_STREAM_REASON_CANT_ATTACH);
519 /** Tell any AP streams that are waiting for a one-hop tunnel to
520 * <b>failed_digest</b> that they are going to fail. */
521 /* XXX022 We should get rid of this function, and instead attach
522 * one-hop streams to circ->p_streams so they get marked in
523 * circuit_mark_for_close like normal p_streams. */
524 void
525 connection_ap_fail_onehop(const char *failed_digest,
526 cpath_build_state_t *build_state)
528 edge_connection_t *edge_conn;
529 char digest[DIGEST_LEN];
530 smartlist_t *conns = get_connection_array();
531 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
532 if (conn->marked_for_close ||
533 conn->type != CONN_TYPE_AP ||
534 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
535 continue;
536 edge_conn = TO_EDGE_CONN(conn);
537 if (!edge_conn->want_onehop)
538 continue;
539 if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
540 memcmp(digest, failed_digest, DIGEST_LEN))
541 continue;
542 if (tor_digest_is_zero(digest)) {
543 /* we don't know the digest; have to compare addr:port */
544 tor_addr_t addr;
545 if (!build_state || !build_state->chosen_exit ||
546 !edge_conn->socks_request || !edge_conn->socks_request->address)
547 continue;
548 if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
549 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
550 build_state->chosen_exit->port != edge_conn->socks_request->port)
551 continue;
553 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
554 "just failed.", edge_conn->chosen_exit_name,
555 edge_conn->socks_request->address);
556 connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
557 } SMARTLIST_FOREACH_END(conn);
560 /** A circuit failed to finish on its last hop <b>info</b>. If there
561 * are any streams waiting with this exit node in mind, but they
562 * don't absolutely require it, make them give up on it.
564 void
565 circuit_discard_optional_exit_enclaves(extend_info_t *info)
567 edge_connection_t *edge_conn;
568 routerinfo_t *r1, *r2;
570 smartlist_t *conns = get_connection_array();
571 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
572 if (conn->marked_for_close ||
573 conn->type != CONN_TYPE_AP ||
574 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
575 continue;
576 edge_conn = TO_EDGE_CONN(conn);
577 if (!edge_conn->chosen_exit_optional &&
578 !edge_conn->chosen_exit_retries)
579 continue;
580 r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
581 r2 = router_get_by_nickname(info->nickname, 0);
582 if (!r1 || !r2 || r1 != r2)
583 continue;
584 tor_assert(edge_conn->socks_request);
585 if (edge_conn->chosen_exit_optional) {
586 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
587 safe_str_client(edge_conn->chosen_exit_name),
588 escaped_safe_str_client(edge_conn->socks_request->address));
589 edge_conn->chosen_exit_optional = 0;
590 tor_free(edge_conn->chosen_exit_name); /* clears it */
591 /* if this port is dangerous, warn or reject it now that we don't
592 * think it'll be using an enclave. */
593 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
595 if (edge_conn->chosen_exit_retries) {
596 if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
597 clear_trackexithost_mappings(edge_conn->chosen_exit_name);
598 tor_free(edge_conn->chosen_exit_name); /* clears it */
599 /* if this port is dangerous, warn or reject it now that we don't
600 * think it'll be using an enclave. */
601 consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
604 } SMARTLIST_FOREACH_END(conn);
607 /** The AP connection <b>conn</b> has just failed while attaching or
608 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
609 * might work. Detach the circuit, and either reattach it, launch a
610 * new circuit, tell the controller, or give up as a appropriate.
612 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
615 connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
616 int reason)
618 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
619 conn->_base.timestamp_lastread = time(NULL);
620 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
621 /* If we're attaching streams ourself, or if this connection is
622 * a tunneled directory connection, then just attach it. */
623 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
624 circuit_detach_stream(TO_CIRCUIT(circ),conn);
625 return connection_ap_handshake_attach_circuit(conn);
626 } else {
627 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
628 circuit_detach_stream(TO_CIRCUIT(circ),conn);
629 return 0;
633 /** A client-side struct to remember requests to rewrite addresses
634 * to new addresses. These structs are stored in the hash table
635 * "addressmap" below.
637 * There are 5 ways to set an address mapping:
638 * - A MapAddress command from the controller [permanent]
639 * - An AddressMap directive in the torrc [permanent]
640 * - When a TrackHostExits torrc directive is triggered [temporary]
641 * - When a DNS resolve succeeds [temporary]
642 * - When a DNS resolve fails [temporary]
644 * When an addressmap request is made but one is already registered,
645 * the new one is replaced only if the currently registered one has
646 * no "new_address" (that is, it's in the process of DNS resolve),
647 * or if the new one is permanent (expires==0 or 1).
649 * (We overload the 'expires' field, using "0" for mappings set via
650 * the configuration file, "1" for mappings set from the control
651 * interface, and other values for DNS and TrackHostExit mappings that can
652 * expire.)
654 typedef struct {
655 char *new_address;
656 time_t expires;
657 addressmap_entry_source_t source:3;
658 short num_resolve_failures;
659 } addressmap_entry_t;
661 /** Entry for mapping addresses to which virtual address we mapped them to. */
662 typedef struct {
663 char *ipv4_address;
664 char *hostname_address;
665 } virtaddress_entry_t;
667 /** A hash table to store client-side address rewrite instructions. */
668 static strmap_t *addressmap=NULL;
670 * Table mapping addresses to which virtual address, if any, we
671 * assigned them to.
673 * We maintain the following invariant: if [A,B] is in
674 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
675 * must be in addressmap. We do not require that the converse hold:
676 * if it fails, then we could end up mapping two virtual addresses to
677 * the same address, which is no disaster.
679 static strmap_t *virtaddress_reversemap=NULL;
681 /** Initialize addressmap. */
682 void
683 addressmap_init(void)
685 addressmap = strmap_new();
686 virtaddress_reversemap = strmap_new();
689 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
690 static void
691 addressmap_ent_free(void *_ent)
693 addressmap_entry_t *ent;
694 if (!_ent)
695 return;
697 ent = _ent;
698 tor_free(ent->new_address);
699 tor_free(ent);
702 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
703 static void
704 addressmap_virtaddress_ent_free(void *_ent)
706 virtaddress_entry_t *ent;
707 if (!_ent)
708 return;
710 ent = _ent;
711 tor_free(ent->ipv4_address);
712 tor_free(ent->hostname_address);
713 tor_free(ent);
716 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
717 static void
718 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
720 if (ent && ent->new_address &&
721 address_is_in_virtual_range(ent->new_address)) {
722 virtaddress_entry_t *ve =
723 strmap_get(virtaddress_reversemap, ent->new_address);
724 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
725 if (ve) {
726 if (!strcmp(address, ve->ipv4_address))
727 tor_free(ve->ipv4_address);
728 if (!strcmp(address, ve->hostname_address))
729 tor_free(ve->hostname_address);
730 if (!ve->ipv4_address && !ve->hostname_address) {
731 tor_free(ve);
732 strmap_remove(virtaddress_reversemap, ent->new_address);
738 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
739 * client address maps. */
740 static void
741 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
743 addressmap_virtaddress_remove(address, ent);
744 addressmap_ent_free(ent);
747 /** Unregister all TrackHostExits mappings from any address to
748 * *.exitname.exit. */
749 static void
750 clear_trackexithost_mappings(const char *exitname)
752 char *suffix;
753 size_t suffix_len;
754 if (!addressmap || !exitname)
755 return;
756 suffix_len = strlen(exitname) + 16;
757 suffix = tor_malloc(suffix_len);
758 tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
759 tor_strlower(suffix);
761 STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
762 if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
763 addressmap_ent_remove(address, ent);
764 MAP_DEL_CURRENT(address);
766 } STRMAP_FOREACH_END;
768 tor_free(suffix);
771 /** Remove all entries from the addressmap that were set via the
772 * configuration file or the command line. */
773 void
774 addressmap_clear_configured(void)
776 addressmap_get_mappings(NULL, 0, 0, 0);
779 /** Remove all entries from the addressmap that are set to expire, ever. */
780 void
781 addressmap_clear_transient(void)
783 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
786 /** Clean out entries from the addressmap cache that were
787 * added long enough ago that they are no longer valid.
789 void
790 addressmap_clean(time_t now)
792 addressmap_get_mappings(NULL, 2, now, 0);
795 /** Free all the elements in the addressmap, and free the addressmap
796 * itself. */
797 void
798 addressmap_free_all(void)
800 strmap_free(addressmap, addressmap_ent_free);
801 addressmap = NULL;
803 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
804 virtaddress_reversemap = NULL;
807 /** Look at address, and rewrite it until it doesn't want any
808 * more rewrites; but don't get into an infinite loop.
809 * Don't write more than maxlen chars into address. Return true if the
810 * address changed; false otherwise. Set *<b>expires_out</b> to the
811 * expiry time of the result, or to <b>time_max</b> if the result does
812 * not expire.
815 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
817 addressmap_entry_t *ent;
818 int rewrites;
819 char *cp;
820 time_t expires = TIME_MAX;
822 for (rewrites = 0; rewrites < 16; rewrites++) {
823 ent = strmap_get(addressmap, address);
825 if (!ent || !ent->new_address) {
826 if (expires_out)
827 *expires_out = expires;
828 return (rewrites > 0); /* done, no rewrite needed */
831 cp = tor_strdup(escaped_safe_str_client(ent->new_address));
832 log_info(LD_APP, "Addressmap: rewriting %s to %s",
833 escaped_safe_str_client(address), cp);
834 if (ent->expires > 1 && ent->expires < expires)
835 expires = ent->expires;
836 tor_free(cp);
837 strlcpy(address, ent->new_address, maxlen);
839 log_warn(LD_CONFIG,
840 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
841 escaped_safe_str_client(address));
842 /* it's fine to rewrite a rewrite, but don't loop forever */
843 if (expires_out)
844 *expires_out = TIME_MAX;
845 return 1;
848 /** If we have a cached reverse DNS entry for the address stored in the
849 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
850 * rewrite to the cached value and return 1. Otherwise return 0. Set
851 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
852 * if the result does not expire. */
853 static int
854 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
856 size_t len = maxlen + 16;
857 char *s = tor_malloc(len), *cp;
858 addressmap_entry_t *ent;
859 int r = 0;
860 tor_snprintf(s, len, "REVERSE[%s]", address);
861 ent = strmap_get(addressmap, s);
862 if (ent) {
863 cp = tor_strdup(escaped_safe_str_client(ent->new_address));
864 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
865 escaped_safe_str_client(s), cp);
866 tor_free(cp);
867 strlcpy(address, ent->new_address, maxlen);
868 r = 1;
871 if (expires_out)
872 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
874 tor_free(s);
875 return r;
878 /** Return 1 if <b>address</b> is already registered, else return 0. If address
879 * is already registered, and <b>update_expires</b> is non-zero, then update
880 * the expiry time on the mapping with update_expires if it is a
881 * mapping created by TrackHostExits. */
883 addressmap_have_mapping(const char *address, int update_expiry)
885 addressmap_entry_t *ent;
886 if (!(ent=strmap_get_lc(addressmap, address)))
887 return 0;
888 if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
889 ent->expires=time(NULL) + update_expiry;
890 return 1;
893 /** Register a request to map <b>address</b> to <b>new_address</b>,
894 * which will expire on <b>expires</b> (or 0 if never expires from
895 * config file, 1 if never expires from controller, 2 if never expires
896 * (virtual address mapping) from the controller.)
898 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
899 * free as appropriate. We will leave address alone.
901 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
902 * any mappings that exist from <b>address</b>.
904 void
905 addressmap_register(const char *address, char *new_address, time_t expires,
906 addressmap_entry_source_t source)
908 addressmap_entry_t *ent;
910 ent = strmap_get(addressmap, address);
911 if (!new_address || !strcasecmp(address,new_address)) {
912 /* Remove the mapping, if any. */
913 tor_free(new_address);
914 if (ent) {
915 addressmap_ent_remove(address,ent);
916 strmap_remove(addressmap, address);
918 return;
920 if (!ent) { /* make a new one and register it */
921 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
922 strmap_set(addressmap, address, ent);
923 } else if (ent->new_address) { /* we need to clean up the old mapping. */
924 if (expires > 1) {
925 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
926 "since it's already mapped to '%s'",
927 safe_str_client(address),
928 safe_str_client(new_address),
929 safe_str_client(ent->new_address));
930 tor_free(new_address);
931 return;
933 if (address_is_in_virtual_range(ent->new_address) &&
934 expires != 2) {
935 /* XXX This isn't the perfect test; we want to avoid removing
936 * mappings set from the control interface _as virtual mapping */
937 addressmap_virtaddress_remove(address, ent);
939 tor_free(ent->new_address);
940 } /* else { we have an in-progress resolve with no mapping. } */
942 ent->new_address = new_address;
943 ent->expires = expires==2 ? 1 : expires;
944 ent->num_resolve_failures = 0;
945 ent->source = source;
947 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
948 safe_str_client(address),
949 safe_str_client(ent->new_address));
950 control_event_address_mapped(address, ent->new_address, expires, NULL);
953 /** An attempt to resolve <b>address</b> failed at some OR.
954 * Increment the number of resolve failures we have on record
955 * for it, and then return that number.
958 client_dns_incr_failures(const char *address)
960 addressmap_entry_t *ent = strmap_get(addressmap, address);
961 if (!ent) {
962 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
963 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
964 strmap_set(addressmap,address,ent);
966 if (ent->num_resolve_failures < SHORT_MAX)
967 ++ent->num_resolve_failures; /* don't overflow */
968 log_info(LD_APP, "Address %s now has %d resolve failures.",
969 safe_str_client(address),
970 ent->num_resolve_failures);
971 return ent->num_resolve_failures;
974 /** If <b>address</b> is in the client DNS addressmap, reset
975 * the number of resolve failures we have on record for it.
976 * This is used when we fail a stream because it won't resolve:
977 * otherwise future attempts on that address will only try once.
979 void
980 client_dns_clear_failures(const char *address)
982 addressmap_entry_t *ent = strmap_get(addressmap, address);
983 if (ent)
984 ent->num_resolve_failures = 0;
987 /** Record the fact that <b>address</b> resolved to <b>name</b>.
988 * We can now use this in subsequent streams via addressmap_rewrite()
989 * so we can more correctly choose an exit that will allow <b>address</b>.
991 * If <b>exitname</b> is defined, then append the addresses with
992 * ".exitname.exit" before registering the mapping.
994 * If <b>ttl</b> is nonnegative, the mapping will be valid for
995 * <b>ttl</b>seconds; otherwise, we use the default.
997 static void
998 client_dns_set_addressmap_impl(const char *address, const char *name,
999 const char *exitname,
1000 int ttl)
1002 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
1003 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
1004 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
1005 char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
1007 tor_assert(address);
1008 tor_assert(name);
1010 if (ttl<0)
1011 ttl = DEFAULT_DNS_TTL;
1012 else
1013 ttl = dns_clip_ttl(ttl);
1015 if (exitname) {
1016 /* XXXX fails to ever get attempts to get an exit address of
1017 * google.com.digest[=~]nickname.exit; we need a syntax for this that
1018 * won't make strict RFC952-compliant applications (like us) barf. */
1019 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1020 "%s.%s.exit", address, exitname);
1021 tor_snprintf(extendedval, sizeof(extendedval),
1022 "%s.%s.exit", name, exitname);
1023 } else {
1024 tor_snprintf(extendedaddress, sizeof(extendedaddress),
1025 "%s", address);
1026 tor_snprintf(extendedval, sizeof(extendedval),
1027 "%s", name);
1029 addressmap_register(extendedaddress, tor_strdup(extendedval),
1030 time(NULL) + ttl, ADDRMAPSRC_DNS);
1033 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1034 * We can now use this in subsequent streams via addressmap_rewrite()
1035 * so we can more correctly choose an exit that will allow <b>address</b>.
1037 * If <b>exitname</b> is defined, then append the addresses with
1038 * ".exitname.exit" before registering the mapping.
1040 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1041 * <b>ttl</b>seconds; otherwise, we use the default.
1043 void
1044 client_dns_set_addressmap(const char *address, uint32_t val,
1045 const char *exitname,
1046 int ttl)
1048 struct in_addr in;
1049 char valbuf[INET_NTOA_BUF_LEN];
1051 tor_assert(address);
1053 if (tor_inet_aton(address, &in))
1054 return; /* If address was an IP address already, don't add a mapping. */
1055 in.s_addr = htonl(val);
1056 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
1058 client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
1061 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1062 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1064 * If <b>exitname</b> is defined, then append the addresses with
1065 * ".exitname.exit" before registering the mapping.
1067 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1068 * <b>ttl</b>seconds; otherwise, we use the default.
1070 static void
1071 client_dns_set_reverse_addressmap(const char *address, const char *v,
1072 const char *exitname,
1073 int ttl)
1075 size_t len = strlen(address) + 16;
1076 char *s = tor_malloc(len);
1077 tor_snprintf(s, len, "REVERSE[%s]", address);
1078 client_dns_set_addressmap_impl(s, v, exitname, ttl);
1079 tor_free(s);
1082 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1083 * These addresses should map to localhost, so even if the
1084 * application accidentally tried to connect to them directly (not
1085 * via Tor), it wouldn't get too far astray.
1087 * These options are configured by parse_virtual_addr_network().
1089 /** Which network should we use for virtual IPv4 addresses? Only the first
1090 * bits of this value are fixed. */
1091 static uint32_t virtual_addr_network = 0x7fc00000u;
1092 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1093 static maskbits_t virtual_addr_netmask_bits = 10;
1094 /** What's the next virtual address we will hand out? */
1095 static uint32_t next_virtual_addr = 0x7fc00000u;
1097 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1098 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1099 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1100 * string and return -1 on failure. If validate_only is false, sets the
1101 * actual virtual address range to the parsed value. */
1103 parse_virtual_addr_network(const char *val, int validate_only,
1104 char **msg)
1106 uint32_t addr;
1107 uint16_t port_min, port_max;
1108 maskbits_t bits;
1110 if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
1111 if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
1112 return -1;
1115 if (port_min != 1 || port_max != 65535) {
1116 if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
1117 return -1;
1120 if (bits > 16) {
1121 if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
1122 "network or larger");
1123 return -1;
1126 if (validate_only)
1127 return 0;
1129 virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
1130 virtual_addr_netmask_bits = bits;
1132 if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
1133 next_virtual_addr = addr;
1135 return 0;
1139 * Return true iff <b>addr</b> is likely to have been returned by
1140 * client_dns_get_unused_address.
1142 static int
1143 address_is_in_virtual_range(const char *address)
1145 struct in_addr in;
1146 tor_assert(address);
1147 if (!strcasecmpend(address, ".virtual")) {
1148 return 1;
1149 } else if (tor_inet_aton(address, &in)) {
1150 uint32_t addr = ntohl(in.s_addr);
1151 if (!addr_mask_cmp_bits(addr, virtual_addr_network,
1152 virtual_addr_netmask_bits))
1153 return 1;
1155 return 0;
1158 /** Return a newly allocated string holding an address of <b>type</b>
1159 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1160 * and that is very unlikely to be the address of any real host.
1162 static char *
1163 addressmap_get_virtual_address(int type)
1165 char buf[64];
1166 struct in_addr in;
1167 tor_assert(addressmap);
1169 if (type == RESOLVED_TYPE_HOSTNAME) {
1170 char rand[10];
1171 do {
1172 crypto_rand(rand, sizeof(rand));
1173 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
1174 strlcat(buf, ".virtual", sizeof(buf));
1175 } while (strmap_get(addressmap, buf));
1176 return tor_strdup(buf);
1177 } else if (type == RESOLVED_TYPE_IPV4) {
1178 // This is an imperfect estimate of how many addresses are available, but
1179 // that's ok.
1180 uint32_t available = 1u << (32-virtual_addr_netmask_bits);
1181 while (available) {
1182 /* Don't hand out any .0 or .255 address. */
1183 while ((next_virtual_addr & 0xff) == 0 ||
1184 (next_virtual_addr & 0xff) == 0xff) {
1185 ++next_virtual_addr;
1187 in.s_addr = htonl(next_virtual_addr);
1188 tor_inet_ntoa(&in, buf, sizeof(buf));
1189 if (!strmap_get(addressmap, buf)) {
1190 ++next_virtual_addr;
1191 break;
1194 ++next_virtual_addr;
1195 --available;
1196 log_info(LD_CONFIG, "%d addrs available", (int)available);
1197 if (! --available) {
1198 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
1199 return NULL;
1201 if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
1202 virtual_addr_netmask_bits))
1203 next_virtual_addr = virtual_addr_network;
1205 return tor_strdup(buf);
1206 } else {
1207 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
1208 return NULL;
1212 /** A controller has requested that we map some address of type
1213 * <b>type</b> to the address <b>new_address</b>. Choose an address
1214 * that is unlikely to be used, and map it, and return it in a newly
1215 * allocated string. If another address of the same type is already
1216 * mapped to <b>new_address</b>, try to return a copy of that address.
1218 * The string in <b>new_address</b> may be freed, or inserted into a map
1219 * as appropriate.
1221 const char *
1222 addressmap_register_virtual_address(int type, char *new_address)
1224 char **addrp;
1225 virtaddress_entry_t *vent;
1227 tor_assert(new_address);
1228 tor_assert(addressmap);
1229 tor_assert(virtaddress_reversemap);
1231 vent = strmap_get(virtaddress_reversemap, new_address);
1232 if (!vent) {
1233 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
1234 strmap_set(virtaddress_reversemap, new_address, vent);
1237 addrp = (type == RESOLVED_TYPE_IPV4) ?
1238 &vent->ipv4_address : &vent->hostname_address;
1239 if (*addrp) {
1240 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1241 if (ent && ent->new_address &&
1242 !strcasecmp(new_address, ent->new_address)) {
1243 tor_free(new_address);
1244 return tor_strdup(*addrp);
1245 } else
1246 log_warn(LD_BUG,
1247 "Internal confusion: I thought that '%s' was mapped to by "
1248 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1249 safe_str_client(new_address),
1250 safe_str_client(*addrp),
1251 safe_str_client(*addrp),
1252 ent?safe_str_client(ent->new_address):"(nothing)");
1255 tor_free(*addrp);
1256 *addrp = addressmap_get_virtual_address(type);
1257 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1258 addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_CONTROLLER);
1260 #if 0
1262 /* Try to catch possible bugs */
1263 addressmap_entry_t *ent;
1264 ent = strmap_get(addressmap, *addrp);
1265 tor_assert(ent);
1266 tor_assert(!strcasecmp(ent->new_address,new_address));
1267 vent = strmap_get(virtaddress_reversemap, new_address);
1268 tor_assert(vent);
1269 tor_assert(!strcasecmp(*addrp,
1270 (type == RESOLVED_TYPE_IPV4) ?
1271 vent->ipv4_address : vent->hostname_address));
1272 log_info(LD_APP, "Map from %s to %s okay.",
1273 safe_str_client(*addrp),
1274 safe_str_client(new_address));
1276 #endif
1278 return *addrp;
1281 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1282 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1283 * should be true if we're using this address as a client; false if we're
1284 * using it as a server.
1287 address_is_invalid_destination(const char *address, int client)
1289 if (client) {
1290 if (get_options()->AllowNonRFC953Hostnames)
1291 return 0;
1292 } else {
1293 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1294 return 0;
1297 while (*address) {
1298 if (TOR_ISALNUM(*address) ||
1299 *address == '-' ||
1300 *address == '.' ||
1301 *address == '_') /* Underscore is not allowed, but Windows does it
1302 * sometimes, just to thumb its nose at the IETF. */
1303 ++address;
1304 else
1305 return 1;
1307 return 0;
1310 /** Iterate over all address mappings which have expiry times between
1311 * min_expires and max_expires, inclusive. If sl is provided, add an
1312 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1313 * the expiry time if want_expiry is false. If sl is NULL, remove the
1314 * mappings.
1316 void
1317 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1318 time_t max_expires, int want_expiry)
1320 strmap_iter_t *iter;
1321 const char *key;
1322 void *_val;
1323 addressmap_entry_t *val;
1325 if (!addressmap)
1326 addressmap_init();
1328 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1329 strmap_iter_get(iter, &key, &_val);
1330 val = _val;
1331 if (val->expires >= min_expires && val->expires <= max_expires) {
1332 if (!sl) {
1333 iter = strmap_iter_next_rmv(addressmap,iter);
1334 addressmap_ent_remove(key, val);
1335 continue;
1336 } else if (val->new_address) {
1337 size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
1338 char *line = tor_malloc(len);
1339 if (want_expiry) {
1340 if (val->expires < 3 || val->expires == TIME_MAX)
1341 tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
1342 else {
1343 char time[ISO_TIME_LEN+1];
1344 format_iso_time(time, val->expires);
1345 tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
1346 time);
1348 } else {
1349 tor_snprintf(line, len, "%s %s", key, val->new_address);
1351 smartlist_add(sl, line);
1354 iter = strmap_iter_next(addressmap,iter);
1358 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1359 * reject depending on our config options. */
1360 static int
1361 consider_plaintext_ports(edge_connection_t *conn, uint16_t port)
1363 or_options_t *options = get_options();
1364 int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
1366 if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
1367 log_warn(LD_APP, "Application request to port %d: this port is "
1368 "commonly used for unencrypted protocols. Please make sure "
1369 "you don't send anything you would mind the rest of the "
1370 "Internet reading!%s", port, reject ? " Closing." : "");
1371 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1372 port, reject ? "REJECT" : "WARN");
1375 if (reject) {
1376 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1377 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1378 return -1;
1381 return 0;
1384 /** How many times do we try connecting with an exit configured via
1385 * TrackHostExits before concluding that it won't work any more and trying a
1386 * different one? */
1387 #define TRACKHOSTEXITS_RETRIES 5
1389 /** Connection <b>conn</b> just finished its socks handshake, or the
1390 * controller asked us to take care of it. If <b>circ</b> is defined,
1391 * then that's where we'll want to attach it. Otherwise we have to
1392 * figure it out ourselves.
1394 * First, parse whether it's a .exit address, remap it, and so on. Then
1395 * if it's for a general circuit, try to attach it to a circuit (or launch
1396 * one as needed), else if it's for a rendezvous circuit, fetch a
1397 * rendezvous descriptor first (or attach/launch a circuit if the
1398 * rendezvous descriptor is already here and fresh enough).
1400 * The stream will exit from the hop
1401 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1402 * <b>cpath</b> is NULL.
1405 connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
1406 origin_circuit_t *circ,
1407 crypt_path_t *cpath)
1409 socks_request_t *socks = conn->socks_request;
1410 hostname_type_t addresstype;
1411 or_options_t *options = get_options();
1412 struct in_addr addr_tmp;
1413 int automap = 0;
1414 char orig_address[MAX_SOCKS_ADDR_LEN];
1415 time_t map_expires = TIME_MAX;
1416 int remapped_to_exit = 0;
1417 time_t now = time(NULL);
1419 tor_strlower(socks->address); /* normalize it */
1420 strlcpy(orig_address, socks->address, sizeof(orig_address));
1421 log_debug(LD_APP,"Client asked for %s:%d",
1422 safe_str_client(socks->address),
1423 socks->port);
1425 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1426 !tor_inet_aton(socks->address, &addr_tmp) &&
1427 options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
1428 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
1429 if (!strcasecmpend(socks->address, cp)) {
1430 automap = 1;
1431 break;
1433 if (automap) {
1434 const char *new_addr;
1435 new_addr = addressmap_register_virtual_address(
1436 RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
1437 tor_assert(new_addr);
1438 log_info(LD_APP, "Automapping %s to %s",
1439 escaped_safe_str_client(socks->address),
1440 safe_str_client(new_addr));
1441 strlcpy(socks->address, new_addr, sizeof(socks->address));
1445 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1446 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1447 &map_expires)) {
1448 char *result = tor_strdup(socks->address);
1449 /* remember _what_ is supposed to have been resolved. */
1450 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1451 orig_address);
1452 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1453 strlen(result), result, -1,
1454 map_expires);
1455 connection_mark_unattached_ap(conn,
1456 END_STREAM_REASON_DONE |
1457 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1458 return 0;
1460 if (options->ClientDNSRejectInternalAddresses) {
1461 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1462 tor_addr_t addr;
1463 int ok;
1464 ok = tor_addr_parse_reverse_lookup_name(
1465 &addr, socks->address, AF_UNSPEC, 1);
1466 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1467 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1468 0, NULL, -1, TIME_MAX);
1469 connection_mark_unattached_ap(conn,
1470 END_STREAM_REASON_SOCKSPROTOCOL |
1471 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1472 return -1;
1475 } else if (!automap) {
1476 int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
1477 /* For address map controls, remap the address. */
1478 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1479 &map_expires)) {
1480 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1481 REMAP_STREAM_SOURCE_CACHE);
1482 if (started_without_chosen_exit &&
1483 !strcasecmpend(socks->address, ".exit") &&
1484 map_expires < TIME_MAX)
1485 remapped_to_exit = 1;
1489 if (!automap && address_is_in_virtual_range(socks->address)) {
1490 /* This address was probably handed out by client_dns_get_unmapped_address,
1491 * but the mapping was discarded for some reason. We *don't* want to send
1492 * the address through Tor; that's likely to fail, and may leak
1493 * information.
1495 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1496 safe_str_client(socks->address));
1497 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
1498 return -1;
1501 /* Parse the address provided by SOCKS. Modify it in-place if it
1502 * specifies a hidden-service (.onion) or particular exit node (.exit).
1504 addresstype = parse_extended_hostname(socks->address,
1505 remapped_to_exit || options->AllowDotExit);
1507 if (addresstype == BAD_HOSTNAME) {
1508 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
1509 safe_str_client(socks->address));
1510 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1511 escaped(socks->address));
1512 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1513 return -1;
1516 if (addresstype == EXIT_HOSTNAME) {
1517 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1518 * node, and conn->address to hold only the address portion. */
1519 char *s = strrchr(socks->address,'.');
1520 tor_assert(!automap);
1521 if (s) {
1522 if (s[1] != '\0') {
1523 conn->chosen_exit_name = tor_strdup(s+1);
1524 if (remapped_to_exit) /* 5 tries before it expires the addressmap */
1525 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1526 *s = 0;
1527 } else {
1528 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1529 safe_str_client(socks->address));
1530 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1531 escaped(socks->address));
1532 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1533 return -1;
1535 } else {
1536 routerinfo_t *r;
1537 conn->chosen_exit_name = tor_strdup(socks->address);
1538 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1539 *socks->address = 0;
1540 if (r) {
1541 strlcpy(socks->address, r->address, sizeof(socks->address));
1542 } else {
1543 log_warn(LD_APP,
1544 "Unrecognized server in exit address '%s.exit'. Refusing.",
1545 safe_str_client(socks->address));
1546 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1547 return -1;
1552 if (addresstype != ONION_HOSTNAME) {
1553 /* not a hidden-service request (i.e. normal or .exit) */
1554 if (address_is_invalid_destination(socks->address, 1)) {
1555 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1556 escaped(socks->address));
1557 log_warn(LD_APP,
1558 "Destination '%s' seems to be an invalid hostname. Failing.",
1559 safe_str_client(socks->address));
1560 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1561 return -1;
1564 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1565 uint32_t answer;
1566 struct in_addr in;
1567 /* Reply to resolves immediately if we can. */
1568 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1569 /* leave it in network order */
1570 answer = in.s_addr;
1571 /* remember _what_ is supposed to have been resolved. */
1572 strlcpy(socks->address, orig_address, sizeof(socks->address));
1573 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1574 (char*)&answer,-1,map_expires);
1575 connection_mark_unattached_ap(conn,
1576 END_STREAM_REASON_DONE |
1577 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1578 return 0;
1580 tor_assert(!automap);
1581 rep_hist_note_used_resolve(now); /* help predict this next time */
1582 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1583 tor_assert(!automap);
1584 if (socks->port == 0) {
1585 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1586 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1587 return -1;
1590 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1591 /* see if we can find a suitable enclave exit */
1592 routerinfo_t *r =
1593 router_find_exact_exit_enclave(socks->address, socks->port);
1594 if (r) {
1595 log_info(LD_APP,
1596 "Redirecting address %s to exit at enclave router %s",
1597 safe_str_client(socks->address), r->nickname);
1598 /* use the hex digest, not nickname, in case there are two
1599 routers with this nickname */
1600 conn->chosen_exit_name =
1601 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1602 conn->chosen_exit_optional = 1;
1606 /* warn or reject if it's using a dangerous port */
1607 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1608 if (consider_plaintext_ports(conn, socks->port) < 0)
1609 return -1;
1611 if (!conn->use_begindir) {
1612 /* help predict this next time */
1613 rep_hist_note_used_port(now, socks->port);
1615 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1616 rep_hist_note_used_resolve(now); /* help predict this next time */
1617 /* no extra processing needed */
1618 } else {
1619 tor_fragile_assert();
1621 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1622 if ((circ && connection_ap_handshake_attach_chosen_circuit(
1623 conn, circ, cpath) < 0) ||
1624 (!circ &&
1625 connection_ap_handshake_attach_circuit(conn) < 0)) {
1626 if (!conn->_base.marked_for_close)
1627 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1628 return -1;
1630 return 0;
1631 } else {
1632 /* it's a hidden-service request */
1633 rend_cache_entry_t *entry;
1634 int r;
1635 rend_service_authorization_t *client_auth;
1636 tor_assert(!automap);
1637 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1638 /* if it's a resolve request, fail it right now, rather than
1639 * building all the circuits and then realizing it won't work. */
1640 log_warn(LD_APP,
1641 "Resolve requests to hidden services not allowed. Failing.");
1642 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1643 0,NULL,-1,TIME_MAX);
1644 connection_mark_unattached_ap(conn,
1645 END_STREAM_REASON_SOCKSPROTOCOL |
1646 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1647 return -1;
1650 if (circ) {
1651 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1652 "supported for .onion addresses currently. Failing.");
1653 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1654 return -1;
1657 conn->rend_data = tor_malloc_zero(sizeof(rend_data_t));
1658 strlcpy(conn->rend_data->onion_address, socks->address,
1659 sizeof(conn->rend_data->onion_address));
1660 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1661 safe_str_client(conn->rend_data->onion_address));
1662 /* see if we already have it cached */
1663 r = rend_cache_lookup_entry(conn->rend_data->onion_address, -1, &entry);
1664 if (r<0) {
1665 log_warn(LD_BUG,"Invalid service name '%s'",
1666 safe_str_client(conn->rend_data->onion_address));
1667 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1668 return -1;
1671 /* Help predict this next time. We're not sure if it will need
1672 * a stable circuit yet, but we know we'll need *something*. */
1673 rep_hist_note_used_internal(now, 0, 1);
1675 /* Look up if we have client authorization for it. */
1676 client_auth = rend_client_lookup_service_authorization(
1677 conn->rend_data->onion_address);
1678 if (client_auth) {
1679 log_info(LD_REND, "Using previously configured client authorization "
1680 "for hidden service request.");
1681 memcpy(conn->rend_data->descriptor_cookie,
1682 client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
1683 conn->rend_data->auth_type = client_auth->auth_type;
1685 if (r==0) {
1686 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1687 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1688 safe_str_client(conn->rend_data->onion_address));
1689 rend_client_refetch_v2_renddesc(conn->rend_data);
1690 } else { /* r > 0 */
1691 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1692 log_info(LD_REND, "Descriptor is here. Great.");
1693 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1694 if (!conn->_base.marked_for_close)
1695 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1696 return -1;
1699 return 0;
1701 return 0; /* unreached but keeps the compiler happy */
1704 #ifdef TRANS_PF
1705 static int pf_socket = -1;
1707 get_pf_socket(void)
1709 int pf;
1710 /* This should be opened before dropping privileges. */
1711 if (pf_socket >= 0)
1712 return pf_socket;
1714 #ifdef OPENBSD
1715 /* only works on OpenBSD */
1716 pf = open("/dev/pf", O_RDONLY);
1717 #else
1718 /* works on NetBSD and FreeBSD */
1719 pf = open("/dev/pf", O_RDWR);
1720 #endif
1722 if (pf < 0) {
1723 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1724 return -1;
1727 pf_socket = pf;
1728 return pf_socket;
1730 #endif
1732 /** Fetch the original destination address and port from a
1733 * system-specific interface and put them into a
1734 * socks_request_t as if they came from a socks request.
1736 * Return -1 if an error prevents fetching the destination,
1737 * else return 0.
1739 static int
1740 connection_ap_get_original_destination(edge_connection_t *conn,
1741 socks_request_t *req)
1743 #ifdef TRANS_NETFILTER
1744 /* Linux 2.4+ */
1745 struct sockaddr_storage orig_dst;
1746 socklen_t orig_dst_len = sizeof(orig_dst);
1747 tor_addr_t addr;
1749 if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
1750 (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
1751 int e = tor_socket_errno(conn->_base.s);
1752 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1753 return -1;
1756 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1757 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1759 return 0;
1760 #elif defined(TRANS_PF)
1761 struct sockaddr_storage proxy_addr;
1762 socklen_t proxy_addr_len = sizeof(proxy_addr);
1763 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1764 struct pfioc_natlook pnl;
1765 tor_addr_t addr;
1766 int pf = -1;
1768 if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
1769 &proxy_addr_len) < 0) {
1770 int e = tor_socket_errno(conn->_base.s);
1771 log_warn(LD_NET, "getsockname() to determine transocks destination "
1772 "failed: %s", tor_socket_strerror(e));
1773 return -1;
1776 memset(&pnl, 0, sizeof(pnl));
1777 pnl.proto = IPPROTO_TCP;
1778 pnl.direction = PF_OUT;
1779 if (proxy_sa->sa_family == AF_INET) {
1780 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1781 pnl.af = AF_INET;
1782 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&conn->_base.addr);
1783 pnl.sport = htons(conn->_base.port);
1784 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1785 pnl.dport = sin->sin_port;
1786 } else if (proxy_sa->sa_family == AF_INET6) {
1787 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1788 pnl.af = AF_INET6;
1789 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&conn->_base.addr),
1790 sizeof(struct in6_addr));
1791 pnl.sport = htons(conn->_base.port);
1792 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1793 pnl.dport = sin6->sin6_port;
1794 } else {
1795 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1796 (int)proxy_sa->sa_family);
1797 return -1;
1800 pf = get_pf_socket();
1801 if (pf<0)
1802 return -1;
1804 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1805 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1806 return -1;
1809 if (pnl.af == AF_INET) {
1810 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1811 } else if (pnl.af == AF_INET6) {
1812 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1813 } else {
1814 tor_fragile_assert();
1815 return -1;
1818 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1819 req->port = ntohs(pnl.rdport);
1821 return 0;
1822 #else
1823 (void)conn;
1824 (void)req;
1825 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1826 "transparent proxy method was configured.");
1827 return -1;
1828 #endif
1831 /** connection_edge_process_inbuf() found a conn in state
1832 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1833 * the socks handshake.
1835 * If the handshake is complete, send it to
1836 * connection_ap_handshake_rewrite_and_attach().
1838 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1839 * else return 0.
1841 static int
1842 connection_ap_handshake_process_socks(edge_connection_t *conn)
1844 socks_request_t *socks;
1845 int sockshere;
1846 or_options_t *options = get_options();
1848 tor_assert(conn);
1849 tor_assert(conn->_base.type == CONN_TYPE_AP);
1850 tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
1851 tor_assert(conn->socks_request);
1852 socks = conn->socks_request;
1854 log_debug(LD_APP,"entered.");
1856 sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
1857 options->TestSocks, options->SafeSocks);
1858 if (sockshere == 0) {
1859 if (socks->replylen) {
1860 connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
1861 /* zero it out so we can do another round of negotiation */
1862 socks->replylen = 0;
1863 } else {
1864 log_debug(LD_APP,"socks handshake not all here yet.");
1866 return 0;
1867 } else if (sockshere == -1) {
1868 if (socks->replylen) { /* we should send reply back */
1869 log_debug(LD_APP,"reply is already set for us. Using it.");
1870 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1871 END_STREAM_REASON_SOCKSPROTOCOL);
1873 } else {
1874 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
1875 connection_ap_handshake_socks_reply(conn, NULL, 0,
1876 END_STREAM_REASON_SOCKSPROTOCOL);
1878 connection_mark_unattached_ap(conn,
1879 END_STREAM_REASON_SOCKSPROTOCOL |
1880 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1881 return -1;
1882 } /* else socks handshake is done, continue processing */
1884 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
1885 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1886 else
1887 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
1889 if (options->LeaveStreamsUnattached) {
1890 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1891 return 0;
1893 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1896 /** connection_init_accepted_conn() found a new trans AP conn.
1897 * Get the original destination and send it to
1898 * connection_ap_handshake_rewrite_and_attach().
1900 * Return -1 if an unexpected error with conn (and it should be marked
1901 * for close), else return 0.
1904 connection_ap_process_transparent(edge_connection_t *conn)
1906 socks_request_t *socks;
1907 or_options_t *options = get_options();
1909 tor_assert(conn);
1910 tor_assert(conn->_base.type == CONN_TYPE_AP);
1911 tor_assert(conn->socks_request);
1912 socks = conn->socks_request;
1914 /* pretend that a socks handshake completed so we don't try to
1915 * send a socks reply down a transparent conn */
1916 socks->command = SOCKS_COMMAND_CONNECT;
1917 socks->has_finished = 1;
1919 log_debug(LD_APP,"entered.");
1921 if (connection_ap_get_original_destination(conn, socks) < 0) {
1922 log_warn(LD_APP,"Fetching original destination failed. Closing.");
1923 connection_mark_unattached_ap(conn,
1924 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
1925 return -1;
1927 /* we have the original destination */
1929 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1931 if (options->LeaveStreamsUnattached) {
1932 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1933 return 0;
1935 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1938 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1939 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1940 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1941 * form of the original destination.
1943 * If the original destination is complete, send it to
1944 * connection_ap_handshake_rewrite_and_attach().
1946 * Return -1 if an unexpected error with conn (and it should be marked
1947 * for close), else return 0.
1949 static int
1950 connection_ap_process_natd(edge_connection_t *conn)
1952 char tmp_buf[36], *tbuf, *daddr;
1953 size_t tlen = 30;
1954 int err, port_ok;
1955 socks_request_t *socks;
1956 or_options_t *options = get_options();
1958 tor_assert(conn);
1959 tor_assert(conn->_base.type == CONN_TYPE_AP);
1960 tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
1961 tor_assert(conn->socks_request);
1962 socks = conn->socks_request;
1964 log_debug(LD_APP,"entered.");
1966 /* look for LF-terminated "[DEST ip_addr port]"
1967 * where ip_addr is a dotted-quad and port is in string form */
1968 err = fetch_from_buf_line(conn->_base.inbuf, tmp_buf, &tlen);
1969 if (err == 0)
1970 return 0;
1971 if (err < 0) {
1972 log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
1973 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1974 return -1;
1977 if (strcmpstart(tmp_buf, "[DEST ")) {
1978 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1979 "said: %s",
1980 escaped(tmp_buf));
1981 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1982 return -1;
1985 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
1986 if (!(tbuf = strchr(tbuf, ' '))) {
1987 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1988 "said: %s",
1989 escaped(tmp_buf));
1990 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1991 return -1;
1993 *tbuf++ = '\0';
1995 /* pretend that a socks handshake completed so we don't try to
1996 * send a socks reply down a natd conn */
1997 strlcpy(socks->address, daddr, sizeof(socks->address));
1998 socks->port = (uint16_t)
1999 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2000 if (!port_ok) {
2001 log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
2002 "of range.", escaped(tbuf));
2003 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2004 return -1;
2007 socks->command = SOCKS_COMMAND_CONNECT;
2008 socks->has_finished = 1;
2010 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2012 if (options->LeaveStreamsUnattached) {
2013 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
2014 return 0;
2016 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2018 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
2021 /** Iterate over the two bytes of stream_id until we get one that is not
2022 * already in use; return it. Return 0 if can't get a unique stream_id.
2024 static streamid_t
2025 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2027 edge_connection_t *tmpconn;
2028 streamid_t test_stream_id;
2029 uint32_t attempts=0;
2031 again:
2032 test_stream_id = circ->next_stream_id++;
2033 if (++attempts > 1<<16) {
2034 /* Make sure we don't loop forever if all stream_id's are used. */
2035 log_warn(LD_APP,"No unused stream IDs. Failing.");
2036 return 0;
2038 if (test_stream_id == 0)
2039 goto again;
2040 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2041 if (tmpconn->stream_id == test_stream_id)
2042 goto again;
2043 return test_stream_id;
2046 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2047 * socks_request field, and send it down circ.
2049 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2052 connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
2054 char payload[CELL_PAYLOAD_SIZE];
2055 int payload_len;
2056 int begin_type;
2057 origin_circuit_t *circ;
2058 tor_assert(ap_conn->on_circuit);
2059 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2061 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2062 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2063 tor_assert(ap_conn->socks_request);
2064 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2066 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2067 if (ap_conn->stream_id==0) {
2068 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2069 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2070 return -1;
2073 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2074 (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2075 ap_conn->socks_request->address : "",
2076 ap_conn->socks_request->port);
2077 payload_len = (int)strlen(payload)+1;
2079 log_debug(LD_APP,
2080 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
2082 begin_type = ap_conn->use_begindir ?
2083 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2084 if (begin_type == RELAY_COMMAND_BEGIN) {
2085 tor_assert(circ->build_state->onehop_tunnel == 0);
2088 if (connection_edge_send_command(ap_conn, begin_type,
2089 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2090 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2091 return -1; /* circuit is closed, don't continue */
2093 ap_conn->package_window = STREAMWINDOW_START;
2094 ap_conn->deliver_window = STREAMWINDOW_START;
2095 ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
2096 log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
2097 ap_conn->_base.s, circ->_base.n_circ_id);
2098 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2099 return 0;
2102 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2103 * socks_request field, and send it down circ.
2105 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2108 connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
2110 int payload_len, command;
2111 const char *string_addr;
2112 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2113 origin_circuit_t *circ;
2114 tor_assert(ap_conn->on_circuit);
2115 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
2117 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
2118 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
2119 tor_assert(ap_conn->socks_request);
2120 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2122 command = ap_conn->socks_request->command;
2123 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2125 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
2126 if (ap_conn->stream_id==0) {
2127 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2128 /*XXXX022 _close_ the circuit because it's full? That sounds dumb. */
2129 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
2130 return -1;
2133 if (command == SOCKS_COMMAND_RESOLVE) {
2134 string_addr = ap_conn->socks_request->address;
2135 payload_len = (int)strlen(string_addr)+1;
2136 } else {
2137 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2138 const char *a = ap_conn->socks_request->address;
2139 tor_addr_t addr;
2140 int r;
2142 /* We're doing a reverse lookup. The input could be an IP address, or
2143 * could be an .in-addr.arpa or .ip6.arpa address */
2144 r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
2145 if (r <= 0) {
2146 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2147 safe_str_client(a));
2148 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2149 return -1;
2152 r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2153 if (r < 0) {
2154 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2155 safe_str_client(a));
2156 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2157 return -1;
2160 string_addr = inaddr_buf;
2161 payload_len = (int)strlen(inaddr_buf)+1;
2162 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
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",
2197 safe_str_client(address), port);
2199 conn = edge_connection_new(CONN_TYPE_AP, AF_INET);
2200 conn->_base.linked = 1; /* so that we can add it safely below. */
2202 /* populate conn->socks_request */
2204 /* leave version at zero, so the socks_reply is empty */
2205 conn->socks_request->socks_version = 0;
2206 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2207 strlcpy(conn->socks_request->address, address,
2208 sizeof(conn->socks_request->address));
2209 conn->socks_request->port = port;
2210 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2211 conn->want_onehop = want_onehop;
2212 conn->use_begindir = use_begindir;
2213 if (use_begindir) {
2214 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2215 conn->chosen_exit_name[0] = '$';
2216 tor_assert(digest);
2217 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2218 digest, DIGEST_LEN);
2221 conn->_base.address = tor_strdup("(Tor_internal)");
2222 tor_addr_make_unspec(&conn->_base.addr);
2223 conn->_base.port = 0;
2225 if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
2226 connection_free(TO_CONN(conn));
2227 return NULL;
2230 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
2232 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2234 /* attaching to a dirty circuit is fine */
2235 if (connection_ap_handshake_attach_circuit(conn) < 0) {
2236 if (!conn->_base.marked_for_close)
2237 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2238 return NULL;
2241 log_info(LD_APP,"... application connection created and linked.");
2242 return conn;
2245 /** Notify any interested controller connections about a new hostname resolve
2246 * or resolve error. Takes the same arguments as does
2247 * connection_ap_handshake_socks_resolved(). */
2248 static void
2249 tell_controller_about_resolved_result(edge_connection_t *conn,
2250 int answer_type,
2251 size_t answer_len,
2252 const char *answer,
2253 int ttl,
2254 time_t expires)
2257 if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
2258 answer_type == RESOLVED_TYPE_HOSTNAME)) {
2259 return; /* we already told the controller. */
2260 } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2261 struct in_addr in;
2262 char buf[INET_NTOA_BUF_LEN];
2263 in.s_addr = get_uint32(answer);
2264 tor_inet_ntoa(&in, buf, sizeof(buf));
2265 control_event_address_mapped(conn->socks_request->address,
2266 buf, expires, NULL);
2267 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len <256) {
2268 char *cp = tor_strndup(answer, answer_len);
2269 control_event_address_mapped(conn->socks_request->address,
2270 cp, expires, NULL);
2271 tor_free(cp);
2272 } else {
2273 control_event_address_mapped(conn->socks_request->address,
2274 "<error>",
2275 time(NULL)+ttl,
2276 "error=yes");
2280 /** Send an answer to an AP connection that has requested a DNS lookup via
2281 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2282 * for unreachable; the answer should be in the format specified in the socks
2283 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2284 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2285 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2287 /* XXXX022 the use of the ttl and expires fields is nutty. Let's make this
2288 * interface and those that use it less ugly. */
2289 void
2290 connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2291 int answer_type,
2292 size_t answer_len,
2293 const char *answer,
2294 int ttl,
2295 time_t expires)
2297 char buf[384];
2298 size_t replylen;
2300 if (ttl >= 0) {
2301 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2302 uint32_t a = ntohl(get_uint32(answer));
2303 if (a)
2304 client_dns_set_addressmap(conn->socks_request->address, a,
2305 conn->chosen_exit_name, ttl);
2306 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2307 char *cp = tor_strndup(answer, answer_len);
2308 client_dns_set_reverse_addressmap(conn->socks_request->address,
2310 conn->chosen_exit_name, ttl);
2311 tor_free(cp);
2315 if (conn->is_dns_request) {
2316 if (conn->dns_server_request) {
2317 /* We had a request on our DNS port: answer it. */
2318 dnsserv_resolved(conn, answer_type, answer_len, answer, ttl);
2319 conn->socks_request->has_finished = 1;
2320 return;
2321 } else {
2322 /* This must be a request from the controller. We already sent
2323 * a mapaddress if there's a ttl. */
2324 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2325 answer, ttl, expires);
2326 conn->socks_request->has_finished = 1;
2327 return;
2329 /* We shouldn't need to free conn here; it gets marked by the caller. */
2332 if (conn->socks_request->socks_version == 4) {
2333 buf[0] = 0x00; /* version */
2334 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2335 buf[1] = SOCKS4_GRANTED;
2336 set_uint16(buf+2, 0);
2337 memcpy(buf+4, answer, 4); /* address */
2338 replylen = SOCKS4_NETWORK_LEN;
2339 } else { /* "error" */
2340 buf[1] = SOCKS4_REJECT;
2341 memset(buf+2, 0, 6);
2342 replylen = SOCKS4_NETWORK_LEN;
2344 } else if (conn->socks_request->socks_version == 5) {
2345 /* SOCKS5 */
2346 buf[0] = 0x05; /* version */
2347 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2348 buf[1] = SOCKS5_SUCCEEDED;
2349 buf[2] = 0; /* reserved */
2350 buf[3] = 0x01; /* IPv4 address type */
2351 memcpy(buf+4, answer, 4); /* address */
2352 set_uint16(buf+8, 0); /* port == 0. */
2353 replylen = 10;
2354 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2355 buf[1] = SOCKS5_SUCCEEDED;
2356 buf[2] = 0; /* reserved */
2357 buf[3] = 0x04; /* IPv6 address type */
2358 memcpy(buf+4, answer, 16); /* address */
2359 set_uint16(buf+20, 0); /* port == 0. */
2360 replylen = 22;
2361 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2362 buf[1] = SOCKS5_SUCCEEDED;
2363 buf[2] = 0; /* reserved */
2364 buf[3] = 0x03; /* Domainname address type */
2365 buf[4] = (char)answer_len;
2366 memcpy(buf+5, answer, answer_len); /* address */
2367 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2368 replylen = 5+answer_len+2;
2369 } else {
2370 buf[1] = SOCKS5_HOST_UNREACHABLE;
2371 memset(buf+2, 0, 8);
2372 replylen = 10;
2374 } else {
2375 /* no socks version info; don't send anything back */
2376 return;
2378 connection_ap_handshake_socks_reply(conn, buf, replylen,
2379 (answer_type == RESOLVED_TYPE_IPV4 ||
2380 answer_type == RESOLVED_TYPE_IPV6) ?
2381 0 : END_STREAM_REASON_RESOLVEFAILED);
2384 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2385 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2386 * handshaking.
2388 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2389 * and return, else reply based on <b>endreason</b> (one of
2390 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2391 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2393 void
2394 connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2395 size_t replylen, int endreason)
2397 char buf[256];
2398 socks5_reply_status_t status =
2399 stream_end_reason_to_socks5_response(endreason);
2401 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2403 control_event_stream_status(conn,
2404 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2405 endreason);
2407 if (conn->socks_request->has_finished) {
2408 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2409 "connection_ap_handshake_socks_reply.");
2410 return;
2412 if (replylen) { /* we already have a reply in mind */
2413 connection_write_to_buf(reply, replylen, TO_CONN(conn));
2414 conn->socks_request->has_finished = 1;
2415 return;
2417 if (conn->socks_request->socks_version == 4) {
2418 memset(buf,0,SOCKS4_NETWORK_LEN);
2419 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2420 /* leave version, destport, destip zero */
2421 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
2422 } else if (conn->socks_request->socks_version == 5) {
2423 buf[0] = 5; /* version 5 */
2424 buf[1] = (char)status;
2425 buf[2] = 0;
2426 buf[3] = 1; /* ipv4 addr */
2427 memset(buf+4,0,6); /* Set external addr/port to 0.
2428 The spec doesn't seem to say what to do here. -RD */
2429 connection_write_to_buf(buf,10,TO_CONN(conn));
2431 /* If socks_version isn't 4 or 5, don't send anything.
2432 * This can happen in the case of AP bridges. */
2433 conn->socks_request->has_finished = 1;
2434 return;
2437 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2438 * an exit hop for the circuit, or we are the origin and it is a
2439 * rendezvous begin.
2441 * Launch a new exit connection and initialize things appropriately.
2443 * If it's a rendezvous stream, call connection_exit_connect() on
2444 * it.
2446 * For general streams, call dns_resolve() on it first, and only call
2447 * connection_exit_connect() if the dns answer is already known.
2449 * Note that we don't call connection_add() on the new stream! We wait
2450 * for connection_exit_connect() to do that.
2452 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2453 * Else return 0.
2456 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2458 edge_connection_t *n_stream;
2459 relay_header_t rh;
2460 char *address=NULL;
2461 uint16_t port;
2462 or_circuit_t *or_circ = NULL;
2464 assert_circuit_ok(circ);
2465 if (!CIRCUIT_IS_ORIGIN(circ))
2466 or_circ = TO_OR_CIRCUIT(circ);
2468 relay_header_unpack(&rh, cell->payload);
2470 /* Note: we have to use relay_send_command_from_edge here, not
2471 * connection_edge_end or connection_edge_send_command, since those require
2472 * that we have a stream connected to a circuit, and we don't connect to a
2473 * circuit until we have a pending/successful resolve. */
2475 if (!server_mode(get_options()) &&
2476 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2477 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2478 "Relay begin cell at non-server. Closing.");
2479 relay_send_end_cell_from_edge(rh.stream_id, circ,
2480 END_STREAM_REASON_EXITPOLICY, NULL);
2481 return 0;
2484 if (rh.command == RELAY_COMMAND_BEGIN) {
2485 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
2486 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2487 "Relay begin cell has no \\0. Closing.");
2488 relay_send_end_cell_from_edge(rh.stream_id, circ,
2489 END_STREAM_REASON_TORPROTOCOL, NULL);
2490 return 0;
2492 if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
2493 &address,NULL,&port)<0) {
2494 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2495 "Unable to parse addr:port in relay begin cell. Closing.");
2496 relay_send_end_cell_from_edge(rh.stream_id, circ,
2497 END_STREAM_REASON_TORPROTOCOL, NULL);
2498 return 0;
2500 if (port==0) {
2501 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2502 "Missing port in relay begin cell. Closing.");
2503 relay_send_end_cell_from_edge(rh.stream_id, circ,
2504 END_STREAM_REASON_TORPROTOCOL, NULL);
2505 tor_free(address);
2506 return 0;
2508 if (or_circ && or_circ->is_first_hop &&
2509 !get_options()->AllowSingleHopExits) {
2510 /* Don't let clients use us as a single-hop proxy, unless the user
2511 * has explicitly allowed that in the config. It attracts attackers
2512 * and users who'd be better off with, well, single-hop proxies.
2514 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2515 "Attempt to open a stream on first hop of circuit. Closing.");
2516 relay_send_end_cell_from_edge(rh.stream_id, circ,
2517 END_STREAM_REASON_TORPROTOCOL, NULL);
2518 tor_free(address);
2519 return 0;
2521 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2522 if (!directory_permits_begindir_requests(get_options()) ||
2523 circ->purpose != CIRCUIT_PURPOSE_OR) {
2524 relay_send_end_cell_from_edge(rh.stream_id, circ,
2525 END_STREAM_REASON_NOTDIRECTORY, NULL);
2526 return 0;
2528 /* Make sure to get the 'real' address of the previous hop: the
2529 * caller might want to know whether his IP address has changed, and
2530 * we might already have corrected _base.addr[ess] for the relay's
2531 * canonical IP address. */
2532 if (or_circ && or_circ->p_conn)
2533 address = tor_dup_addr(&or_circ->p_conn->real_addr);
2534 else
2535 address = tor_strdup("127.0.0.1");
2536 port = 1; /* XXXX This value is never actually used anywhere, and there
2537 * isn't "really" a connection here. But we
2538 * need to set it to something nonzero. */
2539 } else {
2540 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2541 relay_send_end_cell_from_edge(rh.stream_id, circ,
2542 END_STREAM_REASON_INTERNAL, NULL);
2543 return 0;
2546 log_debug(LD_EXIT,"Creating new exit connection.");
2547 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2549 /* Remember the tunneled request ID in the new edge connection, so that
2550 * we can measure download times. */
2551 TO_CONN(n_stream)->dirreq_id = circ->dirreq_id;
2553 n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
2555 n_stream->stream_id = rh.stream_id;
2556 n_stream->_base.port = port;
2557 /* leave n_stream->s at -1, because it's not yet valid */
2558 n_stream->package_window = STREAMWINDOW_START;
2559 n_stream->deliver_window = STREAMWINDOW_START;
2561 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
2562 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2563 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
2564 n_stream->_base.address = tor_strdup("(rendezvous)");
2565 n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
2566 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
2567 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
2568 assert_circuit_ok(circ);
2569 if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
2570 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
2571 n_stream->_base.port);
2572 relay_send_end_cell_from_edge(rh.stream_id, circ,
2573 END_STREAM_REASON_EXITPOLICY,
2574 origin_circ->cpath->prev);
2575 connection_free(TO_CONN(n_stream));
2576 tor_free(address);
2577 return 0;
2579 assert_circuit_ok(circ);
2580 log_debug(LD_REND,"Finished assigning addr/port");
2581 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
2583 /* add it into the linked list of n_streams on this circuit */
2584 n_stream->next_stream = origin_circ->p_streams;
2585 n_stream->on_circuit = circ;
2586 origin_circ->p_streams = n_stream;
2587 assert_circuit_ok(circ);
2589 connection_exit_connect(n_stream);
2590 tor_free(address);
2591 return 0;
2593 tor_strlower(address);
2594 n_stream->_base.address = address;
2595 n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2596 /* default to failed, change in dns_resolve if it turns out not to fail */
2598 if (we_are_hibernating()) {
2599 relay_send_end_cell_from_edge(rh.stream_id, circ,
2600 END_STREAM_REASON_HIBERNATING, NULL);
2601 connection_free(TO_CONN(n_stream));
2602 return 0;
2605 n_stream->on_circuit = circ;
2607 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2608 tor_assert(or_circ);
2609 if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->real_addr))
2610 tor_addr_assign(&n_stream->_base.addr, &or_circ->p_conn->real_addr);
2611 return connection_exit_connect_dir(n_stream);
2614 log_debug(LD_EXIT,"about to start the dns_resolve().");
2616 /* send it off to the gethostbyname farm */
2617 switch (dns_resolve(n_stream)) {
2618 case 1: /* resolve worked; now n_stream is attached to circ. */
2619 assert_circuit_ok(circ);
2620 log_debug(LD_EXIT,"about to call connection_exit_connect().");
2621 connection_exit_connect(n_stream);
2622 return 0;
2623 case -1: /* resolve failed */
2624 relay_send_end_cell_from_edge(rh.stream_id, circ,
2625 END_STREAM_REASON_RESOLVEFAILED, NULL);
2626 /* n_stream got freed. don't touch it. */
2627 break;
2628 case 0: /* resolve added to pending list */
2629 assert_circuit_ok(circ);
2630 break;
2632 return 0;
2636 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2637 * circuit <b>circ</b>;
2638 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2641 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
2643 edge_connection_t *dummy_conn;
2644 relay_header_t rh;
2646 assert_circuit_ok(TO_CIRCUIT(circ));
2647 relay_header_unpack(&rh, cell->payload);
2649 /* This 'dummy_conn' only exists to remember the stream ID
2650 * associated with the resolve request; and to make the
2651 * implementation of dns.c more uniform. (We really only need to
2652 * remember the circuit, the stream ID, and the hostname to be
2653 * resolved; but if we didn't store them in a connection like this,
2654 * the housekeeping in dns.c would get way more complicated.)
2656 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2657 dummy_conn->stream_id = rh.stream_id;
2658 dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
2659 rh.length);
2660 dummy_conn->_base.port = 0;
2661 dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2662 dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
2664 dummy_conn->on_circuit = TO_CIRCUIT(circ);
2666 /* send it off to the gethostbyname farm */
2667 switch (dns_resolve(dummy_conn)) {
2668 case -1: /* Impossible to resolve; a resolved cell was sent. */
2669 /* Connection freed; don't touch it. */
2670 return 0;
2671 case 1: /* The result was cached; a resolved cell was sent. */
2672 if (!dummy_conn->_base.marked_for_close)
2673 connection_free(TO_CONN(dummy_conn));
2674 return 0;
2675 case 0: /* resolve added to pending list */
2676 assert_circuit_ok(TO_CIRCUIT(circ));
2677 break;
2679 return 0;
2682 /** Connect to conn's specified addr and port. If it worked, conn
2683 * has now been added to the connection_array.
2685 * Send back a connected cell. Include the resolved IP of the destination
2686 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2687 * streams must not reveal what IP they connected to.)
2689 void
2690 connection_exit_connect(edge_connection_t *edge_conn)
2692 const tor_addr_t *addr;
2693 uint16_t port;
2694 connection_t *conn = TO_CONN(edge_conn);
2695 int socket_error = 0;
2697 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
2698 router_compare_to_my_exit_policy(edge_conn)) {
2699 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
2700 escaped_safe_str_client(conn->address), conn->port);
2701 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
2702 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2703 connection_free(conn);
2704 return;
2707 addr = &conn->addr;
2708 port = conn->port;
2710 log_debug(LD_EXIT,"about to try connecting");
2711 switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
2712 case -1:
2713 /* XXX021 use socket_error below rather than trying to piece things
2714 * together from the current errno, which may have been clobbered. */
2715 connection_edge_end_errno(edge_conn);
2716 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2717 connection_free(conn);
2718 return;
2719 case 0:
2720 conn->state = EXIT_CONN_STATE_CONNECTING;
2722 connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
2723 /* writable indicates finish;
2724 * readable/error indicates broken link in windows-land. */
2725 return;
2726 /* case 1: fall through */
2729 conn->state = EXIT_CONN_STATE_OPEN;
2730 if (connection_wants_to_flush(conn)) {
2731 /* in case there are any queued data cells */
2732 log_warn(LD_BUG,"newly connected conn had data waiting!");
2733 // connection_start_writing(conn);
2735 connection_watch_events(conn, READ_EVENT);
2737 /* also, deliver a 'connected' cell back through the circuit. */
2738 if (connection_edge_is_rendezvous_stream(edge_conn)) {
2739 /* rendezvous stream */
2740 /* don't send an address back! */
2741 connection_edge_send_command(edge_conn,
2742 RELAY_COMMAND_CONNECTED,
2743 NULL, 0);
2744 } else { /* normal stream */
2745 char connected_payload[20];
2746 int connected_payload_len;
2747 if (tor_addr_family(&conn->addr) == AF_INET) {
2748 set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
2749 connected_payload_len = 4;
2750 } else {
2751 memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
2752 connected_payload_len = 16;
2754 set_uint32(connected_payload+connected_payload_len,
2755 htonl(dns_clip_ttl(edge_conn->address_ttl)));
2756 connected_payload_len += 4;
2757 connection_edge_send_command(edge_conn,
2758 RELAY_COMMAND_CONNECTED,
2759 connected_payload, connected_payload_len);
2763 /** Given an exit conn that should attach to us as a directory server, open a
2764 * bridge connection with a linked connection pair, create a new directory
2765 * conn, and join them together. Return 0 on success (or if there was an
2766 * error we could send back an end cell for). Return -(some circuit end
2767 * reason) if the circuit needs to be torn down. Either connects
2768 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2770 static int
2771 connection_exit_connect_dir(edge_connection_t *exitconn)
2773 dir_connection_t *dirconn = NULL;
2774 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
2776 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
2778 exitconn->_base.state = EXIT_CONN_STATE_OPEN;
2780 dirconn = dir_connection_new(AF_INET);
2782 tor_addr_assign(&dirconn->_base.addr, &exitconn->_base.addr);
2783 dirconn->_base.port = 0;
2784 dirconn->_base.address = tor_strdup(exitconn->_base.address);
2785 dirconn->_base.type = CONN_TYPE_DIR;
2786 dirconn->_base.purpose = DIR_PURPOSE_SERVER;
2787 dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2789 /* Note that the new dir conn belongs to the same tunneled request as
2790 * the edge conn, so that we can measure download times. */
2791 TO_CONN(dirconn)->dirreq_id = TO_CONN(exitconn)->dirreq_id;
2793 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
2795 if (connection_add(TO_CONN(exitconn))<0) {
2796 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2797 connection_free(TO_CONN(exitconn));
2798 connection_free(TO_CONN(dirconn));
2799 return 0;
2802 /* link exitconn to circ, now that we know we can use it. */
2803 exitconn->next_stream = circ->n_streams;
2804 circ->n_streams = exitconn;
2806 if (connection_add(TO_CONN(dirconn))<0) {
2807 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2808 connection_close_immediate(TO_CONN(exitconn));
2809 connection_mark_for_close(TO_CONN(exitconn));
2810 connection_free(TO_CONN(dirconn));
2811 return 0;
2814 connection_start_reading(TO_CONN(dirconn));
2815 connection_start_reading(TO_CONN(exitconn));
2817 if (connection_edge_send_command(exitconn,
2818 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
2819 connection_mark_for_close(TO_CONN(exitconn));
2820 connection_mark_for_close(TO_CONN(dirconn));
2821 return 0;
2824 return 0;
2827 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2828 * it is a general stream.
2831 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
2833 tor_assert(conn);
2834 if (conn->rend_data)
2835 return 1;
2836 return 0;
2839 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2840 * to exit from it, or 0 if it probably will not allow it.
2841 * (We might be uncertain if conn's destination address has not yet been
2842 * resolved.)
2844 * If <b>excluded_means_no</b> is 1 and Exclude*Nodes is set and excludes
2845 * this relay, return 0.
2848 connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit,
2849 int excluded_means_no)
2851 or_options_t *options = get_options();
2853 tor_assert(conn);
2854 tor_assert(conn->_base.type == CONN_TYPE_AP);
2855 tor_assert(conn->socks_request);
2856 tor_assert(exit);
2858 /* If a particular exit node has been requested for the new connection,
2859 * make sure the exit node of the existing circuit matches exactly.
2861 if (conn->chosen_exit_name) {
2862 routerinfo_t *chosen_exit =
2863 router_get_by_nickname(conn->chosen_exit_name, 1);
2864 if (!chosen_exit || memcmp(chosen_exit->cache_info.identity_digest,
2865 exit->cache_info.identity_digest, DIGEST_LEN)) {
2866 /* doesn't match */
2867 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2868 // conn->chosen_exit_name, exit->nickname);
2869 return 0;
2873 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2874 !conn->use_begindir) {
2875 struct in_addr in;
2876 uint32_t addr = 0;
2877 addr_policy_result_t r;
2878 if (tor_inet_aton(conn->socks_request->address, &in))
2879 addr = ntohl(in.s_addr);
2880 r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
2881 exit->exit_policy);
2882 if (r == ADDR_POLICY_REJECTED)
2883 return 0; /* We know the address, and the exit policy rejects it. */
2884 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
2885 return 0; /* We don't know the addr, but the exit policy rejects most
2886 * addresses with this port. Since the user didn't ask for
2887 * this node, err on the side of caution. */
2888 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2889 /* Can't support reverse lookups without eventdns. */
2890 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
2891 exit->has_old_dnsworkers)
2892 return 0;
2894 /* Don't send DNS requests to non-exit servers by default. */
2895 if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
2896 return 0;
2898 if (options->_ExcludeExitNodesUnion &&
2899 (options->StrictNodes || excluded_means_no) &&
2900 routerset_contains_router(options->_ExcludeExitNodesUnion, exit)) {
2901 /* If we are trying to avoid this node as exit, and we have StrictNodes
2902 * set, then this is not a suitable exit. Refuse it.
2904 * If we don't have StrictNodes set, then this function gets called in
2905 * two contexts. First, we've got a circuit open and we want to know
2906 * whether we can use it. In that case, we somehow built this circuit
2907 * despite having the last hop in ExcludeExitNodes, so we should be
2908 * willing to use it. Second, we are evaluating whether this is an
2909 * acceptable exit for a new circuit. In that case, skip it. */
2910 return 0;
2913 return 1;
2916 /** If address is of the form "y.onion" with a well-formed handle y:
2917 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2919 * If address is of the form "y.exit" and <b>allowdotexit</b> is true:
2920 * Put a NUL after y and return EXIT_HOSTNAME.
2922 * Otherwise:
2923 * Return NORMAL_HOSTNAME and change nothing.
2925 hostname_type_t
2926 parse_extended_hostname(char *address, int allowdotexit)
2928 char *s;
2929 char query[REND_SERVICE_ID_LEN_BASE32+1];
2931 s = strrchr(address,'.');
2932 if (!s)
2933 return NORMAL_HOSTNAME; /* no dot, thus normal */
2934 if (!strcmp(s+1,"exit")) {
2935 if (allowdotexit) {
2936 *s = 0; /* NUL-terminate it */
2937 return EXIT_HOSTNAME; /* .exit */
2938 } /* else */
2939 log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
2940 "security risks. Set AllowDotExit in your torrc to enable it.");
2941 /* FFFF send a controller event too to notify Vidalia users */
2943 if (strcmp(s+1,"onion"))
2944 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
2946 /* so it is .onion */
2947 *s = 0; /* NUL-terminate it */
2948 if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
2949 REND_SERVICE_ID_LEN_BASE32+1)
2950 goto failed;
2951 if (rend_valid_service_id(query)) {
2952 return ONION_HOSTNAME; /* success */
2954 failed:
2955 /* otherwise, return to previous state and return 0 */
2956 *s = '.';
2957 return BAD_HOSTNAME;