routerlist.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerlist_c_id[] = "$Id$";
  7. /**
  8. * \file routerlist.c
  9. * \brief Code to
  10. * maintain and access the global list of routerinfos for known
  11. * servers.
  12. **/
  13. #include "or.h"
  14. /****************************************************************************/
  15. static smartlist_t *trusted_dir_servers = NULL;
  16. /* static function prototypes */
  17. static routerinfo_t *
  18. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  19. int for_runningrouters);
  20. static trusted_dir_server_t *
  21. router_pick_trusteddirserver_impl(int requireother, int fascistfirewall);
  22. static void mark_all_trusteddirservers_up(void);
  23. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  24. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  25. static int router_resolve(routerinfo_t *router);
  26. static int router_resolve_routerlist(routerlist_t *dir);
  27. /****************************************************************************/
  28. /****
  29. * Functions to manage and access our list of known routers. (Note:
  30. * dirservers maintain a separate, independent list of known router
  31. * descriptors.)
  32. ****/
  33. /** Global list of all of the routers that we, as an OR or OP, know about. */
  34. static routerlist_t *routerlist = NULL;
  35. extern int has_fetched_directory; /**< from main.c */
  36. /**
  37. * Reload the most recent cached directory (if present).
  38. */
  39. int
  40. router_reload_router_list(void)
  41. {
  42. char filename[512];
  43. int is_recent;
  44. struct stat st;
  45. char *s;
  46. tor_assert(get_options()->DataDirectory);
  47. tor_snprintf(filename,sizeof(filename),"%s/cached-directory",
  48. get_options()->DataDirectory);
  49. s = read_file_to_str(filename,0);
  50. if (s) {
  51. stat(filename, &st); /* if s is true, stat probably worked */
  52. log_fn(LOG_INFO, "Loading cached directory from %s", filename);
  53. is_recent = st.st_mtime > time(NULL) - 60*15;
  54. if (router_load_routerlist_from_directory(s, NULL, is_recent, 1) < 0) {
  55. log_fn(LOG_WARN, "Cached directory at '%s' was unparseable; ignoring.", filename);
  56. }
  57. if (routerlist &&
  58. ((routerlist->published_on > time(NULL) - MIN_ONION_KEY_LIFETIME/2)
  59. || is_recent)) {
  60. directory_has_arrived(st.st_mtime, NULL); /* do things we've been waiting to do */
  61. }
  62. tor_free(s);
  63. }
  64. return 0;
  65. }
  66. /* Set *<b>outp</b> to a smartlist containing a list of
  67. * trusted_dir_server_t * for all known trusted dirservers. Callers
  68. * must not modify the list or its contents.
  69. */
  70. void
  71. router_get_trusted_dir_servers(smartlist_t **outp)
  72. {
  73. if (!trusted_dir_servers)
  74. trusted_dir_servers = smartlist_create();
  75. *outp = trusted_dir_servers;
  76. }
  77. /** Try to find a running dirserver. If there are no running dirservers
  78. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  79. * set all the authoritative ones as running again, and pick one;
  80. * if there are then no dirservers at all in our routerlist,
  81. * reload the routerlist and try one last time. If for_runningrouters is
  82. * true, then only pick a dirserver that can answer runningrouters queries
  83. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  84. * Other args are as in router_pick_directory_server_impl().
  85. */
  86. routerinfo_t *
  87. router_pick_directory_server(int requireother,
  88. int fascistfirewall,
  89. int for_runningrouters,
  90. int retry_if_no_servers)
  91. {
  92. routerinfo_t *choice;
  93. if (!routerlist)
  94. return NULL;
  95. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  96. for_runningrouters);
  97. if (choice || !retry_if_no_servers)
  98. return choice;
  99. log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
  100. /* mark all authdirservers as up again */
  101. mark_all_trusteddirservers_up();
  102. /* try again */
  103. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  104. for_runningrouters);
  105. if (choice)
  106. return choice;
  107. log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
  108. get_options()->FascistFirewall ? "reachable" : "known");
  109. has_fetched_directory=0; /* reset it */
  110. if (router_reload_router_list()) {
  111. return NULL;
  112. }
  113. /* give it one last try */
  114. choice = router_pick_directory_server_impl(requireother, 0,
  115. for_runningrouters);
  116. return choice;
  117. }
  118. /** Try to find a running trusted dirserver. If there are no running
  119. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  120. * set them all as running again, and try again.
  121. * Other args are as in router_pick_trusteddirserver_impl().
  122. */
  123. trusted_dir_server_t *
  124. router_pick_trusteddirserver(int requireother,
  125. int fascistfirewall,
  126. int retry_if_no_servers)
  127. {
  128. trusted_dir_server_t *choice;
  129. choice = router_pick_trusteddirserver_impl(requireother, fascistfirewall);
  130. if (choice || !retry_if_no_servers)
  131. return choice;
  132. log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
  133. mark_all_trusteddirservers_up();
  134. return router_pick_trusteddirserver_impl(requireother, fascistfirewall);
  135. }
  136. /** Pick a random running verified directory server/mirror from our
  137. * routerlist.
  138. * If <b>fascistfirewall</b> and we're not using a proxy,
  139. * make sure the port we pick is allowed by options-\>firewallports.
  140. * If <b>requireother</b>, it cannot be us.
  141. * If <b>for_runningrouters</b>, make sure we pick a dirserver that
  142. * can answer queries for running-routers (this option will become obsolete
  143. * once 0.0.9-rc5 is dead).
  144. */
  145. static routerinfo_t *
  146. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  147. int for_runningrouters)
  148. {
  149. int i;
  150. routerinfo_t *router;
  151. smartlist_t *sl;
  152. if (!routerlist)
  153. return NULL;
  154. if (get_options()->HttpProxy)
  155. fascistfirewall = 0;
  156. /* Find all the running dirservers we know about. */
  157. sl = smartlist_create();
  158. for (i=0;i < smartlist_len(routerlist->routers); i++) {
  159. router = smartlist_get(routerlist->routers, i);
  160. if (!router->is_running || !router->dir_port || !router->is_verified)
  161. continue;
  162. if (requireother && router_is_me(router))
  163. continue;
  164. if (fascistfirewall) {
  165. if (!smartlist_string_num_isin(get_options()->FirewallPorts, router->dir_port))
  166. continue;
  167. }
  168. /* before 0.0.9rc5-cvs, only trusted dirservers served status info. */
  169. if (for_runningrouters &&
  170. !(tor_version_as_new_as(router->platform,"0.0.9rc5-cvs") ||
  171. router_digest_is_trusted_dir(router->identity_digest)))
  172. continue;
  173. smartlist_add(sl, router);
  174. }
  175. router = smartlist_choose(sl);
  176. smartlist_free(sl);
  177. return router;
  178. }
  179. /** Choose randomly from among the trusted dirservers that are up.
  180. * If <b>fascistfirewall</b> and we're not using a proxy,
  181. * make sure the port we pick is allowed by options-\>firewallports.
  182. * If <b>requireother</b>, it cannot be us.
  183. */
  184. static trusted_dir_server_t *
  185. router_pick_trusteddirserver_impl(int requireother, int fascistfirewall)
  186. {
  187. smartlist_t *sl;
  188. routerinfo_t *me;
  189. trusted_dir_server_t *ds;
  190. sl = smartlist_create();
  191. me = router_get_my_routerinfo();
  192. if (!trusted_dir_servers)
  193. return NULL;
  194. if (get_options()->HttpProxy)
  195. fascistfirewall = 0;
  196. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  197. {
  198. if (!d->is_running) continue;
  199. if (requireother && me &&
  200. !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
  201. continue;
  202. if (fascistfirewall) {
  203. if (!smartlist_string_num_isin(get_options()->FirewallPorts, d->dir_port))
  204. continue;
  205. }
  206. smartlist_add(sl, d);
  207. });
  208. ds = smartlist_choose(sl);
  209. smartlist_free(sl);
  210. return ds;
  211. }
  212. /** Go through and mark the authoritative dirservers as up. */
  213. static void
  214. mark_all_trusteddirservers_up(void)
  215. {
  216. if (routerlist) {
  217. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  218. if (router_digest_is_trusted_dir(router->identity_digest) &&
  219. router->dir_port > 0) {
  220. router->is_running = 1;
  221. router->status_set_at = time(NULL);
  222. });
  223. }
  224. if (trusted_dir_servers) {
  225. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  226. dir->is_running = 1);
  227. }
  228. }
  229. /** Return 0 if \\exists an authoritative dirserver that's currently
  230. * thought to be running, else return 1.
  231. */
  232. int
  233. all_trusted_directory_servers_down(void)
  234. {
  235. if (!trusted_dir_servers)
  236. return 1;
  237. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  238. if (dir->is_running) return 0);
  239. return 1;
  240. }
  241. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  242. * This is used to make sure we don't pick siblings in a single path.
  243. */
  244. void
  245. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  246. {
  247. routerinfo_t *r;
  248. struct config_line_t *cl;
  249. if (!router->declared_family)
  250. return;
  251. /* Add every r such that router declares familyness with r, and r
  252. * declares familyhood with router. */
  253. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  254. {
  255. if (!(r = router_get_by_nickname(n)))
  256. continue;
  257. if (!r->declared_family)
  258. continue;
  259. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  260. {
  261. if (router_nickname_matches(router, n2))
  262. smartlist_add(sl, r);
  263. });
  264. });
  265. /* If the user declared any families locally, honor those too. */
  266. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  267. if (router_nickname_is_in_list(router, cl->value)) {
  268. add_nickname_list_to_smartlist(sl, cl->value, 0);
  269. }
  270. }
  271. }
  272. /** List of strings for nicknames we've already warned about and that are
  273. * still unknown / unavailable. */
  274. static smartlist_t *warned_nicknames = NULL;
  275. /** Given a comma-and-whitespace separated list of nicknames, see which
  276. * nicknames in <b>list</b> name routers in our routerlist that are
  277. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  278. */
  279. void
  280. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
  281. {
  282. routerinfo_t *router;
  283. smartlist_t *nickname_list;
  284. if (!list)
  285. return; /* nothing to do */
  286. tor_assert(sl);
  287. nickname_list = smartlist_create();
  288. if (!warned_nicknames)
  289. warned_nicknames = smartlist_create();
  290. smartlist_split_string(nickname_list, list, ",",
  291. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  292. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  293. int warned;
  294. if (!is_legal_nickname_or_hexdigest(nick)) {
  295. log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
  296. continue;
  297. }
  298. router = router_get_by_nickname(nick);
  299. warned = smartlist_string_isin(warned_nicknames, nick);
  300. if (router) {
  301. if (router->is_running) {
  302. smartlist_add(sl,router);
  303. if (warned)
  304. smartlist_string_remove(warned_nicknames, nick);
  305. } else {
  306. if (!warned) {
  307. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
  308. "Nickname list includes '%s' which is known but down.",nick);
  309. smartlist_add(warned_nicknames, tor_strdup(nick));
  310. }
  311. }
  312. } else {
  313. if (!warned) {
  314. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  315. "Nickname list includes '%s' which isn't a known router.",nick);
  316. smartlist_add(warned_nicknames, tor_strdup(nick));
  317. }
  318. }
  319. });
  320. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  321. smartlist_free(nickname_list);
  322. }
  323. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  324. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  325. */
  326. static int
  327. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  328. {
  329. smartlist_t *nickname_list;
  330. int v = 0;
  331. if (!list)
  332. return 0; /* definitely not */
  333. tor_assert(router);
  334. nickname_list = smartlist_create();
  335. smartlist_split_string(nickname_list, list, ",",
  336. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  337. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  338. if (router_nickname_matches(router, cp)) {v=1;break;});
  339. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  340. smartlist_free(nickname_list);
  341. return v;
  342. }
  343. /** Add every router from our routerlist that is currently running to
  344. * <b>sl</b>.
  345. */
  346. static void
  347. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
  348. int need_uptime, int need_capacity)
  349. {
  350. routerinfo_t *router;
  351. int i;
  352. if (!routerlist)
  353. return;
  354. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  355. router = smartlist_get(routerlist->routers, i);
  356. if (router->is_running &&
  357. (router->is_verified ||
  358. (allow_unverified &&
  359. !router_is_unreliable(router, need_uptime, need_capacity)))) {
  360. /* If it's running, and either it's verified or we're ok picking
  361. * unverified routers and this one is suitable.
  362. */
  363. smartlist_add(sl, router);
  364. }
  365. }
  366. }
  367. /** Look through the routerlist until we find a router that has my key.
  368. Return it. */
  369. routerinfo_t *
  370. routerlist_find_my_routerinfo(void)
  371. {
  372. routerinfo_t *router;
  373. int i;
  374. if (!routerlist)
  375. return NULL;
  376. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  377. router = smartlist_get(routerlist->routers, i);
  378. if (router_is_me(router))
  379. return router;
  380. }
  381. return NULL;
  382. }
  383. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  384. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  385. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  386. * bandwidth.
  387. */
  388. int
  389. router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
  390. {
  391. if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
  392. return 1;
  393. if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  394. return 1;
  395. return 0;
  396. }
  397. /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
  398. static void
  399. routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
  400. {
  401. int i;
  402. routerinfo_t *router;
  403. for (i = 0; i < smartlist_len(sl); ++i) {
  404. router = smartlist_get(sl, i);
  405. if (router_is_unreliable(router, 1, 0)) {
  406. log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  407. router->nickname);
  408. smartlist_del(sl, i--);
  409. }
  410. }
  411. }
  412. #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
  413. /** Choose a random element of router list <b>sl</b>, weighted by
  414. * the advertised bandwidth of each router.
  415. */
  416. routerinfo_t *
  417. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  418. {
  419. int i;
  420. routerinfo_t *router;
  421. smartlist_t *bandwidths;
  422. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  423. uint32_t *p;
  424. /* First count the total bandwidth weight, and make a smartlist
  425. * of each value. */
  426. bandwidths = smartlist_create();
  427. for (i = 0; i < smartlist_len(sl); ++i) {
  428. router = smartlist_get(sl, i);
  429. this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
  430. router->bandwidthcapacity : router->bandwidthrate;
  431. /* if they claim something huge, don't believe it */
  432. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  433. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  434. p = tor_malloc(sizeof(uint32_t));
  435. *p = this_bw;
  436. smartlist_add(bandwidths, p);
  437. total_bw += this_bw;
  438. }
  439. if (!total_bw) {
  440. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  441. smartlist_free(bandwidths);
  442. return smartlist_choose(sl);
  443. }
  444. /* Second, choose a random value from the bandwidth weights. */
  445. rand_bw = crypto_pseudo_rand_int(total_bw);
  446. /* Last, count through sl until we get to the element we picked */
  447. tmp = 0;
  448. for (i=0; ; i++) {
  449. tor_assert(i < smartlist_len(sl));
  450. p = smartlist_get(bandwidths, i);
  451. tmp += *p;
  452. if (tmp >= rand_bw)
  453. break;
  454. }
  455. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  456. smartlist_free(bandwidths);
  457. return (routerinfo_t *)smartlist_get(sl, i);
  458. }
  459. /** Return a random running router from the routerlist. If any node
  460. * named in <b>preferred</b> is available, pick one of those. Never
  461. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  462. * <b>excludedsmartlist</b>, even if they are the only nodes
  463. * available. If <b>strict</b> is true, never pick any node besides
  464. * those in <b>preferred</b>.
  465. * If <b>need_uptime</b> is non-zero, don't return a router with less
  466. * than a minimum uptime.
  467. * If <b>need_capacity</b> is non-zero, weight your choice by the
  468. * advertised capacity of each router.
  469. */
  470. routerinfo_t *
  471. router_choose_random_node(const char *preferred,
  472. const char *excluded,
  473. smartlist_t *excludedsmartlist,
  474. int need_uptime, int need_capacity,
  475. int allow_unverified, int strict)
  476. {
  477. smartlist_t *sl, *excludednodes;
  478. routerinfo_t *choice;
  479. excludednodes = smartlist_create();
  480. add_nickname_list_to_smartlist(excludednodes,excluded,0);
  481. /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
  482. * since the user explicitly asked for these nodes. */
  483. sl = smartlist_create();
  484. add_nickname_list_to_smartlist(sl,preferred,1);
  485. smartlist_subtract(sl,excludednodes);
  486. if (excludedsmartlist)
  487. smartlist_subtract(sl,excludedsmartlist);
  488. choice = smartlist_choose(sl);
  489. smartlist_free(sl);
  490. if (!choice && !strict) {
  491. /* Then give up on our preferred choices: any node
  492. * will do that has the required attributes. */
  493. sl = smartlist_create();
  494. router_add_running_routers_to_smartlist(sl, allow_unverified,
  495. need_uptime, need_capacity);
  496. smartlist_subtract(sl,excludednodes);
  497. if (excludedsmartlist)
  498. smartlist_subtract(sl,excludedsmartlist);
  499. if (need_uptime)
  500. routerlist_sl_remove_unreliable_routers(sl);
  501. if (need_capacity)
  502. choice = routerlist_sl_choose_by_bandwidth(sl);
  503. else
  504. choice = smartlist_choose(sl);
  505. smartlist_free(sl);
  506. }
  507. smartlist_free(excludednodes);
  508. if (!choice)
  509. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  510. return choice;
  511. }
  512. /** Return true iff the digest of <b>router</b>'s identity key,
  513. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  514. * optionally prefixed with a single dollar sign). Return false if
  515. * <b>hexdigest</b> is malformed, or it doesn't match. */
  516. static INLINE int
  517. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  518. {
  519. char digest[DIGEST_LEN];
  520. tor_assert(hexdigest);
  521. if (hexdigest[0] == '$')
  522. ++hexdigest;
  523. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  524. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  525. return 0;
  526. return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
  527. }
  528. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  529. * (case-insensitive), or if <b>router's</b> identity key digest
  530. * matches a hexadecimal value stored in <b>nickname</b>. Return
  531. * false otherwise. */
  532. static int
  533. router_nickname_matches(routerinfo_t *router, const char *nickname)
  534. {
  535. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  536. return 1;
  537. return router_hex_digest_matches(router, nickname);
  538. }
  539. /** Return the router in our routerlist whose (case-insensitive)
  540. * nickname or (case-sensitive) hexadecimal key digest is
  541. * <b>nickname</b>. Return NULL if no such router is known.
  542. */
  543. routerinfo_t *
  544. router_get_by_nickname(const char *nickname)
  545. {
  546. int i, maybedigest;
  547. routerinfo_t *router;
  548. char digest[DIGEST_LEN];
  549. tor_assert(nickname);
  550. if (!routerlist)
  551. return NULL;
  552. if (nickname[0] == '$')
  553. return router_get_by_hexdigest(nickname);
  554. if (server_mode(get_options()) &&
  555. !strcasecmp(nickname, get_options()->Nickname))
  556. return router_get_my_routerinfo();
  557. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  558. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  559. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  560. router = smartlist_get(routerlist->routers, i);
  561. if (0 == strcasecmp(router->nickname, nickname) ||
  562. (maybedigest && 0 == memcmp(digest, router->identity_digest,
  563. DIGEST_LEN)))
  564. return router;
  565. }
  566. return NULL;
  567. }
  568. /** Return true iff <b>digest</b> is the digest of the identity key of
  569. * a trusted directory. */
  570. int
  571. router_digest_is_trusted_dir(const char *digest)
  572. {
  573. if (!trusted_dir_servers)
  574. return 0;
  575. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  576. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  577. return 0;
  578. }
  579. /** Return the router in our routerlist whose hexadecimal key digest
  580. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  581. routerinfo_t *
  582. router_get_by_hexdigest(const char *hexdigest)
  583. {
  584. char digest[DIGEST_LEN];
  585. tor_assert(hexdigest);
  586. if (!routerlist)
  587. return NULL;
  588. if (hexdigest[0]=='$')
  589. ++hexdigest;
  590. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  591. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  592. return NULL;
  593. return router_get_by_digest(digest);
  594. }
  595. /** Return the router in our routerlist whose 20-byte key digest
  596. * is <b>digest</b>. Return NULL if no such router is known. */
  597. routerinfo_t *
  598. router_get_by_digest(const char *digest)
  599. {
  600. int i;
  601. routerinfo_t *router;
  602. tor_assert(digest);
  603. if (!routerlist) return NULL;
  604. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  605. router = smartlist_get(routerlist->routers, i);
  606. if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
  607. return router;
  608. }
  609. return NULL;
  610. }
  611. /** Set *<b>prouterlist</b> to the current list of all known routers. */
  612. void
  613. router_get_routerlist(routerlist_t **prouterlist)
  614. {
  615. *prouterlist = routerlist;
  616. }
  617. /** Return the publication time on the current routerlist, or 0 if we have no
  618. * routerlist. */
  619. time_t
  620. routerlist_get_published_time(void)
  621. {
  622. return routerlist ? routerlist->published_on : 0;
  623. }
  624. /** Free all storage held by <b>router</b>. */
  625. void
  626. routerinfo_free(routerinfo_t *router)
  627. {
  628. if (!router)
  629. return;
  630. tor_free(router->signed_descriptor);
  631. tor_free(router->address);
  632. tor_free(router->nickname);
  633. tor_free(router->platform);
  634. tor_free(router->contact_info);
  635. if (router->onion_pkey)
  636. crypto_free_pk_env(router->onion_pkey);
  637. if (router->identity_pkey)
  638. crypto_free_pk_env(router->identity_pkey);
  639. if (router->declared_family) {
  640. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  641. smartlist_free(router->declared_family);
  642. }
  643. addr_policy_free(router->exit_policy);
  644. tor_free(router);
  645. }
  646. /** Allocate a fresh copy of <b>router</b> */
  647. routerinfo_t *
  648. routerinfo_copy(const routerinfo_t *router)
  649. {
  650. routerinfo_t *r;
  651. addr_policy_t **e, *tmp;
  652. r = tor_malloc(sizeof(routerinfo_t));
  653. memcpy(r, router, sizeof(routerinfo_t));
  654. r->address = tor_strdup(r->address);
  655. r->nickname = tor_strdup(r->nickname);
  656. r->platform = tor_strdup(r->platform);
  657. if (r->signed_descriptor)
  658. r->signed_descriptor = tor_strdup(r->signed_descriptor);
  659. if (r->onion_pkey)
  660. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  661. if (r->identity_pkey)
  662. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  663. e = &r->exit_policy;
  664. while (*e) {
  665. tmp = tor_malloc(sizeof(addr_policy_t));
  666. memcpy(tmp,*e,sizeof(addr_policy_t));
  667. *e = tmp;
  668. (*e)->string = tor_strdup((*e)->string);
  669. e = & ((*e)->next);
  670. }
  671. if (r->declared_family) {
  672. r->declared_family = smartlist_create();
  673. SMARTLIST_FOREACH(router->declared_family, const char *, s,
  674. smartlist_add(r->declared_family, tor_strdup(s)));
  675. }
  676. return r;
  677. }
  678. /** Free all storage held by a routerlist <b>rl</b> */
  679. void
  680. routerlist_free(routerlist_t *rl)
  681. {
  682. tor_assert(rl);
  683. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  684. routerinfo_free(r));
  685. smartlist_free(rl->routers);
  686. running_routers_free(rl->running_routers);
  687. tor_free(rl->software_versions);
  688. tor_free(rl);
  689. }
  690. /** Free all entries in the current router list. */
  691. void
  692. routerlist_free_current(void)
  693. {
  694. if (routerlist)
  695. routerlist_free(routerlist);
  696. routerlist = NULL;
  697. if (warned_nicknames) {
  698. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  699. smartlist_free(warned_nicknames);
  700. warned_nicknames = NULL;
  701. }
  702. }
  703. /** Free all entries in the list of trusted directory servers. */
  704. void
  705. free_trusted_dir_servers(void)
  706. {
  707. if (trusted_dir_servers) {
  708. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  709. { tor_free(ds->address); tor_free(ds); });
  710. smartlist_free(trusted_dir_servers);
  711. trusted_dir_servers = NULL;
  712. }
  713. }
  714. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  715. void
  716. router_mark_as_down(const char *digest)
  717. {
  718. routerinfo_t *router;
  719. tor_assert(digest);
  720. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  721. if (!memcmp(d->digest, digest, DIGEST_LEN))
  722. d->is_running = 0);
  723. router = router_get_by_digest(digest);
  724. if (!router) /* we don't seem to know about him in the first place */
  725. return;
  726. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  727. if (router_is_me(router))
  728. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  729. router->is_running = 0;
  730. router->status_set_at = time(NULL);
  731. }
  732. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  733. * older entries (if any) with the same name. Note: Callers should not hold
  734. * their pointers to <b>router</b> if this function fails; <b>router</b>
  735. * will either be inserted into the routerlist or freed. Returns 0 if the
  736. * router was added; -1 if it was not.
  737. *
  738. * If we're returning -1 and <b>msg</b> is not NULL, then assign to
  739. * *<b>msg</b> a static string describing the reason for refusing the
  740. * routerinfo.
  741. */
  742. static int
  743. router_add_to_routerlist(routerinfo_t *router, const char **msg)
  744. {
  745. int i;
  746. routerinfo_t *r;
  747. char id_digest[DIGEST_LEN];
  748. tor_assert(routerlist);
  749. crypto_pk_get_digest(router->identity_pkey, id_digest);
  750. /* If we have a router with this name, and the identity key is the same,
  751. * choose the newer one. If the identity key has changed, drop the router.
  752. */
  753. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  754. r = smartlist_get(routerlist->routers, i);
  755. if (!crypto_pk_cmp_keys(router->identity_pkey, r->identity_pkey)) {
  756. if (router->published_on > r->published_on) {
  757. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  758. router->nickname, r->nickname, hex_str(id_digest,DIGEST_LEN));
  759. //XXXRD /* Remember whether we trust this router as a dirserver. */
  760. /* If the address hasn't changed; no need to re-resolve. */
  761. if (!strcasecmp(r->address, router->address))
  762. router->addr = r->addr;
  763. routerinfo_free(r);
  764. smartlist_set(routerlist->routers, i, router);
  765. return 0;
  766. } else {
  767. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  768. router->nickname);
  769. /* Update the is_running status to whatever we were told. */
  770. r->is_running = router->is_running;
  771. routerinfo_free(router);
  772. if (msg) *msg = "Router descriptor was not new.";
  773. return -1;
  774. }
  775. } else if (!strcasecmp(router->nickname, r->nickname)) {
  776. /* nicknames match, keys don't. */
  777. if (router->is_verified) {
  778. /* The new verified router replaces the old one; remove the
  779. * old one. And carry on to the end of the list, in case
  780. * there are more old unverified routers with this nickname
  781. */
  782. /* mark-for-close connections using the old key, so we can
  783. * make new ones with the new key.
  784. */
  785. connection_t *conn;
  786. while ((conn = connection_get_by_identity_digest(r->identity_digest,
  787. CONN_TYPE_OR))) {
  788. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'", r->nickname);
  789. connection_mark_for_close(conn);
  790. }
  791. routerinfo_free(r);
  792. smartlist_del_keeporder(routerlist->routers, i--);
  793. } else if (r->is_verified) {
  794. /* Can't replace a verified router with an unverified one. */
  795. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  796. router->nickname);
  797. routerinfo_free(router);
  798. if (msg) *msg = "Already have verified router with same nickname and different key.";
  799. return -1;
  800. }
  801. }
  802. }
  803. /* We haven't seen a router with this name before. Add it to the end of
  804. * the list. */
  805. smartlist_add(routerlist->routers, router);
  806. return 0;
  807. }
  808. /** Remove any routers from the routerlist that are more than <b>age</b>
  809. * seconds old.
  810. *
  811. * (This function is just like dirserv_remove_old_servers. One day we should
  812. * merge them.)
  813. */
  814. //XXXRD
  815. void
  816. routerlist_remove_old_routers(int age)
  817. {
  818. int i;
  819. time_t cutoff;
  820. routerinfo_t *router;
  821. if (!routerlist)
  822. return;
  823. cutoff = time(NULL) - age;
  824. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  825. router = smartlist_get(routerlist->routers, i);
  826. if (router->published_on <= cutoff) {
  827. /* Too old. Remove it. */
  828. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  829. routerinfo_free(router);
  830. smartlist_del(routerlist->routers, i--);
  831. }
  832. }
  833. }
  834. /*
  835. * Code to parse a single router descriptor and insert it into the
  836. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  837. * descriptor was well-formed but could not be added; and 1 if the
  838. * descriptor was added.
  839. *
  840. * If we don't add it and <b>msg</b> is not NULL, then assign to
  841. * *<b>msg</b> a static string describing the reason for refusing the
  842. * descriptor.
  843. */
  844. int
  845. router_load_single_router(const char *s, const char **msg)
  846. {
  847. routerinfo_t *ri;
  848. tor_assert(msg);
  849. *msg = NULL;
  850. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  851. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  852. *msg = "Couldn't parse router descriptor.";
  853. return -1;
  854. }
  855. if (router_is_me(ri)) {
  856. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  857. *msg = "Router's identity key matches mine.";
  858. routerinfo_free(ri);
  859. return 0;
  860. }
  861. if (router_resolve(ri)<0) {
  862. log_fn(LOG_WARN, "Couldn't resolve router address '%s'; dropping.", ri->address);
  863. *msg = "Couldn't resolve router address.";
  864. routerinfo_free(ri);
  865. return 0;
  866. }
  867. if (routerlist && routerlist->running_routers) {
  868. running_routers_t *rr = routerlist->running_routers;
  869. router_update_status_from_smartlist(ri,
  870. rr->published_on,
  871. rr->running_routers);
  872. }
  873. if (router_add_to_routerlist(ri, msg)<0) {
  874. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  875. *msg?*msg:"(No message).");
  876. /* we've already assigned to *msg now, and ri is already freed */
  877. return 0;
  878. } else {
  879. smartlist_t *changed = smartlist_create();
  880. smartlist_add(changed, ri);
  881. control_event_descriptors_changed(changed);
  882. smartlist_free(changed);
  883. }
  884. log_fn(LOG_DEBUG, "Added router to list");
  885. return 1;
  886. }
  887. /** Add to the current routerlist each router stored in the
  888. * signed directory <b>s</b>. If pkey is provided, check the signature
  889. * against pkey; else check against the pkey of the signing directory
  890. * server.
  891. *
  892. * If <b>dir_is_recent</b> is non-zero, then examine the
  893. * Recommended-versions line and take appropriate action.
  894. *
  895. * If <b>dir_is_cached</b> is non-zero, then we're reading it
  896. * from the cache so don't bother to re-write it to the cache.
  897. */
  898. int
  899. router_load_routerlist_from_directory(const char *s,
  900. crypto_pk_env_t *pkey,
  901. int dir_is_recent,
  902. int dir_is_cached)
  903. {
  904. routerlist_t *new_list = NULL;
  905. if (router_parse_routerlist_from_directory(s, &new_list, pkey,
  906. dir_is_recent,
  907. !dir_is_cached)) {
  908. log_fn(LOG_WARN, "Couldn't parse directory.");
  909. return -1;
  910. }
  911. if (routerlist) {
  912. /* Merge the new_list into routerlist, then free new_list. Also
  913. * keep a list of changed descriptors to inform controllers. */
  914. smartlist_t *changed = smartlist_create();
  915. SMARTLIST_FOREACH(new_list->routers, routerinfo_t *, r,
  916. {
  917. if (router_add_to_routerlist(r,NULL)==0)
  918. smartlist_add(changed, r);
  919. });
  920. smartlist_clear(new_list->routers);
  921. routerlist->published_on = new_list->published_on;
  922. tor_free(routerlist->software_versions);
  923. routerlist->software_versions = new_list->software_versions;
  924. new_list->software_versions = NULL;
  925. routerlist_free(new_list);
  926. control_event_descriptors_changed(changed);
  927. smartlist_free(changed);
  928. } else {
  929. routerlist = new_list;
  930. control_event_descriptors_changed(routerlist->routers);
  931. }
  932. if (router_resolve_routerlist(routerlist)) {
  933. log_fn(LOG_WARN, "Error resolving routerlist");
  934. return -1;
  935. }
  936. if (get_options()->AuthoritativeDir) {
  937. /* Learn about the descriptors in the directory. */
  938. dirserv_load_from_directory_string(s);
  939. //XXXRD
  940. }
  941. return 0;
  942. }
  943. /** Helper function: resolve the hostname for <b>router</b>. */
  944. static int
  945. router_resolve(routerinfo_t *router)
  946. {
  947. if (authdir_mode(get_options())) {
  948. /* don't let authdirservers do resolves; this is an easy DoS avenue */
  949. struct in_addr iaddr;
  950. if (!tor_inet_aton(router->address, &iaddr)) { /* not an IP */
  951. log_fn(LOG_WARN,"Refusing to resolve non-IP address '%s' for router '%s'",
  952. router->address, router->nickname);
  953. return -1;
  954. }
  955. memcpy((void *)&router->addr, &iaddr.s_addr, 4);
  956. } else {
  957. if (tor_lookup_hostname(router->address, &router->addr) != 0
  958. || !router->addr) {
  959. log_fn(LOG_WARN,"Could not resolve address '%s' for router '%s'",
  960. router->address, router->nickname);
  961. return -1;
  962. }
  963. }
  964. router->addr = ntohl(router->addr); /* get it back into host order */
  965. return 0;
  966. }
  967. /** Helper function: resolve every router in rl, and ensure that our own
  968. * routerinfo is at the front.
  969. */
  970. static int
  971. router_resolve_routerlist(routerlist_t *rl)
  972. {
  973. int i, remove;
  974. routerinfo_t *r;
  975. if (!rl)
  976. rl = routerlist;
  977. i = 0;
  978. if ((r = router_get_my_routerinfo())) {
  979. smartlist_insert(rl->routers, 0, routerinfo_copy(r));
  980. ++i;
  981. }
  982. for ( ; i < smartlist_len(rl->routers); ++i) {
  983. remove = 0;
  984. r = smartlist_get(rl->routers,i);
  985. if (router_is_me(r)) {
  986. remove = 1;
  987. } else if (r->addr) {
  988. /* already resolved. */
  989. } else if (router_resolve(r)) {
  990. log_fn(LOG_WARN, "Couldn't resolve address '%s' for router '%s'; not using",
  991. r->address, r->nickname);
  992. remove = 1;
  993. }
  994. if (remove) {
  995. routerinfo_free(r);
  996. smartlist_del_keeporder(rl->routers, i--);
  997. }
  998. }
  999. return 0;
  1000. }
  1001. /** Decide whether a given addr:port is definitely accepted,
  1002. * definitely rejected, probably accepted, or probably rejected by a
  1003. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1004. * target address. If <b>port</b> is 0, we don't know the port of the
  1005. * target address.
  1006. *
  1007. * For now, the algorithm is pretty simple: we look for definite and
  1008. * uncertain matches. The first definite match is what we guess; if
  1009. * it was preceded by no uncertain matches of the opposite policy,
  1010. * then the guess is definite; otherwise it is probable. (If we
  1011. * have a known addr and port, all matches are definite; if we have an
  1012. * unknown addr/port, any address/port ranges other than "all" are
  1013. * uncertain.)
  1014. *
  1015. * We could do better by assuming that some ranges never match typical
  1016. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1017. */
  1018. addr_policy_result_t
  1019. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1020. addr_policy_t *policy)
  1021. {
  1022. int maybe_reject = 0;
  1023. int maybe_accept = 0;
  1024. int match = 0;
  1025. int maybe = 0;
  1026. addr_policy_t *tmpe;
  1027. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1028. maybe = 0;
  1029. if (!addr) {
  1030. /* Address is unknown. */
  1031. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1032. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1033. /* The port definitely matches. */
  1034. if (tmpe->msk == 0) {
  1035. match = 1;
  1036. } else {
  1037. maybe = 1;
  1038. }
  1039. } else if (!port) {
  1040. /* The port maybe matches. */
  1041. maybe = 1;
  1042. }
  1043. } else {
  1044. /* Address is known */
  1045. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1046. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1047. /* Exact match for the policy */
  1048. match = 1;
  1049. } else if (!port) {
  1050. maybe = 1;
  1051. }
  1052. }
  1053. }
  1054. if (maybe) {
  1055. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1056. maybe_reject = 1;
  1057. else
  1058. maybe_accept = 1;
  1059. }
  1060. if (match) {
  1061. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1062. /* If we already hit a clause that might trigger a 'reject', than we
  1063. * can't be sure of this certain 'accept'.*/
  1064. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1065. } else {
  1066. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1067. }
  1068. }
  1069. }
  1070. /* accept all by default. */
  1071. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1072. }
  1073. /** Return 1 if all running sufficiently-stable routers will reject
  1074. * addr:port, return 0 if any might accept it. */
  1075. int
  1076. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1077. int need_uptime)
  1078. {
  1079. int i;
  1080. routerinfo_t *router;
  1081. addr_policy_result_t r;
  1082. if (!routerlist) return 1;
  1083. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  1084. router = smartlist_get(routerlist->routers, i);
  1085. if (router->is_running &&
  1086. !router_is_unreliable(router, need_uptime, 0)) {
  1087. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1088. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1089. return 0; /* this one could be ok. good enough. */
  1090. }
  1091. }
  1092. return 1; /* all will reject. */
  1093. }
  1094. /**
  1095. * If <b>policy</b> implicitly allows connections to any port in the
  1096. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1097. * part of the policy that allows it, and return 1. Else return 0.
  1098. *
  1099. * A policy allows an IP:Port combination <em>implicitly</em> if
  1100. * it is included in a *: pattern, or in a fallback pattern.
  1101. */
  1102. static int
  1103. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1104. uint32_t addr, uint32_t mask,
  1105. addr_policy_t **policy_out)
  1106. {
  1107. uint32_t addr2;
  1108. tor_assert(policy_out);
  1109. addr &= mask;
  1110. addr2 = addr | ~mask;
  1111. for (; policy; policy=policy->next) {
  1112. /* Does this policy cover all of the address range we're looking at? */
  1113. /* Boolean logic time: range X is contained in range Y if, for
  1114. * each bit B, all possible values of B in X are values of B in Y.
  1115. * In "addr", we have every fixed bit set to its value, and every
  1116. * free bit set to 0. In "addr2", we have every fixed bit set to
  1117. * its value, and every free bit set to 1. So if addr and addr2 are
  1118. * both in the policy, the range is covered by the policy.
  1119. */
  1120. uint32_t p_addr = policy->addr & policy->msk;
  1121. if (p_addr == (addr & policy->msk) &&
  1122. p_addr == (addr2 & policy->msk) &&
  1123. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1124. return 0;
  1125. }
  1126. /* Does this policy cover some of the address range we're looking at? */
  1127. /* Boolean logic time: range X and range Y intersect if there is
  1128. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1129. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1130. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1131. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1132. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1133. */
  1134. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1135. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1136. *policy_out = policy;
  1137. return 1;
  1138. }
  1139. }
  1140. *policy_out = NULL;
  1141. return 1;
  1142. }
  1143. /** If <b>policy</b> implicitly allows connections to any port on
  1144. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1145. * true. Else return false.
  1146. **/
  1147. int
  1148. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1149. int warn)
  1150. {
  1151. addr_policy_t *p;
  1152. int r=0,i;
  1153. static struct {
  1154. uint32_t addr; uint32_t mask; const char *network;
  1155. } private_networks[] = {
  1156. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1157. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1158. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1159. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1160. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1161. { 0,0,NULL},
  1162. };
  1163. for (i=0; private_networks[i].addr; ++i) {
  1164. p = NULL;
  1165. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1166. if (policy_includes_addr_mask_implicitly(
  1167. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1168. if (warn)
  1169. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1170. p?p->string:"(default)",
  1171. private_networks[i].network);
  1172. r = 1;
  1173. }
  1174. }
  1175. return r;
  1176. }
  1177. /** Return true iff <b>router</b> does not permit exit streams.
  1178. */
  1179. int
  1180. router_exit_policy_rejects_all(routerinfo_t *router)
  1181. {
  1182. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1183. == ADDR_POLICY_REJECTED;
  1184. }
  1185. /** Release all space held in <b>rr</b>. */
  1186. void
  1187. running_routers_free(running_routers_t *rr)
  1188. {
  1189. if (!rr)
  1190. return;
  1191. if (rr->running_routers) {
  1192. SMARTLIST_FOREACH(rr->running_routers, char *, s, tor_free(s));
  1193. smartlist_free(rr->running_routers);
  1194. }
  1195. tor_free(rr);
  1196. }
  1197. /** Update the running/not-running status of every router in <b>list</b>, based
  1198. * on the contents of <b>rr</b>. */
  1199. static void
  1200. routerlist_update_from_runningrouters(routerlist_t *list,
  1201. running_routers_t *rr)
  1202. {
  1203. routerinfo_t *me = router_get_my_routerinfo();
  1204. smartlist_t *all_routers;
  1205. if (!list)
  1206. return;
  1207. if (list->published_on >= rr->published_on)
  1208. return;
  1209. if (list->running_routers_updated_on >= rr->published_on)
  1210. return;
  1211. all_routers = smartlist_create();
  1212. if (me) /* learn if the dirservers think I'm verified */
  1213. smartlist_add(all_routers, me);
  1214. smartlist_add_all(all_routers,list->routers);
  1215. SMARTLIST_FOREACH(rr->running_routers, const char *, cp,
  1216. routers_update_status_from_entry(all_routers, rr->published_on,
  1217. cp));
  1218. smartlist_free(all_routers);
  1219. list->running_routers_updated_on = rr->published_on;
  1220. }
  1221. /** We've just got a running routers list in <b>rr</b>; update the
  1222. * status of the routers in <b>list</b>, and cache <b>rr</b> */
  1223. void
  1224. routerlist_set_runningrouters(routerlist_t *list, running_routers_t *rr)
  1225. {
  1226. routerlist_update_from_runningrouters(list,rr);
  1227. if (list->running_routers != rr) {
  1228. running_routers_free(list->running_routers);
  1229. list->running_routers = rr;
  1230. }
  1231. }
  1232. /** Update the is_running and is_verified fields of the router <b>router</b>,
  1233. * based in its status in the list of strings stored in <b>running_list</b>.
  1234. * All entries in <b>running_list</b> follow one of these formats:
  1235. * <ol><li> <b>nickname</b> -- router is running and verified.
  1236. * (running-routers format)
  1237. * <li> !<b>nickname</b> -- router is not-running and verified.
  1238. * (running-routers format)
  1239. * <li> <b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1240. * verified. (router-status format)
  1241. * (router-status format)
  1242. * <li> !<b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1243. * verified. (router-status format)
  1244. * <li> !<b>nickname</b> -- router is not-running and verified.
  1245. * <li> $<b>hexdigest</b> -- router is running and unverified.
  1246. * <li> !$<b>hexdigest</b> -- router is not-running and unverified.
  1247. * </ol>
  1248. *
  1249. * Return 1 if we found router in running_list, else return 0.
  1250. */
  1251. int
  1252. routers_update_status_from_entry(smartlist_t *routers,
  1253. time_t list_time,
  1254. const char *s)
  1255. {
  1256. int is_running = 1;
  1257. int is_verified = 0;
  1258. int hex_digest_set = 0;
  1259. char nickname[MAX_NICKNAME_LEN+1];
  1260. char hexdigest[HEX_DIGEST_LEN+1];
  1261. char digest[DIGEST_LEN];
  1262. const char *cp, *end;
  1263. /* First, parse the entry. */
  1264. cp = s;
  1265. if (*cp == '!') {
  1266. is_running = 0;
  1267. ++cp;
  1268. }
  1269. if (*cp != '$') {
  1270. /* It starts with a non-dollar character; that's a nickname. The nickname
  1271. * entry will either extend to a NUL (old running-routers format) or to an
  1272. * equals sign (new router-status format). */
  1273. is_verified = 1;
  1274. end = strchr(cp, '=');
  1275. if (!end)
  1276. end = strchr(cp,'\0');
  1277. tor_assert(end);
  1278. /* 'end' now points on character beyond the end of the nickname */
  1279. if (end == cp || end-cp > MAX_NICKNAME_LEN) {
  1280. log_fn(LOG_WARN, "Bad nickname length (%d) in router status entry (%s)",
  1281. (int)(end-cp), s);
  1282. return -1;
  1283. }
  1284. memcpy(nickname, cp, end-cp);
  1285. nickname[end-cp]='\0';
  1286. if (!is_legal_nickname(nickname)) {
  1287. log_fn(LOG_WARN, "Bad nickname (%s) in router status entry (%s)",
  1288. nickname, s);
  1289. return -1;
  1290. }
  1291. cp = end;
  1292. if (*cp == '=')
  1293. ++cp;
  1294. }
  1295. /* 'end' now points to the start of a hex digest, or EOS. */
  1296. /* Parse the hexdigest portion of the status. */
  1297. if (*cp == '$') {
  1298. hex_digest_set = 1;
  1299. ++cp;
  1300. if (strlen(cp) != HEX_DIGEST_LEN) {
  1301. log_fn(LOG_WARN, "Bad length (%d) on digest in router status entry (%s)",
  1302. (int)strlen(cp), s);
  1303. return -1;
  1304. }
  1305. strlcpy(hexdigest, cp, sizeof(hexdigest));
  1306. if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0) {
  1307. log_fn(LOG_WARN, "Invalid digest in router status entry (%s)", s);
  1308. return -1;
  1309. }
  1310. }
  1311. /* Make sure that the entry was in the right format. */
  1312. if (!hex_digest_set) {
  1313. log_fn(LOG_WARN, "Invalid syntax for router-status member (%s)", s);
  1314. return -1;
  1315. }
  1316. /* Okay, we're done parsing. For all routers that match, update their status.
  1317. */
  1318. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1319. {
  1320. int nickname_matches = is_verified && !strcasecmp(r->nickname, nickname);
  1321. int digest_matches = !memcmp(digest, r->identity_digest, DIGEST_LEN);
  1322. if (nickname_matches && digest_matches)
  1323. r->is_verified = 1;
  1324. else if (digest_matches)
  1325. r->is_verified = 0;
  1326. if (digest_matches)
  1327. if (r->status_set_at < list_time) {
  1328. r->is_running = is_running;
  1329. r->status_set_at = time(NULL);
  1330. }
  1331. });
  1332. return 0;
  1333. }
  1334. /** As router_update_status_from_entry, but consider all entries in
  1335. * running_list. */
  1336. int
  1337. router_update_status_from_smartlist(routerinfo_t *router,
  1338. time_t list_time,
  1339. smartlist_t *running_list)
  1340. {
  1341. smartlist_t *rl;
  1342. rl = smartlist_create();
  1343. smartlist_add(rl,router);
  1344. SMARTLIST_FOREACH(running_list, const char *, cp,
  1345. routers_update_status_from_entry(rl,list_time,cp));
  1346. smartlist_free(rl);
  1347. return 0;
  1348. }
  1349. /** Add to the list of authorized directory servers one at
  1350. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. */
  1351. void
  1352. add_trusted_dir_server(const char *address, uint16_t port, const char *digest)
  1353. {
  1354. trusted_dir_server_t *ent;
  1355. uint32_t a;
  1356. if (!trusted_dir_servers)
  1357. trusted_dir_servers = smartlist_create();
  1358. if (tor_lookup_hostname(address, &a)) {
  1359. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1360. address);
  1361. return;
  1362. }
  1363. ent = tor_malloc(sizeof(trusted_dir_server_t));
  1364. ent->address = tor_strdup(address);
  1365. ent->addr = ntohl(a);
  1366. ent->dir_port = port;
  1367. ent->is_running = 1;
  1368. memcpy(ent->digest, digest, DIGEST_LEN);
  1369. smartlist_add(trusted_dir_servers, ent);
  1370. }
  1371. /** Remove all members from the list of trusted dir servers. */
  1372. void
  1373. clear_trusted_dir_servers(void)
  1374. {
  1375. if (trusted_dir_servers) {
  1376. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1377. { tor_free(ent->address); tor_free(ent); });
  1378. smartlist_clear(trusted_dir_servers);
  1379. } else {
  1380. trusted_dir_servers = smartlist_create();
  1381. }
  1382. }