routerlist.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  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_v2_directory);
  20. static trusted_dir_server_t *
  21. router_pick_trusteddirserver_impl(int need_v1_support,
  22. int requireother, int fascistfirewall);
  23. static void mark_all_trusteddirservers_up(void);
  24. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  25. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  26. static void router_normalize_routerlist(routerlist_t *rl);
  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 know about. */
  34. static routerlist_t *routerlist = NULL;
  35. extern int has_fetched_directory; /**< from main.c */
  36. /** Global list of all of the current network_status documents that we know
  37. * about. */
  38. static smartlist_t *networkstatus_list = NULL;
  39. /**
  40. * Reload the most recent cached directory (if present).
  41. */
  42. int
  43. router_reload_router_list(void)
  44. {
  45. char filename[512];
  46. int is_recent;
  47. struct stat st;
  48. char *s;
  49. tor_assert(get_options()->DataDirectory);
  50. tor_snprintf(filename,sizeof(filename),"%s/cached-directory",
  51. get_options()->DataDirectory);
  52. s = read_file_to_str(filename,0);
  53. if (s) {
  54. stat(filename, &st); /* if s is true, stat probably worked */
  55. log_fn(LOG_INFO, "Loading cached directory from %s", filename);
  56. is_recent = st.st_mtime > time(NULL) - 60*15;
  57. if (router_load_routerlist_from_directory(s, NULL, is_recent, 1) < 0) {
  58. log_fn(LOG_WARN, "Cached directory at '%s' was unparseable; ignoring.", filename);
  59. }
  60. if (routerlist &&
  61. ((routerlist->published_on > time(NULL) - MIN_ONION_KEY_LIFETIME/2)
  62. || is_recent)) {
  63. directory_has_arrived(st.st_mtime, NULL); /* do things we've been waiting to do */
  64. }
  65. tor_free(s);
  66. }
  67. return 0;
  68. }
  69. /** DOCDOC */
  70. int
  71. router_reload_networkstatus(void)
  72. {
  73. char filename[512];
  74. struct stat st;
  75. smartlist_t *entries, *bad_names;
  76. char *s;
  77. tor_assert(get_options()->DataDirectory);
  78. if (!networkstatus_list)
  79. networkstatus_list = smartlist_create();
  80. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  81. get_options()->DataDirectory);
  82. entries = tor_listdir(filename);
  83. bad_names = smartlist_create();
  84. SMARTLIST_FOREACH(entries, const char *, fn, {
  85. char buf[DIGEST_LEN];
  86. if (strlen(fn) != HEX_DIGEST_LEN ||
  87. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  88. log_fn(LOG_INFO,
  89. "Skipping cached-status file with unexpected name \"%s\"",fn);
  90. continue;
  91. }
  92. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  93. get_options()->DataDirectory, fn);
  94. s = read_file_to_str(filename, 0);
  95. if (s) {
  96. stat(filename, &st);
  97. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  98. log_fn(LOG_WARN, "Couldn't load networkstatus from \"%s\"",filename);
  99. }
  100. tor_free(s);
  101. }
  102. });
  103. return 0;
  104. }
  105. /* Set *<b>outp</b> to a smartlist containing a list of
  106. * trusted_dir_server_t * for all known trusted dirservers. Callers
  107. * must not modify the list or its contents.
  108. */
  109. void
  110. router_get_trusted_dir_servers(smartlist_t **outp)
  111. {
  112. if (!trusted_dir_servers)
  113. trusted_dir_servers = smartlist_create();
  114. *outp = trusted_dir_servers;
  115. }
  116. /** Try to find a running dirserver. If there are no running dirservers
  117. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  118. * set all the authoritative ones as running again, and pick one;
  119. * if there are then no dirservers at all in our routerlist,
  120. * reload the routerlist and try one last time. If for_runningrouters is
  121. * true, then only pick a dirserver that can answer runningrouters queries
  122. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  123. * Other args are as in router_pick_directory_server_impl().
  124. */
  125. routerinfo_t *
  126. router_pick_directory_server(int requireother,
  127. int fascistfirewall,
  128. int for_v2_directory,
  129. int retry_if_no_servers)
  130. {
  131. routerinfo_t *choice;
  132. if (!routerlist)
  133. return NULL;
  134. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  135. for_v2_directory);
  136. if (choice || !retry_if_no_servers)
  137. return choice;
  138. log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
  139. /* mark all authdirservers as up again */
  140. mark_all_trusteddirservers_up();
  141. /* try again */
  142. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  143. for_v2_directory);
  144. if (choice)
  145. return choice;
  146. log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
  147. firewall_is_fascist() ? "reachable" : "known");
  148. has_fetched_directory=0; /* reset it */
  149. if (router_reload_router_list()) {
  150. return NULL;
  151. }
  152. /* give it one last try */
  153. choice = router_pick_directory_server_impl(requireother, 0,
  154. for_v2_directory);
  155. return choice;
  156. }
  157. trusted_dir_server_t *
  158. router_get_trusteddirserver_by_digest(const char *digest)
  159. {
  160. if (!trusted_dir_servers)
  161. return NULL;
  162. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  163. {
  164. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  165. return ds;
  166. });
  167. return NULL;
  168. }
  169. /** Try to find a running trusted dirserver. If there are no running
  170. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  171. * set them all as running again, and try again.
  172. * Other args are as in router_pick_trusteddirserver_impl().
  173. *
  174. * DOCDOC need_v1_support
  175. */
  176. trusted_dir_server_t *
  177. router_pick_trusteddirserver(int need_v1_support,
  178. int requireother,
  179. int fascistfirewall,
  180. int retry_if_no_servers)
  181. {
  182. trusted_dir_server_t *choice;
  183. choice = router_pick_trusteddirserver_impl(need_v1_support,
  184. requireother, fascistfirewall);
  185. if (choice || !retry_if_no_servers)
  186. return choice;
  187. log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
  188. mark_all_trusteddirservers_up();
  189. return router_pick_trusteddirserver_impl(need_v1_support,
  190. requireother, fascistfirewall);
  191. }
  192. /** Pick a random running verified directory server/mirror from our
  193. * routerlist.
  194. * If <b>fascistfirewall</b> and we're not using a proxy,
  195. * make sure the port we pick is allowed by options-\>firewallports.
  196. * If <b>requireother</b>, it cannot be us.
  197. *
  198. * DOCDOC need_v1_support, for_v2_directory
  199. */
  200. static routerinfo_t *
  201. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  202. int for_v2_directory)
  203. {
  204. int i;
  205. routerinfo_t *router;
  206. smartlist_t *sl;
  207. if (!routerlist)
  208. return NULL;
  209. if (get_options()->HttpProxy)
  210. fascistfirewall = 0;
  211. /* Find all the running dirservers we know about. */
  212. sl = smartlist_create();
  213. for (i=0;i < smartlist_len(routerlist->routers); i++) {
  214. router = smartlist_get(routerlist->routers, i);
  215. if (!router->is_running || !router->dir_port || !router->is_verified)
  216. continue;
  217. if (requireother && router_is_me(router))
  218. continue;
  219. if (fascistfirewall) {
  220. if (!fascist_firewall_allows_address(router->addr, router->dir_port))
  221. continue;
  222. }
  223. /* before 0.1.1.6-alpha, only trusted dirservers served status info. */
  224. if (for_v2_directory &&
  225. !(tor_version_as_new_as(router->platform,"0.1.1.6-alpha") ||
  226. router_digest_is_trusted_dir(router->identity_digest)))
  227. continue;
  228. smartlist_add(sl, router);
  229. }
  230. router = smartlist_choose(sl);
  231. smartlist_free(sl);
  232. return router;
  233. }
  234. /** Choose randomly from among the trusted dirservers that are up.
  235. * If <b>fascistfirewall</b> and we're not using a proxy,
  236. * make sure the port we pick is allowed by options-\>firewallports.
  237. * If <b>requireother</b>, it cannot be us.
  238. */
  239. static trusted_dir_server_t *
  240. router_pick_trusteddirserver_impl(int need_v1_support,
  241. int requireother, int fascistfirewall)
  242. {
  243. smartlist_t *sl;
  244. routerinfo_t *me;
  245. trusted_dir_server_t *ds;
  246. sl = smartlist_create();
  247. me = router_get_my_routerinfo();
  248. if (!trusted_dir_servers)
  249. return NULL;
  250. if (get_options()->HttpProxy)
  251. fascistfirewall = 0;
  252. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  253. {
  254. if (!d->is_running) continue;
  255. if (need_v1_support && !d->supports_v1_protocol)
  256. continue;
  257. if (requireother && me &&
  258. !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
  259. continue;
  260. if (fascistfirewall) {
  261. if (!fascist_firewall_allows_address(d->addr, d->dir_port))
  262. continue;
  263. }
  264. smartlist_add(sl, d);
  265. });
  266. ds = smartlist_choose(sl);
  267. smartlist_free(sl);
  268. return ds;
  269. }
  270. /** Go through and mark the authoritative dirservers as up. */
  271. static void
  272. mark_all_trusteddirservers_up(void)
  273. {
  274. if (routerlist) {
  275. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  276. if (router_digest_is_trusted_dir(router->identity_digest) &&
  277. router->dir_port > 0) {
  278. router->is_running = 1;
  279. router->status_set_at = time(NULL);
  280. });
  281. }
  282. if (trusted_dir_servers) {
  283. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  284. dir->is_running = 1);
  285. }
  286. }
  287. /** Return 0 if \\exists an authoritative dirserver that's currently
  288. * thought to be running, else return 1.
  289. */
  290. int
  291. all_trusted_directory_servers_down(void)
  292. {
  293. if (!trusted_dir_servers)
  294. return 1;
  295. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  296. if (dir->is_running) return 0);
  297. return 1;
  298. }
  299. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  300. * This is used to make sure we don't pick siblings in a single path.
  301. */
  302. void
  303. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  304. {
  305. routerinfo_t *r;
  306. config_line_t *cl;
  307. if (!router->declared_family)
  308. return;
  309. /* Add every r such that router declares familyness with r, and r
  310. * declares familyhood with router. */
  311. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  312. {
  313. if (!(r = router_get_by_nickname(n)))
  314. continue;
  315. if (!r->declared_family)
  316. continue;
  317. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  318. {
  319. if (router_nickname_matches(router, n2))
  320. smartlist_add(sl, r);
  321. });
  322. });
  323. /* If the user declared any families locally, honor those too. */
  324. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  325. if (router_nickname_is_in_list(router, cl->value)) {
  326. add_nickname_list_to_smartlist(sl, cl->value, 0);
  327. }
  328. }
  329. }
  330. /** List of strings for nicknames we've already warned about and that are
  331. * still unknown / unavailable. */
  332. static smartlist_t *warned_nicknames = NULL;
  333. /** Given a comma-and-whitespace separated list of nicknames, see which
  334. * nicknames in <b>list</b> name routers in our routerlist that are
  335. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  336. */
  337. void
  338. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
  339. {
  340. routerinfo_t *router;
  341. smartlist_t *nickname_list;
  342. if (!list)
  343. return; /* nothing to do */
  344. tor_assert(sl);
  345. nickname_list = smartlist_create();
  346. if (!warned_nicknames)
  347. warned_nicknames = smartlist_create();
  348. smartlist_split_string(nickname_list, list, ",",
  349. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  350. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  351. int warned;
  352. if (!is_legal_nickname_or_hexdigest(nick)) {
  353. log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
  354. continue;
  355. }
  356. router = router_get_by_nickname(nick);
  357. warned = smartlist_string_isin(warned_nicknames, nick);
  358. if (router) {
  359. if (router->is_running) {
  360. smartlist_add(sl,router);
  361. if (warned)
  362. smartlist_string_remove(warned_nicknames, nick);
  363. } else {
  364. if (!warned) {
  365. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
  366. "Nickname list includes '%s' which is known but down.",nick);
  367. smartlist_add(warned_nicknames, tor_strdup(nick));
  368. }
  369. }
  370. } else {
  371. if (!warned) {
  372. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  373. "Nickname list includes '%s' which isn't a known router.",nick);
  374. smartlist_add(warned_nicknames, tor_strdup(nick));
  375. }
  376. }
  377. });
  378. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  379. smartlist_free(nickname_list);
  380. }
  381. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  382. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  383. */
  384. static int
  385. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  386. {
  387. smartlist_t *nickname_list;
  388. int v = 0;
  389. if (!list)
  390. return 0; /* definitely not */
  391. tor_assert(router);
  392. nickname_list = smartlist_create();
  393. smartlist_split_string(nickname_list, list, ",",
  394. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  395. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  396. if (router_nickname_matches(router, cp)) {v=1;break;});
  397. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  398. smartlist_free(nickname_list);
  399. return v;
  400. }
  401. /** Add every router from our routerlist that is currently running to
  402. * <b>sl</b>.
  403. */
  404. static void
  405. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
  406. int need_uptime, int need_capacity)
  407. {
  408. routerinfo_t *router;
  409. int i;
  410. if (!routerlist)
  411. return;
  412. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  413. router = smartlist_get(routerlist->routers, i);
  414. if (router->is_running &&
  415. (router->is_verified ||
  416. (allow_unverified &&
  417. !router_is_unreliable(router, need_uptime, need_capacity)))) {
  418. /* If it's running, and either it's verified or we're ok picking
  419. * unverified routers and this one is suitable.
  420. */
  421. smartlist_add(sl, router);
  422. }
  423. }
  424. }
  425. /** Look through the routerlist until we find a router that has my key.
  426. Return it. */
  427. routerinfo_t *
  428. routerlist_find_my_routerinfo(void)
  429. {
  430. routerinfo_t *router;
  431. int i;
  432. if (!routerlist)
  433. return NULL;
  434. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  435. router = smartlist_get(routerlist->routers, i);
  436. if (router_is_me(router))
  437. return router;
  438. }
  439. return NULL;
  440. }
  441. /** Find a router that's up, that has this IP address, and
  442. * that allows exit to this address:port, or return NULL if there
  443. * isn't a good one.
  444. */
  445. routerinfo_t *
  446. router_find_exact_exit_enclave(const char *address, uint16_t port) {
  447. int i;
  448. routerinfo_t *router;
  449. uint32_t addr;
  450. struct in_addr in;
  451. if (!tor_inet_aton(address, &in))
  452. return NULL; /* it's not an IP already */
  453. addr = ntohl(in.s_addr);
  454. for (i=0;i < smartlist_len(routerlist->routers); i++) {
  455. router = smartlist_get(routerlist->routers, i);
  456. log_fn(LOG_DEBUG,"Considering %s: %d, %u==%u, %d.",
  457. router->nickname,
  458. router->is_running,
  459. router->addr, addr,
  460. router_compare_addr_to_addr_policy(addr, port, router->exit_policy));
  461. if (router->is_running &&
  462. router->addr == addr &&
  463. router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  464. ADDR_POLICY_ACCEPTED)
  465. return router;
  466. }
  467. return NULL;
  468. }
  469. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  470. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  471. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  472. * bandwidth.
  473. */
  474. int
  475. router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
  476. {
  477. if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
  478. return 1;
  479. if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  480. return 1;
  481. return 0;
  482. }
  483. /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
  484. static void
  485. routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
  486. {
  487. int i;
  488. routerinfo_t *router;
  489. for (i = 0; i < smartlist_len(sl); ++i) {
  490. router = smartlist_get(sl, i);
  491. if (router_is_unreliable(router, 1, 0)) {
  492. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  493. // router->nickname);
  494. smartlist_del(sl, i--);
  495. }
  496. }
  497. }
  498. #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
  499. /** Choose a random element of router list <b>sl</b>, weighted by
  500. * the advertised bandwidth of each router.
  501. */
  502. routerinfo_t *
  503. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  504. {
  505. int i;
  506. routerinfo_t *router;
  507. smartlist_t *bandwidths;
  508. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  509. uint32_t *p;
  510. /* First count the total bandwidth weight, and make a smartlist
  511. * of each value. */
  512. bandwidths = smartlist_create();
  513. for (i = 0; i < smartlist_len(sl); ++i) {
  514. router = smartlist_get(sl, i);
  515. this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
  516. router->bandwidthcapacity : router->bandwidthrate;
  517. /* if they claim something huge, don't believe it */
  518. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  519. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  520. p = tor_malloc(sizeof(uint32_t));
  521. *p = this_bw;
  522. smartlist_add(bandwidths, p);
  523. total_bw += this_bw;
  524. }
  525. if (!total_bw) {
  526. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  527. smartlist_free(bandwidths);
  528. return smartlist_choose(sl);
  529. }
  530. /* Second, choose a random value from the bandwidth weights. */
  531. rand_bw = crypto_pseudo_rand_int(total_bw);
  532. /* Last, count through sl until we get to the element we picked */
  533. tmp = 0;
  534. for (i=0; ; i++) {
  535. tor_assert(i < smartlist_len(sl));
  536. p = smartlist_get(bandwidths, i);
  537. tmp += *p;
  538. if (tmp >= rand_bw)
  539. break;
  540. }
  541. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  542. smartlist_free(bandwidths);
  543. return (routerinfo_t *)smartlist_get(sl, i);
  544. }
  545. /** Return a random running router from the routerlist. If any node
  546. * named in <b>preferred</b> is available, pick one of those. Never
  547. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  548. * <b>excludedsmartlist</b>, even if they are the only nodes
  549. * available. If <b>strict</b> is true, never pick any node besides
  550. * those in <b>preferred</b>.
  551. * If <b>need_uptime</b> is non-zero, don't return a router with less
  552. * than a minimum uptime.
  553. * If <b>need_capacity</b> is non-zero, weight your choice by the
  554. * advertised capacity of each router.
  555. */
  556. routerinfo_t *
  557. router_choose_random_node(const char *preferred,
  558. const char *excluded,
  559. smartlist_t *excludedsmartlist,
  560. int need_uptime, int need_capacity,
  561. int allow_unverified, int strict)
  562. {
  563. smartlist_t *sl, *excludednodes;
  564. routerinfo_t *choice;
  565. excludednodes = smartlist_create();
  566. add_nickname_list_to_smartlist(excludednodes,excluded,0);
  567. /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
  568. * since the user explicitly asked for these nodes. */
  569. sl = smartlist_create();
  570. add_nickname_list_to_smartlist(sl,preferred,1);
  571. smartlist_subtract(sl,excludednodes);
  572. if (excludedsmartlist)
  573. smartlist_subtract(sl,excludedsmartlist);
  574. choice = smartlist_choose(sl);
  575. smartlist_free(sl);
  576. if (!choice && !strict) {
  577. /* Then give up on our preferred choices: any node
  578. * will do that has the required attributes. */
  579. sl = smartlist_create();
  580. router_add_running_routers_to_smartlist(sl, allow_unverified,
  581. need_uptime, need_capacity);
  582. smartlist_subtract(sl,excludednodes);
  583. if (excludedsmartlist)
  584. smartlist_subtract(sl,excludedsmartlist);
  585. if (need_uptime)
  586. routerlist_sl_remove_unreliable_routers(sl);
  587. if (need_capacity)
  588. choice = routerlist_sl_choose_by_bandwidth(sl);
  589. else
  590. choice = smartlist_choose(sl);
  591. smartlist_free(sl);
  592. }
  593. smartlist_free(excludednodes);
  594. if (!choice)
  595. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  596. return choice;
  597. }
  598. /** Return true iff the digest of <b>router</b>'s identity key,
  599. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  600. * optionally prefixed with a single dollar sign). Return false if
  601. * <b>hexdigest</b> is malformed, or it doesn't match. */
  602. static INLINE int
  603. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  604. {
  605. char digest[DIGEST_LEN];
  606. tor_assert(hexdigest);
  607. if (hexdigest[0] == '$')
  608. ++hexdigest;
  609. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  610. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  611. return 0;
  612. return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
  613. }
  614. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  615. * (case-insensitive), or if <b>router's</b> identity key digest
  616. * matches a hexadecimal value stored in <b>nickname</b>. Return
  617. * false otherwise. */
  618. static int
  619. router_nickname_matches(routerinfo_t *router, const char *nickname)
  620. {
  621. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  622. return 1;
  623. return router_hex_digest_matches(router, nickname);
  624. }
  625. /** Return the router in our routerlist whose (case-insensitive)
  626. * nickname or (case-sensitive) hexadecimal key digest is
  627. * <b>nickname</b>. Return NULL if no such router is known.
  628. */
  629. routerinfo_t *
  630. router_get_by_nickname(const char *nickname)
  631. {
  632. int i, maybedigest;
  633. routerinfo_t *router;
  634. char digest[DIGEST_LEN];
  635. tor_assert(nickname);
  636. if (!routerlist)
  637. return NULL;
  638. if (nickname[0] == '$')
  639. return router_get_by_hexdigest(nickname);
  640. if (server_mode(get_options()) &&
  641. !strcasecmp(nickname, get_options()->Nickname))
  642. return router_get_my_routerinfo();
  643. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  644. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  645. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  646. router = smartlist_get(routerlist->routers, i);
  647. if (0 == strcasecmp(router->nickname, nickname) ||
  648. (maybedigest && 0 == memcmp(digest, router->identity_digest,
  649. DIGEST_LEN)))
  650. return router;
  651. }
  652. return NULL;
  653. }
  654. /** Return true iff <b>digest</b> is the digest of the identity key of
  655. * a trusted directory. */
  656. int
  657. router_digest_is_trusted_dir(const char *digest)
  658. {
  659. if (!trusted_dir_servers)
  660. return 0;
  661. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  662. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  663. return 0;
  664. }
  665. /** Return the router in our routerlist whose hexadecimal key digest
  666. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  667. routerinfo_t *
  668. router_get_by_hexdigest(const char *hexdigest)
  669. {
  670. char digest[DIGEST_LEN];
  671. tor_assert(hexdigest);
  672. if (!routerlist)
  673. return NULL;
  674. if (hexdigest[0]=='$')
  675. ++hexdigest;
  676. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  677. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  678. return NULL;
  679. return router_get_by_digest(digest);
  680. }
  681. /** Return the router in our routerlist whose 20-byte key digest
  682. * is <b>digest</b>. Return NULL if no such router is known. */
  683. routerinfo_t *
  684. router_get_by_digest(const char *digest)
  685. {
  686. int i;
  687. routerinfo_t *router;
  688. tor_assert(digest);
  689. if (!routerlist) return NULL;
  690. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  691. router = smartlist_get(routerlist->routers, i);
  692. if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
  693. return router;
  694. }
  695. return NULL;
  696. }
  697. /** Set *<b>prouterlist</b> to the current list of all known routers. */
  698. void
  699. router_get_routerlist(routerlist_t **prouterlist)
  700. {
  701. *prouterlist = routerlist;
  702. }
  703. /** Return the publication time on the current routerlist, or 0 if we have no
  704. * routerlist. */
  705. time_t
  706. routerlist_get_published_time(void)
  707. {
  708. return routerlist ? routerlist->published_on : 0;
  709. }
  710. /** Free all storage held by <b>router</b>. */
  711. void
  712. routerinfo_free(routerinfo_t *router)
  713. {
  714. if (!router)
  715. return;
  716. tor_free(router->signed_descriptor);
  717. tor_free(router->address);
  718. tor_free(router->nickname);
  719. tor_free(router->platform);
  720. tor_free(router->contact_info);
  721. if (router->onion_pkey)
  722. crypto_free_pk_env(router->onion_pkey);
  723. if (router->identity_pkey)
  724. crypto_free_pk_env(router->identity_pkey);
  725. if (router->declared_family) {
  726. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  727. smartlist_free(router->declared_family);
  728. }
  729. addr_policy_free(router->exit_policy);
  730. tor_free(router);
  731. }
  732. /** Allocate a fresh copy of <b>router</b> */
  733. routerinfo_t *
  734. routerinfo_copy(const routerinfo_t *router)
  735. {
  736. routerinfo_t *r;
  737. addr_policy_t **e, *tmp;
  738. r = tor_malloc(sizeof(routerinfo_t));
  739. memcpy(r, router, sizeof(routerinfo_t));
  740. r->address = tor_strdup(r->address);
  741. r->nickname = tor_strdup(r->nickname);
  742. r->platform = tor_strdup(r->platform);
  743. if (r->signed_descriptor)
  744. r->signed_descriptor = tor_strdup(r->signed_descriptor);
  745. if (r->onion_pkey)
  746. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  747. if (r->identity_pkey)
  748. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  749. e = &r->exit_policy;
  750. while (*e) {
  751. tmp = tor_malloc(sizeof(addr_policy_t));
  752. memcpy(tmp,*e,sizeof(addr_policy_t));
  753. *e = tmp;
  754. (*e)->string = tor_strdup((*e)->string);
  755. e = & ((*e)->next);
  756. }
  757. if (r->declared_family) {
  758. r->declared_family = smartlist_create();
  759. SMARTLIST_FOREACH(router->declared_family, const char *, s,
  760. smartlist_add(r->declared_family, tor_strdup(s)));
  761. }
  762. return r;
  763. }
  764. /** Free all storage held by a routerlist <b>rl</b> */
  765. void
  766. routerlist_free(routerlist_t *rl)
  767. {
  768. tor_assert(rl);
  769. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  770. routerinfo_free(r));
  771. smartlist_free(rl->routers);
  772. running_routers_free(rl->running_routers);
  773. tor_free(rl->software_versions);
  774. tor_free(rl);
  775. }
  776. /** Free all entries in the current router list. */
  777. void
  778. routerlist_free_current(void)
  779. {
  780. if (routerlist)
  781. routerlist_free(routerlist);
  782. routerlist = NULL;
  783. if (warned_nicknames) {
  784. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  785. smartlist_free(warned_nicknames);
  786. warned_nicknames = NULL;
  787. }
  788. }
  789. /** Free all storage held by the routerstatus object <b>rs</b>. */
  790. void
  791. routerstatus_free(routerstatus_t *rs)
  792. {
  793. tor_free(rs);
  794. }
  795. /** Free all storage held by the networkstatus object <b>ns</b>. */
  796. void
  797. networkstatus_free(networkstatus_t *ns)
  798. {
  799. tor_free(ns->source_address);
  800. tor_free(ns->contact);
  801. if (ns->signing_key)
  802. crypto_free_pk_env(ns->signing_key);
  803. tor_free(ns->client_versions);
  804. tor_free(ns->server_versions);
  805. if (ns->entries) {
  806. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
  807. smartlist_free(ns->entries);
  808. }
  809. tor_free(ns);
  810. }
  811. /** Free all entries in the list of trusted directory servers. */
  812. void
  813. free_trusted_dir_servers(void)
  814. {
  815. if (trusted_dir_servers) {
  816. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  817. { tor_free(ds->address); tor_free(ds); });
  818. smartlist_free(trusted_dir_servers);
  819. trusted_dir_servers = NULL;
  820. }
  821. }
  822. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  823. void
  824. router_mark_as_down(const char *digest)
  825. {
  826. routerinfo_t *router;
  827. tor_assert(digest);
  828. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  829. if (!memcmp(d->digest, digest, DIGEST_LEN))
  830. d->is_running = 0);
  831. router = router_get_by_digest(digest);
  832. if (!router) /* we don't seem to know about him in the first place */
  833. return;
  834. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  835. if (router_is_me(router) && !we_are_hibernating())
  836. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  837. router->is_running = 0;
  838. router->status_set_at = time(NULL);
  839. }
  840. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  841. * older entries (if any) with the same name. Note: Callers should not hold
  842. * their pointers to <b>router</b> if this function fails; <b>router</b>
  843. * will either be inserted into the routerlist or freed.
  844. *
  845. * Returns >= 0 if the router was added; less than 0 if it was not.
  846. *
  847. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  848. * describing the reason for not liking the routerinfo.
  849. *
  850. * If the return value is less than -1, there was a problem with the
  851. * routerinfo. If the return value is equal to -1, then the routerinfo was
  852. * fine, but out-of-date. If the return value is equal to 1, the
  853. * routerinfo was accepted, but we should notify the generator of the
  854. * descriptor using the message *<b>msg</b>.
  855. */
  856. int
  857. router_add_to_routerlist(routerinfo_t *router, const char **msg)
  858. {
  859. int i;
  860. char id_digest[DIGEST_LEN];
  861. int authdir = get_options()->AuthoritativeDir;
  862. int authdir_verified = 0;
  863. tor_assert(msg);
  864. if (!routerlist) {
  865. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  866. routerlist->routers = smartlist_create();
  867. }
  868. crypto_pk_get_digest(router->identity_pkey, id_digest);
  869. if (authdir) {
  870. if (dirserv_wants_to_reject_router(router, &authdir_verified, msg)) {
  871. tor_assert(*msg);
  872. routerinfo_free(router);
  873. return -2;
  874. }
  875. router->is_verified = authdir_verified;
  876. if (tor_version_as_new_as(router->platform,"0.1.0.2-rc"))
  877. router->is_verified = 1;
  878. }
  879. /* If we have a router with this name, and the identity key is the same,
  880. * choose the newer one. If the identity key has changed, drop the router.
  881. */
  882. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  883. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  884. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  885. if (router->published_on <= old_router->published_on) {
  886. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  887. router->nickname);
  888. if (authdir) {
  889. /* Update the is_verified status based on our lookup. */
  890. old_router->is_verified = router->is_verified;
  891. } else {
  892. /* Update the is_running status to whatever we were told. */
  893. old_router->is_running = router->is_running;
  894. }
  895. routerinfo_free(router);
  896. *msg = "Router descriptor was not new.";
  897. return -1;
  898. } else {
  899. int unreachable = 0;
  900. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  901. router->nickname, old_router->nickname,
  902. hex_str(id_digest,DIGEST_LEN));
  903. if (router->addr == old_router->addr &&
  904. router->or_port == old_router->or_port) {
  905. /* these carry over when the address and orport are unchanged.*/
  906. router->last_reachable = old_router->last_reachable;
  907. router->testing_since = old_router->testing_since;
  908. router->num_unreachable_notifications =
  909. old_router->num_unreachable_notifications;
  910. }
  911. if (authdir &&
  912. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  913. if (router->num_unreachable_notifications >= 3) {
  914. unreachable = 1;
  915. log_fn(LOG_NOTICE, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
  916. router->nickname, router->contact_info ? router->contact_info : "",
  917. router->platform ? router->platform : "");
  918. } else {
  919. log_fn(LOG_INFO,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
  920. router->num_unreachable_notifications++;
  921. }
  922. }
  923. routerinfo_free(old_router);
  924. smartlist_set(routerlist->routers, i, router);
  925. directory_set_dirty();
  926. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  927. authdir_verified ? "Verified server updated" :
  928. "Unverified server updated. (Have you sent us your key fingerprint?)";
  929. return unreachable ? 1 : 0;
  930. }
  931. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  932. /* nicknames match, keys don't. */
  933. if (router->is_verified) {
  934. /* The new verified router replaces the old one; remove the
  935. * old one. And carry on to the end of the list, in case
  936. * there are more old unverified routers with this nickname
  937. */
  938. /* mark-for-close connections using the old key, so we can
  939. * make new ones with the new key.
  940. */
  941. connection_t *conn;
  942. while ((conn = connection_get_by_identity_digest(
  943. old_router->identity_digest, CONN_TYPE_OR))) {
  944. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
  945. old_router->nickname);
  946. connection_mark_for_close(conn);
  947. }
  948. routerinfo_free(old_router);
  949. smartlist_del_keeporder(routerlist->routers, i--);
  950. } else if (old_router->is_verified) {
  951. /* Can't replace a verified router with an unverified one. */
  952. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  953. router->nickname);
  954. routerinfo_free(router);
  955. *msg = "Already have verified router with same nickname and different key.";
  956. return -2;
  957. }
  958. }
  959. }
  960. /* We haven't seen a router with this name before. Add it to the end of
  961. * the list. */
  962. smartlist_add(routerlist->routers, router);
  963. directory_set_dirty();
  964. return 0;
  965. }
  966. /** Remove any routers from the routerlist that are more than <b>age</b>
  967. * seconds old.
  968. */
  969. void
  970. routerlist_remove_old_routers(int age)
  971. {
  972. int i;
  973. time_t cutoff;
  974. routerinfo_t *router;
  975. if (!routerlist)
  976. return;
  977. cutoff = time(NULL) - age;
  978. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  979. router = smartlist_get(routerlist->routers, i);
  980. if (router->published_on <= cutoff) {
  981. /* Too old. Remove it. */
  982. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  983. routerinfo_free(router);
  984. smartlist_del(routerlist->routers, i--);
  985. }
  986. }
  987. }
  988. /**
  989. * Code to parse a single router descriptor and insert it into the
  990. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  991. * descriptor was well-formed but could not be added; and 1 if the
  992. * descriptor was added.
  993. *
  994. * If we don't add it and <b>msg</b> is not NULL, then assign to
  995. * *<b>msg</b> a static string describing the reason for refusing the
  996. * descriptor.
  997. *
  998. * This is used only by the controller.
  999. */
  1000. int
  1001. router_load_single_router(const char *s, const char **msg)
  1002. {
  1003. routerinfo_t *ri;
  1004. tor_assert(msg);
  1005. *msg = NULL;
  1006. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  1007. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  1008. *msg = "Couldn't parse router descriptor.";
  1009. return -1;
  1010. }
  1011. if (router_is_me(ri)) {
  1012. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  1013. *msg = "Router's identity key matches mine.";
  1014. routerinfo_free(ri);
  1015. return 0;
  1016. }
  1017. if (routerlist && routerlist->running_routers) {
  1018. running_routers_t *rr = routerlist->running_routers;
  1019. router_update_status_from_smartlist(ri,
  1020. rr->published_on,
  1021. rr->running_routers);
  1022. }
  1023. if (router_add_to_routerlist(ri, msg)<0) {
  1024. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  1025. *msg?*msg:"(No message).");
  1026. /* we've already assigned to *msg now, and ri is already freed */
  1027. return 0;
  1028. } else {
  1029. smartlist_t *changed = smartlist_create();
  1030. smartlist_add(changed, ri);
  1031. control_event_descriptors_changed(changed);
  1032. smartlist_free(changed);
  1033. }
  1034. log_fn(LOG_DEBUG, "Added router to list");
  1035. return 1;
  1036. }
  1037. /** Add to the current routerlist each router stored in the
  1038. * signed directory <b>s</b>. If pkey is provided, check the signature
  1039. * against pkey; else check against the pkey of the signing directory
  1040. * server.
  1041. *
  1042. * If <b>dir_is_recent</b> is non-zero, then examine the
  1043. * Recommended-versions line and take appropriate action.
  1044. *
  1045. * If <b>dir_is_cached</b> is non-zero, then we're reading it
  1046. * from the cache so don't bother to re-write it to the cache.
  1047. */
  1048. int
  1049. router_load_routerlist_from_directory(const char *s,
  1050. crypto_pk_env_t *pkey,
  1051. int dir_is_recent,
  1052. int dir_is_cached)
  1053. {
  1054. routerlist_t *new_list = NULL;
  1055. if (router_parse_routerlist_from_directory(s, &new_list, pkey,
  1056. dir_is_recent,
  1057. !dir_is_cached)) {
  1058. log_fn(LOG_WARN, "Couldn't parse directory.");
  1059. return -1;
  1060. }
  1061. if (routerlist) {
  1062. /* Merge the new_list into routerlist, then free new_list. Also
  1063. * keep a list of changed descriptors to inform controllers. */
  1064. smartlist_t *changed = smartlist_create();
  1065. SMARTLIST_FOREACH(new_list->routers, routerinfo_t *, r,
  1066. {
  1067. const char *msg;
  1068. if (router_add_to_routerlist(r,&msg)>=0)
  1069. smartlist_add(changed, r);
  1070. });
  1071. smartlist_clear(new_list->routers);
  1072. routerlist->published_on = new_list->published_on;
  1073. tor_free(routerlist->software_versions);
  1074. routerlist->software_versions = new_list->software_versions;
  1075. new_list->software_versions = NULL;
  1076. routerlist_free(new_list);
  1077. control_event_descriptors_changed(changed);
  1078. smartlist_free(changed);
  1079. } else {
  1080. routerlist = new_list;
  1081. control_event_descriptors_changed(routerlist->routers);
  1082. }
  1083. router_normalize_routerlist(routerlist);
  1084. return 0;
  1085. }
  1086. /** How far in the future do we allow a network-status to get? (seconds) */
  1087. #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
  1088. /** DOCDOC returns 0 on no problems, -1 on problems.
  1089. * requested fingerprints must be upcased.
  1090. */
  1091. int
  1092. router_set_networkstatus(const char *s, time_t arrived_at,
  1093. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1094. {
  1095. networkstatus_t *ns;
  1096. int i, found;
  1097. time_t now;
  1098. char fp[HEX_DIGEST_LEN+1];
  1099. int skewed = 0;
  1100. ns = networkstatus_parse_from_string(s);
  1101. if (!ns) {
  1102. log_fn(LOG_WARN, "Couldn't parse network status.");
  1103. return -1;
  1104. }
  1105. if (!router_digest_is_trusted_dir(ns->identity_digest)) {
  1106. log_fn(LOG_INFO, "Network status was signed, but not by an authoritative directory we recognize.");
  1107. networkstatus_free(ns);
  1108. return -1;
  1109. }
  1110. now = time(NULL);
  1111. if (arrived_at > now)
  1112. arrived_at = now;
  1113. ns->received_on = arrived_at;
  1114. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1115. log_fn(LOG_WARN, "Network status was published in the future (?). Somebody is skewed here: check your clock. Not caching.");
  1116. skewed = 1;
  1117. }
  1118. if (!networkstatus_list)
  1119. networkstatus_list = smartlist_create();
  1120. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1121. /* Drop our own networkstatus when we get it from somebody else. */
  1122. networkstatus_free(ns);
  1123. return 0;
  1124. }
  1125. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1126. if (requested_fingerprints &&
  1127. !smartlist_string_isin(requested_fingerprints, fp)) {
  1128. char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1129. log_fn(LOG_WARN, "We received a network status with a fingerprint (%s) that we never requested. (%s) Dropping.", fp, requested);
  1130. tor_free(requested);
  1131. return 0;
  1132. }
  1133. found = 0;
  1134. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  1135. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  1136. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  1137. if (!memcmp(old_ns->networkstatus_digest,
  1138. ns->networkstatus_digest, DIGEST_LEN)) {
  1139. /* Same one we had before. */
  1140. networkstatus_free(ns);
  1141. if (old_ns->received_on < arrived_at)
  1142. old_ns->received_on = arrived_at;
  1143. return 0;
  1144. } else if (old_ns->published_on >= ns->published_on) {
  1145. log_fn(LOG_INFO, "Dropping network-status; we have a newer one for this authority.");
  1146. networkstatus_free(ns);
  1147. return 0;
  1148. } else {
  1149. networkstatus_free(old_ns);
  1150. smartlist_set(networkstatus_list, i, ns);
  1151. found = 1;
  1152. break;
  1153. }
  1154. }
  1155. }
  1156. if (!found)
  1157. smartlist_add(networkstatus_list, ns);
  1158. if (source != NS_FROM_CACHE && !skewed) {
  1159. const char *datadir = get_options()->DataDirectory;
  1160. size_t len = strlen(datadir)+64;
  1161. char *fn = tor_malloc(len+1);
  1162. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1163. if (write_str_to_file(fn, s, 0)<0) {
  1164. log_fn(LOG_NOTICE, "Couldn't write cached network status to \"%s\"", fn);
  1165. }
  1166. tor_free(fn);
  1167. }
  1168. if (get_options()->DirPort && !skewed)
  1169. dirserv_set_cached_networkstatus_v2(s, fp, ns->published_on);
  1170. return 0;
  1171. }
  1172. /* XXXX These should be configurable, perhaps? NM */
  1173. #define AUTHORITY_NS_CACHE_INTERVAL 10*60
  1174. #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
  1175. /* DOCDOC*/
  1176. void
  1177. update_networkstatus_cache_downloads(time_t now)
  1178. {
  1179. static time_t last_downloaded = 0;
  1180. int authority = authdir_mode(get_options());
  1181. int interval =
  1182. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  1183. if (last_downloaded + interval >= now)
  1184. return;
  1185. if (!trusted_dir_servers)
  1186. return;
  1187. last_downloaded = now;
  1188. if (authority) {
  1189. /* An authority launches a separate connection for everybody. */
  1190. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1191. {
  1192. char resource[HEX_DIGEST_LEN+6];
  1193. if (router_digest_is_me(ds->digest))
  1194. continue;
  1195. strlcpy(resource, "fp/", sizeof(resource));
  1196. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  1197. strlcat(resource, ".z", sizeof(resource));
  1198. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
  1199. });
  1200. } else {
  1201. /* A non-authority cache launches one connection to a random authority. */
  1202. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  1203. }
  1204. }
  1205. /*XXXX Should these be configurable? NM*/
  1206. /** How old (in seconds) can a network-status be before we stop believing it? */
  1207. #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
  1208. /** How long (in seconds) does a client wait after getting a network status
  1209. * before downloading the next in sequence? */
  1210. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  1211. /** DOCDOC */
  1212. void
  1213. update_networkstatus_client_downloads(time_t now)
  1214. {
  1215. int n_live = 0, needed = 0, n_dirservers, i;
  1216. int most_recent_idx = -1;
  1217. trusted_dir_server_t *most_recent = NULL;
  1218. time_t most_recent_received = 0;
  1219. char *resource, *cp;
  1220. size_t resource_len;
  1221. /* This is a little tricky. We want to download enough network-status
  1222. * objects so that we have at least half of them under NETWORKSTATUS_MAX_VALIDITY
  1223. * publication time. We want to download a new *one* if the most recent
  1224. * one's publication time is under NETWORKSTATUS_CLIENT_DL_INTERVAL.
  1225. */
  1226. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  1227. return;
  1228. n_dirservers = smartlist_len(trusted_dir_servers);
  1229. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1230. {
  1231. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  1232. if (!ns)
  1233. continue;
  1234. if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
  1235. ++n_live;
  1236. if (!most_recent || ns->received_on > most_recent_received) {
  1237. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH*/
  1238. most_recent = ds;
  1239. most_recent_received = ns->received_on;
  1240. }
  1241. });
  1242. /* Download enough so we have at least half live, but no more than all the
  1243. * trusted dirservers we know.
  1244. */
  1245. if (n_live < (n_dirservers/2)+1)
  1246. needed = (n_dirservers/2)+1-n_live;
  1247. if (needed > n_dirservers)
  1248. needed = n_dirservers;
  1249. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  1250. if (most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1)
  1251. needed = 1;
  1252. if (!needed)
  1253. return;
  1254. /* If no networkstatus was found, choose a dirserver at random as "most
  1255. * recent". */
  1256. if (most_recent_idx<0)
  1257. most_recent_idx = crypto_pseudo_rand_int(n_dirservers);
  1258. /* Build a request string for all the resources we want. */
  1259. resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
  1260. resource = tor_malloc(resource_len);
  1261. memcpy(resource, "fp/", 3);
  1262. cp = resource+3;
  1263. for (i = most_recent_idx+1; needed; ++i) {
  1264. trusted_dir_server_t *ds;
  1265. if (i >= n_dirservers)
  1266. i = 0;
  1267. ds = smartlist_get(trusted_dir_servers, i);
  1268. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1269. cp += HEX_DIGEST_LEN;
  1270. --needed;
  1271. if (needed)
  1272. *cp++ = '+';
  1273. }
  1274. memcpy(cp, ".z", 3);
  1275. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  1276. tor_free(resource);
  1277. }
  1278. /** Ensure that our own routerinfo is at the front, and remove duplicates
  1279. * of our routerinfo.
  1280. */
  1281. static void
  1282. router_normalize_routerlist(routerlist_t *rl)
  1283. {
  1284. int i=0;
  1285. routerinfo_t *r;
  1286. if ((r = router_get_my_routerinfo())) {
  1287. smartlist_insert(rl->routers, 0, routerinfo_copy(r));
  1288. ++i;
  1289. }
  1290. for ( ; i < smartlist_len(rl->routers); ++i) {
  1291. r = smartlist_get(rl->routers,i);
  1292. if (router_is_me(r)) {
  1293. routerinfo_free(r);
  1294. smartlist_del_keeporder(rl->routers, i--);
  1295. }
  1296. }
  1297. }
  1298. /** Decide whether a given addr:port is definitely accepted,
  1299. * definitely rejected, probably accepted, or probably rejected by a
  1300. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1301. * target address. If <b>port</b> is 0, we don't know the port of the
  1302. * target address.
  1303. *
  1304. * For now, the algorithm is pretty simple: we look for definite and
  1305. * uncertain matches. The first definite match is what we guess; if
  1306. * it was preceded by no uncertain matches of the opposite policy,
  1307. * then the guess is definite; otherwise it is probable. (If we
  1308. * have a known addr and port, all matches are definite; if we have an
  1309. * unknown addr/port, any address/port ranges other than "all" are
  1310. * uncertain.)
  1311. *
  1312. * We could do better by assuming that some ranges never match typical
  1313. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1314. */
  1315. addr_policy_result_t
  1316. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1317. addr_policy_t *policy)
  1318. {
  1319. int maybe_reject = 0;
  1320. int maybe_accept = 0;
  1321. int match = 0;
  1322. int maybe = 0;
  1323. addr_policy_t *tmpe;
  1324. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1325. maybe = 0;
  1326. if (!addr) {
  1327. /* Address is unknown. */
  1328. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1329. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1330. /* The port definitely matches. */
  1331. if (tmpe->msk == 0) {
  1332. match = 1;
  1333. } else {
  1334. maybe = 1;
  1335. }
  1336. } else if (!port) {
  1337. /* The port maybe matches. */
  1338. maybe = 1;
  1339. }
  1340. } else {
  1341. /* Address is known */
  1342. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1343. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1344. /* Exact match for the policy */
  1345. match = 1;
  1346. } else if (!port) {
  1347. maybe = 1;
  1348. }
  1349. }
  1350. }
  1351. if (maybe) {
  1352. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1353. maybe_reject = 1;
  1354. else
  1355. maybe_accept = 1;
  1356. }
  1357. if (match) {
  1358. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1359. /* If we already hit a clause that might trigger a 'reject', than we
  1360. * can't be sure of this certain 'accept'.*/
  1361. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1362. } else {
  1363. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1364. }
  1365. }
  1366. }
  1367. /* accept all by default. */
  1368. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1369. }
  1370. /** Return 1 if all running sufficiently-stable routers will reject
  1371. * addr:port, return 0 if any might accept it. */
  1372. int
  1373. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1374. int need_uptime)
  1375. {
  1376. int i;
  1377. routerinfo_t *router;
  1378. addr_policy_result_t r;
  1379. if (!routerlist) return 1;
  1380. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  1381. router = smartlist_get(routerlist->routers, i);
  1382. if (router->is_running &&
  1383. !router_is_unreliable(router, need_uptime, 0)) {
  1384. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1385. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1386. return 0; /* this one could be ok. good enough. */
  1387. }
  1388. }
  1389. return 1; /* all will reject. */
  1390. }
  1391. /**
  1392. * If <b>policy</b> implicitly allows connections to any port in the
  1393. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1394. * part of the policy that allows it, and return 1. Else return 0.
  1395. *
  1396. * A policy allows an IP:Port combination <em>implicitly</em> if
  1397. * it is included in a *: pattern, or in a fallback pattern.
  1398. */
  1399. static int
  1400. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1401. uint32_t addr, uint32_t mask,
  1402. addr_policy_t **policy_out)
  1403. {
  1404. uint32_t addr2;
  1405. tor_assert(policy_out);
  1406. addr &= mask;
  1407. addr2 = addr | ~mask;
  1408. for (; policy; policy=policy->next) {
  1409. /* Does this policy cover all of the address range we're looking at? */
  1410. /* Boolean logic time: range X is contained in range Y if, for
  1411. * each bit B, all possible values of B in X are values of B in Y.
  1412. * In "addr", we have every fixed bit set to its value, and every
  1413. * free bit set to 0. In "addr2", we have every fixed bit set to
  1414. * its value, and every free bit set to 1. So if addr and addr2 are
  1415. * both in the policy, the range is covered by the policy.
  1416. */
  1417. uint32_t p_addr = policy->addr & policy->msk;
  1418. if (p_addr == (addr & policy->msk) &&
  1419. p_addr == (addr2 & policy->msk) &&
  1420. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1421. return 0;
  1422. }
  1423. /* Does this policy cover some of the address range we're looking at? */
  1424. /* Boolean logic time: range X and range Y intersect if there is
  1425. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1426. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1427. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1428. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1429. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1430. */
  1431. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1432. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1433. *policy_out = policy;
  1434. return 1;
  1435. }
  1436. }
  1437. *policy_out = NULL;
  1438. return 1;
  1439. }
  1440. /** If <b>policy</b> implicitly allows connections to any port on
  1441. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1442. * true. Else return false.
  1443. **/
  1444. int
  1445. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1446. int warn)
  1447. {
  1448. addr_policy_t *p;
  1449. int r=0,i;
  1450. static struct {
  1451. uint32_t addr; uint32_t mask; const char *network;
  1452. } private_networks[] = {
  1453. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1454. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1455. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1456. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1457. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1458. { 0,0,NULL},
  1459. };
  1460. for (i=0; private_networks[i].addr; ++i) {
  1461. p = NULL;
  1462. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1463. if (policy_includes_addr_mask_implicitly(
  1464. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1465. if (warn)
  1466. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1467. p?p->string:"(default)",
  1468. private_networks[i].network);
  1469. r = 1;
  1470. }
  1471. }
  1472. return r;
  1473. }
  1474. /** Return true iff <b>router</b> does not permit exit streams.
  1475. */
  1476. int
  1477. router_exit_policy_rejects_all(routerinfo_t *router)
  1478. {
  1479. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1480. == ADDR_POLICY_REJECTED;
  1481. }
  1482. /** Release all space held in <b>rr</b>. */
  1483. void
  1484. running_routers_free(running_routers_t *rr)
  1485. {
  1486. if (!rr)
  1487. return;
  1488. if (rr->running_routers) {
  1489. SMARTLIST_FOREACH(rr->running_routers, char *, s, tor_free(s));
  1490. smartlist_free(rr->running_routers);
  1491. }
  1492. tor_free(rr);
  1493. }
  1494. /** Update the running/not-running status of every router in <b>list</b>, based
  1495. * on the contents of <b>rr</b>. */
  1496. static void
  1497. routerlist_update_from_runningrouters(routerlist_t *list,
  1498. running_routers_t *rr)
  1499. {
  1500. routerinfo_t *me = router_get_my_routerinfo();
  1501. smartlist_t *all_routers;
  1502. if (!list)
  1503. return;
  1504. if (list->published_on >= rr->published_on)
  1505. return;
  1506. if (list->running_routers_updated_on >= rr->published_on)
  1507. return;
  1508. all_routers = smartlist_create();
  1509. if (me) /* learn if the dirservers think I'm verified */
  1510. smartlist_add(all_routers, me);
  1511. smartlist_add_all(all_routers,list->routers);
  1512. SMARTLIST_FOREACH(rr->running_routers, const char *, cp,
  1513. routers_update_status_from_entry(all_routers, rr->published_on,
  1514. cp));
  1515. smartlist_free(all_routers);
  1516. list->running_routers_updated_on = rr->published_on;
  1517. }
  1518. /** We've just got a running routers list in <b>rr</b>; update the
  1519. * status of the routers in <b>list</b>, and cache <b>rr</b> */
  1520. void
  1521. routerlist_set_runningrouters(routerlist_t *list, running_routers_t *rr)
  1522. {
  1523. routerlist_update_from_runningrouters(list,rr);
  1524. if (list->running_routers != rr) {
  1525. running_routers_free(list->running_routers);
  1526. list->running_routers = rr;
  1527. }
  1528. }
  1529. /** Update the is_running and is_verified fields of the router <b>router</b>,
  1530. * based in its status in the list of strings stored in <b>running_list</b>.
  1531. * All entries in <b>running_list</b> follow one of these formats:
  1532. * <ol><li> <b>nickname</b> -- router is running and verified.
  1533. * (running-routers format)
  1534. * <li> !<b>nickname</b> -- router is not-running and verified.
  1535. * (running-routers format)
  1536. * <li> <b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1537. * verified. (router-status format)
  1538. * (router-status format)
  1539. * <li> !<b>nickname</b>=$<b>hexdigest</b> -- router is running and
  1540. * verified. (router-status format)
  1541. * <li> !<b>nickname</b> -- router is not-running and verified.
  1542. * <li> $<b>hexdigest</b> -- router is running and unverified.
  1543. * <li> !$<b>hexdigest</b> -- router is not-running and unverified.
  1544. * </ol>
  1545. *
  1546. * Return 1 if we found router in running_list, else return 0.
  1547. */
  1548. int
  1549. routers_update_status_from_entry(smartlist_t *routers,
  1550. time_t list_time,
  1551. const char *s)
  1552. {
  1553. int authdir = get_options()->AuthoritativeDir;
  1554. int is_running = 1;
  1555. int is_verified = 0;
  1556. int hex_digest_set = 0;
  1557. char nickname[MAX_NICKNAME_LEN+1];
  1558. char hexdigest[HEX_DIGEST_LEN+1];
  1559. char digest[DIGEST_LEN];
  1560. const char *cp, *end;
  1561. /* First, parse the entry. */
  1562. cp = s;
  1563. if (*cp == '!') {
  1564. is_running = 0;
  1565. ++cp;
  1566. }
  1567. if (*cp != '$') {
  1568. /* It starts with a non-dollar character; that's a nickname. The nickname
  1569. * entry will either extend to a NUL (old running-routers format) or to an
  1570. * equals sign (new router-status format). */
  1571. is_verified = 1;
  1572. end = strchr(cp, '=');
  1573. if (!end)
  1574. end = strchr(cp,'\0');
  1575. tor_assert(end);
  1576. /* 'end' now points on character beyond the end of the nickname */
  1577. if (end == cp || end-cp > MAX_NICKNAME_LEN) {
  1578. log_fn(LOG_WARN, "Bad nickname length (%d) in router status entry (%s)",
  1579. (int)(end-cp), s);
  1580. return -1;
  1581. }
  1582. memcpy(nickname, cp, end-cp);
  1583. nickname[end-cp]='\0';
  1584. if (!is_legal_nickname(nickname)) {
  1585. log_fn(LOG_WARN, "Bad nickname (%s) in router status entry (%s)",
  1586. nickname, s);
  1587. return -1;
  1588. }
  1589. cp = end;
  1590. if (*cp == '=')
  1591. ++cp;
  1592. }
  1593. /* 'end' now points to the start of a hex digest, or EOS. */
  1594. /* Parse the hexdigest portion of the status. */
  1595. if (*cp == '$') {
  1596. hex_digest_set = 1;
  1597. ++cp;
  1598. if (strlen(cp) != HEX_DIGEST_LEN) {
  1599. log_fn(LOG_WARN, "Bad length (%d) on digest in router status entry (%s)",
  1600. (int)strlen(cp), s);
  1601. return -1;
  1602. }
  1603. strlcpy(hexdigest, cp, sizeof(hexdigest));
  1604. if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0) {
  1605. log_fn(LOG_WARN, "Invalid digest in router status entry (%s)", s);
  1606. return -1;
  1607. }
  1608. }
  1609. /* Make sure that the entry was in the right format. */
  1610. if (!hex_digest_set) {
  1611. log_fn(LOG_WARN, "Invalid syntax for router-status member (%s)", s);
  1612. return -1;
  1613. }
  1614. /* Okay, we're done parsing. For all routers that match, update their status.
  1615. */
  1616. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1617. {
  1618. int nickname_matches = is_verified && !strcasecmp(r->nickname, nickname);
  1619. int digest_matches = !memcmp(digest, r->identity_digest, DIGEST_LEN);
  1620. if (!authdir) {
  1621. /* If we're not an authoritative directory, update verified status.
  1622. */
  1623. if (nickname_matches && digest_matches)
  1624. r->is_verified = 1;
  1625. else if (digest_matches)
  1626. r->is_verified = 0;
  1627. }
  1628. if (digest_matches)
  1629. if (r->status_set_at < list_time) {
  1630. if (!authdir || is_running)
  1631. /* If we're an authoritative directory, only believe that servers
  1632. * are down when we hear it ourselves. Otherwise, believe
  1633. * what we're told.
  1634. */
  1635. r->is_running = is_running;
  1636. r->status_set_at = time(NULL);
  1637. }
  1638. });
  1639. return 0;
  1640. }
  1641. /** As router_update_status_from_entry, but consider all entries in
  1642. * running_list. */
  1643. int
  1644. router_update_status_from_smartlist(routerinfo_t *router,
  1645. time_t list_time,
  1646. smartlist_t *running_list)
  1647. {
  1648. smartlist_t *rl;
  1649. rl = smartlist_create();
  1650. smartlist_add(rl,router);
  1651. SMARTLIST_FOREACH(running_list, const char *, cp,
  1652. routers_update_status_from_entry(rl,list_time,cp));
  1653. smartlist_free(rl);
  1654. return 0;
  1655. }
  1656. /** Add to the list of authorized directory servers one at
  1657. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  1658. * <b>address</b> is NULL, add ourself. */
  1659. void
  1660. add_trusted_dir_server(const char *address, uint16_t port, const char *digest,
  1661. int supports_v1)
  1662. {
  1663. trusted_dir_server_t *ent;
  1664. uint32_t a;
  1665. char *hostname = NULL;
  1666. if (!trusted_dir_servers)
  1667. trusted_dir_servers = smartlist_create();
  1668. if (!address) { /* The address is us; we should guess. */
  1669. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  1670. log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
  1671. return;
  1672. }
  1673. } else {
  1674. if (tor_lookup_hostname(address, &a)) {
  1675. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1676. address);
  1677. return;
  1678. }
  1679. hostname = tor_strdup(address);
  1680. a = ntohl(a);
  1681. }
  1682. ent = tor_malloc(sizeof(trusted_dir_server_t));
  1683. ent->address = hostname;
  1684. ent->addr = a;
  1685. ent->dir_port = port;
  1686. ent->is_running = 1;
  1687. ent->supports_v1_protocol = supports_v1;
  1688. memcpy(ent->digest, digest, DIGEST_LEN);
  1689. smartlist_add(trusted_dir_servers, ent);
  1690. }
  1691. /** Remove all members from the list of trusted dir servers. */
  1692. void
  1693. clear_trusted_dir_servers(void)
  1694. {
  1695. if (trusted_dir_servers) {
  1696. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1697. { tor_free(ent->address); tor_free(ent); });
  1698. smartlist_clear(trusted_dir_servers);
  1699. } else {
  1700. trusted_dir_servers = smartlist_create();
  1701. }
  1702. }
  1703. networkstatus_t *
  1704. networkstatus_get_by_digest(const char *digest)
  1705. {
  1706. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1707. {
  1708. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  1709. return ns;
  1710. });
  1711. return NULL;
  1712. }