1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char connection_edge_c_id
[] =
10 * \file connection_edge.c
11 * \brief Handle edge streams.
16 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
17 #include <linux/netfilter_ipv4.h>
18 #define TRANS_NETFILTER
21 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
23 #include <net/pfvar.h>
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
*exit_conn
);
33 static int hostname_is_noconnect_address(const char *address
);
35 /** An AP stream has failed/finished. If it hasn't already sent back
36 * a socks reply, send one now (based on endreason). Also set
37 * has_sent_end to 1, and mark the conn.
40 _connection_mark_unattached_ap(edge_connection_t
*conn
, int endreason
,
41 int line
, const char *file
)
43 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
44 conn
->_base
.edge_has_sent_end
= 1; /* no circ yet */
46 if (conn
->_base
.marked_for_close
) {
47 /* This call will warn as appropriate. */
48 _connection_mark_for_close(TO_CONN(conn
), line
, file
);
52 if (!conn
->socks_request
->has_finished
) {
53 if (endreason
== END_STREAM_REASON_ALREADY_SOCKS_REPLIED
)
55 "Bug: stream (marked at %s:%d) sending two socks replies?",
58 if (SOCKS_COMMAND_IS_CONNECT(conn
->socks_request
->command
))
59 connection_ap_handshake_socks_reply(conn
, NULL
, 0, endreason
);
61 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_ERROR
,
65 _connection_mark_for_close(TO_CONN(conn
), line
, file
);
66 conn
->_base
.hold_open_until_flushed
= 1;
67 conn
->end_reason
= endreason
;
70 /** There was an EOF. Send an end and mark the connection for close.
73 connection_edge_reached_eof(edge_connection_t
*conn
)
75 if (buf_datalen(conn
->_base
.inbuf
) &&
76 connection_state_is_open(TO_CONN(conn
))) {
77 /* it still has stuff to process. don't let it die yet. */
80 log_info(LD_EDGE
,"conn (fd %d) reached eof. Closing.", conn
->_base
.s
);
81 if (!conn
->_base
.marked_for_close
) {
82 /* only mark it if not already marked. it's possible to
83 * get the 'end' right around when the client hangs up on us. */
84 connection_edge_end(conn
, END_STREAM_REASON_DONE
, conn
->cpath_layer
);
85 if (conn
->socks_request
) /* eof, so don't send a socks reply back */
86 conn
->socks_request
->has_finished
= 1;
87 connection_mark_for_close(TO_CONN(conn
));
92 /** Handle new bytes on conn->inbuf based on state:
93 * - If it's waiting for socks info, try to read another step of the
94 * socks handshake out of conn->inbuf.
95 * - If it's waiting for the original destination, fetch it.
96 * - If it's open, then package more relay cells from the stream.
97 * - Else, leave the bytes on inbuf alone for now.
99 * Mark and return -1 if there was an unexpected error with the conn,
103 connection_edge_process_inbuf(edge_connection_t
*conn
, int package_partial
)
107 switch (conn
->_base
.state
) {
108 case AP_CONN_STATE_SOCKS_WAIT
:
109 if (connection_ap_handshake_process_socks(conn
) < 0) {
114 case AP_CONN_STATE_NATD_WAIT
:
115 if (connection_ap_process_natd(conn
) < 0) {
120 case AP_CONN_STATE_OPEN
:
121 case EXIT_CONN_STATE_OPEN
:
122 if (connection_edge_package_raw_inbuf(conn
, package_partial
) < 0) {
123 /* (We already sent an end cell if possible) */
124 connection_mark_for_close(TO_CONN(conn
));
128 case EXIT_CONN_STATE_CONNECTING
:
129 case AP_CONN_STATE_RENDDESC_WAIT
:
130 case AP_CONN_STATE_CIRCUIT_WAIT
:
131 case AP_CONN_STATE_CONNECT_WAIT
:
132 case AP_CONN_STATE_RESOLVE_WAIT
:
133 case AP_CONN_STATE_CONTROLLER_WAIT
:
135 "data from edge while in '%s' state. Leaving it on buffer.",
136 conn_state_to_string(conn
->_base
.type
, conn
->_base
.state
));
139 log_warn(LD_BUG
,"Bug: Got unexpected state %d. Closing.",conn
->_base
.state
);
140 tor_fragile_assert();
141 connection_edge_end(conn
, END_STREAM_REASON_INTERNAL
, conn
->cpath_layer
);
142 connection_mark_for_close(TO_CONN(conn
));
146 /** This edge needs to be closed, because its circuit has closed.
147 * Mark it for close and return 0.
150 connection_edge_destroy(uint16_t circ_id
, edge_connection_t
*conn
)
152 if (!conn
->_base
.marked_for_close
) {
154 "CircID %d: At an edge. Marking connection for close.", circ_id
);
155 if (conn
->_base
.type
== CONN_TYPE_AP
) {
156 connection_mark_unattached_ap(conn
, END_STREAM_REASON_DESTROY
);
158 /* closing the circuit, nothing to send an END to */
159 conn
->_base
.edge_has_sent_end
= 1;
160 conn
->end_reason
= END_STREAM_REASON_DESTROY
;
161 connection_mark_for_close(TO_CONN(conn
));
162 conn
->_base
.hold_open_until_flushed
= 1;
165 conn
->cpath_layer
= NULL
;
166 conn
->on_circuit
= NULL
;
170 /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
171 * with a destination of cpath_layer. (If cpath_layer is NULL, the
172 * destination is the circuit's origin.) Mark the relay end cell as
173 * closing because of <b>reason</b>.
175 * Return -1 if this function has already been called on this conn,
179 connection_edge_end(edge_connection_t
*conn
, char reason
,
180 crypt_path_t
*cpath_layer
)
182 char payload
[RELAY_PAYLOAD_SIZE
];
183 size_t payload_len
=1;
186 if (conn
->_base
.edge_has_sent_end
) {
187 log_warn(LD_BUG
,"Harmless bug: Calling connection_edge_end (reason %d) "
188 "on an already ended stream?", reason
);
189 tor_fragile_assert();
193 if (conn
->_base
.marked_for_close
) {
195 "Bug: called on conn that's already marked for close at %s:%d.",
196 conn
->_base
.marked_for_close_file
, conn
->_base
.marked_for_close
);
201 if (reason
== END_STREAM_REASON_EXITPOLICY
&&
202 !connection_edge_is_rendezvous_stream(conn
)) {
203 set_uint32(payload
+1, htonl(conn
->_base
.addr
));
204 set_uint32(payload
+5, htonl(dns_clip_ttl(conn
->address_ttl
)));
208 circ
= circuit_get_by_edge_conn(conn
);
209 if (circ
&& !circ
->marked_for_close
) {
210 log_debug(LD_EDGE
,"Marking conn (fd %d) and sending end.",conn
->_base
.s
);
211 connection_edge_send_command(conn
, circ
, RELAY_COMMAND_END
,
212 payload
, payload_len
, cpath_layer
);
214 log_debug(LD_EDGE
,"Marking conn (fd %d); no circ to send end.",
218 conn
->_base
.edge_has_sent_end
= 1;
219 conn
->end_reason
= reason
;
223 /** An error has just occured on an operation on an edge connection
224 * <b>conn</b>. Extract the errno; convert it to an end reason, and send
225 * an appropriate relay end cell to <b>cpath_layer</b>.
228 connection_edge_end_errno(edge_connection_t
*conn
, crypt_path_t
*cpath_layer
)
232 reason
= (uint8_t)errno_to_end_reason(tor_socket_errno(conn
->_base
.s
));
233 return connection_edge_end(conn
, reason
, cpath_layer
);
236 /** Connection <b>conn</b> has finished writing and has no bytes left on
239 * If it's in state 'open', stop writing, consider responding with a
240 * sendme, and return.
241 * Otherwise, stop writing and return.
243 * If <b>conn</b> is broken, mark it for close and return -1, else
247 connection_edge_finished_flushing(edge_connection_t
*conn
)
251 switch (conn
->_base
.state
) {
252 case AP_CONN_STATE_OPEN
:
253 case EXIT_CONN_STATE_OPEN
:
254 connection_stop_writing(TO_CONN(conn
));
255 connection_edge_consider_sending_sendme(conn
);
257 case AP_CONN_STATE_SOCKS_WAIT
:
258 case AP_CONN_STATE_NATD_WAIT
:
259 case AP_CONN_STATE_RENDDESC_WAIT
:
260 case AP_CONN_STATE_CIRCUIT_WAIT
:
261 case AP_CONN_STATE_CONNECT_WAIT
:
262 case AP_CONN_STATE_CONTROLLER_WAIT
:
263 connection_stop_writing(TO_CONN(conn
));
266 log_warn(LD_BUG
,"BUG: called in unexpected state %d.",conn
->_base
.state
);
267 tor_fragile_assert();
273 /** Connected handler for exit connections: start writing pending
274 * data, deliver 'CONNECTED' relay cells as appropriate, and check
275 * any pending data that may have been received. */
277 connection_edge_finished_connecting(edge_connection_t
*edge_conn
)
279 char valbuf
[INET_NTOA_BUF_LEN
];
283 tor_assert(edge_conn
);
284 tor_assert(edge_conn
->_base
.type
== CONN_TYPE_EXIT
);
285 conn
= TO_CONN(edge_conn
);
286 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
288 in
.s_addr
= htonl(conn
->addr
);
289 tor_inet_ntoa(&in
,valbuf
,sizeof(valbuf
));
290 log_info(LD_EXIT
,"Exit connection to %s:%u (%s) established.",
291 escaped_safe_str(conn
->address
),conn
->port
,safe_str(valbuf
));
293 conn
->state
= EXIT_CONN_STATE_OPEN
;
294 connection_watch_events(conn
, EV_READ
); /* stop writing, continue reading */
295 if (connection_wants_to_flush(conn
)) /* in case there are any queued relay
297 connection_start_writing(conn
);
298 /* deliver a 'connected' relay cell back through the circuit. */
299 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
300 if (connection_edge_send_command(edge_conn
,
301 circuit_get_by_edge_conn(edge_conn
),
302 RELAY_COMMAND_CONNECTED
, NULL
, 0,
303 edge_conn
->cpath_layer
) < 0)
304 return 0; /* circuit is closed, don't continue */
306 char connected_payload
[8];
307 set_uint32(connected_payload
, htonl(conn
->addr
));
308 set_uint32(connected_payload
+4,
309 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
310 if (connection_edge_send_command(edge_conn
,
311 circuit_get_by_edge_conn(edge_conn
),
312 RELAY_COMMAND_CONNECTED
,
313 connected_payload
, 8,
314 edge_conn
->cpath_layer
) < 0)
315 return 0; /* circuit is closed, don't continue */
317 tor_assert(edge_conn
->package_window
> 0);
318 /* in case the server has written anything */
319 return connection_edge_process_inbuf(edge_conn
, 1);
322 /** Define a schedule for how long to wait between retrying
323 * application connections. Rather than waiting a fixed amount of
324 * time between each retry, we wait 10 seconds each for the first
325 * two tries, and 15 seconds for each retry after
326 * that. Hopefully this will improve the expected user experience. */
328 compute_socks_timeout(edge_connection_t
*conn
)
330 if (conn
->num_socks_retries
< 2) /* try 0 and try 1 */
335 /** Find all general-purpose AP streams waiting for a response that sent their
336 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
337 * mark their current circuit as unsuitable for new streams. Then call
338 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
339 * available) or launch a new one.
341 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
345 connection_ap_expire_beginning(void)
347 connection_t
**carray
;
348 edge_connection_t
*conn
;
350 const char *nickname
;
352 time_t now
= time(NULL
);
353 or_options_t
*options
= get_options();
358 get_connection_array(&carray
, &n
);
360 for (i
= 0; i
< n
; ++i
) {
361 if (carray
[i
]->type
!= CONN_TYPE_AP
)
363 conn
= TO_EDGE_CONN(carray
[i
]);
364 /* if it's an internal bridge connection, don't yell its status. */
365 severity
= (!conn
->_base
.addr
&& !conn
->_base
.port
)
366 ? LOG_INFO
: LOG_NOTICE
;
367 seconds_idle
= now
- conn
->_base
.timestamp_lastread
;
369 if (AP_CONN_STATE_IS_UNATTACHED(conn
->_base
.state
)) {
370 if (seconds_idle
>= options
->SocksTimeout
) {
371 if (conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
) {
372 log_fn(severity
, LD_APP
,
373 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
374 seconds_idle
, safe_str(conn
->socks_request
->address
),
375 conn
->socks_request
->port
);
377 log_fn(severity
, LD_APP
, "Closing unattached stream (state %d).",
379 /* XXX012 remove the below clause before stable release -RD */
380 if (conn
->_base
.state
== AP_CONN_STATE_SOCKS_WAIT
) {
381 /* extra debugging */
382 log_fn(severity
, LD_APP
,
383 "Hints: is_reading %d, inbuf len %lu, socks: version %d, "
384 "command %d, has_finished %d, address %s, port %d.",
385 connection_is_reading(TO_CONN(conn
)),
386 (unsigned long)buf_datalen(conn
->_base
.inbuf
),
387 (int)conn
->socks_request
->socks_version
,
388 conn
->socks_request
->command
,
389 conn
->socks_request
->has_finished
,
390 conn
->socks_request
->address
,
391 (int)conn
->socks_request
->port
);
394 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
399 if (conn
->_base
.state
== AP_CONN_STATE_OPEN
)
402 cutoff
= compute_socks_timeout(conn
);
403 if (seconds_idle
< cutoff
)
405 circ
= circuit_get_by_edge_conn(conn
);
406 if (!circ
) { /* it's vanished? */
407 log_info(LD_APP
,"Conn is waiting (address %s), but lost its circ.",
408 safe_str(conn
->socks_request
->address
));
409 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
412 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
413 if (seconds_idle
> options
->SocksTimeout
) {
414 log_fn(severity
, LD_REND
,
415 "Rend stream is %d seconds late. Giving up on address"
418 safe_str(conn
->socks_request
->address
));
419 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
,
421 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
425 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
426 nickname
= build_state_get_exit_nickname(
427 TO_ORIGIN_CIRCUIT(circ
)->build_state
);
428 log_fn(cutoff
< 15 ? LOG_INFO
: severity
, LD_APP
,
429 "We tried for %d seconds to connect to '%s' using exit '%s'."
430 " Retrying on a new circuit.",
431 seconds_idle
, safe_str(conn
->socks_request
->address
),
432 nickname
? nickname
: "*unnamed*");
433 /* send an end down the circuit */
434 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
, conn
->cpath_layer
);
435 /* un-mark it as ending, since we're going to reuse it */
436 conn
->_base
.edge_has_sent_end
= 0;
437 conn
->end_reason
= 0;
438 /* kludge to make us not try this circuit again, yet to allow
439 * current streams on it to survive if they can: make it
440 * unattractive to use for new streams */
441 tor_assert(circ
->timestamp_dirty
);
442 circ
->timestamp_dirty
-= options
->MaxCircuitDirtiness
;
443 /* give our stream another 'cutoff' seconds to try */
444 conn
->_base
.timestamp_lastread
+= cutoff
;
445 if (conn
->num_socks_retries
< 250) /* avoid overflow */
446 conn
->num_socks_retries
++;
447 /* move it back into 'pending' state, and try to attach. */
448 if (connection_ap_detach_retriable(conn
, TO_ORIGIN_CIRCUIT(circ
),
449 END_STREAM_REASON_TIMEOUT
)<0) {
450 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
455 /** Tell any AP streams that are waiting for a new circuit to try again,
456 * either attaching to an available circ or launching a new one.
459 connection_ap_attach_pending(void)
461 connection_t
**carray
;
463 edge_connection_t
*edge_conn
;
466 get_connection_array(&carray
, &n
);
468 for (i
= 0; i
< n
; ++i
) {
470 if (conn
->marked_for_close
||
471 conn
->type
!= CONN_TYPE_AP
||
472 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
474 edge_conn
= TO_EDGE_CONN(conn
);
475 if (connection_ap_handshake_attach_circuit(edge_conn
) < 0) {
476 connection_mark_unattached_ap(edge_conn
, END_STREAM_REASON_CANT_ATTACH
);
481 /** A circuit failed to finish on its last hop <b>info</b>. If there
482 * are any streams waiting with this exit node in mind, but they
483 * don't absolutely require it, make them give up on it.
486 circuit_discard_optional_exit_enclaves(extend_info_t
*info
)
488 connection_t
**carray
;
490 edge_connection_t
*edge_conn
;
491 routerinfo_t
*r1
, *r2
;
494 get_connection_array(&carray
, &n
);
496 for (i
= 0; i
< n
; ++i
) {
498 if (conn
->marked_for_close
||
499 conn
->type
!= CONN_TYPE_AP
||
500 !conn
->chosen_exit_optional
)
502 edge_conn
= TO_EDGE_CONN(conn
);
503 r1
= router_get_by_nickname(edge_conn
->chosen_exit_name
, 0);
504 r2
= router_get_by_nickname(info
->nickname
, 0);
505 if (r1
&& r2
&& r1
==r2
) {
506 tor_assert(edge_conn
->socks_request
);
507 log_info(LD_APP
, "Giving up on enclave exit '%s' for destination %s.",
508 safe_str(edge_conn
->chosen_exit_name
),
509 escaped_safe_str(edge_conn
->socks_request
->address
));
510 conn
->chosen_exit_optional
= 0;
511 tor_free(edge_conn
->chosen_exit_name
); /* clears it */
516 /** The AP connection <b>conn</b> has just failed while attaching or
517 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
518 * might work. Detach the circuit, and either reattach it, launch a
519 * new circuit, tell the controller, or give up as a appropriate.
521 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
524 connection_ap_detach_retriable(edge_connection_t
*conn
, origin_circuit_t
*circ
,
527 control_event_stream_status(conn
, STREAM_EVENT_FAILED_RETRIABLE
, reason
);
528 conn
->_base
.timestamp_lastread
= time(NULL
);
529 if (! get_options()->LeaveStreamsUnattached
) {
530 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
531 circuit_detach_stream(TO_CIRCUIT(circ
),conn
);
532 return connection_ap_handshake_attach_circuit(conn
);
534 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
535 circuit_detach_stream(TO_CIRCUIT(circ
),conn
);
540 /** A client-side struct to remember requests to rewrite addresses
541 * to new addresses. These structs are stored in the hash table
542 * "addressmap" below.
544 * There are 5 ways to set an address mapping:
545 * - A MapAddress command from the controller [permanent]
546 * - An AddressMap directive in the torrc [permanent]
547 * - When a TrackHostExits torrc directive is triggered [temporary]
548 * - When a dns resolve succeeds [temporary]
549 * - When a dns resolve fails [temporary]
551 * When an addressmap request is made but one is already registered,
552 * the new one is replaced only if the currently registered one has
553 * no "new_address" (that is, it's in the process of dns resolve),
554 * or if the new one is permanent (expires==0 or 1).
556 * (We overload the 'expires' field, using "0" for mappings set via
557 * the configuration file, "1" for mappings set from the control
558 * interface, and other values for DNS mappings that can expire.)
563 int num_resolve_failures
;
564 } addressmap_entry_t
;
566 /** Entry for mapping addresses to which virtual address we mapped them to. */
569 char *hostname_address
;
570 } virtaddress_entry_t
;
572 /** A hash table to store client-side address rewrite instructions. */
573 static strmap_t
*addressmap
=NULL
;
575 * Table mapping addresses to which virtual address, if any, we
578 * We maintain the following invariant: if [A,B] is in
579 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
580 * must be in addressmap. We do not require that the converse hold:
581 * if it fails, then we could end up mapping two virtual addresses to
582 * the same address, which is no disaster.
584 static strmap_t
*virtaddress_reversemap
=NULL
;
586 /** Initialize addressmap. */
588 addressmap_init(void)
590 addressmap
= strmap_new();
591 virtaddress_reversemap
= strmap_new();
594 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
596 addressmap_ent_free(void *_ent
)
598 addressmap_entry_t
*ent
= _ent
;
599 tor_free(ent
->new_address
);
603 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
605 addressmap_virtaddress_ent_free(void *_ent
)
607 virtaddress_entry_t
*ent
= _ent
;
608 tor_free(ent
->ipv4_address
);
609 tor_free(ent
->hostname_address
);
613 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
615 addressmap_virtaddress_remove(const char *address
, addressmap_entry_t
*ent
)
617 if (ent
&& ent
->new_address
&&
618 address_is_in_virtual_range(ent
->new_address
)) {
619 virtaddress_entry_t
*ve
=
620 strmap_get(virtaddress_reversemap
, ent
->new_address
);
621 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
623 if (!strcmp(address
, ve
->ipv4_address
))
624 tor_free(ve
->ipv4_address
);
625 if (!strcmp(address
, ve
->hostname_address
))
626 tor_free(ve
->hostname_address
);
627 if (!ve
->ipv4_address
&& !ve
->hostname_address
) {
629 strmap_remove(virtaddress_reversemap
, ent
->new_address
);
635 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
636 * client address maps. */
638 addressmap_ent_remove(const char *address
, addressmap_entry_t
*ent
)
640 addressmap_virtaddress_remove(address
, ent
);
641 addressmap_ent_free(ent
);
644 /** Remove all entries from the addressmap that were set via the
645 * configuration file or the command line. */
647 addressmap_clear_configured(void)
649 addressmap_get_mappings(NULL
, 0, 0);
652 /** Remove all entries from the addressmap that are set to expire, ever. */
654 addressmap_clear_transient(void)
656 addressmap_get_mappings(NULL
, 2, TIME_MAX
);
659 /** Clean out entries from the addressmap cache that were
660 * added long enough ago that they are no longer valid.
663 addressmap_clean(time_t now
)
665 addressmap_get_mappings(NULL
, 2, now
);
668 /** Free all the elements in the addressmap, and free the addressmap
671 addressmap_free_all(void)
674 strmap_free(addressmap
, addressmap_ent_free
);
677 if (virtaddress_reversemap
) {
678 strmap_free(virtaddress_reversemap
, addressmap_virtaddress_ent_free
);
679 virtaddress_reversemap
= NULL
;
683 /** Look at address, and rewrite it until it doesn't want any
684 * more rewrites; but don't get into an infinite loop.
685 * Don't write more than maxlen chars into address.
688 addressmap_rewrite(char *address
, size_t maxlen
)
690 addressmap_entry_t
*ent
;
694 for (rewrites
= 0; rewrites
< 16; rewrites
++) {
695 ent
= strmap_get(addressmap
, address
);
697 if (!ent
|| !ent
->new_address
)
698 return; /* done, no rewrite needed */
700 cp
= tor_strdup(escaped_safe_str(ent
->new_address
));
701 log_info(LD_APP
, "Addressmap: rewriting %s to %s",
702 escaped_safe_str(address
), cp
);
704 strlcpy(address
, ent
->new_address
, maxlen
);
707 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
708 escaped_safe_str(address
));
709 /* it's fine to rewrite a rewrite, but don't loop forever */
712 /** If we have a cached reverse DNS entry for the address stored in the
713 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) with
714 * the cached value and return 1. Otherwise return 0. */
716 addressmap_rewrite_reverse(char *address
, size_t maxlen
)
718 size_t len
= maxlen
+ 16;
719 char *s
= tor_malloc(len
), *cp
;
720 addressmap_entry_t
*ent
;
722 tor_snprintf(s
, len
, "REVERSE[%s]", address
);
723 ent
= strmap_get(addressmap
, s
);
725 cp
= tor_strdup(escaped_safe_str(ent
->new_address
));
726 log_info(LD_APP
, "Rewrote reverse lookup %s -> %s",
727 escaped_safe_str(s
), cp
);
729 strlcpy(address
, ent
->new_address
, maxlen
);
736 /** Return 1 if <b>address</b> is already registered, else return 0 */
738 addressmap_have_mapping(const char *address
)
740 return strmap_get_lc(addressmap
, address
) ? 1 : 0;
743 /** Register a request to map <b>address</b> to <b>new_address</b>,
744 * which will expire on <b>expires</b> (or 0 if never expires from
745 * config file, 1 if never expires from controller, 2 if never expires
746 * (virtual address mapping) from the controller.)
748 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
749 * free as appropriate. We will leave address alone.
751 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
752 * any mappings that exist from <b>address</b>.
755 addressmap_register(const char *address
, char *new_address
, time_t expires
)
757 addressmap_entry_t
*ent
;
759 ent
= strmap_get(addressmap
, address
);
760 if (!new_address
|| !strcasecmp(address
,new_address
)) {
761 /* Remove the mapping, if any. */
762 tor_free(new_address
);
764 addressmap_ent_remove(address
,ent
);
765 strmap_remove(addressmap
, address
);
769 if (!ent
) { /* make a new one and register it */
770 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
771 strmap_set(addressmap
, address
, ent
);
772 } else if (ent
->new_address
) { /* we need to clean up the old mapping. */
774 log_info(LD_APP
,"Temporary addressmap ('%s' to '%s') not performed, "
775 "since it's already mapped to '%s'",
776 safe_str(address
), safe_str(new_address
), safe_str(ent
->new_address
));
777 tor_free(new_address
);
780 if (address_is_in_virtual_range(ent
->new_address
) &&
782 /* XXX This isn't the perfect test; we want to avoid removing
783 * mappings set from the control interface _as virtual mapping */
784 addressmap_virtaddress_remove(address
, ent
);
786 tor_free(ent
->new_address
);
787 } /* else { we have an in-progress resolve with no mapping. } */
789 ent
->new_address
= new_address
;
790 ent
->expires
= expires
==2 ? 1 : expires
;
791 ent
->num_resolve_failures
= 0;
793 log_info(LD_CONFIG
, "Addressmap: (re)mapped '%s' to '%s'",
794 safe_str(address
), safe_str(ent
->new_address
));
795 control_event_address_mapped(address
, ent
->new_address
, expires
);
798 /** An attempt to resolve <b>address</b> failed at some OR.
799 * Increment the number of resolve failures we have on record
800 * for it, and then return that number.
803 client_dns_incr_failures(const char *address
)
805 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
807 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
808 ent
->expires
= time(NULL
) + MAX_DNS_ENTRY_AGE
;
809 strmap_set(addressmap
,address
,ent
);
811 ++ent
->num_resolve_failures
;
812 log_info(LD_APP
, "Address %s now has %d resolve failures.",
813 safe_str(address
), ent
->num_resolve_failures
);
814 return ent
->num_resolve_failures
;
817 /** If <b>address</b> is in the client dns addressmap, reset
818 * the number of resolve failures we have on record for it.
819 * This is used when we fail a stream because it won't resolve:
820 * otherwise future attempts on that address will only try once.
823 client_dns_clear_failures(const char *address
)
825 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
827 ent
->num_resolve_failures
= 0;
830 /** Record the fact that <b>address</b> resolved to <b>name</b>.
831 * We can now use this in subsequent streams via addressmap_rewrite()
832 * so we can more correctly choose an exit that will allow <b>address</b>.
834 * If <b>exitname</b> is defined, then append the addresses with
835 * ".exitname.exit" before registering the mapping.
837 * If <b>ttl</b> is nonnegative, the mapping will be valid for
838 * <b>ttl</b>seconds; otherwise, we use the default.
841 client_dns_set_addressmap_impl(const char *address
, const char *name
,
842 const char *exitname
,
845 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
846 char extendedaddress
[MAX_SOCKS_ADDR_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
847 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
848 char extendedval
[INET_NTOA_BUF_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
854 ttl
= DEFAULT_DNS_TTL
;
856 ttl
= dns_clip_ttl(ttl
);
859 /* XXXX fails to ever get attempts to get an exit address of
860 * google.com.digest[=~]nickname.exit; we need a syntax for this that
861 * won't make strict RFC952-compliant applications (like us) barf. */
862 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
863 "%s.%s.exit", address
, exitname
);
864 tor_snprintf(extendedval
, sizeof(extendedval
),
865 "%s.%s.exit", name
, exitname
);
867 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
869 tor_snprintf(extendedval
, sizeof(extendedval
),
872 addressmap_register(extendedaddress
, tor_strdup(extendedval
),
876 /** Record the fact that <b>address</b> resolved to <b>val</b>.
877 * We can now use this in subsequent streams via addressmap_rewrite()
878 * so we can more correctly choose an exit that will allow <b>address</b>.
880 * If <b>exitname</b> is defined, then append the addresses with
881 * ".exitname.exit" before registering the mapping.
883 * If <b>ttl</b> is nonnegative, the mapping will be valid for
884 * <b>ttl</b>seconds; otherwise, we use the default.
887 client_dns_set_addressmap(const char *address
, uint32_t val
,
888 const char *exitname
,
892 char valbuf
[INET_NTOA_BUF_LEN
];
896 if (tor_inet_aton(address
, &in
))
897 return; /* If address was an IP address already, don't add a mapping. */
898 in
.s_addr
= htonl(val
);
899 tor_inet_ntoa(&in
,valbuf
,sizeof(valbuf
));
901 client_dns_set_addressmap_impl(address
, valbuf
, exitname
, ttl
);
904 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
905 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
907 * If <b>exitname</b> is defined, then append the addresses with
908 * ".exitname.exit" before registering the mapping.
910 * If <b>ttl</b> is nonnegative, the mapping will be valid for
911 * <b>ttl</b>seconds; otherwise, we use the default.
914 client_dns_set_reverse_addressmap(const char *address
, const char *v
,
915 const char *exitname
,
918 size_t len
= strlen(address
) + 16;
919 char *s
= tor_malloc(len
);
920 tor_snprintf(s
, len
, "REVERSE[%s]", address
);
921 client_dns_set_addressmap_impl(s
, v
, exitname
, ttl
);
925 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
926 * These addresses should map to localhost, so even if the
927 * application accidentally tried to connect to them directly (not
928 * via Tor), it wouldn't get too far astray.
930 * These options are configured by parse_virtual_addr_network().
932 static uint32_t virtual_addr_network
= 0x7fc00000u
;
933 static uint32_t virtual_addr_netmask
= 0xffc00000u
;
934 static int virtual_addr_netmask_bits
= 10;
935 static uint32_t next_virtual_addr
= 0x7fc00000u
;
937 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
938 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
939 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
940 * string and return -1 on failure. If validate_only is false, sets the
941 * actual virtual address range to the parsed value. */
943 parse_virtual_addr_network(const char *val
, int validate_only
,
947 uint16_t port_min
, port_max
;
950 if (parse_addr_and_port_range(val
, &addr
, &mask
, &port_min
, &port_max
)) {
951 if (msg
) *msg
= tor_strdup("Error parsing VirtualAddressNetwork");
955 if (port_min
!= 1 || port_max
!= 65535) {
956 if (msg
) *msg
= tor_strdup("Can't specify ports on VirtualAddressNetwork");
960 bits
= addr_mask_get_bits(mask
);
962 if (msg
) *msg
= tor_strdup("VirtualAddressNetwork must have a mask that "
963 "can be expressed as a prefix");
968 if (msg
) *msg
= tor_strdup("VirtualAddressNetwork expects a /16 "
969 "network or larger");
976 virtual_addr_network
= addr
& mask
;
977 virtual_addr_netmask
= mask
;
978 virtual_addr_netmask_bits
= bits
;
980 if ((next_virtual_addr
& mask
) != addr
)
981 next_virtual_addr
= addr
;
987 * Return true iff <b>addr</b> is likely to have been returned by
988 * client_dns_get_unused_address.
991 address_is_in_virtual_range(const char *address
)
995 if (!strcasecmpend(address
, ".virtual")) {
997 } else if (tor_inet_aton(address
, &in
)) {
998 uint32_t addr
= ntohl(in
.s_addr
);
999 if ((addr
& virtual_addr_netmask
) == virtual_addr_network
)
1005 /** Return a newly allocated string holding an address of <b>type</b>
1006 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1007 * and that is very unlikely to be the address of any real host.
1010 addressmap_get_virtual_address(int type
)
1015 if (type
== RESOLVED_TYPE_HOSTNAME
) {
1018 crypto_rand(rand
, sizeof(rand
));
1019 base32_encode(buf
,sizeof(buf
),rand
,sizeof(rand
));
1020 strlcat(buf
, ".virtual", sizeof(buf
));
1021 } while (strmap_get(addressmap
, buf
));
1022 return tor_strdup(buf
);
1023 } else if (type
== RESOLVED_TYPE_IPV4
) {
1024 // This is an imperfect estimate of how many addresses are available, but
1026 uint32_t available
= 1u << (32-virtual_addr_netmask_bits
);
1028 /* Don't hand out any .0 or .255 address. */
1029 while ((next_virtual_addr
& 0xff) == 0 ||
1030 (next_virtual_addr
& 0xff) == 0xff) {
1031 ++next_virtual_addr
;
1033 in
.s_addr
= htonl(next_virtual_addr
);
1034 tor_inet_ntoa(&in
, buf
, sizeof(buf
));
1035 if (!strmap_get(addressmap
, buf
))
1038 ++next_virtual_addr
;
1040 log_notice(LD_CONFIG
, "%d addrs available", (int)available
);
1041 if (! --available
) {
1042 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
1045 if ((next_virtual_addr
& virtual_addr_netmask
) != virtual_addr_network
)
1046 next_virtual_addr
= virtual_addr_network
;
1048 return tor_strdup(buf
);
1050 log_warn(LD_BUG
, "Called with unsupported address type (%d)", type
);
1055 /** A controller has requested that we map some address of type
1056 * <b>type</b> to the address <b>new_address</b>. Choose an address
1057 * that is unlikely to be used, and map it, and return it in a newly
1058 * allocated string. If another address of the same type is already
1059 * mapped to <b>new_address</b>, try to return a copy of that address.
1061 * The string in <b>new_address</b> may be freed, or inserted into a map
1065 addressmap_register_virtual_address(int type
, char *new_address
)
1068 virtaddress_entry_t
*vent
;
1070 tor_assert(new_address
);
1071 tor_assert(addressmap
);
1072 tor_assert(virtaddress_reversemap
);
1074 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1076 vent
= tor_malloc_zero(sizeof(virtaddress_entry_t
));
1077 strmap_set(virtaddress_reversemap
, new_address
, vent
);
1080 addrp
= (type
== RESOLVED_TYPE_IPV4
) ?
1081 &vent
->ipv4_address
: &vent
->hostname_address
;
1083 addressmap_entry_t
*ent
= strmap_get(addressmap
, *addrp
);
1084 if (ent
&& ent
->new_address
&&
1085 !strcasecmp(new_address
, ent
->new_address
)) {
1086 tor_free(new_address
);
1087 return tor_strdup(*addrp
);
1090 "Internal confusion: I thought that '%s' was mapped to by "
1091 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1092 safe_str(new_address
), safe_str(*addrp
), safe_str(*addrp
),
1093 ent
?safe_str(ent
->new_address
):"(nothing)");
1097 *addrp
= addressmap_get_virtual_address(type
);
1098 addressmap_register(*addrp
, new_address
, 2);
1102 /* Try to catch possible bugs */
1103 addressmap_entry_t
*ent
;
1104 ent
= strmap_get(addressmap
, *addrp
);
1106 tor_assert(!strcasecmp(ent
->new_address
,new_address
));
1107 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1109 tor_assert(!strcasecmp(*addrp
,
1110 (type
== RESOLVED_TYPE_IPV4
) ?
1111 vent
->ipv4_address
: vent
->hostname_address
));
1112 log_fn(LOG_INFO
, "Map from %s to %s okay.",
1113 safe_str(*addrp
),safe_str(new_address
));
1120 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1121 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1122 * should be true if we're using this address as a client; false if we're
1123 * using it as a server.
1126 address_is_invalid_destination(const char *address
, int client
)
1129 if (get_options()->AllowNonRFC953Hostnames
)
1132 if (get_options()->ServerDNSAllowNonRFC953Hostnames
)
1137 if (TOR_ISALNUM(*address
) ||
1140 *address
== '_') /* Underscore is not allowed, but Windows does it
1141 * sometimes, just to thumb its nose at the IETF. */
1149 /** Iterate over all address mappings which have expiry times between
1150 * min_expires and max_expires, inclusive. If sl is provided, add an
1151 * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
1152 * remove the mappings.
1155 addressmap_get_mappings(smartlist_t
*sl
, time_t min_expires
,
1158 strmap_iter_t
*iter
;
1161 addressmap_entry_t
*val
;
1166 for (iter
= strmap_iter_init(addressmap
); !strmap_iter_done(iter
); ) {
1167 strmap_iter_get(iter
, &key
, &_val
);
1169 if (val
->expires
>= min_expires
&& val
->expires
<= max_expires
) {
1171 iter
= strmap_iter_next_rmv(addressmap
,iter
);
1172 addressmap_ent_remove(key
, val
);
1174 } else if (val
->new_address
) {
1175 size_t len
= strlen(key
)+strlen(val
->new_address
)+2;
1176 char *line
= tor_malloc(len
);
1177 tor_snprintf(line
, len
, "%s %s", key
, val
->new_address
);
1178 smartlist_add(sl
, line
);
1181 iter
= strmap_iter_next(addressmap
,iter
);
1185 /** Connection <b>conn</b> just finished its socks handshake, or the
1186 * controller asked us to take care of it. If <b>circ</b> is defined,
1187 * then that's where we'll want to attach it. Otherwise we have to
1188 * figure it out ourselves.
1190 * First, parse whether it's a .exit address, remap it, and so on. Then
1191 * if it's for a general circuit, try to attach it to a circuit (or launch
1192 * one as needed), else if it's for a rendezvous circuit, fetch a
1193 * rendezvous descriptor first (or attach/launch a circuit if the
1194 * rendezvous descriptor is already here and fresh enough).
1197 connection_ap_handshake_rewrite_and_attach(edge_connection_t
*conn
,
1198 origin_circuit_t
*circ
)
1200 socks_request_t
*socks
= conn
->socks_request
;
1201 hostname_type_t addresstype
;
1203 tor_strlower(socks
->address
); /* normalize it */
1204 log_debug(LD_APP
,"Client asked for %s:%d",
1205 safe_str(socks
->address
),
1208 if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1209 if (addressmap_rewrite_reverse(socks
->address
, sizeof(socks
->address
))) {
1210 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_HOSTNAME
,
1211 strlen(socks
->address
),
1212 socks
->address
, -1);
1213 connection_mark_unattached_ap(conn
,
1214 END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
1218 /* For address map controls, remap the address */
1219 addressmap_rewrite(socks
->address
, sizeof(socks
->address
));
1222 if (address_is_in_virtual_range(socks
->address
)) {
1223 /* This address was probably handed out by client_dns_get_unmapped_address,
1224 * but the mapping was discarded for some reason. We *don't* want to send
1225 * the address through Tor; that's likely to fail, and may leak
1228 log_warn(LD_APP
,"Missing mapping for virtual address '%s'. Refusing.",
1229 socks
->address
); /* don't safe_str() this yet. */
1230 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
1234 /* Parse the address provided by SOCKS. Modify it in-place if it
1235 * specifies a hidden-service (.onion) or particular exit node (.exit).
1237 addresstype
= parse_extended_hostname(socks
->address
);
1239 if (addresstype
== BAD_HOSTNAME
) {
1240 log_warn(LD_APP
, "Invalid hostname %s; rejecting", socks
->address
);
1241 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1242 escaped(socks
->address
));
1243 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1247 if (addresstype
== EXIT_HOSTNAME
) {
1248 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1249 * node, and conn->address to hold only the address portion.*/
1250 char *s
= strrchr(socks
->address
,'.');
1253 conn
->chosen_exit_name
= tor_strdup(s
+1);
1256 log_warn(LD_APP
,"Malformed exit address '%s.exit'. Refusing.",
1257 safe_str(socks
->address
));
1258 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1259 escaped(socks
->address
));
1260 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1265 conn
->chosen_exit_name
= tor_strdup(socks
->address
);
1266 r
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1267 *socks
->address
= 0;
1269 strlcpy(socks
->address
, r
->address
, sizeof(socks
->address
));
1272 "Unrecognized server in exit address '%s.exit'. Refusing.",
1273 safe_str(socks
->address
));
1274 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1280 if (addresstype
!= ONION_HOSTNAME
) {
1281 /* not a hidden-service request (i.e. normal or .exit) */
1282 if (address_is_invalid_destination(socks
->address
, 1)) {
1283 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1284 escaped(socks
->address
));
1286 "Destination '%s' seems to be an invalid hostname. Failing.",
1287 safe_str(socks
->address
));
1288 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1292 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
1295 /* Reply to resolves immediately if we can. */
1296 if (strlen(socks
->address
) > RELAY_PAYLOAD_SIZE
) {
1297 log_warn(LD_APP
,"Address to be resolved is too large. Failing.");
1298 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1299 escaped(socks
->address
));
1300 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
1302 connection_mark_unattached_ap(conn
,
1303 END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
1306 if (tor_inet_aton(socks
->address
, &in
)) { /* see if it's an IP already */
1307 answer
= in
.s_addr
; /* leave it in network order */
1308 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
1310 connection_mark_unattached_ap(conn
,
1311 END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
1314 rep_hist_note_used_resolve(time(NULL
)); /* help predict this next time */
1315 } else if (socks
->command
== SOCKS_COMMAND_CONNECT
) {
1316 if (socks
->port
== 0) {
1317 log_notice(LD_APP
,"Application asked to connect to port 0. Refusing.");
1318 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1322 if (!conn
->chosen_exit_name
&& !circ
) {
1323 /* see if we can find a suitable enclave exit */
1325 router_find_exact_exit_enclave(socks
->address
, socks
->port
);
1328 "Redirecting address %s to exit at enclave router %s",
1329 safe_str(socks
->address
), r
->nickname
);
1330 /* use the hex digest, not nickname, in case there are two
1331 routers with this nickname */
1332 conn
->chosen_exit_name
=
1333 tor_strdup(hex_str(r
->cache_info
.identity_digest
, DIGEST_LEN
));
1334 conn
->_base
.chosen_exit_optional
= 1;
1338 /* help predict this next time */
1339 rep_hist_note_used_port(socks
->port
, time(NULL
));
1340 } else if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1341 rep_hist_note_used_resolve(time(NULL
)); /* help predict this next time */
1342 } else if (socks
->command
== SOCKS_COMMAND_CONNECT_DIR
) {
1345 tor_fragile_assert();
1347 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1349 connection_ap_handshake_attach_chosen_circuit(conn
, circ
) < 0) ||
1351 connection_ap_handshake_attach_circuit(conn
) < 0)) {
1352 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1357 /* it's a hidden-service request */
1358 rend_cache_entry_t
*entry
;
1361 if (!SOCKS_COMMAND_IS_CONNECT(socks
->command
)) {
1362 /* if it's a resolve request, fail it right now, rather than
1363 * building all the circuits and then realizing it won't work. */
1365 "Resolve requests to hidden services not allowed. Failing.");
1366 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
1368 connection_mark_unattached_ap(conn
,
1369 END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
1374 log_warn(LD_CONTROL
, "Attachstream to a circuit is not "
1375 "supported for .onion addresses currently. Failing.");
1376 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1380 strlcpy(conn
->rend_query
, socks
->address
, sizeof(conn
->rend_query
));
1381 log_info(LD_REND
,"Got a hidden service request for ID '%s'",
1382 safe_str(conn
->rend_query
));
1383 /* see if we already have it cached */
1384 r
= rend_cache_lookup_entry(conn
->rend_query
, -1, &entry
);
1386 log_warn(LD_BUG
,"Bug: Invalid service name '%s'",
1387 safe_str(conn
->rend_query
));
1388 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1392 conn
->_base
.state
= AP_CONN_STATE_RENDDESC_WAIT
;
1393 log_info(LD_REND
, "Unknown descriptor %s. Fetching.",
1394 safe_str(conn
->rend_query
));
1395 rend_client_refetch_renddesc(conn
->rend_query
);
1396 } else { /* r > 0 */
1398 #define NUM_SECONDS_BEFORE_REFETCH (60*15)
1399 if (time(NULL
) - entry
->received
< NUM_SECONDS_BEFORE_REFETCH
) {
1400 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1401 log_info(LD_REND
, "Descriptor is here and fresh enough. Great.");
1402 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
1403 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1407 conn
->_base
.state
= AP_CONN_STATE_RENDDESC_WAIT
;
1408 log_info(LD_REND
, "Stale descriptor %s. Refetching.",
1409 safe_str(conn
->rend_query
));
1410 rend_client_refetch_renddesc(conn
->rend_query
);
1415 return 0; /* unreached but keeps the compiler happy */
1419 static int pf_socket
= -1;
1424 /* Ideally, this should be opened before dropping privs. */
1429 /* only works on OpenBSD */
1430 pf
= open("/dev/pf", O_RDONLY
);
1432 /* works on NetBSD and FreeBSD */
1433 pf
= open("/dev/pf", O_RDWR
);
1437 log_warn(LD_NET
, "open(\"/dev/pf\") failed: %s", strerror(errno
));
1446 /** Fetch the original destination address and port from a
1447 * system-specific interface and put them into a
1448 * socks_request_t as if they came from a socks request.
1450 * Return -1 if an error prevents fetching the destination,
1454 connection_ap_get_original_destination(edge_connection_t
*conn
,
1455 socks_request_t
*req
)
1457 #ifdef TRANS_NETFILTER
1459 struct sockaddr_in orig_dst
;
1460 socklen_t orig_dst_len
= sizeof(orig_dst
);
1461 char tmpbuf
[INET_NTOA_BUF_LEN
];
1463 if (getsockopt(conn
->_base
.s
, SOL_IP
, SO_ORIGINAL_DST
,
1464 (struct sockaddr
*)&orig_dst
, &orig_dst_len
) < 0) {
1465 int e
= tor_socket_errno(conn
->_base
.s
);
1466 log_warn(LD_NET
, "getsockopt() failed: %s", tor_socket_strerror(e
));
1470 tor_inet_ntoa(&orig_dst
.sin_addr
, tmpbuf
, sizeof(tmpbuf
));
1471 strlcpy(req
->address
, tmpbuf
, sizeof(req
->address
));
1472 req
->port
= ntohs(orig_dst
.sin_port
);
1475 #elif defined(TRANS_PF)
1476 struct sockaddr_in proxy_addr
;
1477 socklen_t proxy_addr_len
= sizeof(proxy_addr
);
1478 char tmpbuf
[INET_NTOA_BUF_LEN
];
1479 struct pfioc_natlook pnl
;
1482 if (getsockname(conn
->_base
.s
, (struct sockaddr
*)&proxy_addr
,
1483 &proxy_addr_len
) < 0) {
1484 int e
= tor_socket_errno(conn
->_base
.s
);
1485 log_warn(LD_NET
, "getsockname() to determine transocks destination "
1486 "failed: %s", tor_socket_strerror(e
));
1490 memset(&pnl
, 0, sizeof(pnl
));
1492 pnl
.proto
= IPPROTO_TCP
;
1493 pnl
.direction
= PF_OUT
;
1494 pnl
.saddr
.v4
.s_addr
= htonl(conn
->_base
.addr
);
1495 pnl
.sport
= htons(conn
->_base
.port
);
1496 pnl
.daddr
.v4
.s_addr
= proxy_addr
.sin_addr
.s_addr
;
1497 pnl
.dport
= proxy_addr
.sin_port
;
1499 pf
= get_pf_socket();
1503 if (ioctl(pf
, DIOCNATLOOK
, &pnl
) < 0) {
1504 log_warn(LD_NET
, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno
));
1508 tor_inet_ntoa(&pnl
.rdaddr
.v4
, tmpbuf
, sizeof(tmpbuf
));
1509 strlcpy(req
->address
, tmpbuf
, sizeof(req
->address
));
1510 req
->port
= ntohs(pnl
.rdport
);
1516 log_warn(LD_BUG
, "Called connection_ap_get_original_destination, but no "
1517 "transparent proxy method was configured.");
1522 /** connection_edge_process_inbuf() found a conn in state
1523 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1524 * the socks handshake.
1526 * If the handshake is complete, send it to
1527 * connection_ap_handshake_rewrite_and_attach().
1529 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1533 connection_ap_handshake_process_socks(edge_connection_t
*conn
)
1535 socks_request_t
*socks
;
1537 or_options_t
*options
= get_options();
1540 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
1541 tor_assert(conn
->_base
.state
== AP_CONN_STATE_SOCKS_WAIT
);
1542 tor_assert(conn
->socks_request
);
1543 socks
= conn
->socks_request
;
1545 log_debug(LD_APP
,"entered.");
1547 sockshere
= fetch_from_buf_socks(conn
->_base
.inbuf
, socks
,
1548 options
->TestSocks
, options
->SafeSocks
);
1549 if (sockshere
== 0) {
1550 if (socks
->replylen
) {
1551 connection_write_to_buf(socks
->reply
, socks
->replylen
, TO_CONN(conn
));
1552 /* zero it out so we can do another round of negotiation */
1553 socks
->replylen
= 0;
1555 log_debug(LD_APP
,"socks handshake not all here yet.");
1558 } else if (sockshere
== -1) {
1559 if (socks
->replylen
) { /* we should send reply back */
1560 log_debug(LD_APP
,"reply is already set for us. Using it.");
1561 connection_ap_handshake_socks_reply(conn
, socks
->reply
, socks
->replylen
,
1562 END_STREAM_REASON_SOCKSPROTOCOL
);
1565 log_warn(LD_APP
,"Fetching socks handshake failed. Closing.");
1566 connection_ap_handshake_socks_reply(conn
, NULL
, 0,
1567 END_STREAM_REASON_SOCKSPROTOCOL
);
1569 connection_mark_unattached_ap(conn
,
1570 END_STREAM_REASON_ALREADY_SOCKS_REPLIED
);
1572 } /* else socks handshake is done, continue processing */
1574 if (hostname_is_noconnect_address(socks
->address
))
1576 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1577 control_event_stream_status(conn
, STREAM_EVENT_CLOSED
, 0);
1578 connection_mark_unattached_ap(conn
, END_STREAM_REASON_DONE
);
1582 if (SOCKS_COMMAND_IS_CONNECT(socks
->command
))
1583 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1585 control_event_stream_status(conn
, STREAM_EVENT_NEW_RESOLVE
, 0);
1587 if (options
->LeaveStreamsUnattached
) {
1588 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1591 return connection_ap_handshake_rewrite_and_attach(conn
, NULL
);
1594 /** connection_init_accepted_conn() found a new trans AP conn.
1595 * Get the original destination and send it to
1596 * connection_ap_handshake_rewrite_and_attach().
1598 * Return -1 if an unexpected error with conn (and it should be marked
1599 * for close), else return 0.
1602 connection_ap_process_transparent(edge_connection_t
*conn
)
1604 socks_request_t
*socks
;
1605 or_options_t
*options
= get_options();
1608 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
1609 tor_assert(conn
->socks_request
);
1610 socks
= conn
->socks_request
;
1612 /* pretend that a socks handshake completed so we don't try to
1613 * send a socks reply down a transparent conn */
1614 socks
->command
= SOCKS_COMMAND_CONNECT
;
1615 socks
->has_finished
= 1;
1617 log_debug(LD_APP
,"entered.");
1619 if (connection_ap_get_original_destination(conn
, socks
) < 0) {
1620 log_warn(LD_APP
,"Fetching original destination failed. Closing.");
1621 connection_mark_unattached_ap(conn
,
1622 END_STREAM_REASON_CANT_FETCH_ORIG_DEST
);
1625 /* we have the original destination */
1627 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1629 if (options
->LeaveStreamsUnattached
) {
1630 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1633 return connection_ap_handshake_rewrite_and_attach(conn
, NULL
);
1636 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1637 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1638 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1639 * form of the original destination.
1641 * If the original destination is complete, send it to
1642 * connection_ap_handshake_rewrite_and_attach().
1644 * Return -1 if an unexpected error with conn (and it should be marked
1645 * for close), else return 0.
1648 connection_ap_process_natd(edge_connection_t
*conn
)
1650 char tmp_buf
[36], *tbuf
, *daddr
;
1653 socks_request_t
*socks
;
1654 or_options_t
*options
= get_options();
1657 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
1658 tor_assert(conn
->_base
.state
== AP_CONN_STATE_NATD_WAIT
);
1659 tor_assert(conn
->socks_request
);
1660 socks
= conn
->socks_request
;
1662 log_debug(LD_APP
,"entered.");
1664 /* look for LF-terminated "[DEST ip_addr port]"
1665 * where ip_addr is a dotted-quad and port is in string form */
1666 err
= fetch_from_buf_line_lf(conn
->_base
.inbuf
, tmp_buf
, &tlen
);
1670 log_warn(LD_APP
,"Natd handshake failed (DEST too long). Closing");
1671 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1675 if (strcmpstart(tmp_buf
, "[DEST ")) {
1676 log_warn(LD_APP
,"Natd handshake was ill-formed; closing. The client "
1679 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1683 daddr
= tbuf
= &tmp_buf
[0] + 6; /* after end of "[DEST " */
1684 while (*tbuf
!= '\0' && *tbuf
!= ' ')
1689 /* pretend that a socks handshake completed so we don't try to
1690 * send a socks reply down a natd conn */
1691 strlcpy(socks
->address
, daddr
, sizeof(socks
->address
));
1692 socks
->port
= (uint16_t)
1693 tor_parse_long(tbuf
, 10, 1, 65535, &port_ok
, &daddr
);
1695 log_warn(LD_APP
,"Natd handshake failed; port %s is ill-formed or out "
1696 "of range.", escaped(tbuf
));
1697 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1701 socks
->command
= SOCKS_COMMAND_CONNECT
;
1702 socks
->has_finished
= 1;
1704 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1706 if (options
->LeaveStreamsUnattached
) {
1707 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1710 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1712 return connection_ap_handshake_rewrite_and_attach(conn
, NULL
);
1715 /** Iterate over the two bytes of stream_id until we get one that is not
1716 * already in use; return it. Return 0 if can't get a unique stream_id.
1719 get_unique_stream_id_by_circ(origin_circuit_t
*circ
)
1721 edge_connection_t
*tmpconn
;
1722 uint16_t test_stream_id
;
1723 uint32_t attempts
=0;
1726 test_stream_id
= circ
->next_stream_id
++;
1727 if (++attempts
> 1<<16) {
1728 /* Make sure we don't loop forever if all stream_id's are used. */
1729 log_warn(LD_APP
,"No unused stream IDs. Failing.");
1732 if (test_stream_id
== 0)
1734 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
1735 if (tmpconn
->stream_id
== test_stream_id
)
1737 return test_stream_id
;
1740 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1741 * socks_request field, and send it down circ.
1743 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1746 connection_ap_handshake_send_begin(edge_connection_t
*ap_conn
,
1747 origin_circuit_t
*circ
)
1749 char payload
[CELL_PAYLOAD_SIZE
];
1753 tor_assert(ap_conn
->_base
.type
== CONN_TYPE_AP
);
1754 tor_assert(ap_conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1755 tor_assert(ap_conn
->socks_request
);
1756 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn
->socks_request
->command
));
1758 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
1759 if (ap_conn
->stream_id
==0) {
1760 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1761 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_RESOURCELIMIT
);
1765 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:%d",
1766 (circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
) ?
1767 ap_conn
->socks_request
->address
: "",
1768 ap_conn
->socks_request
->port
);
1769 payload_len
= strlen(payload
)+1;
1772 "Sending relay cell to begin stream %d.", ap_conn
->stream_id
);
1774 begin_type
= ap_conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
?
1775 RELAY_COMMAND_BEGIN
: RELAY_COMMAND_BEGIN_DIR
;
1776 if (begin_type
== RELAY_COMMAND_BEGIN
) {
1777 tor_assert(circ
->build_state
->onehop_tunnel
== 0);
1780 if (connection_edge_send_command(ap_conn
, TO_CIRCUIT(circ
), begin_type
,
1781 begin_type
== RELAY_COMMAND_BEGIN
? payload
: NULL
,
1782 begin_type
== RELAY_COMMAND_BEGIN
? payload_len
: 0,
1783 ap_conn
->cpath_layer
) < 0)
1784 return -1; /* circuit is closed, don't continue */
1786 ap_conn
->package_window
= STREAMWINDOW_START
;
1787 ap_conn
->deliver_window
= STREAMWINDOW_START
;
1788 ap_conn
->_base
.state
= AP_CONN_STATE_CONNECT_WAIT
;
1789 log_info(LD_APP
,"Address/port sent, ap socket %d, n_circ_id %d",
1790 ap_conn
->_base
.s
, circ
->_base
.n_circ_id
);
1791 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
, 0);
1795 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1796 * socks_request field, and send it down circ.
1798 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1801 connection_ap_handshake_send_resolve(edge_connection_t
*ap_conn
,
1802 origin_circuit_t
*circ
)
1804 int payload_len
, command
;
1805 const char *string_addr
;
1806 char inaddr_buf
[32];
1808 tor_assert(ap_conn
->_base
.type
== CONN_TYPE_AP
);
1809 tor_assert(ap_conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1810 tor_assert(ap_conn
->socks_request
);
1811 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
1813 command
= ap_conn
->socks_request
->command
;
1814 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command
));
1816 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
1817 if (ap_conn
->stream_id
==0) {
1818 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1819 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_RESOURCELIMIT
);
1823 if (command
== SOCKS_COMMAND_RESOLVE
) {
1824 string_addr
= ap_conn
->socks_request
->address
;
1825 payload_len
= strlen(string_addr
)+1;
1826 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
);
1830 if (tor_inet_aton(ap_conn
->socks_request
->address
, &in
) == 0) {
1831 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1834 a
= ntohl(in
.s_addr
);
1835 tor_snprintf(inaddr_buf
, sizeof(inaddr_buf
), "%d.%d.%d.%d.in-addr.arpa",
1836 (int)(uint8_t)((a
)&0xff),
1837 (int)(uint8_t)((a
>>8 )&0xff),
1838 (int)(uint8_t)((a
>>16)&0xff),
1839 (int)(uint8_t)((a
>>24)&0xff));
1840 string_addr
= inaddr_buf
;
1841 payload_len
= strlen(inaddr_buf
)+1;
1842 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
);
1846 "Sending relay cell to begin stream %d.", ap_conn
->stream_id
);
1848 if (connection_edge_send_command(ap_conn
, TO_CIRCUIT(circ
),
1849 RELAY_COMMAND_RESOLVE
,
1850 string_addr
, payload_len
, ap_conn
->cpath_layer
) < 0)
1851 return -1; /* circuit is closed, don't continue */
1853 ap_conn
->_base
.state
= AP_CONN_STATE_RESOLVE_WAIT
;
1854 log_info(LD_APP
,"Address sent for resolve, ap socket %d, n_circ_id %d",
1855 ap_conn
->_base
.s
, circ
->_base
.n_circ_id
);
1856 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
, 0);
1860 /** Make an AP connection_t, do a socketpair and attach one side
1861 * to the conn, connection_add it, initialize it to circuit_wait,
1862 * and call connection_ap_handshake_attach_circuit(conn) on it.
1864 * Return the other end of the socketpair, or -1 if error.
1867 connection_ap_make_bridge(char *address
, uint16_t port
,
1868 const char *digest
, int command
)
1871 edge_connection_t
*conn
;
1874 log_info(LD_APP
,"Making AP bridge to %s:%d ...",safe_str(address
),port
);
1876 if ((err
= tor_socketpair(AF_UNIX
, SOCK_STREAM
, 0, fd
)) < 0) {
1878 "Couldn't construct socketpair (%s). Network down? Delaying.",
1879 tor_socket_strerror(-err
));
1883 tor_assert(fd
[0] >= 0);
1884 tor_assert(fd
[1] >= 0);
1886 set_socket_nonblocking(fd
[0]);
1887 set_socket_nonblocking(fd
[1]);
1889 conn
= TO_EDGE_CONN(connection_new(CONN_TYPE_AP
));
1890 conn
->_base
.s
= fd
[0];
1892 /* populate conn->socks_request */
1894 /* leave version at zero, so the socks_reply is empty */
1895 conn
->socks_request
->socks_version
= 0;
1896 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
1897 strlcpy(conn
->socks_request
->address
, address
,
1898 sizeof(conn
->socks_request
->address
));
1899 conn
->socks_request
->port
= port
;
1900 conn
->socks_request
->command
= command
;
1901 if (command
== SOCKS_COMMAND_CONNECT_DIR
) {
1902 conn
->chosen_exit_name
= tor_malloc(HEX_DIGEST_LEN
+2);
1903 conn
->chosen_exit_name
[0] = '$';
1904 base16_encode(conn
->chosen_exit_name
+1,HEX_DIGEST_LEN
+1,
1905 digest
, DIGEST_LEN
);
1908 conn
->_base
.address
= tor_strdup("(local bridge)");
1909 conn
->_base
.addr
= 0;
1910 conn
->_base
.port
= 0;
1912 if (connection_add(TO_CONN(conn
)) < 0) { /* no space, forget it */
1913 connection_free(TO_CONN(conn
)); /* this closes fd[0] */
1914 tor_close_socket(fd
[1]);
1918 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1919 connection_start_reading(TO_CONN(conn
));
1921 /* attaching to a dirty circuit is fine */
1922 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
1923 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1924 tor_close_socket(fd
[1]);
1928 log_info(LD_APP
,"... AP bridge created and connected.");
1932 /** Send an answer to an AP connection that has requested a DNS lookup
1933 * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or
1934 * -1 for unreachable; the answer should be in the format specified
1935 * in the socks extensions document.
1938 connection_ap_handshake_socks_resolved(edge_connection_t
*conn
,
1948 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
1949 uint32_t a
= ntohl(get_uint32(answer
));
1951 client_dns_set_addressmap(conn
->socks_request
->address
, a
,
1952 conn
->chosen_exit_name
, ttl
);
1953 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
1954 char *cp
= tor_strndup(answer
, answer_len
);
1955 client_dns_set_reverse_addressmap(conn
->socks_request
->address
,
1957 conn
->chosen_exit_name
, ttl
);
1962 if (conn
->socks_request
->socks_version
== 4) {
1963 buf
[0] = 0x00; /* version */
1964 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
1965 buf
[1] = 90; /* "Granted" */
1966 set_uint16(buf
+2, 0);
1967 memcpy(buf
+4, answer
, 4); /* address */
1968 replylen
= SOCKS4_NETWORK_LEN
;
1970 buf
[1] = 91; /* "error" */
1971 memset(buf
+2, 0, 6);
1972 replylen
= SOCKS4_NETWORK_LEN
;
1974 } else if (conn
->socks_request
->socks_version
== 5) {
1976 buf
[0] = 0x05; /* version */
1977 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
1978 buf
[1] = SOCKS5_SUCCEEDED
;
1979 buf
[2] = 0; /* reserved */
1980 buf
[3] = 0x01; /* IPv4 address type */
1981 memcpy(buf
+4, answer
, 4); /* address */
1982 set_uint16(buf
+8, 0); /* port == 0. */
1984 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
1985 buf
[1] = SOCKS5_SUCCEEDED
;
1986 buf
[2] = 0; /* reserved */
1987 buf
[3] = 0x04; /* IPv6 address type */
1988 memcpy(buf
+4, answer
, 16); /* address */
1989 set_uint16(buf
+20, 0); /* port == 0. */
1991 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
1992 buf
[1] = SOCKS5_SUCCEEDED
;
1993 buf
[2] = 0; /* reserved */
1994 buf
[3] = 0x03; /* Domainname address type */
1995 buf
[4] = (char)answer_len
;
1996 memcpy(buf
+5, answer
, answer_len
); /* address */
1997 set_uint16(buf
+5+answer_len
, 0); /* port == 0. */
1998 replylen
= 5+answer_len
+2;
2000 buf
[1] = SOCKS5_HOST_UNREACHABLE
;
2001 memset(buf
+2, 0, 8);
2005 /* no socks version info; don't send anything back */
2008 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
2009 (answer_type
== RESOLVED_TYPE_IPV4
||
2010 answer_type
== RESOLVED_TYPE_IPV6
) ?
2011 0 : END_STREAM_REASON_RESOLVEFAILED
);
2014 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2015 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2018 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2019 * and return, else reply based on <b>endreason</b> (one of
2020 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't 0
2021 * or REASON_DONE. Send endreason to the controller, if appropriate.
2024 connection_ap_handshake_socks_reply(edge_connection_t
*conn
, char *reply
,
2025 size_t replylen
, int endreason
)
2028 socks5_reply_status_t status
=
2029 connection_edge_end_reason_socks5_response(endreason
);
2031 tor_assert(conn
->socks_request
); /* make sure it's an AP stream */
2033 control_event_stream_status(conn
,
2034 status
==SOCKS5_SUCCEEDED
? STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
,
2037 if (conn
->socks_request
->has_finished
) {
2038 log_warn(LD_BUG
, "Harmless bug: duplicate calls to "
2039 "connection_ap_handshake_socks_reply.");
2042 if (replylen
) { /* we already have a reply in mind */
2043 connection_write_to_buf(reply
, replylen
, TO_CONN(conn
));
2044 conn
->socks_request
->has_finished
= 1;
2047 if (conn
->socks_request
->socks_version
== 4) {
2048 memset(buf
,0,SOCKS4_NETWORK_LEN
);
2049 #define SOCKS4_GRANTED 90
2050 #define SOCKS4_REJECT 91
2051 buf
[1] = (status
==SOCKS5_SUCCEEDED
? SOCKS4_GRANTED
: SOCKS4_REJECT
);
2052 /* leave version, destport, destip zero */
2053 connection_write_to_buf(buf
, SOCKS4_NETWORK_LEN
, TO_CONN(conn
));
2054 } else if (conn
->socks_request
->socks_version
== 5) {
2055 buf
[0] = 5; /* version 5 */
2056 buf
[1] = (char)status
;
2058 buf
[3] = 1; /* ipv4 addr */
2059 memset(buf
+4,0,6); /* Set external addr/port to 0.
2060 The spec doesn't seem to say what to do here. -RD */
2061 connection_write_to_buf(buf
,10,TO_CONN(conn
));
2063 /* If socks_version isn't 4 or 5, don't send anything.
2064 * This can happen in the case of AP bridges. */
2065 conn
->socks_request
->has_finished
= 1;
2069 /** A relay 'begin' cell has arrived, and either we are an exit hop
2070 * for the circuit, or we are the origin and it is a rendezvous begin.
2072 * Launch a new exit connection and initialize things appropriately.
2074 * If it's a rendezvous stream, call connection_exit_connect() on
2077 * For general streams, call dns_resolve() on it first, and only call
2078 * connection_exit_connect() if the dns answer is already known.
2080 * Note that we don't call connection_add() on the new stream! We wait
2081 * for connection_exit_connect() to do that.
2083 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2087 connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
)
2089 edge_connection_t
*n_stream
;
2093 char end_payload
[1];
2094 or_circuit_t
*or_circ
= NULL
;
2096 assert_circuit_ok(circ
);
2097 if (!CIRCUIT_IS_ORIGIN(circ
))
2098 or_circ
= TO_OR_CIRCUIT(circ
);
2100 relay_header_unpack(&rh
, cell
->payload
);
2102 /* Note: we have to use relay_send_command_from_edge here, not
2103 * connection_edge_end or connection_edge_send_command, since those require
2104 * that we have a stream connected to a circuit, and we don't connect to a
2105 * circuit until we have a pending/successful resolve. */
2107 if (!server_mode(get_options()) &&
2108 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
2109 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2110 "Relay begin cell at non-server. Closing.");
2111 end_payload
[0] = END_STREAM_REASON_EXITPOLICY
;
2112 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2113 end_payload
, 1, NULL
);
2117 if (rh
.command
== RELAY_COMMAND_BEGIN
) {
2118 if (!memchr(cell
->payload
+RELAY_HEADER_SIZE
, 0, rh
.length
)) {
2119 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2120 "Relay begin cell has no \\0. Closing.");
2121 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2122 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2123 end_payload
, 1, NULL
);
2126 if (parse_addr_port(LOG_PROTOCOL_WARN
, cell
->payload
+RELAY_HEADER_SIZE
,
2127 &address
,NULL
,&port
)<0) {
2128 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2129 "Unable to parse addr:port in relay begin cell. Closing.");
2130 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2131 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2132 end_payload
, 1, NULL
);
2136 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2137 "Missing port in relay begin cell. Closing.");
2138 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2139 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2140 end_payload
, 1, NULL
);
2144 if (or_circ
&& or_circ
->is_first_hop
) {
2145 /* Don't let clients use us as a single-hop proxy; it attracts attackers
2146 * and users who'd be better off with, well, single-hop proxies.
2148 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2149 "Attempt to open a stream on first hop of circuit. Closing.");
2150 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2151 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2152 end_payload
, 1, NULL
);
2156 } else if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2157 or_options_t
*options
= get_options();
2158 port
= options
->DirPort
; /* not actually used to open a connection */
2159 if (!port
|| circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
2160 end_payload
[0] = END_STREAM_REASON_NOTDIRECTORY
;
2161 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2162 end_payload
, 1, NULL
);
2165 if (or_circ
&& or_circ
->p_conn
&& or_circ
->p_conn
->_base
.address
)
2166 address
= tor_strdup(or_circ
->p_conn
->_base
.address
);
2168 address
= tor_strdup("127.0.0.1");
2170 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
2171 end_payload
[0] = END_STREAM_REASON_INTERNAL
;
2172 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2173 end_payload
, 1, NULL
);
2177 log_debug(LD_EXIT
,"Creating new exit connection.");
2178 n_stream
= TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT
));
2179 n_stream
->_base
.purpose
= EXIT_PURPOSE_CONNECT
;
2181 n_stream
->stream_id
= rh
.stream_id
;
2182 n_stream
->_base
.port
= port
;
2183 /* leave n_stream->s at -1, because it's not yet valid */
2184 n_stream
->package_window
= STREAMWINDOW_START
;
2185 n_stream
->deliver_window
= STREAMWINDOW_START
;
2187 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
2188 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2189 log_debug(LD_REND
,"begin is for rendezvous. configuring stream.");
2190 n_stream
->_base
.address
= tor_strdup("(rendezvous)");
2191 n_stream
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
2192 strlcpy(n_stream
->rend_query
, origin_circ
->rend_query
,
2193 sizeof(n_stream
->rend_query
));
2194 tor_assert(connection_edge_is_rendezvous_stream(n_stream
));
2195 assert_circuit_ok(circ
);
2196 if (rend_service_set_connection_addr_port(n_stream
, origin_circ
) < 0) {
2197 log_info(LD_REND
,"Didn't find rendezvous service (port %d)",
2198 n_stream
->_base
.port
);
2199 end_payload
[0] = END_STREAM_REASON_EXITPOLICY
;
2200 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2201 end_payload
, 1, NULL
);
2202 connection_free(TO_CONN(n_stream
));
2203 /* knock the whole thing down, somebody screwed up */
2204 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
2208 assert_circuit_ok(circ
);
2209 log_debug(LD_REND
,"Finished assigning addr/port");
2210 n_stream
->cpath_layer
= origin_circ
->cpath
->prev
; /* link it */
2212 /* add it into the linked list of n_streams on this circuit */
2213 n_stream
->next_stream
= origin_circ
->p_streams
;
2214 n_stream
->on_circuit
= circ
;
2215 origin_circ
->p_streams
= n_stream
;
2216 assert_circuit_ok(circ
);
2218 connection_exit_connect(n_stream
);
2222 tor_strlower(address
);
2223 n_stream
->_base
.address
= address
;
2224 n_stream
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2225 /* default to failed, change in dns_resolve if it turns out not to fail */
2227 if (we_are_hibernating()) {
2228 end_payload
[0] = END_STREAM_REASON_HIBERNATING
;
2229 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2230 end_payload
, 1, NULL
);
2231 connection_free(TO_CONN(n_stream
));
2234 log_debug(LD_EXIT
,"about to start the dns_resolve().");
2236 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2237 if (or_circ
&& or_circ
->p_conn
&& or_circ
->p_conn
->_base
.addr
)
2238 n_stream
->_base
.addr
= or_circ
->p_conn
->_base
.addr
;
2239 n_stream
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
2240 n_stream
->on_circuit
= circ
;
2241 TO_OR_CIRCUIT(circ
)->n_streams
= n_stream
;
2242 return connection_exit_connect_dir(n_stream
);
2245 /* send it off to the gethostbyname farm */
2246 switch (dns_resolve(n_stream
, NULL
)) {
2247 case 1: /* resolve worked */
2249 /* add it into the linked list of n_streams on this circuit */
2250 n_stream
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
2251 n_stream
->on_circuit
= circ
;
2252 TO_OR_CIRCUIT(circ
)->n_streams
= n_stream
;
2253 assert_circuit_ok(circ
);
2255 log_debug(LD_EXIT
,"about to call connection_exit_connect().");
2256 connection_exit_connect(n_stream
);
2258 case -1: /* resolve failed */
2259 end_payload
[0] = END_STREAM_REASON_RESOLVEFAILED
;
2260 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2261 end_payload
, 1, NULL
);
2262 /* n_stream got freed. don't touch it. */
2264 case 0: /* resolve added to pending list */
2265 /* add it into the linked list of resolving_streams on this circuit */
2266 n_stream
->next_stream
= TO_OR_CIRCUIT(circ
)->resolving_streams
;
2267 n_stream
->on_circuit
= circ
;
2268 TO_OR_CIRCUIT(circ
)->resolving_streams
= n_stream
;
2269 assert_circuit_ok(circ
);
2276 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
2277 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2280 connection_exit_begin_resolve(cell_t
*cell
, or_circuit_t
*circ
)
2282 edge_connection_t
*dummy_conn
;
2285 assert_circuit_ok(TO_CIRCUIT(circ
));
2286 relay_header_unpack(&rh
, cell
->payload
);
2288 /* This 'dummy_conn' only exists to remember the stream ID
2289 * associated with the resolve request; and to make the
2290 * implementation of dns.c more uniform. (We really only need to
2291 * remember the circuit, the stream ID, and the hostname to be
2292 * resolved; but if we didn't store them in a connection like this,
2293 * the housekeeping in dns.c would get way more complicated.)
2295 dummy_conn
= TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT
));
2296 dummy_conn
->stream_id
= rh
.stream_id
;
2297 dummy_conn
->_base
.address
= tor_strndup(cell
->payload
+RELAY_HEADER_SIZE
,
2299 dummy_conn
->_base
.port
= 0;
2300 dummy_conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2301 dummy_conn
->_base
.purpose
= EXIT_PURPOSE_RESOLVE
;
2303 /* send it off to the gethostbyname farm */
2304 switch (dns_resolve(dummy_conn
, circ
)) {
2305 case -1: /* Impossible to resolve; a resolved cell was sent. */
2306 /* Connection freed; don't touch it. */
2308 case 1: /* The result was cached; a resolved cell was sent. */
2309 if (!dummy_conn
->_base
.marked_for_close
)
2310 connection_free(TO_CONN(dummy_conn
));
2312 case 0: /* resolve added to pending list */
2313 dummy_conn
->next_stream
= circ
->resolving_streams
;
2314 dummy_conn
->on_circuit
= TO_CIRCUIT(circ
);
2315 circ
->resolving_streams
= dummy_conn
;
2316 assert_circuit_ok(TO_CIRCUIT(circ
));
2322 /** Connect to conn's specified addr and port. If it worked, conn
2323 * has now been added to the connection_array.
2325 * Send back a connected cell. Include the resolved IP of the destination
2326 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2327 * streams must not reveal what IP they connected to.)
2330 connection_exit_connect(edge_connection_t
*edge_conn
)
2334 connection_t
*conn
= TO_CONN(edge_conn
);
2336 if (!connection_edge_is_rendezvous_stream(edge_conn
) &&
2337 router_compare_to_my_exit_policy(edge_conn
)) {
2338 log_info(LD_EXIT
,"%s:%d failed exit policy. Closing.",
2339 escaped_safe_str(conn
->address
), conn
->port
);
2340 connection_edge_end(edge_conn
, END_STREAM_REASON_EXITPOLICY
,
2341 edge_conn
->cpath_layer
);
2342 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2343 connection_free(conn
);
2349 if (redirect_exit_list
) {
2350 SMARTLIST_FOREACH(redirect_exit_list
, exit_redirect_t
*, r
,
2352 if ((addr
&r
->mask
)==(r
->addr
&r
->mask
) &&
2353 (r
->port_min
<= port
) && (port
<= r
->port_max
)) {
2355 if (r
->is_redirect
) {
2356 char tmpbuf
[INET_NTOA_BUF_LEN
];
2357 addr
= r
->addr_dest
;
2358 port
= r
->port_dest
;
2359 in
.s_addr
= htonl(addr
);
2360 tor_inet_ntoa(&in
, tmpbuf
, sizeof(tmpbuf
));
2361 log_debug(LD_EXIT
, "Redirecting connection from %s:%d to %s:%d",
2362 escaped_safe_str(conn
->address
), conn
->port
,
2363 safe_str(tmpbuf
), port
);
2370 log_debug(LD_EXIT
,"about to try connecting");
2371 switch (connection_connect(conn
, conn
->address
, addr
, port
)) {
2373 connection_edge_end_errno(edge_conn
, edge_conn
->cpath_layer
);
2374 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2375 connection_free(conn
);
2378 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
2380 connection_watch_events(conn
, EV_WRITE
| EV_READ
);
2381 /* writable indicates finish;
2382 * readable/error indicates broken link in windowsland. */
2384 /* case 1: fall through */
2387 conn
->state
= EXIT_CONN_STATE_OPEN
;
2388 if (connection_wants_to_flush(conn
)) {
2389 /* in case there are any queued data cells */
2390 log_warn(LD_BUG
,"Bug: newly connected conn had data waiting!");
2391 // connection_start_writing(conn);
2393 connection_watch_events(conn
, EV_READ
);
2395 /* also, deliver a 'connected' cell back through the circuit. */
2396 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
2397 /* rendezvous stream */
2398 /* don't send an address back! */
2399 connection_edge_send_command(edge_conn
,
2400 circuit_get_by_edge_conn(edge_conn
),
2401 RELAY_COMMAND_CONNECTED
,
2402 NULL
, 0, edge_conn
->cpath_layer
);
2403 } else { /* normal stream */
2404 /* This must be the original address, not the redirected address. */
2405 char connected_payload
[8];
2406 set_uint32(connected_payload
, htonl(conn
->addr
));
2407 set_uint32(connected_payload
+4,
2408 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
2409 connection_edge_send_command(edge_conn
,
2410 circuit_get_by_edge_conn(edge_conn
),
2411 RELAY_COMMAND_CONNECTED
,
2412 connected_payload
, 8, edge_conn
->cpath_layer
);
2416 /** Given an exit conn that should attach to us as a directory server, open a
2417 * bridge connection with a socketpair, create a new directory conn, and join
2418 * them together. Return 0 on success (or if there was an error we could send
2419 * back an end cell for). Return -(some circuit end reason) if the circuit
2420 * needs to be torn down. Either connects exit_conn, frees it, or marks it,
2424 connection_exit_connect_dir(edge_connection_t
*exit_conn
)
2428 dir_connection_t
*dir_conn
= NULL
;
2430 log_info(LD_EXIT
, "Opening dir bridge");
2432 if ((err
= tor_socketpair(AF_UNIX
, SOCK_STREAM
, 0, fd
)) < 0) {
2434 "Couldn't construct socketpair (%s). "
2435 "Network down? Out of sockets?",
2436 tor_socket_strerror(-err
));
2437 connection_edge_end(exit_conn
, END_STREAM_REASON_RESOURCELIMIT
,
2438 exit_conn
->cpath_layer
);
2439 connection_free(TO_CONN(exit_conn
));
2443 tor_assert(fd
[0] >= 0);
2444 tor_assert(fd
[1] >= 0);
2446 set_socket_nonblocking(fd
[0]);
2447 set_socket_nonblocking(fd
[1]);
2449 exit_conn
->_base
.s
= fd
[0];
2450 exit_conn
->_base
.state
= EXIT_CONN_STATE_OPEN
;
2452 dir_conn
= TO_DIR_CONN(connection_new(CONN_TYPE_DIR
));
2453 dir_conn
->_base
.s
= fd
[1];
2455 dir_conn
->_base
.addr
= 0x7f000001;
2456 dir_conn
->_base
.port
= 0;
2457 dir_conn
->_base
.address
= tor_strdup("Tor network");
2458 dir_conn
->_base
.type
= CONN_TYPE_DIR
;
2459 dir_conn
->_base
.purpose
= DIR_PURPOSE_SERVER
;
2460 dir_conn
->_base
.state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
2462 if (connection_add(TO_CONN(exit_conn
))<0) {
2463 connection_edge_end(exit_conn
, END_STREAM_REASON_RESOURCELIMIT
,
2464 exit_conn
->cpath_layer
);
2465 connection_free(TO_CONN(exit_conn
));
2466 connection_free(TO_CONN(dir_conn
));
2470 if (connection_add(TO_CONN(dir_conn
))<0) {
2471 connection_edge_end(exit_conn
, END_STREAM_REASON_RESOURCELIMIT
,
2472 exit_conn
->cpath_layer
);
2473 connection_close_immediate(TO_CONN(exit_conn
));
2474 connection_mark_for_close(TO_CONN(exit_conn
));
2475 connection_free(TO_CONN(dir_conn
));
2479 dir_conn
->bridge_conn
= exit_conn
;
2480 exit_conn
->bridge_for_conn
= dir_conn
;
2482 connection_start_reading(TO_CONN(dir_conn
));
2483 connection_start_reading(TO_CONN(exit_conn
));
2485 if (connection_edge_send_command(exit_conn
,
2486 circuit_get_by_edge_conn(exit_conn
),
2487 RELAY_COMMAND_CONNECTED
, NULL
, 0,
2488 exit_conn
->cpath_layer
) < 0) {
2489 connection_mark_for_close(TO_CONN(exit_conn
));
2490 connection_mark_for_close(TO_CONN(dir_conn
));
2497 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2498 * it is a general stream.
2501 connection_edge_is_rendezvous_stream(edge_connection_t
*conn
)
2504 if (*conn
->rend_query
) /* XXX */
2509 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2510 * to exit from it, or 0 if it probably will not allow it.
2511 * (We might be uncertain if conn's destination address has not yet been
2515 connection_ap_can_use_exit(edge_connection_t
*conn
, routerinfo_t
*exit
)
2518 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
2519 tor_assert(conn
->socks_request
);
2522 /* If a particular exit node has been requested for the new connection,
2523 * make sure the exit node of the existing circuit matches exactly.
2525 if (conn
->chosen_exit_name
) {
2526 if (router_get_by_nickname(conn
->chosen_exit_name
, 1) != exit
) {
2528 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2529 // conn->chosen_exit_name, exit->nickname);
2534 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
2537 addr_policy_result_t r
;
2538 if (tor_inet_aton(conn
->socks_request
->address
, &in
))
2539 addr
= ntohl(in
.s_addr
);
2540 r
= compare_addr_to_addr_policy(addr
, conn
->socks_request
->port
,
2542 if (r
== ADDR_POLICY_REJECTED
|| r
== ADDR_POLICY_PROBABLY_REJECTED
)
2544 } else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
2545 /* Can't support reverse lookups without eventdns. */
2546 if (conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE_PTR
&&
2547 exit
->has_old_dnsworkers
)
2550 /* Don't send DNS requests to non-exit servers by default. */
2551 if (!conn
->chosen_exit_name
&& policy_is_reject_star(exit
->exit_policy
))
2557 /** Make connection redirection follow the provided list of
2558 * exit_redirect_t */
2560 set_exit_redirects(smartlist_t
*lst
)
2562 if (redirect_exit_list
) {
2563 SMARTLIST_FOREACH(redirect_exit_list
, exit_redirect_t
*, p
, tor_free(p
));
2564 smartlist_free(redirect_exit_list
);
2566 redirect_exit_list
= lst
;
2569 /** If address is of the form "y.onion" with a well-formed handle y:
2570 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2572 * If address is of the form "y.exit":
2573 * Put a NUL after y and return EXIT_HOSTNAME.
2576 * Return NORMAL_HOSTNAME and change nothing.
2579 parse_extended_hostname(char *address
)
2582 char query
[REND_SERVICE_ID_LEN
+1];
2584 s
= strrchr(address
,'.');
2586 return NORMAL_HOSTNAME
; /* no dot, thus normal */
2587 if (!strcmp(s
+1,"exit")) {
2588 *s
= 0; /* nul-terminate it */
2589 return EXIT_HOSTNAME
; /* .exit */
2591 if (strcmp(s
+1,"onion"))
2592 return NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
2594 /* so it is .onion */
2595 *s
= 0; /* nul-terminate it */
2596 if (strlcpy(query
, address
, REND_SERVICE_ID_LEN
+1) >=
2597 REND_SERVICE_ID_LEN
+1)
2599 if (rend_valid_service_id(query
)) {
2600 return ONION_HOSTNAME
; /* success */
2603 /* otherwise, return to previous state and return 0 */
2605 return BAD_HOSTNAME
;
2608 /** Check if the address is of the form "y.noconnect"
2611 hostname_is_noconnect_address(const char *address
)
2613 return ! strcasecmpend(address
, ".noconnect");