Drop support for v1 rendezvous descriptors, since we never used
[tor.git] / src / or / connection_edge.c
blobcb319bda2ff271a14bcfea39392e18af46104e53
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char connection_edge_c_id[] =
7 "$Id$";
9 /**
10 * \file connection_edge.c
11 * \brief Handle edge streams.
12 **/
14 #include "or.h"
16 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
17 #include <linux/netfilter_ipv4.h>
18 #define TRANS_NETFILTER
19 #endif
21 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
22 #include <net/if.h>
23 #include <net/pfvar.h>
24 #define TRANS_PF
25 #endif
27 /** List of exit_redirect_t for every configured RedirectExit. */
28 static smartlist_t *redirect_exit_list = NULL;
30 static int connection_ap_handshake_process_socks(edge_connection_t *conn);
31 static int connection_ap_process_natd(edge_connection_t *conn);
32 static int connection_exit_connect_dir(edge_connection_t *exitconn);
34 /** An AP stream has failed/finished. If it hasn't already sent back
35 * a socks reply, send one now (based on endreason). Also set
36 * has_sent_end to 1, and mark the conn.
38 void
39 _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
40 int line, const char *file)
42 tor_assert(conn->_base.type == CONN_TYPE_AP);
43 conn->_base.edge_has_sent_end = 1; /* no circ yet */
45 if (conn->_base.marked_for_close) {
46 /* This call will warn as appropriate. */
47 _connection_mark_for_close(TO_CONN(conn), line, file);
48 return;
51 if (!conn->socks_request->has_finished) {
52 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
53 log_warn(LD_BUG,
54 "stream (marked at %s:%d) sending two socks replies?",
55 file, line);
57 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
58 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
59 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
60 connection_ap_handshake_socks_resolved(conn,
61 RESOLVED_TYPE_ERROR_TRANSIENT,
62 0, NULL, -1, -1);
63 else /* unknown or no handshake at all. send no response. */
64 conn->socks_request->has_finished = 1;
67 _connection_mark_for_close(TO_CONN(conn), line, file);
68 conn->_base.hold_open_until_flushed = 1;
69 conn->end_reason = endreason;
72 /** There was an EOF. Send an end and mark the connection for close.
74 int
75 connection_edge_reached_eof(edge_connection_t *conn)
77 if (buf_datalen(conn->_base.inbuf) &&
78 connection_state_is_open(TO_CONN(conn))) {
79 /* it still has stuff to process. don't let it die yet. */
80 return 0;
82 log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
83 if (!conn->_base.marked_for_close) {
84 /* only mark it if not already marked. it's possible to
85 * get the 'end' right around when the client hangs up on us. */
86 connection_edge_end(conn, END_STREAM_REASON_DONE);
87 if (conn->socks_request) /* eof, so don't send a socks reply back */
88 conn->socks_request->has_finished = 1;
89 connection_mark_for_close(TO_CONN(conn));
91 return 0;
94 /** Handle new bytes on conn->inbuf based on state:
95 * - If it's waiting for socks info, try to read another step of the
96 * socks handshake out of conn->inbuf.
97 * - If it's waiting for the original destination, fetch it.
98 * - If it's open, then package more relay cells from the stream.
99 * - Else, leave the bytes on inbuf alone for now.
101 * Mark and return -1 if there was an unexpected error with the conn,
102 * else return 0.
105 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
107 tor_assert(conn);
109 switch (conn->_base.state) {
110 case AP_CONN_STATE_SOCKS_WAIT:
111 if (connection_ap_handshake_process_socks(conn) < 0) {
112 /* already marked */
113 return -1;
115 return 0;
116 case AP_CONN_STATE_NATD_WAIT:
117 if (connection_ap_process_natd(conn) < 0) {
118 /* already marked */
119 return -1;
121 return 0;
122 case AP_CONN_STATE_OPEN:
123 case EXIT_CONN_STATE_OPEN:
124 if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
125 /* (We already sent an end cell if possible) */
126 connection_mark_for_close(TO_CONN(conn));
127 return -1;
129 return 0;
130 case EXIT_CONN_STATE_CONNECTING:
131 case AP_CONN_STATE_RENDDESC_WAIT:
132 case AP_CONN_STATE_CIRCUIT_WAIT:
133 case AP_CONN_STATE_CONNECT_WAIT:
134 case AP_CONN_STATE_RESOLVE_WAIT:
135 case AP_CONN_STATE_CONTROLLER_WAIT:
136 log_info(LD_EDGE,
137 "data from edge while in '%s' state. Leaving it on buffer.",
138 conn_state_to_string(conn->_base.type, conn->_base.state));
139 return 0;
141 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
142 tor_fragile_assert();
143 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
144 connection_mark_for_close(TO_CONN(conn));
145 return -1;
148 /** This edge needs to be closed, because its circuit has closed.
149 * Mark it for close and return 0.
152 connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn)
154 if (!conn->_base.marked_for_close) {
155 log_info(LD_EDGE,
156 "CircID %d: At an edge. Marking connection for close.", circ_id);
157 if (conn->_base.type == CONN_TYPE_AP) {
158 connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
159 } else {
160 /* closing the circuit, nothing to send an END to */
161 conn->_base.edge_has_sent_end = 1;
162 conn->end_reason = END_STREAM_REASON_DESTROY;
163 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
164 if (conn->_base.type == CONN_TYPE_AP)
165 control_event_stream_status(conn, STREAM_EVENT_CLOSED,
166 END_STREAM_REASON_DESTROY);
167 connection_mark_for_close(TO_CONN(conn));
168 conn->_base.hold_open_until_flushed = 1;
171 conn->cpath_layer = NULL;
172 conn->on_circuit = NULL;
173 return 0;
176 /** Send a relay end cell from stream <b>conn</b> down conn's circuit. Set
177 * the relay end cell's reason for closing as <b>reason</b>.
179 * Return -1 if this function has already been called on this conn,
180 * else return 0.
183 connection_edge_end(edge_connection_t *conn, char reason)
185 char payload[RELAY_PAYLOAD_SIZE];
186 size_t payload_len=1;
187 circuit_t *circ;
189 if (conn->_base.edge_has_sent_end) {
190 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
191 "on an already ended stream?", reason);
192 tor_fragile_assert();
193 return -1;
196 if (conn->_base.marked_for_close) {
197 log_warn(LD_BUG,
198 "called on conn that's already marked for close at %s:%d.",
199 conn->_base.marked_for_close_file, conn->_base.marked_for_close);
200 return 0;
203 payload[0] = reason;
204 if (reason == END_STREAM_REASON_EXITPOLICY &&
205 !connection_edge_is_rendezvous_stream(conn)) {
206 set_uint32(payload+1, htonl(conn->_base.addr));
207 set_uint32(payload+5, htonl(dns_clip_ttl(conn->address_ttl)));
208 payload_len += 8;
211 circ = circuit_get_by_edge_conn(conn);
212 if (circ && !circ->marked_for_close) {
213 log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
214 connection_edge_send_command(conn, RELAY_COMMAND_END,
215 payload, payload_len);
216 } else {
217 log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
218 conn->_base.s);
221 conn->_base.edge_has_sent_end = 1;
222 conn->end_reason = reason;
223 return 0;
226 /** An error has just occured on an operation on an edge connection
227 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
228 * appropriate relay end cell to the other end of the connection's circuit.
231 connection_edge_end_errno(edge_connection_t *conn)
233 uint8_t reason;
234 tor_assert(conn);
235 reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->_base.s));
236 return connection_edge_end(conn, reason);
239 /** Connection <b>conn</b> has finished writing and has no bytes left on
240 * its outbuf.
242 * If it's in state 'open', stop writing, consider responding with a
243 * sendme, and return.
244 * Otherwise, stop writing and return.
246 * If <b>conn</b> is broken, mark it for close and return -1, else
247 * return 0.
250 connection_edge_finished_flushing(edge_connection_t *conn)
252 tor_assert(conn);
254 switch (conn->_base.state) {
255 case AP_CONN_STATE_OPEN:
256 case EXIT_CONN_STATE_OPEN:
257 connection_stop_writing(TO_CONN(conn));
258 connection_edge_consider_sending_sendme(conn);
259 return 0;
260 case AP_CONN_STATE_SOCKS_WAIT:
261 case AP_CONN_STATE_NATD_WAIT:
262 case AP_CONN_STATE_RENDDESC_WAIT:
263 case AP_CONN_STATE_CIRCUIT_WAIT:
264 case AP_CONN_STATE_CONNECT_WAIT:
265 case AP_CONN_STATE_CONTROLLER_WAIT:
266 connection_stop_writing(TO_CONN(conn));
267 return 0;
268 default:
269 log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
270 tor_fragile_assert();
271 return -1;
273 return 0;
276 /** Connected handler for exit connections: start writing pending
277 * data, deliver 'CONNECTED' relay cells as appropriate, and check
278 * any pending data that may have been received. */
280 connection_edge_finished_connecting(edge_connection_t *edge_conn)
282 char valbuf[INET_NTOA_BUF_LEN];
283 connection_t *conn;
284 struct in_addr in;
286 tor_assert(edge_conn);
287 tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
288 conn = TO_CONN(edge_conn);
289 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
291 in.s_addr = htonl(conn->addr);
292 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
293 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
294 escaped_safe_str(conn->address),conn->port,safe_str(valbuf));
296 conn->state = EXIT_CONN_STATE_OPEN;
297 connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
298 if (connection_wants_to_flush(conn)) /* in case there are any queued relay
299 * cells */
300 connection_start_writing(conn);
301 /* deliver a 'connected' relay cell back through the circuit. */
302 if (connection_edge_is_rendezvous_stream(edge_conn)) {
303 if (connection_edge_send_command(edge_conn,
304 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
305 return 0; /* circuit is closed, don't continue */
306 } else {
307 char connected_payload[8];
308 set_uint32(connected_payload, htonl(conn->addr));
309 set_uint32(connected_payload+4,
310 htonl(dns_clip_ttl(edge_conn->address_ttl)));
311 if (connection_edge_send_command(edge_conn,
312 RELAY_COMMAND_CONNECTED,
313 connected_payload, 8) < 0)
314 return 0; /* circuit is closed, don't continue */
316 tor_assert(edge_conn->package_window > 0);
317 /* in case the server has written anything */
318 return connection_edge_process_inbuf(edge_conn, 1);
321 /** Define a schedule for how long to wait between retrying
322 * application connections. Rather than waiting a fixed amount of
323 * time between each retry, we wait 10 seconds each for the first
324 * two tries, and 15 seconds for each retry after
325 * that. Hopefully this will improve the expected user experience. */
326 static int
327 compute_retry_timeout(edge_connection_t *conn)
329 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
330 return 10;
331 return 15;
334 /** Find all general-purpose AP streams waiting for a response that sent their
335 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
336 * mark their current circuit as unsuitable for new streams. Then call
337 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
338 * available) or launch a new one.
340 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
341 * retry attempt).
343 void
344 connection_ap_expire_beginning(void)
346 edge_connection_t *conn;
347 circuit_t *circ;
348 time_t now = time(NULL);
349 or_options_t *options = get_options();
350 int severity;
351 int cutoff;
352 int seconds_idle;
353 smartlist_t *conns = get_connection_array();
355 SMARTLIST_FOREACH(conns, connection_t *, c,
357 if (c->type != CONN_TYPE_AP)
358 continue;
359 conn = TO_EDGE_CONN(c);
360 /* if it's an internal linked connection, don't yell its status. */
361 severity = (!conn->_base.addr && !conn->_base.port)
362 ? LOG_INFO : LOG_NOTICE;
363 seconds_idle = now - conn->_base.timestamp_lastread;
365 if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
366 if (seconds_idle >= options->SocksTimeout) {
367 log_fn(severity, LD_APP,
368 "Tried for %d seconds to get a connection to %s:%d. "
369 "Giving up. (%s)",
370 seconds_idle, safe_str(conn->socks_request->address),
371 conn->socks_request->port,
372 conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
373 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
375 continue;
378 if (conn->_base.state == AP_CONN_STATE_OPEN)
379 continue;
381 /* We're in state connect_wait or resolve_wait now -- waiting for a
382 * reply to our relay cell. See if we want to retry/give up. */
384 cutoff = compute_retry_timeout(conn);
385 if (seconds_idle < cutoff)
386 continue;
387 circ = circuit_get_by_edge_conn(conn);
388 if (!circ) { /* it's vanished? */
389 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
390 safe_str(conn->socks_request->address));
391 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
392 continue;
394 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
395 if (seconds_idle >= options->SocksTimeout) {
396 log_fn(severity, LD_REND,
397 "Rend stream is %d seconds late. Giving up on address"
398 " '%s.onion'.",
399 seconds_idle,
400 safe_str(conn->socks_request->address));
401 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
402 connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
404 continue;
406 tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
407 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
408 "We tried for %d seconds to connect to '%s' using exit '%s'."
409 " Retrying on a new circuit.",
410 seconds_idle, safe_str(conn->socks_request->address),
411 conn->cpath_layer ?
412 conn->cpath_layer->extend_info->nickname : "*unnamed*");
413 /* send an end down the circuit */
414 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
415 /* un-mark it as ending, since we're going to reuse it */
416 conn->_base.edge_has_sent_end = 0;
417 conn->end_reason = 0;
418 /* kludge to make us not try this circuit again, yet to allow
419 * current streams on it to survive if they can: make it
420 * unattractive to use for new streams */
421 tor_assert(circ->timestamp_dirty);
422 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
423 /* give our stream another 'cutoff' seconds to try */
424 conn->_base.timestamp_lastread += cutoff;
425 if (conn->num_socks_retries < 250) /* avoid overflow */
426 conn->num_socks_retries++;
427 /* move it back into 'pending' state, and try to attach. */
428 if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
429 END_STREAM_REASON_TIMEOUT)<0) {
430 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
432 }); /* end foreach */
435 /** Tell any AP streams that are waiting for a new circuit to try again,
436 * either attaching to an available circ or launching a new one.
438 void
439 connection_ap_attach_pending(void)
441 edge_connection_t *edge_conn;
442 smartlist_t *conns = get_connection_array();
443 SMARTLIST_FOREACH(conns, connection_t *, conn,
445 if (conn->marked_for_close ||
446 conn->type != CONN_TYPE_AP ||
447 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
448 continue;
449 edge_conn = TO_EDGE_CONN(conn);
450 if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
451 connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_CANT_ATTACH);
456 /** A circuit failed to finish on its last hop <b>info</b>. If there
457 * are any streams waiting with this exit node in mind, but they
458 * don't absolutely require it, make them give up on it.
460 void
461 circuit_discard_optional_exit_enclaves(extend_info_t *info)
463 edge_connection_t *edge_conn;
464 routerinfo_t *r1, *r2;
466 smartlist_t *conns = get_connection_array();
467 SMARTLIST_FOREACH(conns, connection_t *, conn,
469 if (conn->marked_for_close ||
470 conn->type != CONN_TYPE_AP ||
471 !conn->chosen_exit_optional)
472 continue;
473 edge_conn = TO_EDGE_CONN(conn);
474 r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
475 r2 = router_get_by_nickname(info->nickname, 0);
476 if (r1 && r2 && r1==r2) {
477 tor_assert(edge_conn->socks_request);
478 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
479 safe_str(edge_conn->chosen_exit_name),
480 escaped_safe_str(edge_conn->socks_request->address));
481 conn->chosen_exit_optional = 0;
482 tor_free(edge_conn->chosen_exit_name); /* clears it */
487 /** The AP connection <b>conn</b> has just failed while attaching or
488 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
489 * might work. Detach the circuit, and either reattach it, launch a
490 * new circuit, tell the controller, or give up as a appropriate.
492 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
495 connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
496 int reason)
498 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
499 conn->_base.timestamp_lastread = time(NULL);
500 if (! get_options()->LeaveStreamsUnattached) {
501 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
502 circuit_detach_stream(TO_CIRCUIT(circ),conn);
503 return connection_ap_handshake_attach_circuit(conn);
504 } else {
505 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
506 circuit_detach_stream(TO_CIRCUIT(circ),conn);
507 return 0;
511 /** A client-side struct to remember requests to rewrite addresses
512 * to new addresses. These structs are stored in the hash table
513 * "addressmap" below.
515 * There are 5 ways to set an address mapping:
516 * - A MapAddress command from the controller [permanent]
517 * - An AddressMap directive in the torrc [permanent]
518 * - When a TrackHostExits torrc directive is triggered [temporary]
519 * - When a dns resolve succeeds [temporary]
520 * - When a dns resolve fails [temporary]
522 * When an addressmap request is made but one is already registered,
523 * the new one is replaced only if the currently registered one has
524 * no "new_address" (that is, it's in the process of dns resolve),
525 * or if the new one is permanent (expires==0 or 1).
527 * (We overload the 'expires' field, using "0" for mappings set via
528 * the configuration file, "1" for mappings set from the control
529 * interface, and other values for DNS mappings that can expire.)
531 typedef struct {
532 char *new_address;
533 time_t expires;
534 int num_resolve_failures;
535 } addressmap_entry_t;
537 /** Entry for mapping addresses to which virtual address we mapped them to. */
538 typedef struct {
539 char *ipv4_address;
540 char *hostname_address;
541 } virtaddress_entry_t;
543 /** A hash table to store client-side address rewrite instructions. */
544 static strmap_t *addressmap=NULL;
546 * Table mapping addresses to which virtual address, if any, we
547 * assigned them to.
549 * We maintain the following invariant: if [A,B] is in
550 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
551 * must be in addressmap. We do not require that the converse hold:
552 * if it fails, then we could end up mapping two virtual addresses to
553 * the same address, which is no disaster.
555 static strmap_t *virtaddress_reversemap=NULL;
557 /** Initialize addressmap. */
558 void
559 addressmap_init(void)
561 addressmap = strmap_new();
562 virtaddress_reversemap = strmap_new();
565 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
566 static void
567 addressmap_ent_free(void *_ent)
569 addressmap_entry_t *ent = _ent;
570 tor_free(ent->new_address);
571 tor_free(ent);
574 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
575 static void
576 addressmap_virtaddress_ent_free(void *_ent)
578 virtaddress_entry_t *ent = _ent;
579 tor_free(ent->ipv4_address);
580 tor_free(ent->hostname_address);
581 tor_free(ent);
584 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
585 static void
586 addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
588 if (ent && ent->new_address &&
589 address_is_in_virtual_range(ent->new_address)) {
590 virtaddress_entry_t *ve =
591 strmap_get(virtaddress_reversemap, ent->new_address);
592 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
593 if (ve) {
594 if (!strcmp(address, ve->ipv4_address))
595 tor_free(ve->ipv4_address);
596 if (!strcmp(address, ve->hostname_address))
597 tor_free(ve->hostname_address);
598 if (!ve->ipv4_address && !ve->hostname_address) {
599 tor_free(ve);
600 strmap_remove(virtaddress_reversemap, ent->new_address);
606 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
607 * client address maps. */
608 static void
609 addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
611 addressmap_virtaddress_remove(address, ent);
612 addressmap_ent_free(ent);
615 /** Remove all entries from the addressmap that were set via the
616 * configuration file or the command line. */
617 void
618 addressmap_clear_configured(void)
620 addressmap_get_mappings(NULL, 0, 0, 0);
623 /** Remove all entries from the addressmap that are set to expire, ever. */
624 void
625 addressmap_clear_transient(void)
627 addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
630 /** Clean out entries from the addressmap cache that were
631 * added long enough ago that they are no longer valid.
633 void
634 addressmap_clean(time_t now)
636 addressmap_get_mappings(NULL, 2, now, 0);
639 /** Free all the elements in the addressmap, and free the addressmap
640 * itself. */
641 void
642 addressmap_free_all(void)
644 if (addressmap) {
645 strmap_free(addressmap, addressmap_ent_free);
646 addressmap = NULL;
648 if (virtaddress_reversemap) {
649 strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
650 virtaddress_reversemap = NULL;
654 /** Look at address, and rewrite it until it doesn't want any
655 * more rewrites; but don't get into an infinite loop.
656 * Don't write more than maxlen chars into address. Return true if the
657 * address changed; false otherwise. Set *<b>expires_out</b> to the
658 * expiry time of the result, or to <b>time_max</b> if the result does
659 * not expire.
662 addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
664 addressmap_entry_t *ent;
665 int rewrites;
666 char *cp;
667 time_t expires = TIME_MAX;
669 for (rewrites = 0; rewrites < 16; rewrites++) {
670 ent = strmap_get(addressmap, address);
672 if (!ent || !ent->new_address) {
673 if (expires_out)
674 *expires_out = expires;
675 return (rewrites > 0); /* done, no rewrite needed */
678 cp = tor_strdup(escaped_safe_str(ent->new_address));
679 log_info(LD_APP, "Addressmap: rewriting %s to %s",
680 escaped_safe_str(address), cp);
681 if (ent->expires > 1 && ent->expires < expires)
682 expires = ent->expires;
683 tor_free(cp);
684 strlcpy(address, ent->new_address, maxlen);
686 log_warn(LD_CONFIG,
687 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
688 escaped_safe_str(address));
689 /* it's fine to rewrite a rewrite, but don't loop forever */
690 if (expires_out)
691 *expires_out = TIME_MAX;
692 return 1;
695 /** If we have a cached reverse DNS entry for the address stored in the
696 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
697 * rewrite to the cached value and return 1. Otherwise return 0. Set
698 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
699 * if the result does not expire. */
700 static int
701 addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
703 size_t len = maxlen + 16;
704 char *s = tor_malloc(len), *cp;
705 addressmap_entry_t *ent;
706 int r = 0;
707 tor_snprintf(s, len, "REVERSE[%s]", address);
708 ent = strmap_get(addressmap, s);
709 if (ent) {
710 cp = tor_strdup(escaped_safe_str(ent->new_address));
711 log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
712 escaped_safe_str(s), cp);
713 tor_free(cp);
714 strlcpy(address, ent->new_address, maxlen);
715 r = 1;
718 if (expires_out)
719 *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
721 tor_free(s);
722 return r;
725 /** Return 1 if <b>address</b> is already registered, else return 0 */
727 addressmap_have_mapping(const char *address)
729 return strmap_get_lc(addressmap, address) ? 1 : 0;
732 /** Register a request to map <b>address</b> to <b>new_address</b>,
733 * which will expire on <b>expires</b> (or 0 if never expires from
734 * config file, 1 if never expires from controller, 2 if never expires
735 * (virtual address mapping) from the controller.)
737 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
738 * free as appropriate. We will leave address alone.
740 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
741 * any mappings that exist from <b>address</b>.
743 void
744 addressmap_register(const char *address, char *new_address, time_t expires)
746 addressmap_entry_t *ent;
748 ent = strmap_get(addressmap, address);
749 if (!new_address || !strcasecmp(address,new_address)) {
750 /* Remove the mapping, if any. */
751 tor_free(new_address);
752 if (ent) {
753 addressmap_ent_remove(address,ent);
754 strmap_remove(addressmap, address);
756 return;
758 if (!ent) { /* make a new one and register it */
759 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
760 strmap_set(addressmap, address, ent);
761 } else if (ent->new_address) { /* we need to clean up the old mapping. */
762 if (expires > 1) {
763 log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
764 "since it's already mapped to '%s'",
765 safe_str(address), safe_str(new_address), safe_str(ent->new_address));
766 tor_free(new_address);
767 return;
769 if (address_is_in_virtual_range(ent->new_address) &&
770 expires != 2) {
771 /* XXX This isn't the perfect test; we want to avoid removing
772 * mappings set from the control interface _as virtual mapping */
773 addressmap_virtaddress_remove(address, ent);
775 tor_free(ent->new_address);
776 } /* else { we have an in-progress resolve with no mapping. } */
778 ent->new_address = new_address;
779 ent->expires = expires==2 ? 1 : expires;
780 ent->num_resolve_failures = 0;
782 log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
783 safe_str(address), safe_str(ent->new_address));
784 control_event_address_mapped(address, ent->new_address, expires, NULL);
787 /** An attempt to resolve <b>address</b> failed at some OR.
788 * Increment the number of resolve failures we have on record
789 * for it, and then return that number.
792 client_dns_incr_failures(const char *address)
794 addressmap_entry_t *ent = strmap_get(addressmap, address);
795 if (!ent) {
796 ent = tor_malloc_zero(sizeof(addressmap_entry_t));
797 ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
798 strmap_set(addressmap,address,ent);
800 ++ent->num_resolve_failures;
801 log_info(LD_APP, "Address %s now has %d resolve failures.",
802 safe_str(address), ent->num_resolve_failures);
803 return ent->num_resolve_failures;
806 /** If <b>address</b> is in the client dns addressmap, reset
807 * the number of resolve failures we have on record for it.
808 * This is used when we fail a stream because it won't resolve:
809 * otherwise future attempts on that address will only try once.
811 void
812 client_dns_clear_failures(const char *address)
814 addressmap_entry_t *ent = strmap_get(addressmap, address);
815 if (ent)
816 ent->num_resolve_failures = 0;
819 /** Record the fact that <b>address</b> resolved to <b>name</b>.
820 * We can now use this in subsequent streams via addressmap_rewrite()
821 * so we can more correctly choose an exit that will allow <b>address</b>.
823 * If <b>exitname</b> is defined, then append the addresses with
824 * ".exitname.exit" before registering the mapping.
826 * If <b>ttl</b> is nonnegative, the mapping will be valid for
827 * <b>ttl</b>seconds; otherwise, we use the default.
829 static void
830 client_dns_set_addressmap_impl(const char *address, const char *name,
831 const char *exitname,
832 int ttl)
834 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
835 char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
836 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
837 char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
839 tor_assert(address);
840 tor_assert(name);
842 if (ttl<0)
843 ttl = DEFAULT_DNS_TTL;
844 else
845 ttl = dns_clip_ttl(ttl);
847 if (exitname) {
848 /* XXXX fails to ever get attempts to get an exit address of
849 * google.com.digest[=~]nickname.exit; we need a syntax for this that
850 * won't make strict RFC952-compliant applications (like us) barf. */
851 tor_snprintf(extendedaddress, sizeof(extendedaddress),
852 "%s.%s.exit", address, exitname);
853 tor_snprintf(extendedval, sizeof(extendedval),
854 "%s.%s.exit", name, exitname);
855 } else {
856 tor_snprintf(extendedaddress, sizeof(extendedaddress),
857 "%s", address);
858 tor_snprintf(extendedval, sizeof(extendedval),
859 "%s", name);
861 addressmap_register(extendedaddress, tor_strdup(extendedval),
862 time(NULL) + ttl);
865 /** Record the fact that <b>address</b> resolved to <b>val</b>.
866 * We can now use this in subsequent streams via addressmap_rewrite()
867 * so we can more correctly choose an exit that will allow <b>address</b>.
869 * If <b>exitname</b> is defined, then append the addresses with
870 * ".exitname.exit" before registering the mapping.
872 * If <b>ttl</b> is nonnegative, the mapping will be valid for
873 * <b>ttl</b>seconds; otherwise, we use the default.
875 void
876 client_dns_set_addressmap(const char *address, uint32_t val,
877 const char *exitname,
878 int ttl)
880 struct in_addr in;
881 char valbuf[INET_NTOA_BUF_LEN];
883 tor_assert(address);
885 if (tor_inet_aton(address, &in))
886 return; /* If address was an IP address already, don't add a mapping. */
887 in.s_addr = htonl(val);
888 tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
890 client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
893 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
894 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
896 * If <b>exitname</b> is defined, then append the addresses with
897 * ".exitname.exit" before registering the mapping.
899 * If <b>ttl</b> is nonnegative, the mapping will be valid for
900 * <b>ttl</b>seconds; otherwise, we use the default.
902 static void
903 client_dns_set_reverse_addressmap(const char *address, const char *v,
904 const char *exitname,
905 int ttl)
907 size_t len = strlen(address) + 16;
908 char *s = tor_malloc(len);
909 tor_snprintf(s, len, "REVERSE[%s]", address);
910 client_dns_set_addressmap_impl(s, v, exitname, ttl);
911 tor_free(s);
914 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
915 * These addresses should map to localhost, so even if the
916 * application accidentally tried to connect to them directly (not
917 * via Tor), it wouldn't get too far astray.
919 * These options are configured by parse_virtual_addr_network().
921 static uint32_t virtual_addr_network = 0x7fc00000u;
922 static maskbits_t virtual_addr_netmask_bits = 10;
923 static uint32_t next_virtual_addr = 0x7fc00000u;
925 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
926 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
927 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
928 * string and return -1 on failure. If validate_only is false, sets the
929 * actual virtual address range to the parsed value. */
931 parse_virtual_addr_network(const char *val, int validate_only,
932 char **msg)
934 uint32_t addr;
935 uint16_t port_min, port_max;
936 maskbits_t bits;
938 if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
939 if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
940 return -1;
943 if (port_min != 1 || port_max != 65535) {
944 if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
945 return -1;
948 if (bits > 16) {
949 if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
950 "network or larger");
951 return -1;
954 if (validate_only)
955 return 0;
957 virtual_addr_network = addr & (0xfffffffful << (32-bits));
958 virtual_addr_netmask_bits = bits;
960 if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
961 next_virtual_addr = addr;
963 return 0;
967 * Return true iff <b>addr</b> is likely to have been returned by
968 * client_dns_get_unused_address.
971 address_is_in_virtual_range(const char *address)
973 struct in_addr in;
974 tor_assert(address);
975 if (!strcasecmpend(address, ".virtual")) {
976 return 1;
977 } else if (tor_inet_aton(address, &in)) {
978 uint32_t addr = ntohl(in.s_addr);
979 if (!addr_mask_cmp_bits(addr, virtual_addr_network,
980 virtual_addr_netmask_bits))
981 return 1;
983 return 0;
986 /** Return a newly allocated string holding an address of <b>type</b>
987 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
988 * and that is very unlikely to be the address of any real host.
990 static char *
991 addressmap_get_virtual_address(int type)
993 char buf[64];
994 struct in_addr in;
995 tor_assert(addressmap);
997 if (type == RESOLVED_TYPE_HOSTNAME) {
998 char rand[10];
999 do {
1000 crypto_rand(rand, sizeof(rand));
1001 base32_encode(buf,sizeof(buf),rand,sizeof(rand));
1002 strlcat(buf, ".virtual", sizeof(buf));
1003 } while (strmap_get(addressmap, buf));
1004 return tor_strdup(buf);
1005 } else if (type == RESOLVED_TYPE_IPV4) {
1006 // This is an imperfect estimate of how many addresses are available, but
1007 // that's ok.
1008 uint32_t available = 1u << (32-virtual_addr_netmask_bits);
1009 while (available) {
1010 /* Don't hand out any .0 or .255 address. */
1011 while ((next_virtual_addr & 0xff) == 0 ||
1012 (next_virtual_addr & 0xff) == 0xff) {
1013 ++next_virtual_addr;
1015 in.s_addr = htonl(next_virtual_addr);
1016 tor_inet_ntoa(&in, buf, sizeof(buf));
1017 if (!strmap_get(addressmap, buf)) {
1018 ++next_virtual_addr;
1019 break;
1022 ++next_virtual_addr;
1023 --available;
1024 log_info(LD_CONFIG, "%d addrs available", (int)available);
1025 if (! --available) {
1026 log_warn(LD_CONFIG, "Ran out of virtual addresses!");
1027 return NULL;
1029 if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
1030 virtual_addr_netmask_bits))
1031 next_virtual_addr = virtual_addr_network;
1033 return tor_strdup(buf);
1034 } else {
1035 log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
1036 return NULL;
1040 /** A controller has requested that we map some address of type
1041 * <b>type</b> to the address <b>new_address</b>. Choose an address
1042 * that is unlikely to be used, and map it, and return it in a newly
1043 * allocated string. If another address of the same type is already
1044 * mapped to <b>new_address</b>, try to return a copy of that address.
1046 * The string in <b>new_address</b> may be freed, or inserted into a map
1047 * as appropriate.
1049 const char *
1050 addressmap_register_virtual_address(int type, char *new_address)
1052 char **addrp;
1053 virtaddress_entry_t *vent;
1055 tor_assert(new_address);
1056 tor_assert(addressmap);
1057 tor_assert(virtaddress_reversemap);
1059 vent = strmap_get(virtaddress_reversemap, new_address);
1060 if (!vent) {
1061 vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
1062 strmap_set(virtaddress_reversemap, new_address, vent);
1065 addrp = (type == RESOLVED_TYPE_IPV4) ?
1066 &vent->ipv4_address : &vent->hostname_address;
1067 if (*addrp) {
1068 addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
1069 if (ent && ent->new_address &&
1070 !strcasecmp(new_address, ent->new_address)) {
1071 tor_free(new_address);
1072 return tor_strdup(*addrp);
1073 } else
1074 log_warn(LD_BUG,
1075 "Internal confusion: I thought that '%s' was mapped to by "
1076 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1077 safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
1078 ent?safe_str(ent->new_address):"(nothing)");
1081 tor_free(*addrp);
1082 *addrp = addressmap_get_virtual_address(type);
1083 log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
1084 addressmap_register(*addrp, new_address, 2);
1086 #if 0
1088 /* Try to catch possible bugs */
1089 addressmap_entry_t *ent;
1090 ent = strmap_get(addressmap, *addrp);
1091 tor_assert(ent);
1092 tor_assert(!strcasecmp(ent->new_address,new_address));
1093 vent = strmap_get(virtaddress_reversemap, new_address);
1094 tor_assert(vent);
1095 tor_assert(!strcasecmp(*addrp,
1096 (type == RESOLVED_TYPE_IPV4) ?
1097 vent->ipv4_address : vent->hostname_address));
1098 log_info(LD_APP, "Map from %s to %s okay.",
1099 safe_str(*addrp),safe_str(new_address));
1101 #endif
1103 return *addrp;
1106 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1107 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1108 * should be true if we're using this address as a client; false if we're
1109 * using it as a server.
1112 address_is_invalid_destination(const char *address, int client)
1114 if (client) {
1115 if (get_options()->AllowNonRFC953Hostnames)
1116 return 0;
1117 } else {
1118 if (get_options()->ServerDNSAllowNonRFC953Hostnames)
1119 return 0;
1122 while (*address) {
1123 if (TOR_ISALNUM(*address) ||
1124 *address == '-' ||
1125 *address == '.' ||
1126 *address == '_') /* Underscore is not allowed, but Windows does it
1127 * sometimes, just to thumb its nose at the IETF. */
1128 ++address;
1129 else
1130 return 1;
1132 return 0;
1135 /** Iterate over all address mappings which have expiry times between
1136 * min_expires and max_expires, inclusive. If sl is provided, add an
1137 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1138 * the expiry time if want_expiry is false. If sl is NULL, remove the
1139 * mappings.
1141 void
1142 addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
1143 time_t max_expires, int want_expiry)
1145 strmap_iter_t *iter;
1146 const char *key;
1147 void *_val;
1148 addressmap_entry_t *val;
1150 if (!addressmap)
1151 addressmap_init();
1153 for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
1154 strmap_iter_get(iter, &key, &_val);
1155 val = _val;
1156 if (val->expires >= min_expires && val->expires <= max_expires) {
1157 if (!sl) {
1158 iter = strmap_iter_next_rmv(addressmap,iter);
1159 addressmap_ent_remove(key, val);
1160 continue;
1161 } else if (val->new_address) {
1162 size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
1163 char *line = tor_malloc(len);
1164 if (want_expiry) {
1165 if (val->expires < 3 || val->expires == TIME_MAX)
1166 tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
1167 else {
1168 char time[ISO_TIME_LEN+1];
1169 format_iso_time(time, val->expires);
1170 tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
1171 time);
1173 } else {
1174 tor_snprintf(line, len, "%s %s", key, val->new_address);
1176 smartlist_add(sl, line);
1179 iter = strmap_iter_next(addressmap,iter);
1183 /** Connection <b>conn</b> just finished its socks handshake, or the
1184 * controller asked us to take care of it. If <b>circ</b> is defined,
1185 * then that's where we'll want to attach it. Otherwise we have to
1186 * figure it out ourselves.
1188 * First, parse whether it's a .exit address, remap it, and so on. Then
1189 * if it's for a general circuit, try to attach it to a circuit (or launch
1190 * one as needed), else if it's for a rendezvous circuit, fetch a
1191 * rendezvous descriptor first (or attach/launch a circuit if the
1192 * rendezvous descriptor is already here and fresh enough).
1194 * The stream will exit from the hop
1195 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1196 * <b>cpath</b> is NULL.
1199 connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
1200 origin_circuit_t *circ,
1201 crypt_path_t *cpath)
1203 socks_request_t *socks = conn->socks_request;
1204 hostname_type_t addresstype;
1205 or_options_t *options = get_options();
1206 struct in_addr addr_tmp;
1207 int automap = 0;
1208 char orig_address[MAX_SOCKS_ADDR_LEN];
1209 time_t map_expires = TIME_MAX;
1211 tor_strlower(socks->address); /* normalize it */
1212 strlcpy(orig_address, socks->address, sizeof(orig_address));
1213 log_debug(LD_APP,"Client asked for %s:%d",
1214 safe_str(socks->address),
1215 socks->port);
1217 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1218 !tor_inet_aton(socks->address, &addr_tmp) &&
1219 options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
1220 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
1221 if (!strcasecmpend(socks->address, cp)) {
1222 automap = 1;
1223 break;
1225 if (automap) {
1226 const char *new_addr;
1227 new_addr = addressmap_register_virtual_address(
1228 RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
1229 tor_assert(new_addr);
1230 log_info(LD_APP, "Automapping %s to %s",
1231 escaped_safe_str(socks->address), safe_str(new_addr));
1232 strlcpy(socks->address, new_addr, sizeof(socks->address));
1236 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1237 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1238 &map_expires)) {
1239 char *result = tor_strdup(socks->address);
1240 /* remember _what_ is supposed to have been resolved. */
1241 strlcpy(socks->address, orig_address, sizeof(socks->address));
1242 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1243 strlen(result), result, -1,
1244 map_expires);
1245 connection_mark_unattached_ap(conn,
1246 END_STREAM_REASON_DONE |
1247 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1248 return 0;
1250 if (options->ClientDNSRejectInternalAddresses) {
1251 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1252 tor_addr_t addr;
1253 if (tor_addr_from_str(&addr, socks->address) >= 0 &&
1254 tor_addr_is_internal(&addr, 0)) {
1255 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1256 0, NULL, -1, TIME_MAX);
1257 connection_mark_unattached_ap(conn,
1258 END_STREAM_REASON_SOCKSPROTOCOL |
1259 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1260 return -1;
1263 } else if (!automap) {
1264 /* For address map controls, remap the address. */
1265 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1266 &map_expires)) {
1267 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1268 REMAP_STREAM_SOURCE_CACHE);
1272 if (!automap && address_is_in_virtual_range(socks->address)) {
1273 /* This address was probably handed out by client_dns_get_unmapped_address,
1274 * but the mapping was discarded for some reason. We *don't* want to send
1275 * the address through Tor; that's likely to fail, and may leak
1276 * information.
1278 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1279 socks->address); /* don't safe_str() this yet. */
1280 connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
1281 return -1;
1284 /* Parse the address provided by SOCKS. Modify it in-place if it
1285 * specifies a hidden-service (.onion) or particular exit node (.exit).
1287 addresstype = parse_extended_hostname(socks->address);
1289 if (addresstype == BAD_HOSTNAME) {
1290 log_warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
1291 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1292 escaped(socks->address));
1293 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1294 return -1;
1297 if (addresstype == EXIT_HOSTNAME) {
1298 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1299 * node, and conn->address to hold only the address portion.*/
1300 char *s = strrchr(socks->address,'.');
1301 tor_assert(!automap);
1302 if (s) {
1303 if (s[1] != '\0') {
1304 conn->chosen_exit_name = tor_strdup(s+1);
1305 *s = 0;
1306 } else {
1307 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1308 safe_str(socks->address));
1309 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1310 escaped(socks->address));
1311 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1312 return -1;
1314 } else {
1315 routerinfo_t *r;
1316 conn->chosen_exit_name = tor_strdup(socks->address);
1317 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1318 *socks->address = 0;
1319 if (r) {
1320 strlcpy(socks->address, r->address, sizeof(socks->address));
1321 } else {
1322 log_warn(LD_APP,
1323 "Unrecognized server in exit address '%s.exit'. Refusing.",
1324 safe_str(socks->address));
1325 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1326 return -1;
1331 if (addresstype != ONION_HOSTNAME) {
1332 /* not a hidden-service request (i.e. normal or .exit) */
1333 if (address_is_invalid_destination(socks->address, 1)) {
1334 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1335 escaped(socks->address));
1336 log_warn(LD_APP,
1337 "Destination '%s' seems to be an invalid hostname. Failing.",
1338 safe_str(socks->address));
1339 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1340 return -1;
1343 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1344 uint32_t answer;
1345 struct in_addr in;
1346 /* Reply to resolves immediately if we can. */
1347 if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
1348 log_warn(LD_APP,"Address to be resolved is too large. Failing.");
1349 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1350 escaped(socks->address));
1351 connection_ap_handshake_socks_resolved(conn,
1352 RESOLVED_TYPE_ERROR_TRANSIENT,
1353 0,NULL,-1,TIME_MAX);
1354 connection_mark_unattached_ap(conn,
1355 END_STREAM_REASON_SOCKSPROTOCOL |
1356 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1357 return -1;
1359 if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
1360 /* leave it in network order */
1361 answer = in.s_addr;
1362 /* remember _what_ is supposed to have been resolved. */
1363 strlcpy(socks->address, orig_address, sizeof(socks->address));
1364 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
1365 (char*)&answer,-1,map_expires);
1366 connection_mark_unattached_ap(conn,
1367 END_STREAM_REASON_DONE |
1368 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1369 return 0;
1371 tor_assert(!automap);
1372 rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
1373 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1374 tor_assert(!automap);
1375 if (socks->port == 0) {
1376 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1377 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1378 return -1;
1381 if (!conn->chosen_exit_name && !circ) {
1382 /* see if we can find a suitable enclave exit */
1383 routerinfo_t *r =
1384 router_find_exact_exit_enclave(socks->address, socks->port);
1385 if (r) {
1386 log_info(LD_APP,
1387 "Redirecting address %s to exit at enclave router %s",
1388 safe_str(socks->address), r->nickname);
1389 /* use the hex digest, not nickname, in case there are two
1390 routers with this nickname */
1391 conn->chosen_exit_name =
1392 tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
1393 conn->_base.chosen_exit_optional = 1;
1397 /* help predict this next time */
1398 rep_hist_note_used_port(socks->port, time(NULL));
1399 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1400 rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
1401 } else if (socks->command == SOCKS_COMMAND_CONNECT_DIR) {
1402 ; /* nothing */
1403 } else {
1404 tor_fragile_assert();
1406 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1407 if ((circ && connection_ap_handshake_attach_chosen_circuit(
1408 conn, circ, cpath) < 0) ||
1409 (!circ &&
1410 connection_ap_handshake_attach_circuit(conn) < 0)) {
1411 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1412 return -1;
1414 return 0;
1415 } else {
1416 /* it's a hidden-service request */
1417 rend_cache_entry_t *entry;
1418 int r;
1419 tor_assert(!automap);
1420 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1421 /* if it's a resolve request, fail it right now, rather than
1422 * building all the circuits and then realizing it won't work. */
1423 log_warn(LD_APP,
1424 "Resolve requests to hidden services not allowed. Failing.");
1425 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1426 0,NULL,-1,TIME_MAX);
1427 connection_mark_unattached_ap(conn,
1428 END_STREAM_REASON_SOCKSPROTOCOL |
1429 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1430 return -1;
1433 if (circ) {
1434 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1435 "supported for .onion addresses currently. Failing.");
1436 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1437 return -1;
1440 strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
1441 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1442 safe_str(conn->rend_query));
1443 /* see if we already have it cached */
1444 r = rend_cache_lookup_entry(conn->rend_query, 0, &entry);
1445 if (r<0) {
1446 log_warn(LD_BUG,"Invalid service name '%s'",
1447 safe_str(conn->rend_query));
1448 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1449 return -1;
1451 if (r==0) {
1452 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1453 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1454 safe_str(conn->rend_query));
1455 rend_client_refetch_renddesc(conn->rend_query);
1456 } else { /* r > 0 */
1457 /** How long after we receive a hidden service descriptor do we consider
1458 * it valid? */
1459 #define NUM_SECONDS_BEFORE_HS_REFETCH (60*15)
1460 if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_HS_REFETCH) {
1461 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1462 log_info(LD_REND, "Descriptor is here and fresh enough. Great.");
1463 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1464 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1465 return -1;
1467 } else {
1468 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1469 log_info(LD_REND, "Stale descriptor %s. Refetching.",
1470 safe_str(conn->rend_query));
1471 rend_client_refetch_renddesc(conn->rend_query);
1474 return 0;
1476 return 0; /* unreached but keeps the compiler happy */
1479 #ifdef TRANS_PF
1480 static int pf_socket = -1;
1481 static int
1482 get_pf_socket(void)
1484 int pf;
1485 /* Ideally, this should be opened before dropping privs. */
1486 if (pf_socket >= 0)
1487 return pf_socket;
1489 #ifdef OPENBSD
1490 /* only works on OpenBSD */
1491 pf = open("/dev/pf", O_RDONLY);
1492 #else
1493 /* works on NetBSD and FreeBSD */
1494 pf = open("/dev/pf", O_RDWR);
1495 #endif
1497 if (pf < 0) {
1498 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1499 return -1;
1502 pf_socket = pf;
1503 return pf_socket;
1505 #endif
1507 /** Fetch the original destination address and port from a
1508 * system-specific interface and put them into a
1509 * socks_request_t as if they came from a socks request.
1511 * Return -1 if an error prevents fetching the destination,
1512 * else return 0.
1514 static int
1515 connection_ap_get_original_destination(edge_connection_t *conn,
1516 socks_request_t *req)
1518 #ifdef TRANS_NETFILTER
1519 /* Linux 2.4+ */
1520 struct sockaddr_in orig_dst;
1521 socklen_t orig_dst_len = sizeof(orig_dst);
1522 char tmpbuf[INET_NTOA_BUF_LEN];
1524 if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
1525 (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
1526 int e = tor_socket_errno(conn->_base.s);
1527 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1528 return -1;
1531 tor_inet_ntoa(&orig_dst.sin_addr, tmpbuf, sizeof(tmpbuf));
1532 strlcpy(req->address, tmpbuf, sizeof(req->address));
1533 req->port = ntohs(orig_dst.sin_port);
1535 return 0;
1536 #elif defined(TRANS_PF)
1537 struct sockaddr_in proxy_addr;
1538 socklen_t proxy_addr_len = sizeof(proxy_addr);
1539 char tmpbuf[INET_NTOA_BUF_LEN];
1540 struct pfioc_natlook pnl;
1541 int pf = -1;
1543 if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
1544 &proxy_addr_len) < 0) {
1545 int e = tor_socket_errno(conn->_base.s);
1546 log_warn(LD_NET, "getsockname() to determine transocks destination "
1547 "failed: %s", tor_socket_strerror(e));
1548 return -1;
1551 memset(&pnl, 0, sizeof(pnl));
1552 pnl.af = AF_INET;
1553 pnl.proto = IPPROTO_TCP;
1554 pnl.direction = PF_OUT;
1555 pnl.saddr.v4.s_addr = htonl(conn->_base.addr);
1556 pnl.sport = htons(conn->_base.port);
1557 pnl.daddr.v4.s_addr = proxy_addr.sin_addr.s_addr;
1558 pnl.dport = proxy_addr.sin_port;
1560 pf = get_pf_socket();
1561 if (pf<0)
1562 return -1;
1564 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1565 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1566 return -1;
1569 tor_inet_ntoa(&pnl.rdaddr.v4, tmpbuf, sizeof(tmpbuf));
1570 strlcpy(req->address, tmpbuf, sizeof(req->address));
1571 req->port = ntohs(pnl.rdport);
1573 return 0;
1574 #else
1575 (void)conn;
1576 (void)req;
1577 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1578 "transparent proxy method was configured.");
1579 return -1;
1580 #endif
1583 /** connection_edge_process_inbuf() found a conn in state
1584 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1585 * the socks handshake.
1587 * If the handshake is complete, send it to
1588 * connection_ap_handshake_rewrite_and_attach().
1590 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1591 * else return 0.
1593 static int
1594 connection_ap_handshake_process_socks(edge_connection_t *conn)
1596 socks_request_t *socks;
1597 int sockshere;
1598 or_options_t *options = get_options();
1600 tor_assert(conn);
1601 tor_assert(conn->_base.type == CONN_TYPE_AP);
1602 tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
1603 tor_assert(conn->socks_request);
1604 socks = conn->socks_request;
1606 log_debug(LD_APP,"entered.");
1608 sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
1609 options->TestSocks, options->SafeSocks);
1610 if (sockshere == 0) {
1611 if (socks->replylen) {
1612 connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
1613 /* zero it out so we can do another round of negotiation */
1614 socks->replylen = 0;
1615 } else {
1616 log_debug(LD_APP,"socks handshake not all here yet.");
1618 return 0;
1619 } else if (sockshere == -1) {
1620 if (socks->replylen) { /* we should send reply back */
1621 log_debug(LD_APP,"reply is already set for us. Using it.");
1622 connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
1623 END_STREAM_REASON_SOCKSPROTOCOL);
1625 } else {
1626 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
1627 connection_ap_handshake_socks_reply(conn, NULL, 0,
1628 END_STREAM_REASON_SOCKSPROTOCOL);
1630 connection_mark_unattached_ap(conn,
1631 END_STREAM_REASON_SOCKSPROTOCOL |
1632 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1633 return -1;
1634 } /* else socks handshake is done, continue processing */
1636 if (hostname_is_noconnect_address(socks->address))
1638 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1639 control_event_stream_status(conn, STREAM_EVENT_CLOSED, 0);
1640 connection_mark_unattached_ap(conn, END_STREAM_REASON_DONE);
1641 return -1;
1644 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
1645 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1646 else
1647 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
1649 if (options->LeaveStreamsUnattached) {
1650 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1651 return 0;
1653 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1656 /** connection_init_accepted_conn() found a new trans AP conn.
1657 * Get the original destination and send it to
1658 * connection_ap_handshake_rewrite_and_attach().
1660 * Return -1 if an unexpected error with conn (and it should be marked
1661 * for close), else return 0.
1664 connection_ap_process_transparent(edge_connection_t *conn)
1666 socks_request_t *socks;
1667 or_options_t *options = get_options();
1669 tor_assert(conn);
1670 tor_assert(conn->_base.type == CONN_TYPE_AP);
1671 tor_assert(conn->socks_request);
1672 socks = conn->socks_request;
1674 /* pretend that a socks handshake completed so we don't try to
1675 * send a socks reply down a transparent conn */
1676 socks->command = SOCKS_COMMAND_CONNECT;
1677 socks->has_finished = 1;
1679 log_debug(LD_APP,"entered.");
1681 if (connection_ap_get_original_destination(conn, socks) < 0) {
1682 log_warn(LD_APP,"Fetching original destination failed. Closing.");
1683 connection_mark_unattached_ap(conn,
1684 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
1685 return -1;
1687 /* we have the original destination */
1689 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1691 if (options->LeaveStreamsUnattached) {
1692 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1693 return 0;
1695 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1698 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1699 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1700 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1701 * form of the original destination.
1703 * If the original destination is complete, send it to
1704 * connection_ap_handshake_rewrite_and_attach().
1706 * Return -1 if an unexpected error with conn (and it should be marked
1707 * for close), else return 0.
1709 static int
1710 connection_ap_process_natd(edge_connection_t *conn)
1712 char tmp_buf[36], *tbuf, *daddr;
1713 size_t tlen = 30;
1714 int err, port_ok;
1715 socks_request_t *socks;
1716 or_options_t *options = get_options();
1718 tor_assert(conn);
1719 tor_assert(conn->_base.type == CONN_TYPE_AP);
1720 tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
1721 tor_assert(conn->socks_request);
1722 socks = conn->socks_request;
1724 log_debug(LD_APP,"entered.");
1726 /* look for LF-terminated "[DEST ip_addr port]"
1727 * where ip_addr is a dotted-quad and port is in string form */
1728 err = fetch_from_buf_line(conn->_base.inbuf, tmp_buf, &tlen);
1729 if (err == 0)
1730 return 0;
1731 if (err < 0) {
1732 log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
1733 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1734 return -1;
1737 if (strcmpstart(tmp_buf, "[DEST ")) {
1738 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1739 "said: %s",
1740 escaped(tmp_buf));
1741 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1742 return -1;
1745 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
1746 if (!(tbuf = strchr(tbuf, ' '))) {
1747 log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
1748 "said: %s",
1749 escaped(tmp_buf));
1750 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1751 return -1;
1753 *tbuf++ = '\0';
1755 /* pretend that a socks handshake completed so we don't try to
1756 * send a socks reply down a natd conn */
1757 strlcpy(socks->address, daddr, sizeof(socks->address));
1758 socks->port = (uint16_t)
1759 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
1760 if (!port_ok) {
1761 log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
1762 "of range.", escaped(tbuf));
1763 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
1764 return -1;
1767 socks->command = SOCKS_COMMAND_CONNECT;
1768 socks->has_finished = 1;
1770 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1772 if (options->LeaveStreamsUnattached) {
1773 conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
1774 return 0;
1776 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1778 return connection_ap_handshake_rewrite_and_attach(conn, NULL, NULL);
1781 /** Iterate over the two bytes of stream_id until we get one that is not
1782 * already in use; return it. Return 0 if can't get a unique stream_id.
1784 static uint16_t
1785 get_unique_stream_id_by_circ(origin_circuit_t *circ)
1787 edge_connection_t *tmpconn;
1788 uint16_t test_stream_id;
1789 uint32_t attempts=0;
1791 again:
1792 test_stream_id = circ->next_stream_id++;
1793 if (++attempts > 1<<16) {
1794 /* Make sure we don't loop forever if all stream_id's are used. */
1795 log_warn(LD_APP,"No unused stream IDs. Failing.");
1796 return 0;
1798 if (test_stream_id == 0)
1799 goto again;
1800 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
1801 if (tmpconn->stream_id == test_stream_id)
1802 goto again;
1803 return test_stream_id;
1806 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1807 * socks_request field, and send it down circ.
1809 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1812 connection_ap_handshake_send_begin(edge_connection_t *ap_conn)
1814 char payload[CELL_PAYLOAD_SIZE];
1815 int payload_len;
1816 int begin_type;
1817 origin_circuit_t *circ;
1818 tor_assert(ap_conn->on_circuit);
1819 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
1821 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
1822 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1823 tor_assert(ap_conn->socks_request);
1824 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
1826 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1827 if (ap_conn->stream_id==0) {
1828 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1829 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
1830 return -1;
1833 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
1834 (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
1835 ap_conn->socks_request->address : "",
1836 ap_conn->socks_request->port);
1837 payload_len = strlen(payload)+1;
1839 log_debug(LD_APP,
1840 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
1842 begin_type = ap_conn->socks_request->command == SOCKS_COMMAND_CONNECT ?
1843 RELAY_COMMAND_BEGIN : RELAY_COMMAND_BEGIN_DIR;
1844 if (begin_type == RELAY_COMMAND_BEGIN) {
1845 tor_assert(circ->build_state->onehop_tunnel == 0);
1848 if (connection_edge_send_command(ap_conn, begin_type,
1849 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
1850 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
1851 return -1; /* circuit is closed, don't continue */
1853 ap_conn->package_window = STREAMWINDOW_START;
1854 ap_conn->deliver_window = STREAMWINDOW_START;
1855 ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
1856 log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
1857 ap_conn->_base.s, circ->_base.n_circ_id);
1858 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
1859 return 0;
1862 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1863 * socks_request field, and send it down circ.
1865 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1868 connection_ap_handshake_send_resolve(edge_connection_t *ap_conn)
1870 int payload_len, command;
1871 const char *string_addr;
1872 char inaddr_buf[32];
1873 origin_circuit_t *circ;
1874 tor_assert(ap_conn->on_circuit);
1875 circ = TO_ORIGIN_CIRCUIT(ap_conn->on_circuit);
1877 tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
1878 tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1879 tor_assert(ap_conn->socks_request);
1880 tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
1882 command = ap_conn->socks_request->command;
1883 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
1885 ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
1886 if (ap_conn->stream_id==0) {
1887 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1888 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
1889 return -1;
1892 if (command == SOCKS_COMMAND_RESOLVE) {
1893 string_addr = ap_conn->socks_request->address;
1894 payload_len = strlen(string_addr)+1;
1895 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
1896 } else {
1897 struct in_addr in;
1898 uint32_t a;
1899 size_t len = strlen(ap_conn->socks_request->address);
1900 char c = 0;
1901 /* XXXX020 This logic is a little ugly: we check for an in-addr.arpa ending
1902 * on the address. If we have one, the address is already in the right
1903 * order, so we'll leave it alone later. Otherwise, we reverse it and
1904 * turn it into an in-addr.arpa address. */
1905 if (!strcasecmpend(ap_conn->socks_request->address, ".in-addr.arpa")) {
1906 /* Temporarily truncate the address, so we can give it to inet_aton. */
1907 c = ap_conn->socks_request->address[len-13];
1908 ap_conn->socks_request->address[len-13] = '\0';
1910 if (tor_inet_aton(ap_conn->socks_request->address, &in) == 0) {
1911 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
1912 return -1;
1914 if (c) {
1915 /* this path happens on DNS. Can we unify? XXXX020 */
1916 ap_conn->socks_request->address[len-13] = c;
1917 strlcpy(inaddr_buf, ap_conn->socks_request->address, sizeof(inaddr_buf));
1918 } else {
1919 /* this path happens on tor-resolve. Can we unify? XXXX020 */
1920 a = ntohl(in.s_addr);
1921 tor_snprintf(inaddr_buf, sizeof(inaddr_buf), "%d.%d.%d.%d.in-addr.arpa",
1922 (int)(uint8_t)((a )&0xff),
1923 (int)(uint8_t)((a>>8 )&0xff),
1924 (int)(uint8_t)((a>>16)&0xff),
1925 (int)(uint8_t)((a>>24)&0xff));
1927 string_addr = inaddr_buf;
1928 payload_len = strlen(inaddr_buf)+1;
1929 tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
1932 log_debug(LD_APP,
1933 "Sending relay cell to begin stream %d.", ap_conn->stream_id);
1935 if (connection_edge_send_command(ap_conn,
1936 RELAY_COMMAND_RESOLVE,
1937 string_addr, payload_len) < 0)
1938 return -1; /* circuit is closed, don't continue */
1940 ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
1941 log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
1942 ap_conn->_base.s, circ->_base.n_circ_id);
1943 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
1944 return 0;
1947 /** Make an AP connection_t, make a new linked connection pair, and attach
1948 * one side to the conn, connection_add it, initialize it to circuit_wait,
1949 * and call connection_ap_handshake_attach_circuit(conn) on it.
1951 * Return the other end of the linked connection pair, or -1 if error.
1953 * DOCDOC start_reading
1955 edge_connection_t *
1956 connection_ap_make_link(char *address, uint16_t port,
1957 const char *digest, int command)
1959 edge_connection_t *conn;
1961 log_info(LD_APP,"Making internal anonymized tunnel to %s:%d ...",
1962 safe_str(address),port);
1964 conn = TO_EDGE_CONN(connection_new(CONN_TYPE_AP, AF_INET));
1965 conn->_base.linked = 1; /* so that we can add it safely below. */
1967 /* populate conn->socks_request */
1969 /* leave version at zero, so the socks_reply is empty */
1970 conn->socks_request->socks_version = 0;
1971 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
1972 strlcpy(conn->socks_request->address, address,
1973 sizeof(conn->socks_request->address));
1974 conn->socks_request->port = port;
1975 conn->socks_request->command = command;
1976 if (command == SOCKS_COMMAND_CONNECT_DIR) {
1977 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
1978 conn->chosen_exit_name[0] = '$';
1979 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
1980 digest, DIGEST_LEN);
1983 conn->_base.address = tor_strdup("(Tor_internal)");
1984 conn->_base.addr = 0;
1985 conn->_base.port = 0;
1987 if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
1988 connection_free(TO_CONN(conn));
1989 return NULL;
1992 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1994 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
1996 /* attaching to a dirty circuit is fine */
1997 if (connection_ap_handshake_attach_circuit(conn) < 0) {
1998 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1999 return NULL;
2002 log_info(LD_APP,"... application connection created and linked.");
2003 return conn;
2006 /** DOCDOC */
2007 static void
2008 tell_controller_about_resolved_result(edge_connection_t *conn,
2009 int answer_type,
2010 size_t answer_len,
2011 const char *answer,
2012 int ttl,
2013 time_t expires)
2016 if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
2017 answer_type == RESOLVED_TYPE_HOSTNAME)) {
2018 return; /* we already told the controller. */
2019 } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2020 struct in_addr in;
2021 char buf[INET_NTOA_BUF_LEN];
2022 in.s_addr = get_uint32(answer);
2023 tor_inet_ntoa(&in, buf, sizeof(buf));
2024 control_event_address_mapped(conn->socks_request->address,
2025 buf, expires, NULL);
2026 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len <256) {
2027 char *cp = tor_strndup(answer, answer_len);
2028 control_event_address_mapped(conn->socks_request->address,
2029 cp, expires, NULL);
2030 tor_free(cp);
2031 } else {
2032 control_event_address_mapped(conn->socks_request->address,
2033 "<error>",
2034 time(NULL)+ttl,
2035 "error=yes");
2039 /** Send an answer to an AP connection that has requested a DNS lookup
2040 * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or
2041 * -1 for unreachable; the answer should be in the format specified
2042 * in the socks extensions document.
2043 * DOCDOC expires
2045 void
2046 connection_ap_handshake_socks_resolved(edge_connection_t *conn,
2047 int answer_type,
2048 size_t answer_len,
2049 const char *answer,
2050 int ttl,
2051 time_t expires)
2053 char buf[384];
2054 size_t replylen;
2056 if (ttl >= 0) {
2057 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2058 uint32_t a = ntohl(get_uint32(answer));
2059 if (a)
2060 client_dns_set_addressmap(conn->socks_request->address, a,
2061 conn->chosen_exit_name, ttl);
2062 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2063 char *cp = tor_strndup(answer, answer_len);
2064 client_dns_set_reverse_addressmap(conn->socks_request->address,
2066 conn->chosen_exit_name, ttl);
2067 tor_free(cp);
2071 if (conn->is_dns_request) {
2072 if (conn->dns_server_request) {
2073 /* We had a request on our DNS port: answer it. */
2074 dnsserv_resolved(conn, answer_type, answer_len, answer, ttl);
2075 conn->socks_request->has_finished = 1;
2076 return;
2077 } else {
2078 /* This must be a request from the controller. We already sent
2079 * a mapaddress if there's a ttl. */
2080 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2081 answer, ttl, expires);
2082 conn->socks_request->has_finished = 1;
2083 return;
2085 /* XXXX020 are we freeing conn anywhere? */
2088 if (conn->socks_request->socks_version == 4) {
2089 buf[0] = 0x00; /* version */
2090 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2091 buf[1] = 90; /* "Granted" */
2092 set_uint16(buf+2, 0);
2093 memcpy(buf+4, answer, 4); /* address */
2094 replylen = SOCKS4_NETWORK_LEN;
2095 } else {
2096 buf[1] = 91; /* "error" */
2097 memset(buf+2, 0, 6);
2098 replylen = SOCKS4_NETWORK_LEN;
2100 } else if (conn->socks_request->socks_version == 5) {
2101 /* SOCKS5 */
2102 buf[0] = 0x05; /* version */
2103 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2104 buf[1] = SOCKS5_SUCCEEDED;
2105 buf[2] = 0; /* reserved */
2106 buf[3] = 0x01; /* IPv4 address type */
2107 memcpy(buf+4, answer, 4); /* address */
2108 set_uint16(buf+8, 0); /* port == 0. */
2109 replylen = 10;
2110 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2111 buf[1] = SOCKS5_SUCCEEDED;
2112 buf[2] = 0; /* reserved */
2113 buf[3] = 0x04; /* IPv6 address type */
2114 memcpy(buf+4, answer, 16); /* address */
2115 set_uint16(buf+20, 0); /* port == 0. */
2116 replylen = 22;
2117 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2118 buf[1] = SOCKS5_SUCCEEDED;
2119 buf[2] = 0; /* reserved */
2120 buf[3] = 0x03; /* Domainname address type */
2121 buf[4] = (char)answer_len;
2122 memcpy(buf+5, answer, answer_len); /* address */
2123 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2124 replylen = 5+answer_len+2;
2125 } else {
2126 buf[1] = SOCKS5_HOST_UNREACHABLE;
2127 memset(buf+2, 0, 8);
2128 replylen = 10;
2130 } else {
2131 /* no socks version info; don't send anything back */
2132 return;
2134 connection_ap_handshake_socks_reply(conn, buf, replylen,
2135 (answer_type == RESOLVED_TYPE_IPV4 ||
2136 answer_type == RESOLVED_TYPE_IPV6) ?
2137 0 : END_STREAM_REASON_RESOLVEFAILED);
2140 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2141 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2142 * handshaking.
2144 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2145 * and return, else reply based on <b>endreason</b> (one of
2146 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2147 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2149 void
2150 connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
2151 size_t replylen, int endreason)
2153 char buf[256];
2154 socks5_reply_status_t status =
2155 connection_edge_end_reason_socks5_response(endreason);
2157 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2159 control_event_stream_status(conn,
2160 status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2161 endreason);
2163 if (conn->socks_request->has_finished) {
2164 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2165 "connection_ap_handshake_socks_reply.");
2166 return;
2168 if (replylen) { /* we already have a reply in mind */
2169 connection_write_to_buf(reply, replylen, TO_CONN(conn));
2170 conn->socks_request->has_finished = 1;
2171 return;
2173 if (conn->socks_request->socks_version == 4) {
2174 memset(buf,0,SOCKS4_NETWORK_LEN);
2175 #define SOCKS4_GRANTED 90
2176 #define SOCKS4_REJECT 91
2177 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2178 /* leave version, destport, destip zero */
2179 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
2180 } else if (conn->socks_request->socks_version == 5) {
2181 buf[0] = 5; /* version 5 */
2182 buf[1] = (char)status;
2183 buf[2] = 0;
2184 buf[3] = 1; /* ipv4 addr */
2185 memset(buf+4,0,6); /* Set external addr/port to 0.
2186 The spec doesn't seem to say what to do here. -RD */
2187 connection_write_to_buf(buf,10,TO_CONN(conn));
2189 /* If socks_version isn't 4 or 5, don't send anything.
2190 * This can happen in the case of AP bridges. */
2191 conn->socks_request->has_finished = 1;
2192 return;
2195 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2196 * an exit hop for the circuit, or we are the origin and it is a
2197 * rendezvous begin.
2199 * Launch a new exit connection and initialize things appropriately.
2201 * If it's a rendezvous stream, call connection_exit_connect() on
2202 * it.
2204 * For general streams, call dns_resolve() on it first, and only call
2205 * connection_exit_connect() if the dns answer is already known.
2207 * Note that we don't call connection_add() on the new stream! We wait
2208 * for connection_exit_connect() to do that.
2210 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2211 * Else return 0.
2214 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2216 edge_connection_t *n_stream;
2217 relay_header_t rh;
2218 char *address=NULL;
2219 uint16_t port;
2220 char end_payload[1];
2221 or_circuit_t *or_circ = NULL;
2223 assert_circuit_ok(circ);
2224 if (!CIRCUIT_IS_ORIGIN(circ))
2225 or_circ = TO_OR_CIRCUIT(circ);
2227 relay_header_unpack(&rh, cell->payload);
2229 /* Note: we have to use relay_send_command_from_edge here, not
2230 * connection_edge_end or connection_edge_send_command, since those require
2231 * that we have a stream connected to a circuit, and we don't connect to a
2232 * circuit until we have a pending/successful resolve. */
2234 if (!server_mode(get_options()) &&
2235 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2236 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2237 "Relay begin cell at non-server. Closing.");
2238 end_payload[0] = END_STREAM_REASON_EXITPOLICY;
2239 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2240 end_payload, 1, NULL);
2241 return 0;
2244 if (rh.command == RELAY_COMMAND_BEGIN) {
2245 if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
2246 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2247 "Relay begin cell has no \\0. Closing.");
2248 end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
2249 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2250 end_payload, 1, NULL);
2251 return 0;
2253 if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
2254 &address,NULL,&port)<0) {
2255 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2256 "Unable to parse addr:port in relay begin cell. Closing.");
2257 end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
2258 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2259 end_payload, 1, NULL);
2260 return 0;
2262 if (port==0) {
2263 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2264 "Missing port in relay begin cell. Closing.");
2265 end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
2266 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2267 end_payload, 1, NULL);
2268 tor_free(address);
2269 return 0;
2271 if (or_circ && or_circ->is_first_hop) {
2272 /* Don't let clients use us as a single-hop proxy; it attracts attackers
2273 * and users who'd be better off with, well, single-hop proxies.
2275 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2276 "Attempt to open a stream on first hop of circuit. Closing.");
2277 end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
2278 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2279 end_payload, 1, NULL);
2280 tor_free(address);
2281 return 0;
2283 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2284 or_options_t *options = get_options();
2285 port = options->DirPort; /* not actually used to open a connection */
2286 if (!port || circ->purpose != CIRCUIT_PURPOSE_OR) {
2287 end_payload[0] = END_STREAM_REASON_NOTDIRECTORY;
2288 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2289 end_payload, 1, NULL);
2290 return 0;
2292 if (or_circ && or_circ->p_conn && or_circ->p_conn->_base.address)
2293 address = tor_strdup(or_circ->p_conn->_base.address);
2294 else
2295 address = tor_strdup("127.0.0.1");
2296 } else {
2297 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2298 end_payload[0] = END_STREAM_REASON_INTERNAL;
2299 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2300 end_payload, 1, NULL);
2301 return 0;
2304 log_debug(LD_EXIT,"Creating new exit connection.");
2305 n_stream = TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT, AF_INET));
2306 n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
2308 n_stream->stream_id = rh.stream_id;
2309 n_stream->_base.port = port;
2310 /* leave n_stream->s at -1, because it's not yet valid */
2311 n_stream->package_window = STREAMWINDOW_START;
2312 n_stream->deliver_window = STREAMWINDOW_START;
2314 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
2315 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2316 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
2317 n_stream->_base.address = tor_strdup("(rendezvous)");
2318 n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
2319 strlcpy(n_stream->rend_query, origin_circ->rend_query,
2320 sizeof(n_stream->rend_query));
2321 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
2322 assert_circuit_ok(circ);
2323 if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
2324 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
2325 n_stream->_base.port);
2326 end_payload[0] = END_STREAM_REASON_EXITPOLICY;
2327 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2328 end_payload, 1, NULL);
2329 connection_free(TO_CONN(n_stream));
2330 tor_free(address);
2331 return 0;
2333 assert_circuit_ok(circ);
2334 log_debug(LD_REND,"Finished assigning addr/port");
2335 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
2337 /* add it into the linked list of n_streams on this circuit */
2338 n_stream->next_stream = origin_circ->p_streams;
2339 n_stream->on_circuit = circ;
2340 origin_circ->p_streams = n_stream;
2341 assert_circuit_ok(circ);
2343 connection_exit_connect(n_stream);
2344 tor_free(address);
2345 return 0;
2347 tor_strlower(address);
2348 n_stream->_base.address = address;
2349 n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2350 /* default to failed, change in dns_resolve if it turns out not to fail */
2352 if (we_are_hibernating()) {
2353 end_payload[0] = END_STREAM_REASON_HIBERNATING;
2354 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2355 end_payload, 1, NULL);
2356 connection_free(TO_CONN(n_stream));
2357 return 0;
2360 n_stream->on_circuit = circ;
2362 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2363 tor_assert(or_circ);
2364 if (or_circ->p_conn && or_circ->p_conn->_base.addr)
2365 n_stream->_base.addr = or_circ->p_conn->_base.addr;
2366 return connection_exit_connect_dir(n_stream);
2369 log_debug(LD_EXIT,"about to start the dns_resolve().");
2371 /* send it off to the gethostbyname farm */
2372 switch (dns_resolve(n_stream)) {
2373 case 1: /* resolve worked; now n_stream is attached to circ. */
2374 assert_circuit_ok(circ);
2375 log_debug(LD_EXIT,"about to call connection_exit_connect().");
2376 connection_exit_connect(n_stream);
2377 return 0;
2378 case -1: /* resolve failed */
2379 end_payload[0] = END_STREAM_REASON_RESOLVEFAILED;
2380 relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
2381 end_payload, 1, NULL);
2382 /* n_stream got freed. don't touch it. */
2383 break;
2384 case 0: /* resolve added to pending list */
2385 assert_circuit_ok(circ);
2386 break;
2388 return 0;
2392 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
2393 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2396 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
2398 edge_connection_t *dummy_conn;
2399 relay_header_t rh;
2401 assert_circuit_ok(TO_CIRCUIT(circ));
2402 relay_header_unpack(&rh, cell->payload);
2404 /* This 'dummy_conn' only exists to remember the stream ID
2405 * associated with the resolve request; and to make the
2406 * implementation of dns.c more uniform. (We really only need to
2407 * remember the circuit, the stream ID, and the hostname to be
2408 * resolved; but if we didn't store them in a connection like this,
2409 * the housekeeping in dns.c would get way more complicated.)
2411 dummy_conn = TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT, AF_INET));
2412 dummy_conn->stream_id = rh.stream_id;
2413 dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
2414 rh.length);
2415 dummy_conn->_base.port = 0;
2416 dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
2417 dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
2419 dummy_conn->on_circuit = TO_CIRCUIT(circ);
2421 /* send it off to the gethostbyname farm */
2422 switch (dns_resolve(dummy_conn)) {
2423 case -1: /* Impossible to resolve; a resolved cell was sent. */
2424 /* Connection freed; don't touch it. */
2425 return 0;
2426 case 1: /* The result was cached; a resolved cell was sent. */
2427 if (!dummy_conn->_base.marked_for_close)
2428 connection_free(TO_CONN(dummy_conn));
2429 return 0;
2430 case 0: /* resolve added to pending list */
2431 assert_circuit_ok(TO_CIRCUIT(circ));
2432 break;
2434 return 0;
2437 /** Connect to conn's specified addr and port. If it worked, conn
2438 * has now been added to the connection_array.
2440 * Send back a connected cell. Include the resolved IP of the destination
2441 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2442 * streams must not reveal what IP they connected to.)
2444 void
2445 connection_exit_connect(edge_connection_t *edge_conn)
2447 uint32_t addr;
2448 uint16_t port;
2449 connection_t *conn = TO_CONN(edge_conn);
2451 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
2452 router_compare_to_my_exit_policy(edge_conn)) {
2453 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
2454 escaped_safe_str(conn->address), conn->port);
2455 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
2456 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2457 connection_free(conn);
2458 return;
2461 addr = conn->addr;
2462 port = conn->port;
2463 if (redirect_exit_list) {
2464 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
2466 if (!addr_mask_cmp_bits(addr, r->addr, r->maskbits) &&
2467 (r->port_min <= port) && (port <= r->port_max)) {
2468 struct in_addr in;
2469 if (r->is_redirect) {
2470 char tmpbuf[INET_NTOA_BUF_LEN];
2471 addr = r->addr_dest;
2472 port = r->port_dest;
2473 in.s_addr = htonl(addr);
2474 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
2475 log_debug(LD_EXIT, "Redirecting connection from %s:%d to %s:%d",
2476 escaped_safe_str(conn->address), conn->port,
2477 safe_str(tmpbuf), port);
2479 break;
2484 log_debug(LD_EXIT,"about to try connecting");
2485 switch (connection_connect(conn, conn->address, addr, port)) {
2486 case -1:
2487 connection_edge_end_errno(edge_conn);
2488 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
2489 connection_free(conn);
2490 return;
2491 case 0:
2492 conn->state = EXIT_CONN_STATE_CONNECTING;
2494 connection_watch_events(conn, EV_WRITE | EV_READ);
2495 /* writable indicates finish;
2496 * readable/error indicates broken link in windowsland. */
2497 return;
2498 /* case 1: fall through */
2501 conn->state = EXIT_CONN_STATE_OPEN;
2502 if (connection_wants_to_flush(conn)) {
2503 /* in case there are any queued data cells */
2504 log_warn(LD_BUG,"newly connected conn had data waiting!");
2505 // connection_start_writing(conn);
2507 connection_watch_events(conn, EV_READ);
2509 /* also, deliver a 'connected' cell back through the circuit. */
2510 if (connection_edge_is_rendezvous_stream(edge_conn)) {
2511 /* rendezvous stream */
2512 /* don't send an address back! */
2513 connection_edge_send_command(edge_conn,
2514 RELAY_COMMAND_CONNECTED,
2515 NULL, 0);
2516 } else { /* normal stream */
2517 /* This must be the original address, not the redirected address. */
2518 char connected_payload[8];
2519 set_uint32(connected_payload, htonl(conn->addr));
2520 set_uint32(connected_payload+4,
2521 htonl(dns_clip_ttl(edge_conn->address_ttl)));
2522 connection_edge_send_command(edge_conn,
2523 RELAY_COMMAND_CONNECTED,
2524 connected_payload, 8);
2528 /** Given an exit conn that should attach to us as a directory server, open a
2529 * bridge connection with a linked connection pir, create a new directory
2530 * conn, and join them together. Return 0 on success (or if there was an
2531 * error we could send back an end cell for). Return -(some circuit end
2532 * reason) if the circuit needs to be torn down. Either connects
2533 * <b>exitconn<b/>, frees it, or marks it, as appropriate.
2535 static int
2536 connection_exit_connect_dir(edge_connection_t *exitconn)
2538 dir_connection_t *dirconn = NULL;
2539 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
2541 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
2543 exitconn->_base.state = EXIT_CONN_STATE_OPEN;
2545 dirconn = TO_DIR_CONN(connection_new(CONN_TYPE_DIR, AF_INET));
2547 dirconn->_base.addr = 0x7f000001;
2548 dirconn->_base.port = 0;
2549 dirconn->_base.address = tor_strdup("Tor network");
2550 dirconn->_base.type = CONN_TYPE_DIR;
2551 dirconn->_base.purpose = DIR_PURPOSE_SERVER;
2552 dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
2554 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
2556 if (connection_add(TO_CONN(exitconn))<0) {
2557 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2558 connection_free(TO_CONN(exitconn));
2559 connection_free(TO_CONN(dirconn));
2560 return 0;
2563 /* link exitconn to circ, now that we know we can use it. */
2564 exitconn->next_stream = circ->n_streams;
2565 circ->n_streams = exitconn;
2567 if (connection_add(TO_CONN(dirconn))<0) {
2568 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
2569 connection_close_immediate(TO_CONN(exitconn));
2570 connection_mark_for_close(TO_CONN(exitconn));
2571 connection_free(TO_CONN(dirconn));
2572 return 0;
2575 connection_start_reading(TO_CONN(dirconn));
2576 connection_start_reading(TO_CONN(exitconn));
2578 if (connection_edge_send_command(exitconn,
2579 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
2580 connection_mark_for_close(TO_CONN(exitconn));
2581 connection_mark_for_close(TO_CONN(dirconn));
2582 return 0;
2585 return 0;
2588 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2589 * it is a general stream.
2592 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
2594 tor_assert(conn);
2595 if (*conn->rend_query) /* XXX */ /* XXXX Why is this XXX? -NM */
2596 return 1;
2597 return 0;
2600 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2601 * to exit from it, or 0 if it probably will not allow it.
2602 * (We might be uncertain if conn's destination address has not yet been
2603 * resolved.)
2606 connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit)
2608 tor_assert(conn);
2609 tor_assert(conn->_base.type == CONN_TYPE_AP);
2610 tor_assert(conn->socks_request);
2611 tor_assert(exit);
2613 /* If a particular exit node has been requested for the new connection,
2614 * make sure the exit node of the existing circuit matches exactly.
2616 if (conn->chosen_exit_name) {
2617 if (router_get_by_nickname(conn->chosen_exit_name, 1) != exit) {
2618 /* doesn't match */
2619 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2620 // conn->chosen_exit_name, exit->nickname);
2621 return 0;
2625 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
2626 struct in_addr in;
2627 uint32_t addr = 0;
2628 addr_policy_result_t r;
2629 if (tor_inet_aton(conn->socks_request->address, &in))
2630 addr = ntohl(in.s_addr);
2631 r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
2632 exit->exit_policy);
2633 if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
2634 return 0;
2635 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2636 /* Can't support reverse lookups without eventdns. */
2637 if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
2638 exit->has_old_dnsworkers)
2639 return 0;
2641 /* Don't send DNS requests to non-exit servers by default. */
2642 if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
2643 return 0;
2645 return 1;
2648 /** Make connection redirection follow the provided list of
2649 * exit_redirect_t */
2650 void
2651 set_exit_redirects(smartlist_t *lst)
2653 if (redirect_exit_list) {
2654 SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
2655 smartlist_free(redirect_exit_list);
2657 if (lst && smartlist_len(lst)) {
2658 log_warn(LD_GENERAL,
2659 "The RedirectExit option is deprecated; it will go away in a "
2660 "future version of Tor.");
2662 redirect_exit_list = lst;
2665 /** If address is of the form "y.onion" with a well-formed handle y:
2666 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2668 * If address is of the form "y.exit":
2669 * Put a NUL after y and return EXIT_HOSTNAME.
2671 * Otherwise:
2672 * Return NORMAL_HOSTNAME and change nothing.
2674 hostname_type_t
2675 parse_extended_hostname(char *address)
2677 char *s;
2678 char query[REND_SERVICE_ID_LEN+1];
2680 s = strrchr(address,'.');
2681 if (!s)
2682 return NORMAL_HOSTNAME; /* no dot, thus normal */
2683 if (!strcmp(s+1,"exit")) {
2684 *s = 0; /* nul-terminate it */
2685 return EXIT_HOSTNAME; /* .exit */
2687 if (strcmp(s+1,"onion"))
2688 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
2690 /* so it is .onion */
2691 *s = 0; /* nul-terminate it */
2692 if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >=
2693 REND_SERVICE_ID_LEN+1)
2694 goto failed;
2695 if (rend_valid_service_id(query)) {
2696 return ONION_HOSTNAME; /* success */
2698 failed:
2699 /* otherwise, return to previous state and return 0 */
2700 *s = '.';
2701 return BAD_HOSTNAME;
2704 /** Check if the address is of the form "y.noconnect"
2707 hostname_is_noconnect_address(const char *address)
2709 return ! strcasecmpend(address, ".noconnect");