Back to index

tor  0.2.3.18-rc
policies.c
Go to the documentation of this file.
00001 /* Copyright (c) 2001-2004, Roger Dingledine.
00002  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00003  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00004 /* See LICENSE for licensing information */
00005 
00011 #include "or.h"
00012 #include "config.h"
00013 #include "dirserv.h"
00014 #include "nodelist.h"
00015 #include "policies.h"
00016 #include "routerparse.h"
00017 #include "geoip.h"
00018 #include "ht.h"
00019 
00021 static smartlist_t *socks_policy = NULL;
00023 static smartlist_t *dir_policy = NULL;
00026 static smartlist_t *authdir_reject_policy = NULL;
00029 static smartlist_t *authdir_invalid_policy = NULL;
00032 static smartlist_t *authdir_baddir_policy = NULL;
00035 static smartlist_t *authdir_badexit_policy = NULL;
00036 
00039 static smartlist_t *reachable_or_addr_policy = NULL;
00042 static smartlist_t *reachable_dir_addr_policy = NULL;
00043 
00045 typedef struct policy_summary_item_t {
00046     uint16_t prt_min; 
00047     uint16_t prt_max; 
00048     uint64_t reject_count; 
00050     unsigned int accepted:1; 
00051 } policy_summary_item_t;
00052 
00059 static const char *private_nets[] = {
00060   "0.0.0.0/8", "169.254.0.0/16",
00061   "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
00062   // "fc00::/7", "fe80::/10", "fec0::/10", "::/127",
00063   NULL };
00064 
00067 void
00068 policy_expand_private(smartlist_t **policy)
00069 {
00070   uint16_t port_min, port_max;
00071 
00072   int i;
00073   smartlist_t *tmp;
00074 
00075   if (!*policy) /*XXXX disallow NULL policies? */
00076     return;
00077 
00078   tmp = smartlist_new();
00079 
00080   SMARTLIST_FOREACH(*policy, addr_policy_t *, p,
00081   {
00082      if (! p->is_private) {
00083        smartlist_add(tmp, p);
00084        continue;
00085      }
00086      for (i = 0; private_nets[i]; ++i) {
00087        addr_policy_t newpolicy;
00088        memcpy(&newpolicy, p, sizeof(addr_policy_t));
00089        newpolicy.is_private = 0;
00090        newpolicy.is_canonical = 0;
00091        if (tor_addr_parse_mask_ports(private_nets[i], &newpolicy.addr,
00092                                &newpolicy.maskbits, &port_min, &port_max)<0) {
00093          tor_assert(0);
00094        }
00095        smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
00096      }
00097      addr_policy_free(p);
00098   });
00099 
00100   smartlist_free(*policy);
00101   *policy = tmp;
00102 }
00103 
00113 static int
00114 parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
00115                   int assume_action)
00116 {
00117   smartlist_t *result;
00118   smartlist_t *entries;
00119   addr_policy_t *item;
00120   int r = 0;
00121 
00122   if (!cfg)
00123     return 0;
00124 
00125   result = smartlist_new();
00126   entries = smartlist_new();
00127   for (; cfg; cfg = cfg->next) {
00128     smartlist_split_string(entries, cfg->value, ",",
00129                            SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
00130     SMARTLIST_FOREACH(entries, const char *, ent,
00131     {
00132       log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
00133       item = router_parse_addr_policy_item_from_string(ent, assume_action);
00134       if (item) {
00135         smartlist_add(result, item);
00136       } else {
00137         log_warn(LD_CONFIG,"Malformed policy '%s'.", ent);
00138         r = -1;
00139       }
00140     });
00141     SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
00142     smartlist_clear(entries);
00143   }
00144   smartlist_free(entries);
00145   if (r == -1) {
00146     addr_policy_list_free(result);
00147   } else {
00148     policy_expand_private(&result);
00149 
00150     if (*dest) {
00151       smartlist_add_all(*dest, result);
00152       smartlist_free(result);
00153     } else {
00154       *dest = result;
00155     }
00156   }
00157 
00158   return r;
00159 }
00160 
00165 static int
00166 parse_reachable_addresses(void)
00167 {
00168   const or_options_t *options = get_options();
00169   int ret = 0;
00170 
00171   if (options->ReachableDirAddresses &&
00172       options->ReachableORAddresses &&
00173       options->ReachableAddresses) {
00174     log_warn(LD_CONFIG,
00175              "Both ReachableDirAddresses and ReachableORAddresses are set. "
00176              "ReachableAddresses setting will be ignored.");
00177   }
00178   addr_policy_list_free(reachable_or_addr_policy);
00179   reachable_or_addr_policy = NULL;
00180   if (!options->ReachableORAddresses && options->ReachableAddresses)
00181     log_info(LD_CONFIG,
00182              "Using ReachableAddresses as ReachableORAddresses.");
00183   if (parse_addr_policy(options->ReachableORAddresses ?
00184                           options->ReachableORAddresses :
00185                           options->ReachableAddresses,
00186                         &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
00187     log_warn(LD_CONFIG,
00188              "Error parsing Reachable%sAddresses entry; ignoring.",
00189              options->ReachableORAddresses ? "OR" : "");
00190     ret = -1;
00191   }
00192 
00193   addr_policy_list_free(reachable_dir_addr_policy);
00194   reachable_dir_addr_policy = NULL;
00195   if (!options->ReachableDirAddresses && options->ReachableAddresses)
00196     log_info(LD_CONFIG,
00197              "Using ReachableAddresses as ReachableDirAddresses");
00198   if (parse_addr_policy(options->ReachableDirAddresses ?
00199                           options->ReachableDirAddresses :
00200                           options->ReachableAddresses,
00201                         &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
00202     if (options->ReachableDirAddresses)
00203       log_warn(LD_CONFIG,
00204                "Error parsing ReachableDirAddresses entry; ignoring.");
00205     ret = -1;
00206   }
00207   return ret;
00208 }
00209 
00213 int
00214 firewall_is_fascist_or(void)
00215 {
00216   return reachable_or_addr_policy != NULL;
00217 }
00218 
00222 static int
00223 addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
00224                             smartlist_t *policy)
00225 {
00226   addr_policy_result_t p;
00227   p = compare_tor_addr_to_addr_policy(addr, port, policy);
00228   switch (p) {
00229     case ADDR_POLICY_PROBABLY_ACCEPTED:
00230     case ADDR_POLICY_ACCEPTED:
00231       return 1;
00232     case ADDR_POLICY_PROBABLY_REJECTED:
00233     case ADDR_POLICY_REJECTED:
00234       return 0;
00235     default:
00236       log_warn(LD_BUG, "Unexpected result: %d", (int)p);
00237       return 0;
00238   }
00239 }
00240 
00244 /* XXXX deprecate when possible. */
00245 static int
00246 addr_policy_permits_address(uint32_t addr, uint16_t port,
00247                             smartlist_t *policy)
00248 {
00249   tor_addr_t a;
00250   tor_addr_from_ipv4h(&a, addr);
00251   return addr_policy_permits_tor_addr(&a, port, policy);
00252 }
00253 
00256 int
00257 fascist_firewall_allows_address_or(const tor_addr_t *addr, uint16_t port)
00258 {
00259   return addr_policy_permits_tor_addr(addr, port,
00260                                      reachable_or_addr_policy);
00261 }
00262 
00265 int
00266 fascist_firewall_allows_or(const routerinfo_t *ri)
00267 {
00268   /* XXXX proposal 118 */
00269   tor_addr_t addr;
00270   tor_addr_from_ipv4h(&addr, ri->addr);
00271   return fascist_firewall_allows_address_or(&addr, ri->or_port);
00272 }
00273 
00276 int
00277 fascist_firewall_allows_node(const node_t *node)
00278 {
00279   if (node->ri) {
00280     return fascist_firewall_allows_or(node->ri);
00281   } else if (node->rs) {
00282     tor_addr_t addr;
00283     tor_addr_from_ipv4h(&addr, node->rs->addr);
00284     return fascist_firewall_allows_address_or(&addr, node->rs->or_port);
00285   } else {
00286     return 1;
00287   }
00288 }
00289 
00292 int
00293 fascist_firewall_allows_address_dir(const tor_addr_t *addr, uint16_t port)
00294 {
00295   return addr_policy_permits_tor_addr(addr, port,
00296                                       reachable_dir_addr_policy);
00297 }
00298 
00302 int
00303 dir_policy_permits_address(const tor_addr_t *addr)
00304 {
00305   return addr_policy_permits_tor_addr(addr, 1, dir_policy);
00306 }
00307 
00311 int
00312 socks_policy_permits_address(const tor_addr_t *addr)
00313 {
00314   return addr_policy_permits_tor_addr(addr, 1, socks_policy);
00315 }
00316 
00319 static int
00320 addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
00321 {
00322   country_t country;
00323   const char *name;
00324   if (!cc_list)
00325     return 0;
00326   country = geoip_get_country_by_ip(addr);
00327   name = geoip_get_country_name(country);
00328   return smartlist_string_isin_case(cc_list, name);
00329 }
00330 
00334 int
00335 authdir_policy_permits_address(uint32_t addr, uint16_t port)
00336 {
00337   if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
00338     return 0;
00339   return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
00340 }
00341 
00345 int
00346 authdir_policy_valid_address(uint32_t addr, uint16_t port)
00347 {
00348   if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
00349     return 0;
00350   return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
00351 }
00352 
00356 int
00357 authdir_policy_baddir_address(uint32_t addr, uint16_t port)
00358 {
00359   if (! addr_policy_permits_address(addr, port, authdir_baddir_policy))
00360     return 1;
00361   return addr_is_in_cc_list(addr, get_options()->AuthDirBadDirCCs);
00362 }
00363 
00367 int
00368 authdir_policy_badexit_address(uint32_t addr, uint16_t port)
00369 {
00370   if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
00371     return 1;
00372   return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
00373 }
00374 
00375 #define REJECT(arg) \
00376   STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
00377 
00381 int
00382 validate_addr_policies(const or_options_t *options, char **msg)
00383 {
00384   /* XXXX Maybe merge this into parse_policies_from_options, to make sure
00385    * that the two can't go out of sync. */
00386 
00387   smartlist_t *addr_policy=NULL;
00388   *msg = NULL;
00389 
00390   if (policies_parse_exit_policy(options->ExitPolicy, &addr_policy,
00391                                  options->ExitPolicyRejectPrivate, NULL,
00392                                  !options->BridgeRelay))
00393     REJECT("Error in ExitPolicy entry.");
00394 
00395   /* The rest of these calls *append* to addr_policy. So don't actually
00396    * use the results for anything other than checking if they parse! */
00397   if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
00398     REJECT("Error in DirPolicy entry.");
00399   if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
00400     REJECT("Error in SocksPolicy entry.");
00401   if (parse_addr_policy(options->AuthDirReject, &addr_policy,
00402                         ADDR_POLICY_REJECT))
00403     REJECT("Error in AuthDirReject entry.");
00404   if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
00405                         ADDR_POLICY_REJECT))
00406     REJECT("Error in AuthDirInvalid entry.");
00407   if (parse_addr_policy(options->AuthDirBadDir, &addr_policy,
00408                         ADDR_POLICY_REJECT))
00409     REJECT("Error in AuthDirBadDir entry.");
00410   if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
00411                         ADDR_POLICY_REJECT))
00412     REJECT("Error in AuthDirBadExit entry.");
00413 
00414   if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
00415                         ADDR_POLICY_ACCEPT))
00416     REJECT("Error in ReachableAddresses entry.");
00417   if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
00418                         ADDR_POLICY_ACCEPT))
00419     REJECT("Error in ReachableORAddresses entry.");
00420   if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
00421                         ADDR_POLICY_ACCEPT))
00422     REJECT("Error in ReachableDirAddresses entry.");
00423 
00424  err:
00425   addr_policy_list_free(addr_policy);
00426   return *msg ? -1 : 0;
00427 #undef REJECT
00428 }
00429 
00434 static int
00435 load_policy_from_option(config_line_t *config, smartlist_t **policy,
00436                         int assume_action)
00437 {
00438   int r;
00439   addr_policy_list_free(*policy);
00440   *policy = NULL;
00441   r = parse_addr_policy(config, policy, assume_action);
00442   if (r < 0) {
00443     return -1;
00444   }
00445   if (*policy) {
00446     SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
00447       /* ports aren't used in these. */
00448       if (n->prt_min > 1 || n->prt_max != 65535) {
00449         addr_policy_t newp, *c;
00450         memcpy(&newp, n, sizeof(newp));
00451         newp.prt_min = 1;
00452         newp.prt_max = 65535;
00453         newp.is_canonical = 0;
00454         c = addr_policy_get_canonical_entry(&newp);
00455         SMARTLIST_REPLACE_CURRENT(*policy, n, c);
00456         addr_policy_free(n);
00457       }
00458     } SMARTLIST_FOREACH_END(n);
00459   }
00460   return 0;
00461 }
00462 
00465 int
00466 policies_parse_from_options(const or_options_t *options)
00467 {
00468   int ret = 0;
00469   if (load_policy_from_option(options->SocksPolicy, &socks_policy, -1) < 0)
00470     ret = -1;
00471   if (load_policy_from_option(options->DirPolicy, &dir_policy, -1) < 0)
00472     ret = -1;
00473   if (load_policy_from_option(options->AuthDirReject,
00474                               &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
00475     ret = -1;
00476   if (load_policy_from_option(options->AuthDirInvalid,
00477                               &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
00478     ret = -1;
00479   if (load_policy_from_option(options->AuthDirBadDir,
00480                               &authdir_baddir_policy, ADDR_POLICY_REJECT) < 0)
00481     ret = -1;
00482   if (load_policy_from_option(options->AuthDirBadExit,
00483                               &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
00484     ret = -1;
00485   if (parse_reachable_addresses() < 0)
00486     ret = -1;
00487   return ret;
00488 }
00489 
00492 static int
00493 cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
00494 {
00495   int r;
00496   if ((r=((int)a->policy_type - (int)b->policy_type)))
00497     return r;
00498   if ((r=((int)a->is_private - (int)b->is_private)))
00499     return r;
00500   if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
00501     return r;
00502   if ((r=((int)a->maskbits - (int)b->maskbits)))
00503     return r;
00504   if ((r=((int)a->prt_min - (int)b->prt_min)))
00505     return r;
00506   if ((r=((int)a->prt_max - (int)b->prt_max)))
00507     return r;
00508   return 0;
00509 }
00510 
00513 int
00514 cmp_addr_policies(smartlist_t *a, smartlist_t *b)
00515 {
00516   int r, i;
00517   int len_a = a ? smartlist_len(a) : 0;
00518   int len_b = b ? smartlist_len(b) : 0;
00519 
00520   for (i = 0; i < len_a && i < len_b; ++i) {
00521     if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
00522       return r;
00523   }
00524   if (i == len_a && i == len_b)
00525     return 0;
00526   if (i < len_a)
00527     return -1;
00528   else
00529     return 1;
00530 }
00531 
00533 typedef struct policy_map_ent_t {
00534   HT_ENTRY(policy_map_ent_t) node;
00535   addr_policy_t *policy;
00536 } policy_map_ent_t;
00537 
00538 /* DOCDOC policy_root */
00539 static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
00540 
00542 static INLINE int
00543 policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
00544 {
00545   return cmp_single_addr_policy(a->policy, b->policy) == 0;
00546 }
00547 
00549 static unsigned int
00550 policy_hash(policy_map_ent_t *ent)
00551 {
00552   addr_policy_t *a = ent->policy;
00553   unsigned int r;
00554   if (a->is_private)
00555     r = 0x1234abcd;
00556   else
00557     r = tor_addr_hash(&a->addr);
00558   r += a->prt_min << 8;
00559   r += a->prt_max << 16;
00560   r += a->maskbits;
00561   if (a->policy_type == ADDR_POLICY_REJECT)
00562     r ^= 0xffffffff;
00563 
00564   return r;
00565 }
00566 
00567 HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
00568              policy_eq)
00569 HT_GENERATE(policy_map, policy_map_ent_t, node, policy_hash,
00570             policy_eq, 0.6, malloc, realloc, free)
00571 
00575 addr_policy_t *
00576 addr_policy_get_canonical_entry(addr_policy_t *e)
00577 {
00578   policy_map_ent_t search, *found;
00579   if (e->is_canonical)
00580     return e;
00581 
00582   search.policy = e;
00583   found = HT_FIND(policy_map, &policy_root, &search);
00584   if (!found) {
00585     found = tor_malloc_zero(sizeof(policy_map_ent_t));
00586     found->policy = tor_memdup(e, sizeof(addr_policy_t));
00587     found->policy->is_canonical = 1;
00588     found->policy->refcnt = 0;
00589     HT_INSERT(policy_map, &policy_root, found);
00590   }
00591 
00592   tor_assert(!cmp_single_addr_policy(found->policy, e));
00593   ++found->policy->refcnt;
00594   return found->policy;
00595 }
00596 
00599 static addr_policy_result_t
00600 compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
00601                                       const smartlist_t *policy)
00602 {
00603   /* We know the address and port, and we know the policy, so we can just
00604    * compute an exact match. */
00605   SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
00606     /* Address is known */
00607     if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
00608                                  CMP_EXACT)) {
00609       if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
00610         /* Exact match for the policy */
00611         return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
00612           ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
00613       }
00614     }
00615   } SMARTLIST_FOREACH_END(tmpe);
00616 
00617   /* accept all by default. */
00618   return ADDR_POLICY_ACCEPTED;
00619 }
00620 
00623 static addr_policy_result_t
00624 compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
00625                                              const smartlist_t *policy)
00626 {
00627   /* We look to see if there's a definite match.  If so, we return that
00628      match's value, unless there's an intervening possible match that says
00629      something different. */
00630   int maybe_accept = 0, maybe_reject = 0;
00631 
00632   SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
00633     if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
00634                                  CMP_EXACT)) {
00635       if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
00636         /* Definitely matches, since it covers all ports. */
00637         if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
00638           /* If we already hit a clause that might trigger a 'reject', than we
00639            * can't be sure of this certain 'accept'.*/
00640           return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
00641             ADDR_POLICY_ACCEPTED;
00642         } else {
00643           return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
00644             ADDR_POLICY_REJECTED;
00645         }
00646       } else {
00647         /* Might match. */
00648         if (tmpe->policy_type == ADDR_POLICY_REJECT)
00649           maybe_reject = 1;
00650         else
00651           maybe_accept = 1;
00652       }
00653     }
00654   } SMARTLIST_FOREACH_END(tmpe);
00655 
00656   /* accept all by default. */
00657   return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
00658 }
00659 
00662 static addr_policy_result_t
00663 compare_unknown_tor_addr_to_addr_policy(uint16_t port,
00664                                         const smartlist_t *policy)
00665 {
00666   /* We look to see if there's a definite match.  If so, we return that
00667      match's value, unless there's an intervening possible match that says
00668      something different. */
00669   int maybe_accept = 0, maybe_reject = 0;
00670 
00671   SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
00672     if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
00673       if (tmpe->maskbits == 0) {
00674         /* Definitely matches, since it covers all addresses. */
00675         if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
00676           /* If we already hit a clause that might trigger a 'reject', than we
00677            * can't be sure of this certain 'accept'.*/
00678           return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
00679             ADDR_POLICY_ACCEPTED;
00680         } else {
00681           return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
00682             ADDR_POLICY_REJECTED;
00683         }
00684       } else {
00685         /* Might match. */
00686         if (tmpe->policy_type == ADDR_POLICY_REJECT)
00687           maybe_reject = 1;
00688         else
00689           maybe_accept = 1;
00690       }
00691     }
00692   } SMARTLIST_FOREACH_END(tmpe);
00693 
00694   /* accept all by default. */
00695   return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
00696 }
00697 
00709 addr_policy_result_t
00710 compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
00711                                 const smartlist_t *policy)
00712 {
00713   if (!policy) {
00714     /* no policy? accept all. */
00715     return ADDR_POLICY_ACCEPTED;
00716   } else if (addr == NULL || tor_addr_is_null(addr)) {
00717     tor_assert(port != 0);
00718     return compare_unknown_tor_addr_to_addr_policy(port, policy);
00719   } else if (port == 0) {
00720     return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
00721   } else {
00722     return compare_known_tor_addr_to_addr_policy(addr, port, policy);
00723   }
00724 }
00725 
00728 static int
00729 addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
00730 {
00731   /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
00732    * to "accept *:80". */
00733   if (a->maskbits > b->maskbits) {
00734     /* a has more fixed bits than b; it can't possibly cover b. */
00735     return 0;
00736   }
00737   if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
00738     /* There's a fixed bit in a that's set differently in b. */
00739     return 0;
00740   }
00741   return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
00742 }
00743 
00748 static int
00749 addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
00750 {
00751   maskbits_t minbits;
00752   /* All the bits we care about are those that are set in both
00753    * netmasks.  If they are equal in a and b's networkaddresses
00754    * then the networks intersect.  If there is a difference,
00755    * then they do not. */
00756   if (a->maskbits < b->maskbits)
00757     minbits = a->maskbits;
00758   else
00759     minbits = b->maskbits;
00760   if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
00761     return 0;
00762   if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
00763     return 0;
00764   return 1;
00765 }
00766 
00769 static void
00770 append_exit_policy_string(smartlist_t **policy, const char *more)
00771 {
00772   config_line_t tmp;
00773 
00774   tmp.key = NULL;
00775   tmp.value = (char*) more;
00776   tmp.next = NULL;
00777   if (parse_addr_policy(&tmp, policy, -1)<0) {
00778     log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
00779   }
00780 }
00781 
00783 static void
00784 exit_policy_remove_redundancies(smartlist_t *dest)
00785 {
00786   addr_policy_t *ap, *tmp, *victim;
00787   int i, j;
00788 
00789   /* Step one: find a *:* entry and cut off everything after it. */
00790   for (i = 0; i < smartlist_len(dest); ++i) {
00791     ap = smartlist_get(dest, i);
00792     if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
00793       /* This is a catch-all line -- later lines are unreachable. */
00794       while (i+1 < smartlist_len(dest)) {
00795         victim = smartlist_get(dest, i+1);
00796         smartlist_del(dest, i+1);
00797         addr_policy_free(victim);
00798       }
00799       break;
00800     }
00801   }
00802 
00803   /* Step two: for every entry, see if there's a redundant entry
00804    * later on, and remove it. */
00805   for (i = 0; i < smartlist_len(dest)-1; ++i) {
00806     ap = smartlist_get(dest, i);
00807     for (j = i+1; j < smartlist_len(dest); ++j) {
00808       tmp = smartlist_get(dest, j);
00809       tor_assert(j > i);
00810       if (addr_policy_covers(ap, tmp)) {
00811         char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
00812         policy_write_item(p1, sizeof(p1), tmp, 0);
00813         policy_write_item(p2, sizeof(p2), ap, 0);
00814         log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s (%d).  It is made "
00815             "redundant by %s (%d).", p1, j, p2, i);
00816         smartlist_del_keeporder(dest, j--);
00817         addr_policy_free(tmp);
00818       }
00819     }
00820   }
00821 
00822   /* Step three: for every entry A, see if there's an entry B making this one
00823    * redundant later on.  This is the case if A and B are of the same type
00824    * (accept/reject), A is a subset of B, and there is no other entry of
00825    * different type in between those two that intersects with A.
00826    *
00827    * Anybody want to double-check the logic here? XXX
00828    */
00829   for (i = 0; i < smartlist_len(dest)-1; ++i) {
00830     ap = smartlist_get(dest, i);
00831     for (j = i+1; j < smartlist_len(dest); ++j) {
00832       // tor_assert(j > i); // j starts out at i+1; j only increases; i only
00833       //                    // decreases.
00834       tmp = smartlist_get(dest, j);
00835       if (ap->policy_type != tmp->policy_type) {
00836         if (addr_policy_intersects(ap, tmp))
00837           break;
00838       } else { /* policy_types are equal. */
00839         if (addr_policy_covers(tmp, ap)) {
00840           char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
00841           policy_write_item(p1, sizeof(p1), ap, 0);
00842           policy_write_item(p2, sizeof(p2), tmp, 0);
00843           log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s.  It is already "
00844               "covered by %s.", p1, p2);
00845           smartlist_del_keeporder(dest, i--);
00846           addr_policy_free(ap);
00847           break;
00848         }
00849       }
00850     }
00851   }
00852 }
00853 
00854 #define DEFAULT_EXIT_POLICY                                         \
00855   "reject *:25,reject *:119,reject *:135-139,reject *:445,"         \
00856   "reject *:563,reject *:1214,reject *:4661-4666,"                  \
00857   "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
00858 
00866 int
00867 policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
00868                            int rejectprivate, const char *local_address,
00869                            int add_default_policy)
00870 {
00871   if (rejectprivate) {
00872     append_exit_policy_string(dest, "reject private:*");
00873     if (local_address) {
00874       char buf[POLICY_BUF_LEN];
00875       tor_snprintf(buf, sizeof(buf), "reject %s:*", local_address);
00876       append_exit_policy_string(dest, buf);
00877     }
00878   }
00879   if (parse_addr_policy(cfg, dest, -1))
00880     return -1;
00881   if (add_default_policy)
00882     append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
00883   else
00884     append_exit_policy_string(dest, "reject *:*");
00885   exit_policy_remove_redundancies(*dest);
00886 
00887   return 0;
00888 }
00889 
00892 void
00893 policies_exit_policy_append_reject_star(smartlist_t **dest)
00894 {
00895   append_exit_policy_string(dest, "reject *:*");
00896 }
00897 
00899 void
00900 policies_set_node_exitpolicy_to_reject_all(node_t *node)
00901 {
00902   node->rejects_all = 1;
00903 }
00904 
00907 static int
00908 exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
00909 {
00910   uint32_t mask, ip, i;
00911   /* Is this /8 rejected (1), or undecided (0)? */
00912   char subnet_status[256];
00913 
00914   memset(subnet_status, 0, sizeof(subnet_status));
00915   SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
00916     if (tor_addr_family(&p->addr) != AF_INET)
00917       continue; /* IPv4 only for now */
00918     if (p->prt_min > port || p->prt_max < port)
00919       continue; /* Doesn't cover our port. */
00920     mask = 0;
00921     tor_assert(p->maskbits <= 32);
00922 
00923     if (p->maskbits)
00924       mask = UINT32_MAX<<(32-p->maskbits);
00925     ip = tor_addr_to_ipv4h(&p->addr);
00926 
00927     /* Calculate the first and last subnet that this exit policy touches
00928      * and set it as loop boundaries. */
00929     for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
00930       tor_addr_t addr;
00931       if (subnet_status[i] != 0)
00932         continue; /* We already reject some part of this /8 */
00933       tor_addr_from_ipv4h(&addr, i<<24);
00934       if (tor_addr_is_internal(&addr, 0))
00935         continue; /* Local or non-routable addresses */
00936       if (p->policy_type == ADDR_POLICY_ACCEPT) {
00937         if (p->maskbits > 8)
00938           continue; /* Narrower than a /8. */
00939         /* We found an allowed subnet of at least size /8. Done
00940          * for this port! */
00941         return 1;
00942       } else if (p->policy_type == ADDR_POLICY_REJECT) {
00943         subnet_status[i] = 1;
00944       }
00945     }
00946   });
00947   return 0;
00948 }
00949 
00953 int
00954 exit_policy_is_general_exit(smartlist_t *policy)
00955 {
00956   static const int ports[] = { 80, 443, 6667 };
00957   int n_allowed = 0;
00958   int i;
00959   if (!policy) /*XXXX disallow NULL policies? */
00960     return 0;
00961 
00962   for (i = 0; i < 3; ++i) {
00963     n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
00964   }
00965   return n_allowed >= 2;
00966 }
00967 
00970 int
00971 policy_is_reject_star(const smartlist_t *policy)
00972 {
00973   if (!policy) /*XXXX disallow NULL policies? */
00974     return 1;
00975   SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
00976     if (p->policy_type == ADDR_POLICY_ACCEPT)
00977       return 0;
00978     else if (p->policy_type == ADDR_POLICY_REJECT &&
00979              p->prt_min <= 1 && p->prt_max == 65535 &&
00980              p->maskbits == 0)
00981       return 1;
00982   });
00983   return 1;
00984 }
00985 
00988 int
00989 policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
00990                   int format_for_desc)
00991 {
00992   size_t written = 0;
00993   char addrbuf[TOR_ADDR_BUF_LEN];
00994   const char *addrpart;
00995   int result;
00996   const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
00997   const int is_ip6 = tor_addr_family(&policy->addr) == AF_INET6;
00998 
00999   tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
01000 
01001   /* write accept/reject 1.2.3.4 */
01002   if (policy->is_private)
01003     addrpart = "private";
01004   else if (policy->maskbits == 0)
01005     addrpart = "*";
01006   else
01007     addrpart = addrbuf;
01008 
01009   result = tor_snprintf(buf, buflen, "%s%s%s %s",
01010                         (is_ip6&&format_for_desc)?"opt ":"",
01011                         is_accept ? "accept" : "reject",
01012                         (is_ip6&&format_for_desc)?"6":"",
01013                         addrpart);
01014   if (result < 0)
01015     return -1;
01016   written += strlen(buf);
01017   /* If the maskbits is 32 we don't need to give it.  If the mask is 0,
01018    * we already wrote "*". */
01019   if (policy->maskbits < 32 && policy->maskbits > 0) {
01020     if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
01021       return -1;
01022     written += strlen(buf+written);
01023   }
01024   if (policy->prt_min <= 1 && policy->prt_max == 65535) {
01025     /* There is no port set; write ":*" */
01026     if (written+4 > buflen)
01027       return -1;
01028     strlcat(buf+written, ":*", buflen-written);
01029     written += 2;
01030   } else if (policy->prt_min == policy->prt_max) {
01031     /* There is only one port; write ":80". */
01032     result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
01033     if (result<0)
01034       return -1;
01035     written += result;
01036   } else {
01037     /* There is a range of ports; write ":79-80". */
01038     result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
01039                           policy->prt_min, policy->prt_max);
01040     if (result<0)
01041       return -1;
01042     written += result;
01043   }
01044   if (written < buflen)
01045     buf[written] = '\0';
01046   else
01047     return -1;
01048 
01049   return (int)written;
01050 }
01051 
01054 /* XXXX This entire thing will do most stuff in O(N^2), or worse.  Use an
01055  *      RB-tree if that turns out to matter. */
01056 static smartlist_t *
01057 policy_summary_create(void)
01058 {
01059   smartlist_t *summary;
01060   policy_summary_item_t* item;
01061 
01062   item = tor_malloc_zero(sizeof(policy_summary_item_t));
01063   item->prt_min = 1;
01064   item->prt_max = 65535;
01065   item->reject_count = 0;
01066   item->accepted = 0;
01067 
01068   summary = smartlist_new();
01069   smartlist_add(summary, item);
01070 
01071   return summary;
01072 }
01073 
01080 static policy_summary_item_t*
01081 policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
01082 {
01083   policy_summary_item_t* new;
01084 
01085   new = tor_malloc_zero(sizeof(policy_summary_item_t));
01086   new->prt_min = new_starts;
01087   new->prt_max = old->prt_max;
01088   new->reject_count = old->reject_count;
01089   new->accepted = old->accepted;
01090 
01091   old->prt_max = new_starts-1;
01092 
01093   tor_assert(old->prt_min <= old->prt_max);
01094   tor_assert(new->prt_min <= new->prt_max);
01095   return new;
01096 }
01097 
01098 /* XXXX Nick says I'm going to hell for this.  If he feels charitably towards
01099  * my immortal soul, he can clean it up himself. */
01100 #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
01101 
01102 #define REJECT_CUTOFF_COUNT (1<<25)
01103 
01106 static int
01107 policy_summary_split(smartlist_t *summary,
01108                      uint16_t prt_min, uint16_t prt_max)
01109 {
01110   int start_at_index;
01111 
01112   int i = 0;
01113 
01114   while (AT(i)->prt_max < prt_min)
01115     i++;
01116   if (AT(i)->prt_min != prt_min) {
01117     policy_summary_item_t* new_item;
01118     new_item = policy_summary_item_split(AT(i), prt_min);
01119     smartlist_insert(summary, i+1, new_item);
01120     i++;
01121   }
01122   start_at_index = i;
01123 
01124   while (AT(i)->prt_max < prt_max)
01125     i++;
01126   if (AT(i)->prt_max != prt_max) {
01127     policy_summary_item_t* new_item;
01128     new_item = policy_summary_item_split(AT(i), prt_max+1);
01129     smartlist_insert(summary, i+1, new_item);
01130   }
01131 
01132   return start_at_index;
01133 }
01134 
01136 static void
01137 policy_summary_accept(smartlist_t *summary,
01138                       uint16_t prt_min, uint16_t prt_max)
01139 {
01140   int i = policy_summary_split(summary, prt_min, prt_max);
01141   while (i < smartlist_len(summary) &&
01142          AT(i)->prt_max <= prt_max) {
01143     if (!AT(i)->accepted &&
01144         AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
01145       AT(i)->accepted = 1;
01146     i++;
01147   }
01148   tor_assert(i < smartlist_len(summary) || prt_max==65535);
01149 }
01150 
01153 static void
01154 policy_summary_reject(smartlist_t *summary,
01155                       maskbits_t maskbits,
01156                       uint16_t prt_min, uint16_t prt_max)
01157 {
01158   int i = policy_summary_split(summary, prt_min, prt_max);
01159   /* XXX: ipv4 specific */
01160   uint64_t count = (U64_LITERAL(1) << (32-maskbits));
01161   while (i < smartlist_len(summary) &&
01162          AT(i)->prt_max <= prt_max) {
01163     AT(i)->reject_count += count;
01164     i++;
01165   }
01166   tor_assert(i < smartlist_len(summary) || prt_max==65535);
01167 }
01168 
01176 static void
01177 policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
01178 {
01179   if (p->policy_type == ADDR_POLICY_ACCEPT) {
01180     if (p->maskbits == 0) {
01181       policy_summary_accept(summary, p->prt_min, p->prt_max);
01182     }
01183   } else if (p->policy_type == ADDR_POLICY_REJECT) {
01184 
01185      int is_private = 0;
01186      int i;
01187      for (i = 0; private_nets[i]; ++i) {
01188        tor_addr_t addr;
01189        maskbits_t maskbits;
01190        if (tor_addr_parse_mask_ports(private_nets[i], &addr,
01191                                   &maskbits, NULL, NULL)<0) {
01192          tor_assert(0);
01193        }
01194        if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
01195            p->maskbits == maskbits) {
01196          is_private = 1;
01197          break;
01198        }
01199      }
01200 
01201      if (!is_private) {
01202        policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
01203      }
01204   } else
01205     tor_assert(0);
01206 }
01207 
01216 char *
01217 policy_summarize(smartlist_t *policy)
01218 {
01219   smartlist_t *summary = policy_summary_create();
01220   smartlist_t *accepts, *rejects;
01221   int i, last, start_prt;
01222   size_t accepts_len, rejects_len;
01223   char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
01224   const char *prefix;
01225 
01226   tor_assert(policy);
01227 
01228   /* Create the summary list */
01229   SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
01230     policy_summary_add_item(summary, p);
01231   });
01232 
01233   /* Now create two lists of strings, one for accepted and one
01234    * for rejected ports.  We take care to merge ranges so that
01235    * we avoid getting stuff like "1-4,5-9,10", instead we want
01236    * "1-10"
01237    */
01238   i = 0;
01239   start_prt = 1;
01240   accepts = smartlist_new();
01241   rejects = smartlist_new();
01242   while (1) {
01243     last = i == smartlist_len(summary)-1;
01244     if (last ||
01245         AT(i)->accepted != AT(i+1)->accepted) {
01246       char buf[POLICY_BUF_LEN];
01247 
01248       if (start_prt == AT(i)->prt_max)
01249         tor_snprintf(buf, sizeof(buf), "%d", start_prt);
01250       else
01251         tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
01252 
01253       if (AT(i)->accepted)
01254         smartlist_add(accepts, tor_strdup(buf));
01255       else
01256         smartlist_add(rejects, tor_strdup(buf));
01257 
01258       if (last)
01259         break;
01260 
01261       start_prt = AT(i+1)->prt_min;
01262     };
01263     i++;
01264   };
01265 
01266   /* Figure out which of the two stringlists will be shorter and use
01267    * that to build the result
01268    */
01269   if (smartlist_len(accepts) == 0) { /* no exits at all */
01270     result = tor_strdup("reject 1-65535");
01271     goto cleanup;
01272   }
01273   if (smartlist_len(rejects) == 0) { /* no rejects at all */
01274     result = tor_strdup("accept 1-65535");
01275     goto cleanup;
01276   }
01277 
01278   accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
01279   rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
01280 
01281   if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
01282       accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
01283     char *c;
01284     shorter_str = accepts_str;
01285     prefix = "accept";
01286 
01287     c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
01288     while (*c != ',' && c >= shorter_str)
01289       c--;
01290     tor_assert(c >= shorter_str);
01291     tor_assert(*c == ',');
01292     *c = '\0';
01293 
01294   } else if (rejects_len < accepts_len) {
01295     shorter_str = rejects_str;
01296     prefix = "reject";
01297   } else {
01298     shorter_str = accepts_str;
01299     prefix = "accept";
01300   }
01301 
01302   tor_asprintf(&result, "%s %s", prefix, shorter_str);
01303 
01304  cleanup:
01305   /* cleanup */
01306   SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
01307   smartlist_free(summary);
01308 
01309   tor_free(accepts_str);
01310   SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
01311   smartlist_free(accepts);
01312 
01313   tor_free(rejects_str);
01314   SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
01315   smartlist_free(rejects);
01316 
01317   return result;
01318 }
01319 
01322 short_policy_t *
01323 parse_short_policy(const char *summary)
01324 {
01325   const char *orig_summary = summary;
01326   short_policy_t *result;
01327   int is_accept;
01328   int n_entries;
01329   short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
01330   const char *next;
01331 
01332   if (!strcmpstart(summary, "accept ")) {
01333     is_accept = 1;
01334     summary += strlen("accept ");
01335   } else if (!strcmpstart(summary, "reject ")) {
01336     is_accept = 0;
01337     summary += strlen("reject ");
01338   } else {
01339     log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
01340     return NULL;
01341   }
01342 
01343   n_entries = 0;
01344   for ( ; *summary; summary = next) {
01345     const char *comma = strchr(summary, ',');
01346     unsigned low, high;
01347     char dummy;
01348     char ent_buf[32];
01349 
01350     next = comma ? comma+1 : strchr(summary, '\0');
01351 
01352     if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
01353       log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
01354              escaped(orig_summary));
01355       return NULL;
01356     }
01357 
01358     if (! TOR_ISDIGIT(*summary) || next-summary > (int)(sizeof(ent_buf)-1)) {
01359       /* unrecognized entry format. skip it. */
01360       continue;
01361     }
01362     if (next-summary < 2) {
01363       /* empty; skip it. */
01364       continue;
01365     }
01366 
01367     memcpy(ent_buf, summary, next-summary-1);
01368     ent_buf[next-summary-1] = '\0';
01369 
01370     if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
01371       if (low<1 || low>65535 || high<1 || high>65535) {
01372         log_fn(LOG_PROTOCOL_WARN, LD_DIR,
01373                "Found bad entry in policy summary %s", escaped(orig_summary));
01374         return NULL;
01375       }
01376     } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
01377       if (low<1 || low>65535) {
01378         log_fn(LOG_PROTOCOL_WARN, LD_DIR,
01379                "Found bad entry in policy summary %s", escaped(orig_summary));
01380         return NULL;
01381       }
01382       high = low;
01383     } else {
01384       log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
01385              escaped(orig_summary));
01386       return NULL;
01387     }
01388 
01389     entries[n_entries].min_port = low;
01390     entries[n_entries].max_port = high;
01391     n_entries++;
01392   }
01393 
01394   if (n_entries == 0) {
01395     log_fn(LOG_PROTOCOL_WARN, LD_DIR,
01396            "Found no port-range entries in summary %s", escaped(orig_summary));
01397     return NULL;
01398   }
01399 
01400   {
01401     size_t size = STRUCT_OFFSET(short_policy_t, entries) +
01402       sizeof(short_policy_entry_t)*(n_entries);
01403     result = tor_malloc_zero(size);
01404 
01405     tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
01406   }
01407 
01408   result->is_accept = is_accept;
01409   result->n_entries = n_entries;
01410   memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
01411   return result;
01412 }
01413 
01415 void
01416 short_policy_free(short_policy_t *policy)
01417 {
01418   tor_free(policy);
01419 }
01420 
01425 addr_policy_result_t
01426 compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
01427                                  const short_policy_t *policy)
01428 {
01429   int i;
01430   int found_match = 0;
01431   int accept;
01432   (void)addr;
01433 
01434   tor_assert(port != 0);
01435 
01436   if (addr && tor_addr_is_null(addr))
01437     addr = NULL; /* Unspec means 'no address at all,' in this context. */
01438 
01439   if (addr && (tor_addr_is_internal(addr, 0) ||
01440                tor_addr_is_loopback(addr)))
01441     return ADDR_POLICY_REJECTED;
01442 
01443   for (i=0; i < policy->n_entries; ++i) {
01444     const short_policy_entry_t *e = &policy->entries[i];
01445     if (e->min_port <= port && port <= e->max_port) {
01446       found_match = 1;
01447       break;
01448     }
01449   }
01450 
01451   if (found_match)
01452     accept = policy->is_accept;
01453   else
01454     accept = ! policy->is_accept;
01455 
01456   /* ???? are these right? -NM */
01457   /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
01458    * case here, because it would cause clients to believe that the node
01459    * allows exit enclaving. Trying it anyway would open up a cool attack
01460    * where the node refuses due to exitpolicy, the client reacts in
01461    * surprise by rewriting the node's exitpolicy to reject *:*, and then
01462    * a bad guy targets users by causing them to attempt such connections
01463    * to 98% of the exits.
01464    *
01465    * Once microdescriptors can handle addresses in special cases (e.g. if
01466    * we ever solve ticket 1774), we can provide certainty here. -RD */
01467   if (accept)
01468     return ADDR_POLICY_PROBABLY_ACCEPTED;
01469   else
01470     return ADDR_POLICY_REJECTED;
01471 }
01472 
01474 int
01475 short_policy_is_reject_star(const short_policy_t *policy)
01476 {
01477   /* This doesn't need to be as much on the lookout as policy_is_reject_star,
01478    * since policy summaries are from the consensus or from consensus
01479    * microdescs.
01480    */
01481   tor_assert(policy);
01482   /* Check for an exact match of "reject 1-65535". */
01483   return (policy->is_accept == 0 && policy->n_entries == 1 &&
01484           policy->entries[0].min_port == 1 &&
01485           policy->entries[0].max_port == 65535);
01486 }
01487 
01491 addr_policy_result_t
01492 compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
01493                                 const node_t *node)
01494 {
01495   if (node->rejects_all)
01496     return ADDR_POLICY_REJECTED;
01497 
01498   if (node->ri)
01499     return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
01500   else if (node->md) {
01501     if (node->md->exit_policy == NULL)
01502       return ADDR_POLICY_REJECTED;
01503     else
01504       return compare_tor_addr_to_short_policy(addr, port,
01505                                               node->md->exit_policy);
01506   } else
01507     return ADDR_POLICY_PROBABLY_REJECTED;
01508 }
01509 
01512 int
01513 getinfo_helper_policies(control_connection_t *conn,
01514                         const char *question, char **answer,
01515                         const char **errmsg)
01516 {
01517   (void) conn;
01518   (void) errmsg;
01519   if (!strcmp(question, "exit-policy/default")) {
01520     *answer = tor_strdup(DEFAULT_EXIT_POLICY);
01521   }
01522   return 0;
01523 }
01524 
01526 void
01527 addr_policy_list_free(smartlist_t *lst)
01528 {
01529   if (!lst)
01530     return;
01531   SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
01532   smartlist_free(lst);
01533 }
01534 
01536 void
01537 addr_policy_free(addr_policy_t *p)
01538 {
01539   if (!p)
01540     return;
01541 
01542   if (--p->refcnt <= 0) {
01543     if (p->is_canonical) {
01544       policy_map_ent_t search, *found;
01545       search.policy = p;
01546       found = HT_REMOVE(policy_map, &policy_root, &search);
01547       if (found) {
01548         tor_assert(p == found->policy);
01549         tor_free(found);
01550       }
01551     }
01552     tor_free(p);
01553   }
01554 }
01555 
01557 void
01558 policies_free_all(void)
01559 {
01560   addr_policy_list_free(reachable_or_addr_policy);
01561   reachable_or_addr_policy = NULL;
01562   addr_policy_list_free(reachable_dir_addr_policy);
01563   reachable_dir_addr_policy = NULL;
01564   addr_policy_list_free(socks_policy);
01565   socks_policy = NULL;
01566   addr_policy_list_free(dir_policy);
01567   dir_policy = NULL;
01568   addr_policy_list_free(authdir_reject_policy);
01569   authdir_reject_policy = NULL;
01570   addr_policy_list_free(authdir_invalid_policy);
01571   authdir_invalid_policy = NULL;
01572   addr_policy_list_free(authdir_baddir_policy);
01573   authdir_baddir_policy = NULL;
01574   addr_policy_list_free(authdir_badexit_policy);
01575   authdir_badexit_policy = NULL;
01576 
01577   if (!HT_EMPTY(&policy_root)) {
01578     policy_map_ent_t **ent;
01579     int n = 0;
01580     char buf[POLICY_BUF_LEN];
01581 
01582     log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
01583              (int)HT_SIZE(&policy_root));
01584 
01585     /* Note the first 10 cached policies to try to figure out where they
01586      * might be coming from. */
01587     HT_FOREACH(ent, policy_map, &policy_root) {
01588       if (++n > 10)
01589         break;
01590       if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
01591         log_warn(LD_MM,"  %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
01592     }
01593   }
01594   HT_CLEAR(policy_map, &policy_root);
01595 }
01596