1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 #define ADDRESSMAP_PRIVATE
10 #include "addressmap.h"
11 #include "circuituse.h"
13 #include "connection_edge.h"
16 #include "routerset.h"
19 /** A client-side struct to remember requests to rewrite addresses
20 * to new addresses. These structs are stored in the hash table
23 * There are 5 ways to set an address mapping:
24 * - A MapAddress command from the controller [permanent]
25 * - An AddressMap directive in the torrc [permanent]
26 * - When a TrackHostExits torrc directive is triggered [temporary]
27 * - When a DNS resolve succeeds [temporary]
28 * - When a DNS resolve fails [temporary]
30 * When an addressmap request is made but one is already registered,
31 * the new one is replaced only if the currently registered one has
32 * no "new_address" (that is, it's in the process of DNS resolve),
33 * or if the new one is permanent (expires==0 or 1).
35 * (We overload the 'expires' field, using "0" for mappings set via
36 * the configuration file, "1" for mappings set from the control
37 * interface, and other values for DNS and TrackHostExit mappings that can
40 * A mapping may be 'wildcarded'. If "src_wildcard" is true, then
41 * any address that ends with a . followed by the key for this entry will
42 * get remapped by it. If "dst_wildcard" is also true, then only the
43 * matching suffix of such addresses will get replaced by new_address.
48 addressmap_entry_source_bitfield_t source
:3;
49 unsigned src_wildcard
:1;
50 unsigned dst_wildcard
:1;
51 short num_resolve_failures
;
54 /** Entry for mapping addresses to which virtual address we mapped them to. */
58 char *hostname_address
;
59 } virtaddress_entry_t
;
61 /** A hash table to store client-side address rewrite instructions. */
62 static strmap_t
*addressmap
=NULL
;
65 * Table mapping addresses to which virtual address, if any, we
68 * We maintain the following invariant: if [A,B] is in
69 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
70 * must be in addressmap. We do not require that the converse hold:
71 * if it fails, then we could end up mapping two virtual addresses to
72 * the same address, which is no disaster.
74 static strmap_t
*virtaddress_reversemap
=NULL
;
76 /** Initialize addressmap. */
80 addressmap
= strmap_new();
81 virtaddress_reversemap
= strmap_new();
84 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
86 addressmap_ent_free(void *_ent
)
88 addressmap_entry_t
*ent
;
93 tor_free(ent
->new_address
);
97 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
99 addressmap_virtaddress_ent_free(void *_ent
)
101 virtaddress_entry_t
*ent
;
106 tor_free(ent
->ipv4_address
);
107 tor_free(ent
->hostname_address
);
111 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
113 addressmap_virtaddress_remove(const char *address
, addressmap_entry_t
*ent
)
115 if (ent
&& ent
->new_address
&&
116 address_is_in_virtual_range(ent
->new_address
)) {
117 virtaddress_entry_t
*ve
=
118 strmap_get(virtaddress_reversemap
, ent
->new_address
);
119 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
121 if (!strcmp(address
, ve
->ipv4_address
))
122 tor_free(ve
->ipv4_address
);
123 if (!strcmp(address
, ve
->hostname_address
))
124 tor_free(ve
->hostname_address
);
125 if (!ve
->ipv4_address
&& !ve
->hostname_address
) {
127 strmap_remove(virtaddress_reversemap
, ent
->new_address
);
133 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
134 * client address maps. */
136 addressmap_ent_remove(const char *address
, addressmap_entry_t
*ent
)
138 addressmap_virtaddress_remove(address
, ent
);
139 addressmap_ent_free(ent
);
142 /** Unregister all TrackHostExits mappings from any address to
143 * *.exitname.exit. */
145 clear_trackexithost_mappings(const char *exitname
)
148 if (!addressmap
|| !exitname
)
150 tor_asprintf(&suffix
, ".%s.exit", exitname
);
151 tor_strlower(suffix
);
153 STRMAP_FOREACH_MODIFY(addressmap
, address
, addressmap_entry_t
*, ent
) {
154 if (ent
->source
== ADDRMAPSRC_TRACKEXIT
&&
155 !strcmpend(ent
->new_address
, suffix
)) {
156 addressmap_ent_remove(address
, ent
);
157 MAP_DEL_CURRENT(address
);
159 } STRMAP_FOREACH_END
;
164 /** Remove all TRACKEXIT mappings from the addressmap for which the target
165 * host is unknown or no longer allowed, or for which the source address
166 * is no longer in trackexithosts. */
168 addressmap_clear_excluded_trackexithosts(const or_options_t
*options
)
170 const routerset_t
*allow_nodes
= options
->ExitNodes
;
171 const routerset_t
*exclude_nodes
= options
->ExcludeExitNodesUnion_
;
175 if (routerset_is_empty(allow_nodes
))
177 if (allow_nodes
== NULL
&& routerset_is_empty(exclude_nodes
))
180 STRMAP_FOREACH_MODIFY(addressmap
, address
, addressmap_entry_t
*, ent
) {
182 const char *target
= ent
->new_address
, *dot
;
187 /* DNS resolving in progress */
189 } else if (strcmpend(target
, ".exit")) {
190 /* Not a .exit mapping */
192 } else if (ent
->source
!= ADDRMAPSRC_TRACKEXIT
) {
193 /* Not a trackexit mapping. */
196 len
= strlen(target
);
198 continue; /* malformed. */
199 dot
= target
+ len
- 6; /* dot now points to just before .exit */
200 while (dot
> target
&& *dot
!= '.')
202 if (*dot
== '.') dot
++;
203 nodename
= tor_strndup(dot
, len
-5-(dot
-target
));;
204 node
= node_get_by_nickname(nodename
, 0);
207 (allow_nodes
&& !routerset_contains_node(allow_nodes
, node
)) ||
208 routerset_contains_node(exclude_nodes
, node
) ||
209 !hostname_in_track_host_exits(options
, address
)) {
210 /* We don't know this one, or we want to be rid of it. */
211 addressmap_ent_remove(address
, ent
);
212 MAP_DEL_CURRENT(address
);
214 } STRMAP_FOREACH_END
;
217 /** Return true iff <b>address</b> is one that we are configured to
218 * automap on resolve according to <b>options</b>. */
220 addressmap_address_should_automap(const char *address
,
221 const or_options_t
*options
)
223 const smartlist_t
*suffix_list
= options
->AutomapHostsSuffixes
;
228 SMARTLIST_FOREACH_BEGIN(suffix_list
, const char *, suffix
) {
229 if (!strcasecmpend(address
, suffix
))
231 } SMARTLIST_FOREACH_END(suffix
);
235 /** Remove all AUTOMAP mappings from the addressmap for which the
236 * source address no longer matches AutomapHostsSuffixes, which is
237 * no longer allowed by AutomapHostsOnResolve, or for which the
238 * target address is no longer in the virtual network. */
240 addressmap_clear_invalid_automaps(const or_options_t
*options
)
242 int clear_all
= !options
->AutomapHostsOnResolve
;
243 const smartlist_t
*suffixes
= options
->AutomapHostsSuffixes
;
249 clear_all
= 1; /* This should be impossible, but let's be sure. */
251 STRMAP_FOREACH_MODIFY(addressmap
, src_address
, addressmap_entry_t
*, ent
) {
252 int remove
= clear_all
;
253 if (ent
->source
!= ADDRMAPSRC_AUTOMAP
)
254 continue; /* not an automap mapping. */
257 remove
= ! addressmap_address_should_automap(src_address
, options
);
260 if (!remove
&& ! address_is_in_virtual_range(ent
->new_address
))
264 addressmap_ent_remove(src_address
, ent
);
265 MAP_DEL_CURRENT(src_address
);
267 } STRMAP_FOREACH_END
;
270 /** Remove all entries from the addressmap that were set via the
271 * configuration file or the command line. */
273 addressmap_clear_configured(void)
275 addressmap_get_mappings(NULL
, 0, 0, 0);
278 /** Remove all entries from the addressmap that are set to expire, ever. */
280 addressmap_clear_transient(void)
282 addressmap_get_mappings(NULL
, 2, TIME_MAX
, 0);
285 /** Clean out entries from the addressmap cache that were
286 * added long enough ago that they are no longer valid.
289 addressmap_clean(time_t now
)
291 addressmap_get_mappings(NULL
, 2, now
, 0);
294 /** Free all the elements in the addressmap, and free the addressmap
297 addressmap_free_all(void)
299 strmap_free(addressmap
, addressmap_ent_free
);
302 strmap_free(virtaddress_reversemap
, addressmap_virtaddress_ent_free
);
303 virtaddress_reversemap
= NULL
;
306 /** Try to find a match for AddressMap expressions that use
307 * wildcard notation such as '*.c.d *.e.f' (so 'a.c.d' will map to 'a.e.f') or
308 * '*.c.d a.b.c' (so 'a.c.d' will map to a.b.c).
309 * Return the matching entry in AddressMap or NULL if no match is found.
310 * For expressions such as '*.c.d *.e.f', truncate <b>address</b> 'a.c.d'
311 * to 'a' before we return the matching AddressMap entry.
313 * This function does not handle the case where a pattern of the form "*.c.d"
314 * matches the address c.d -- that's done by the main addressmap_rewrite
317 static addressmap_entry_t
*
318 addressmap_match_superdomains(char *address
)
320 addressmap_entry_t
*val
;
324 while ((cp
= strchr(cp
, '.'))) {
325 /* cp now points to a suffix of address that begins with a . */
326 val
= strmap_get_lc(addressmap
, cp
+1);
327 if (val
&& val
->src_wildcard
) {
328 if (val
->dst_wildcard
)
337 /** Look at address, and rewrite it until it doesn't want any
338 * more rewrites; but don't get into an infinite loop.
339 * Don't write more than maxlen chars into address. Return true if the
340 * address changed; false otherwise. Set *<b>expires_out</b> to the
341 * expiry time of the result, or to <b>time_max</b> if the result does
344 * If <b>exit_source_out</b> is non-null, we set it as follows. If we the
345 * address starts out as a non-exit address, and we remap it to an .exit
346 * address at any point, then set *<b>exit_source_out</b> to the
347 * address_entry_source_t of the first such rule. Set *<b>exit_source_out</b>
348 * to ADDRMAPSRC_NONE if there is no such rewrite, or if the original address
352 addressmap_rewrite(char *address
, size_t maxlen
,
355 addressmap_entry_source_t
*exit_source_out
)
357 addressmap_entry_t
*ent
;
359 time_t expires
= TIME_MAX
;
360 addressmap_entry_source_t exit_source
= ADDRMAPSRC_NONE
;
361 char *addr_orig
= tor_strdup(address
);
362 char *log_addr_orig
= NULL
;
364 for (rewrites
= 0; rewrites
< 16; rewrites
++) {
366 log_addr_orig
= tor_strdup(escaped_safe_str_client(address
));
368 ent
= strmap_get(addressmap
, address
);
370 if (!ent
|| !ent
->new_address
) {
371 ent
= addressmap_match_superdomains(address
);
373 if (ent
->src_wildcard
&& !ent
->dst_wildcard
&&
374 !strcasecmp(address
, ent
->new_address
)) {
375 /* This is a rule like *.example.com example.com, and we just got
383 if (!ent
|| !ent
->new_address
) {
387 if (ent
&& ent
->source
== ADDRMAPSRC_DNS
) {
390 f
= tor_addr_parse(&tmp
, ent
->new_address
);
391 if (f
== AF_INET
&& !(flags
& AMR_FLAG_USE_IPV4_DNS
))
393 else if (f
== AF_INET6
&& !(flags
& AMR_FLAG_USE_IPV6_DNS
))
397 if (ent
->dst_wildcard
&& !exact_match
) {
398 strlcat(address
, ".", maxlen
);
399 strlcat(address
, ent
->new_address
, maxlen
);
401 strlcpy(address
, ent
->new_address
, maxlen
);
404 if (!strcmpend(address
, ".exit") &&
405 strcmpend(addr_orig
, ".exit") &&
406 exit_source
== ADDRMAPSRC_NONE
) {
407 exit_source
= ent
->source
;
410 log_info(LD_APP
, "Addressmap: rewriting %s to %s",
411 log_addr_orig
, escaped_safe_str_client(address
));
412 if (ent
->expires
> 1 && ent
->expires
< expires
)
413 expires
= ent
->expires
;
415 tor_free(log_addr_orig
);
418 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
419 escaped_safe_str_client(address
));
420 /* it's fine to rewrite a rewrite, but don't loop forever */
424 tor_free(log_addr_orig
);
426 *exit_source_out
= exit_source
;
428 *expires_out
= TIME_MAX
;
429 return (rewrites
> 0);
432 /** If we have a cached reverse DNS entry for the address stored in the
433 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
434 * rewrite to the cached value and return 1. Otherwise return 0. Set
435 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
436 * if the result does not expire. */
438 addressmap_rewrite_reverse(char *address
, size_t maxlen
, unsigned flags
,
442 addressmap_entry_t
*ent
;
447 f
= tor_addr_parse(&tmp
, address
);
448 if (f
== AF_INET
&& !(flags
& AMR_FLAG_USE_IPV4_DNS
))
450 else if (f
== AF_INET6
&& !(flags
& AMR_FLAG_USE_IPV6_DNS
))
454 tor_asprintf(&s
, "REVERSE[%s]", address
);
455 ent
= strmap_get(addressmap
, s
);
457 cp
= tor_strdup(escaped_safe_str_client(ent
->new_address
));
458 log_info(LD_APP
, "Rewrote reverse lookup %s -> %s",
459 escaped_safe_str_client(s
), cp
);
461 strlcpy(address
, ent
->new_address
, maxlen
);
466 *expires_out
= (ent
&& ent
->expires
> 1) ? ent
->expires
: TIME_MAX
;
472 /** Return 1 if <b>address</b> is already registered, else return 0. If address
473 * is already registered, and <b>update_expires</b> is non-zero, then update
474 * the expiry time on the mapping with update_expires if it is a
475 * mapping created by TrackHostExits. */
477 addressmap_have_mapping(const char *address
, int update_expiry
)
479 addressmap_entry_t
*ent
;
480 if (!(ent
=strmap_get_lc(addressmap
, address
)))
482 if (update_expiry
&& ent
->source
==ADDRMAPSRC_TRACKEXIT
)
483 ent
->expires
=time(NULL
) + update_expiry
;
487 /** Register a request to map <b>address</b> to <b>new_address</b>,
488 * which will expire on <b>expires</b> (or 0 if never expires from
489 * config file, 1 if never expires from controller, 2 if never expires
490 * (virtual address mapping) from the controller.)
492 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
493 * free as appropriate. We will leave address alone.
495 * If <b>wildcard_addr</b> is true, then the mapping will match any address
496 * equal to <b>address</b>, or any address ending with a period followed by
497 * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
498 * both true, the mapping will rewrite addresses that end with
499 * ".<b>address</b>" into ones that end with ".<b>new_address</b>."
501 * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
502 * <b>address</b> and <b>wildcard_addr</b> is equal to
503 * <b>wildcard_new_addr</b>, remove any mappings that exist from
507 * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
510 addressmap_register(const char *address
, char *new_address
, time_t expires
,
511 addressmap_entry_source_t source
,
512 const int wildcard_addr
,
513 const int wildcard_new_addr
)
515 addressmap_entry_t
*ent
;
517 if (wildcard_new_addr
)
518 tor_assert(wildcard_addr
);
520 ent
= strmap_get(addressmap
, address
);
521 if (!new_address
|| (!strcasecmp(address
,new_address
) &&
522 wildcard_addr
== wildcard_new_addr
)) {
523 /* Remove the mapping, if any. */
524 tor_free(new_address
);
526 addressmap_ent_remove(address
,ent
);
527 strmap_remove(addressmap
, address
);
531 if (!ent
) { /* make a new one and register it */
532 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
533 strmap_set(addressmap
, address
, ent
);
534 } else if (ent
->new_address
) { /* we need to clean up the old mapping. */
536 log_info(LD_APP
,"Temporary addressmap ('%s' to '%s') not performed, "
537 "since it's already mapped to '%s'",
538 safe_str_client(address
),
539 safe_str_client(new_address
),
540 safe_str_client(ent
->new_address
));
541 tor_free(new_address
);
544 if (address_is_in_virtual_range(ent
->new_address
) &&
546 /* XXX This isn't the perfect test; we want to avoid removing
547 * mappings set from the control interface _as virtual mapping */
548 addressmap_virtaddress_remove(address
, ent
);
550 tor_free(ent
->new_address
);
551 } /* else { we have an in-progress resolve with no mapping. } */
553 ent
->new_address
= new_address
;
554 ent
->expires
= expires
==2 ? 1 : expires
;
555 ent
->num_resolve_failures
= 0;
556 ent
->source
= source
;
557 ent
->src_wildcard
= wildcard_addr
? 1 : 0;
558 ent
->dst_wildcard
= wildcard_new_addr
? 1 : 0;
560 log_info(LD_CONFIG
, "Addressmap: (re)mapped '%s' to '%s'",
561 safe_str_client(address
),
562 safe_str_client(ent
->new_address
));
563 control_event_address_mapped(address
, ent
->new_address
, expires
, NULL
, 1);
566 /** An attempt to resolve <b>address</b> failed at some OR.
567 * Increment the number of resolve failures we have on record
568 * for it, and then return that number.
571 client_dns_incr_failures(const char *address
)
573 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
575 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
576 ent
->expires
= time(NULL
) + MAX_DNS_ENTRY_AGE
;
577 strmap_set(addressmap
,address
,ent
);
579 if (ent
->num_resolve_failures
< SHORT_MAX
)
580 ++ent
->num_resolve_failures
; /* don't overflow */
581 log_info(LD_APP
, "Address %s now has %d resolve failures.",
582 safe_str_client(address
),
583 ent
->num_resolve_failures
);
584 return ent
->num_resolve_failures
;
587 /** If <b>address</b> is in the client DNS addressmap, reset
588 * the number of resolve failures we have on record for it.
589 * This is used when we fail a stream because it won't resolve:
590 * otherwise future attempts on that address will only try once.
593 client_dns_clear_failures(const char *address
)
595 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
597 ent
->num_resolve_failures
= 0;
600 /** Record the fact that <b>address</b> resolved to <b>name</b>.
601 * We can now use this in subsequent streams via addressmap_rewrite()
602 * so we can more correctly choose an exit that will allow <b>address</b>.
604 * If <b>exitname</b> is defined, then append the addresses with
605 * ".exitname.exit" before registering the mapping.
607 * If <b>ttl</b> is nonnegative, the mapping will be valid for
608 * <b>ttl</b>seconds; otherwise, we use the default.
611 client_dns_set_addressmap_impl(entry_connection_t
*for_conn
,
612 const char *address
, const char *name
,
613 const char *exitname
,
616 char *extendedaddress
=NULL
, *extendedval
=NULL
;
623 ttl
= DEFAULT_DNS_TTL
;
625 ttl
= dns_clip_ttl(ttl
);
628 /* XXXX fails to ever get attempts to get an exit address of
629 * google.com.digest[=~]nickname.exit; we need a syntax for this that
630 * won't make strict RFC952-compliant applications (like us) barf. */
631 tor_asprintf(&extendedaddress
,
632 "%s.%s.exit", address
, exitname
);
633 tor_asprintf(&extendedval
,
634 "%s.%s.exit", name
, exitname
);
636 tor_asprintf(&extendedaddress
,
638 tor_asprintf(&extendedval
,
641 addressmap_register(extendedaddress
, extendedval
,
642 time(NULL
) + ttl
, ADDRMAPSRC_DNS
, 0, 0);
643 tor_free(extendedaddress
);
646 /** Record the fact that <b>address</b> resolved to <b>val</b>.
647 * We can now use this in subsequent streams via addressmap_rewrite()
648 * so we can more correctly choose an exit that will allow <b>address</b>.
650 * If <b>exitname</b> is defined, then append the addresses with
651 * ".exitname.exit" before registering the mapping.
653 * If <b>ttl</b> is nonnegative, the mapping will be valid for
654 * <b>ttl</b>seconds; otherwise, we use the default.
657 client_dns_set_addressmap(entry_connection_t
*for_conn
,
659 const tor_addr_t
*val
,
660 const char *exitname
,
664 char valbuf
[TOR_ADDR_BUF_LEN
];
669 if (tor_addr_parse(&addr_tmp
, address
) >= 0)
670 return; /* If address was an IP address already, don't add a mapping. */
672 if (tor_addr_family(val
) == AF_INET
) {
673 if (! for_conn
->cache_ipv4_answers
)
675 } else if (tor_addr_family(val
) == AF_INET6
) {
676 if (! for_conn
->cache_ipv6_answers
)
680 if (! tor_addr_to_str(valbuf
, val
, sizeof(valbuf
), 1))
683 client_dns_set_addressmap_impl(for_conn
, address
, valbuf
, exitname
, ttl
);
686 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
687 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
689 * If <b>exitname</b> is defined, then append the addresses with
690 * ".exitname.exit" before registering the mapping.
692 * If <b>ttl</b> is nonnegative, the mapping will be valid for
693 * <b>ttl</b>seconds; otherwise, we use the default.
696 client_dns_set_reverse_addressmap(entry_connection_t
*for_conn
,
697 const char *address
, const char *v
,
698 const char *exitname
,
704 sa_family_t f
= tor_addr_parse(&tmp_addr
, address
);
705 if ((f
== AF_INET
&& ! for_conn
->cache_ipv4_answers
) ||
706 (f
== AF_INET6
&& ! for_conn
->cache_ipv6_answers
))
709 tor_asprintf(&s
, "REVERSE[%s]", address
);
710 client_dns_set_addressmap_impl(for_conn
, s
, v
, exitname
, ttl
);
714 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
715 * These addresses should map to localhost, so even if the
716 * application accidentally tried to connect to them directly (not
717 * via Tor), it wouldn't get too far astray.
719 * These options are configured by parse_virtual_addr_network().
722 static virtual_addr_conf_t virtaddr_conf_ipv4
;
723 static virtual_addr_conf_t virtaddr_conf_ipv6
;
725 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
726 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
727 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
728 * string and return -1 on failure. If validate_only is false, sets the
729 * actual virtual address range to the parsed value. */
731 parse_virtual_addr_network(const char *val
, sa_family_t family
,
735 const int ipv6
= (family
== AF_INET6
);
738 const int max_bits
= ipv6
? 40 : 16;
739 virtual_addr_conf_t
*conf
= ipv6
? &virtaddr_conf_ipv6
: &virtaddr_conf_ipv4
;
741 if (tor_addr_parse_mask_ports(val
, 0, &addr
, &bits
, NULL
, NULL
) < 0) {
743 tor_asprintf(msg
, "Error parsing VirtualAddressNetwork%s %s",
744 ipv6
?"IPv6":"", val
);
747 if (tor_addr_family(&addr
) != family
) {
749 tor_asprintf(msg
, "Incorrect address type for VirtualAddressNetwork%s",
754 if (port_min
!= 1 || port_max
!= 65535) {
756 tor_asprintf(msg
, "Can't specify ports on VirtualAddressNetwork%s",
762 if (bits
> max_bits
) {
764 tor_asprintf(msg
, "VirtualAddressNetwork%s expects a /%d "
765 "network or larger",ipv6
?"IPv6":"", max_bits
);
772 tor_addr_copy(&conf
->addr
, &addr
);
779 * Return true iff <b>addr</b> is likely to have been returned by
780 * client_dns_get_unused_address.
783 address_is_in_virtual_range(const char *address
)
787 if (!strcasecmpend(address
, ".virtual")) {
789 } else if (tor_addr_parse(&addr
, address
) >= 0) {
790 const virtual_addr_conf_t
*conf
= (tor_addr_family(&addr
) == AF_INET6
) ?
791 &virtaddr_conf_ipv6
: &virtaddr_conf_ipv4
;
792 if (tor_addr_compare_masked(&addr
, &conf
->addr
, conf
->bits
, CMP_EXACT
)==0)
798 /** Return a random address conforming to the virtual address configuration
802 get_random_virtual_addr(const virtual_addr_conf_t
*conf
, tor_addr_t
*addr_out
)
805 const uint8_t *addr_bytes
;
807 const int ipv6
= tor_addr_family(&conf
->addr
) == AF_INET6
;
808 const int total_bytes
= ipv6
? 16 : 4;
810 tor_assert(conf
->bits
<= total_bytes
* 8);
812 /* Set addr_bytes to the bytes of the virtual network, in host order */
814 addr_bytes
= tor_addr_to_in6_addr8(&conf
->addr
);
816 set_uint32(tmp
, tor_addr_to_ipv4n(&conf
->addr
));
820 /* Get an appropriate number of random bytes. */
821 crypto_rand((char*)bytes
, total_bytes
);
823 /* Now replace the first "conf->bits" bits of 'bytes' with addr_bytes*/
825 memcpy(bytes
, addr_bytes
, conf
->bits
/ 8);
826 if (conf
->bits
& 7) {
827 uint8_t mask
= 0xff >> (conf
->bits
& 7);
828 bytes
[conf
->bits
/8] &= mask
;
829 bytes
[conf
->bits
/8] |= addr_bytes
[conf
->bits
/8] & ~mask
;
833 tor_addr_from_ipv6_bytes(addr_out
, (char*) bytes
);
835 tor_addr_from_ipv4n(addr_out
, get_uint32(bytes
));
837 tor_assert(tor_addr_compare_masked(addr_out
, &conf
->addr
,
838 conf
->bits
, CMP_EXACT
)==0);
841 /** Return a newly allocated string holding an address of <b>type</b>
842 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
843 * and that is very unlikely to be the address of any real host.
845 * May return NULL if we have run out of virtual addresses.
848 addressmap_get_virtual_address(int type
)
851 tor_assert(addressmap
);
853 if (type
== RESOLVED_TYPE_HOSTNAME
) {
856 crypto_rand(rand
, sizeof(rand
));
857 base32_encode(buf
,sizeof(buf
),rand
,sizeof(rand
));
858 strlcat(buf
, ".virtual", sizeof(buf
));
859 } while (strmap_get(addressmap
, buf
));
860 return tor_strdup(buf
);
861 } else if (type
== RESOLVED_TYPE_IPV4
|| type
== RESOLVED_TYPE_IPV6
) {
862 const int ipv6
= (type
== RESOLVED_TYPE_IPV6
);
863 const virtual_addr_conf_t
*conf
= ipv6
?
864 &virtaddr_conf_ipv6
: &virtaddr_conf_ipv4
;
866 /* Don't try more than 1000 times. This gives us P < 1e-9 for
867 * failing to get a good address so long as the address space is
868 * less than ~97.95% full. That's always going to be true under
869 * sensible circumstances for an IPv6 /10, and it's going to be
870 * true for an IPv4 /10 as long as we've handed out less than
871 * 4.08 million addresses. */
872 uint32_t attempts
= 1000;
877 get_random_virtual_addr(conf
, &addr
);
880 /* Don't hand out any .0 or .255 address. */
881 const uint32_t a
= tor_addr_to_ipv4h(&addr
);
882 if ((a
& 0xff) == 0 || (a
& 0xff) == 0xff)
886 tor_addr_to_str(buf
, &addr
, sizeof(buf
), 1);
887 if (!strmap_get(addressmap
, buf
)) {
888 /* XXXX This code is to make sure I didn't add an undecorated version
889 * by mistake. I hope it's needless. */
890 char tmp
[TOR_ADDR_BUF_LEN
];
891 tor_addr_to_str(buf
, &addr
, sizeof(tmp
), 0);
892 if (strmap_get(addressmap
, tmp
)) {
893 log_warn(LD_BUG
, "%s wasn't in the addressmap, but %s was.",
898 return tor_strdup(buf
);
901 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
904 log_warn(LD_BUG
, "Called with unsupported address type (%d)", type
);
909 /** A controller has requested that we map some address of type
910 * <b>type</b> to the address <b>new_address</b>. Choose an address
911 * that is unlikely to be used, and map it, and return it in a newly
912 * allocated string. If another address of the same type is already
913 * mapped to <b>new_address</b>, try to return a copy of that address.
915 * The string in <b>new_address</b> may be freed or inserted into a map
916 * as appropriate. May return NULL if are out of virtual addresses.
919 addressmap_register_virtual_address(int type
, char *new_address
)
922 virtaddress_entry_t
*vent
;
923 int vent_needs_to_be_added
= 0;
925 tor_assert(new_address
);
926 tor_assert(addressmap
);
927 tor_assert(virtaddress_reversemap
);
929 vent
= strmap_get(virtaddress_reversemap
, new_address
);
931 vent
= tor_malloc_zero(sizeof(virtaddress_entry_t
));
932 vent_needs_to_be_added
= 1;
935 if (type
== RESOLVED_TYPE_IPV4
)
936 addrp
= &vent
->ipv4_address
;
937 else if (type
== RESOLVED_TYPE_IPV6
)
938 addrp
= &vent
->ipv6_address
;
940 addrp
= &vent
->hostname_address
;
943 addressmap_entry_t
*ent
= strmap_get(addressmap
, *addrp
);
944 if (ent
&& ent
->new_address
&&
945 !strcasecmp(new_address
, ent
->new_address
)) {
946 tor_free(new_address
);
947 tor_assert(!vent_needs_to_be_added
);
948 return tor_strdup(*addrp
);
951 "Internal confusion: I thought that '%s' was mapped to by "
952 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
953 safe_str_client(new_address
),
954 safe_str_client(*addrp
),
955 safe_str_client(*addrp
),
956 ent
?safe_str_client(ent
->new_address
):"(nothing)");
961 *addrp
= addressmap_get_virtual_address(type
);
964 tor_free(new_address
);
967 log_info(LD_APP
, "Registering map from %s to %s", *addrp
, new_address
);
968 if (vent_needs_to_be_added
)
969 strmap_set(virtaddress_reversemap
, new_address
, vent
);
970 addressmap_register(*addrp
, new_address
, 2, ADDRMAPSRC_AUTOMAP
, 0, 0);
974 /* Try to catch possible bugs */
975 addressmap_entry_t
*ent
;
976 ent
= strmap_get(addressmap
, *addrp
);
978 tor_assert(!strcasecmp(ent
->new_address
,new_address
));
979 vent
= strmap_get(virtaddress_reversemap
, new_address
);
981 tor_assert(!strcasecmp(*addrp
,
982 (type
== RESOLVED_TYPE_IPV4
) ?
983 vent
->ipv4_address
: vent
->hostname_address
));
984 log_info(LD_APP
, "Map from %s to %s okay.",
985 safe_str_client(*addrp
),
986 safe_str_client(new_address
));
993 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
994 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
995 * should be true if we're using this address as a client; false if we're
996 * using it as a server.
999 address_is_invalid_destination(const char *address
, int client
)
1002 if (get_options()->AllowNonRFC953Hostnames
)
1005 if (get_options()->ServerDNSAllowNonRFC953Hostnames
)
1009 /* It might be an IPv6 address! */
1012 if (tor_addr_parse(&a
, address
) >= 0)
1017 if (TOR_ISALNUM(*address
) ||
1020 *address
== '_') /* Underscore is not allowed, but Windows does it
1021 * sometimes, just to thumb its nose at the IETF. */
1029 /** Iterate over all address mappings which have expiry times between
1030 * min_expires and max_expires, inclusive. If sl is provided, add an
1031 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1032 * the expiry time if want_expiry is false. If sl is NULL, remove the
1036 addressmap_get_mappings(smartlist_t
*sl
, time_t min_expires
,
1037 time_t max_expires
, int want_expiry
)
1039 strmap_iter_t
*iter
;
1042 addressmap_entry_t
*val
;
1047 for (iter
= strmap_iter_init(addressmap
); !strmap_iter_done(iter
); ) {
1048 strmap_iter_get(iter
, &key
, &val_
);
1050 if (val
->expires
>= min_expires
&& val
->expires
<= max_expires
) {
1052 iter
= strmap_iter_next_rmv(addressmap
,iter
);
1053 addressmap_ent_remove(key
, val
);
1055 } else if (val
->new_address
) {
1056 const char *src_wc
= val
->src_wildcard
? "*." : "";
1057 const char *dst_wc
= val
->dst_wildcard
? "*." : "";
1059 if (val
->expires
< 3 || val
->expires
== TIME_MAX
)
1060 smartlist_add_asprintf(sl
, "%s%s %s%s NEVER",
1061 src_wc
, key
, dst_wc
, val
->new_address
);
1063 char time
[ISO_TIME_LEN
+1];
1064 format_iso_time(time
, val
->expires
);
1065 smartlist_add_asprintf(sl
, "%s%s %s%s \"%s\"",
1066 src_wc
, key
, dst_wc
, val
->new_address
,
1070 smartlist_add_asprintf(sl
, "%s%s %s%s",
1071 src_wc
, key
, dst_wc
, val
->new_address
);
1075 iter
= strmap_iter_next(addressmap
,iter
);