routerlist.c 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609
  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. /** Global list of a trusted_dir_server_t object for each trusted directory
  16. * server. */
  17. static smartlist_t *trusted_dir_servers = NULL;
  18. /* static function prototypes */
  19. static routerinfo_t *router_pick_directory_server_impl(int requireother,
  20. int fascistfirewall,
  21. int for_v2_directory);
  22. static trusted_dir_server_t *router_pick_trusteddirserver_impl(
  23. int need_v1_support, int requireother, int fascistfirewall);
  24. static void mark_all_trusteddirservers_up(void);
  25. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  26. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  27. static void routerstatus_list_update_from_networkstatus(time_t now);
  28. static void local_routerstatus_free(local_routerstatus_t *rs);
  29. /****************************************************************************/
  30. /****
  31. * Functions to manage and access our list of known routers. (Note:
  32. * dirservers maintain a separate, independent list of known router
  33. * descriptors.)
  34. ****/
  35. /** Global list of all of the routers that we know about. */
  36. static routerlist_t *routerlist = NULL;
  37. extern int has_fetched_directory; /**< from main.c */
  38. /** Global list of all of the current network_status documents that we know
  39. * about. This list is kept sorted by published_on. */
  40. static smartlist_t *networkstatus_list = NULL;
  41. /** Global list of routerstatuses_t for each router, known or unknown. */
  42. static smartlist_t *routerstatus_list = NULL;
  43. /** True iff any member of networkstatus_list has changed since the last time
  44. * we called routerstatus_list_update_from_networkstatus(). */
  45. static int networkstatus_list_has_changed = 0;
  46. /** True iff any element of routerstatus_list has changed since the last
  47. * time we called routers_update_all_from_networkstatus().*/
  48. static int routerstatus_list_has_changed = 0;
  49. /** Repopulate our list of network_status_t objects from the list cached on
  50. * disk. Return 0 on success, -1 on failure. */
  51. int
  52. router_reload_networkstatus(void)
  53. {
  54. char filename[512];
  55. struct stat st;
  56. smartlist_t *entries, *bad_names;
  57. char *s;
  58. tor_assert(get_options()->DataDirectory);
  59. if (!networkstatus_list)
  60. networkstatus_list = smartlist_create();
  61. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  62. get_options()->DataDirectory);
  63. entries = tor_listdir(filename);
  64. bad_names = smartlist_create();
  65. SMARTLIST_FOREACH(entries, const char *, fn, {
  66. char buf[DIGEST_LEN];
  67. if (strlen(fn) != HEX_DIGEST_LEN ||
  68. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  69. log_fn(LOG_INFO,
  70. "Skipping cached-status file with unexpected name \"%s\"",fn);
  71. continue;
  72. }
  73. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  74. get_options()->DataDirectory, fn);
  75. s = read_file_to_str(filename, 0);
  76. if (s) {
  77. stat(filename, &st);
  78. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  79. log_fn(LOG_WARN, "Couldn't load networkstatus from \"%s\"",filename);
  80. }
  81. tor_free(s);
  82. }
  83. });
  84. SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
  85. smartlist_free(entries);
  86. networkstatus_list_clean(time(NULL));
  87. routers_update_all_from_networkstatus();
  88. return 0;
  89. }
  90. /* Router descriptor storage.
  91. *
  92. * Routerdescs are stored in a big file, named "cached-routers". As new
  93. * routerdescs arrive, we append them to a journal file named
  94. * "cached-routers.new".
  95. *
  96. * From time to time, we replace "cached-routers" with a new file containing
  97. * only the live, non-superseded descriptors, and clear cached-routers.new.
  98. *
  99. * On startup, we read both files.
  100. */
  101. /** The size of the router log, in bytes. */
  102. static size_t router_journal_len = 0;
  103. /** The size of the router store, in bytes. */
  104. static size_t router_store_len = 0;
  105. /** Helper: return 1 iff the router log is so big we want to rebuild the
  106. * store. */
  107. static int
  108. router_should_rebuild_store(void)
  109. {
  110. if (router_store_len > (1<<16))
  111. return router_journal_len > router_store_len / 2;
  112. else
  113. return router_journal_len > (1<<15);
  114. }
  115. /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
  116. * journal. */
  117. static int
  118. router_append_to_journal(const char *s, size_t len)
  119. {
  120. or_options_t *options = get_options();
  121. size_t fname_len = strlen(options->DataDirectory)+32;
  122. char *fname = tor_malloc(len);
  123. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  124. options->DataDirectory);
  125. if (!len)
  126. len = strlen(s);
  127. if (append_bytes_to_file(fname, s, len, 0)) {
  128. log_fn(LOG_WARN, "Unable to store router descriptor");
  129. tor_free(fname);
  130. return -1;
  131. }
  132. tor_free(fname);
  133. router_journal_len += len;
  134. return 0;
  135. }
  136. /** If the journal is too long, or if <b>force</b> is true, then atomically
  137. * replace the router store with the routers currently in our routerlist, and
  138. * clear the journal. Return 0 on success, -1 on failure.
  139. */
  140. static int
  141. router_rebuild_store(int force)
  142. {
  143. size_t len = 0;
  144. or_options_t *options;
  145. size_t fname_len;
  146. smartlist_t *chunk_list = NULL;
  147. char *fname = NULL;
  148. int r = -1;
  149. if (!force && !router_should_rebuild_store())
  150. return 0;
  151. if (!routerlist)
  152. return 0;
  153. /* Don't save deadweight. */
  154. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  155. options = get_options();
  156. fname_len = strlen(options->DataDirectory)+32;
  157. fname = tor_malloc(fname_len);
  158. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  159. chunk_list = smartlist_create();
  160. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  161. {
  162. sized_chunk_t *c;
  163. if (!ri->signed_descriptor) {
  164. log_fn(LOG_WARN, "Bug! No descriptor stored for router '%s'.",
  165. ri->nickname);
  166. goto done;
  167. }
  168. c = tor_malloc(sizeof(sized_chunk_t));
  169. c->bytes = ri->signed_descriptor;
  170. c->len = ri->signed_descriptor_len;
  171. smartlist_add(chunk_list, c);
  172. });
  173. if (write_chunks_to_file(fname, chunk_list, 0)<0) {
  174. log_fn(LOG_WARN, "Error writing router store to disk.");
  175. goto done;
  176. }
  177. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  178. options->DataDirectory);
  179. write_str_to_file(fname, "", 0);
  180. r = 0;
  181. router_store_len = len;
  182. router_journal_len = 0;
  183. done:
  184. tor_free(fname);
  185. if (chunk_list) {
  186. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  187. smartlist_free(chunk_list);
  188. }
  189. return r;
  190. }
  191. /* Load all cached router descriptors from the store. Return 0 on success and
  192. * -1 on failure.
  193. */
  194. int
  195. router_reload_router_list(void)
  196. {
  197. or_options_t *options = get_options();
  198. size_t fname_len = strlen(options->DataDirectory)+32;
  199. char *fname = tor_malloc(fname_len);
  200. struct stat st;
  201. int j;
  202. if (!routerlist) {
  203. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  204. routerlist->routers = smartlist_create();
  205. }
  206. router_journal_len = router_store_len = 0;
  207. for (j = 0; j < 2; ++j) {
  208. char *contents;
  209. tor_snprintf(fname, fname_len,
  210. (j==0)?"%s/cached-routers":"%s/cached-routers.new",
  211. options->DataDirectory);
  212. contents = read_file_to_str(fname, 0);
  213. if (contents) {
  214. stat(fname, &st);
  215. if (j==0)
  216. router_store_len = st.st_size;
  217. else
  218. router_journal_len = st.st_size;
  219. router_load_routers_from_string(contents, 1, NULL);
  220. tor_free(contents);
  221. }
  222. }
  223. tor_free(fname);
  224. /* Don't cache expired routers. */
  225. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  226. if (router_journal_len) {
  227. /* Always clear the journal on startup.*/
  228. router_rebuild_store(1);
  229. }
  230. return 0;
  231. }
  232. /** Set *<b>outp</b> to a smartlist containing a list of
  233. * trusted_dir_server_t * for all known trusted dirservers. Callers
  234. * must not modify the list or its contents.
  235. */
  236. void
  237. router_get_trusted_dir_servers(smartlist_t **outp)
  238. {
  239. if (!trusted_dir_servers)
  240. trusted_dir_servers = smartlist_create();
  241. *outp = trusted_dir_servers;
  242. }
  243. /** Try to find a running dirserver. If there are no running dirservers
  244. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  245. * set all the authoritative ones as running again, and pick one;
  246. * if there are then no dirservers at all in our routerlist,
  247. * reload the routerlist and try one last time. If for_runningrouters is
  248. * true, then only pick a dirserver that can answer runningrouters queries
  249. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  250. * Other args are as in router_pick_directory_server_impl().
  251. */
  252. routerinfo_t *
  253. router_pick_directory_server(int requireother,
  254. int fascistfirewall,
  255. int for_v2_directory,
  256. int retry_if_no_servers)
  257. {
  258. routerinfo_t *choice;
  259. if (!routerlist)
  260. return NULL;
  261. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  262. for_v2_directory);
  263. if (choice || !retry_if_no_servers)
  264. return choice;
  265. log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
  266. /* mark all authdirservers as up again */
  267. mark_all_trusteddirservers_up();
  268. /* try again */
  269. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  270. for_v2_directory);
  271. if (choice)
  272. return choice;
  273. log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
  274. firewall_is_fascist() ? "reachable" : "known");
  275. has_fetched_directory=0; /* reset it */
  276. if (router_reload_router_list()) {
  277. return NULL;
  278. }
  279. /* give it one last try */
  280. choice = router_pick_directory_server_impl(requireother, 0,
  281. for_v2_directory);
  282. return choice;
  283. }
  284. trusted_dir_server_t *
  285. router_get_trusteddirserver_by_digest(const char *digest)
  286. {
  287. if (!trusted_dir_servers)
  288. return NULL;
  289. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  290. {
  291. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  292. return ds;
  293. });
  294. return NULL;
  295. }
  296. /** Try to find a running trusted dirserver. If there are no running
  297. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  298. * set them all as running again, and try again.
  299. * Other args are as in router_pick_trusteddirserver_impl().
  300. */
  301. trusted_dir_server_t *
  302. router_pick_trusteddirserver(int need_v1_support,
  303. int requireother,
  304. int fascistfirewall,
  305. int retry_if_no_servers)
  306. {
  307. trusted_dir_server_t *choice;
  308. choice = router_pick_trusteddirserver_impl(need_v1_support,
  309. requireother, fascistfirewall);
  310. if (choice || !retry_if_no_servers)
  311. return choice;
  312. log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
  313. mark_all_trusteddirservers_up();
  314. return router_pick_trusteddirserver_impl(need_v1_support,
  315. requireother, fascistfirewall);
  316. }
  317. /** Pick a random running verified directory server/mirror from our
  318. * routerlist.
  319. * If <b>fascistfirewall</b> and we're not using a proxy,
  320. * make sure the port we pick is allowed by options-\>firewallports.
  321. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  322. * choose a directory server new enough to support the v2 directory
  323. * functionality.
  324. */
  325. static routerinfo_t *
  326. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  327. int for_v2_directory)
  328. {
  329. routerinfo_t *result;
  330. smartlist_t *sl;
  331. if (!routerlist)
  332. return NULL;
  333. if (get_options()->HttpProxy)
  334. fascistfirewall = 0;
  335. /* Find all the running dirservers we know about. */
  336. sl = smartlist_create();
  337. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  338. {
  339. if (!router->is_running || !router->dir_port || !router->is_verified)
  340. continue;
  341. if (requireother && router_is_me(router))
  342. continue;
  343. if (fascistfirewall) {
  344. if (!fascist_firewall_allows_address(router->addr, router->dir_port))
  345. continue;
  346. }
  347. /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
  348. * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
  349. * the directory server.
  350. */
  351. if (for_v2_directory &&
  352. !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
  353. router_digest_is_trusted_dir(router->identity_digest)))
  354. continue;
  355. smartlist_add(sl, router);
  356. });
  357. result = smartlist_choose(sl);
  358. smartlist_free(sl);
  359. return result;
  360. }
  361. /** Choose randomly from among the trusted dirservers that are up.
  362. * If <b>fascistfirewall</b> and we're not using a proxy,
  363. * make sure the port we pick is allowed by options-\>firewallports.
  364. * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
  365. * a trusted authority for the v1 directory system.
  366. */
  367. static trusted_dir_server_t *
  368. router_pick_trusteddirserver_impl(int need_v1_support,
  369. int requireother, int fascistfirewall)
  370. {
  371. smartlist_t *sl;
  372. routerinfo_t *me;
  373. trusted_dir_server_t *ds;
  374. sl = smartlist_create();
  375. me = router_get_my_routerinfo();
  376. if (!trusted_dir_servers)
  377. return NULL;
  378. if (get_options()->HttpProxy)
  379. fascistfirewall = 0;
  380. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  381. {
  382. if (!d->is_running) continue;
  383. if (need_v1_support && !d->supports_v1_protocol)
  384. continue;
  385. if (requireother && me &&
  386. !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
  387. continue;
  388. if (fascistfirewall) {
  389. if (!fascist_firewall_allows_address(d->addr, d->dir_port))
  390. continue;
  391. }
  392. smartlist_add(sl, d);
  393. });
  394. ds = smartlist_choose(sl);
  395. smartlist_free(sl);
  396. return ds;
  397. }
  398. /** Go through and mark the authoritative dirservers as up. */
  399. static void
  400. mark_all_trusteddirservers_up(void)
  401. {
  402. if (routerlist) {
  403. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  404. if (router_digest_is_trusted_dir(router->identity_digest) &&
  405. router->dir_port > 0) {
  406. router->is_running = 1;
  407. });
  408. }
  409. if (trusted_dir_servers) {
  410. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  411. {
  412. dir->is_running = 1;
  413. dir->n_networkstatus_failures = 0;
  414. });
  415. }
  416. }
  417. /** Return 0 if \\exists an authoritative dirserver that's currently
  418. * thought to be running, else return 1.
  419. */
  420. int
  421. all_trusted_directory_servers_down(void)
  422. {
  423. if (!trusted_dir_servers)
  424. return 1;
  425. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  426. if (dir->is_running) return 0);
  427. return 1;
  428. }
  429. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  430. * This is used to make sure we don't pick siblings in a single path.
  431. */
  432. void
  433. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  434. {
  435. routerinfo_t *r;
  436. config_line_t *cl;
  437. if (!router->declared_family)
  438. return;
  439. /* Add every r such that router declares familyness with r, and r
  440. * declares familyhood with router. */
  441. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  442. {
  443. if (!(r = router_get_by_nickname(n)))
  444. continue;
  445. if (!r->declared_family)
  446. continue;
  447. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  448. {
  449. if (router_nickname_matches(router, n2))
  450. smartlist_add(sl, r);
  451. });
  452. });
  453. /* If the user declared any families locally, honor those too. */
  454. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  455. if (router_nickname_is_in_list(router, cl->value)) {
  456. add_nickname_list_to_smartlist(sl, cl->value, 0);
  457. }
  458. }
  459. }
  460. /** List of strings for nicknames we've already warned about and that are
  461. * still unknown / unavailable. */
  462. static smartlist_t *warned_nicknames = NULL;
  463. /** Given a comma-and-whitespace separated list of nicknames, see which
  464. * nicknames in <b>list</b> name routers in our routerlist that are
  465. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  466. */
  467. void
  468. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
  469. {
  470. routerinfo_t *router;
  471. smartlist_t *nickname_list;
  472. if (!list)
  473. return; /* nothing to do */
  474. tor_assert(sl);
  475. nickname_list = smartlist_create();
  476. if (!warned_nicknames)
  477. warned_nicknames = smartlist_create();
  478. smartlist_split_string(nickname_list, list, ",",
  479. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  480. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  481. int warned;
  482. if (!is_legal_nickname_or_hexdigest(nick)) {
  483. log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
  484. continue;
  485. }
  486. router = router_get_by_nickname(nick);
  487. warned = smartlist_string_isin(warned_nicknames, nick);
  488. if (router) {
  489. if (router->is_running) {
  490. smartlist_add(sl,router);
  491. if (warned)
  492. smartlist_string_remove(warned_nicknames, nick);
  493. } else {
  494. if (!warned) {
  495. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
  496. "Nickname list includes '%s' which is known but down.",nick);
  497. smartlist_add(warned_nicknames, tor_strdup(nick));
  498. }
  499. }
  500. } else {
  501. if (!warned) {
  502. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  503. "Nickname list includes '%s' which isn't a known router.",nick);
  504. smartlist_add(warned_nicknames, tor_strdup(nick));
  505. }
  506. }
  507. });
  508. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  509. smartlist_free(nickname_list);
  510. }
  511. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  512. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  513. */
  514. static int
  515. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  516. {
  517. smartlist_t *nickname_list;
  518. int v = 0;
  519. if (!list)
  520. return 0; /* definitely not */
  521. tor_assert(router);
  522. nickname_list = smartlist_create();
  523. smartlist_split_string(nickname_list, list, ",",
  524. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  525. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  526. if (router_nickname_matches(router, cp)) {v=1;break;});
  527. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  528. smartlist_free(nickname_list);
  529. return v;
  530. }
  531. /** Add every router from our routerlist that is currently running to
  532. * <b>sl</b>.
  533. */
  534. static void
  535. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
  536. int need_uptime, int need_capacity)
  537. {
  538. if (!routerlist)
  539. return;
  540. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  541. {
  542. if (router->is_running &&
  543. (router->is_verified ||
  544. (allow_unverified &&
  545. !router_is_unreliable(router, need_uptime, need_capacity)))) {
  546. /* If it's running, and either it's verified or we're ok picking
  547. * unverified routers and this one is suitable.
  548. */
  549. smartlist_add(sl, router);
  550. }
  551. });
  552. }
  553. /** Look through the routerlist until we find a router that has my key.
  554. Return it. */
  555. routerinfo_t *
  556. routerlist_find_my_routerinfo(void)
  557. {
  558. if (!routerlist)
  559. return NULL;
  560. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  561. {
  562. if (router_is_me(router))
  563. return router;
  564. });
  565. return NULL;
  566. }
  567. /** Find a router that's up, that has this IP address, and
  568. * that allows exit to this address:port, or return NULL if there
  569. * isn't a good one.
  570. */
  571. routerinfo_t *
  572. router_find_exact_exit_enclave(const char *address, uint16_t port)
  573. {
  574. uint32_t addr;
  575. struct in_addr in;
  576. if (!tor_inet_aton(address, &in))
  577. return NULL; /* it's not an IP already */
  578. addr = ntohl(in.s_addr);
  579. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  580. {
  581. if (router->is_running &&
  582. router->addr == addr &&
  583. router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  584. ADDR_POLICY_ACCEPTED)
  585. return router;
  586. });
  587. return NULL;
  588. }
  589. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  590. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  591. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  592. * bandwidth.
  593. */
  594. int
  595. router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
  596. {
  597. if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
  598. return 1;
  599. if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  600. return 1;
  601. return 0;
  602. }
  603. /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
  604. static void
  605. routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
  606. {
  607. int i;
  608. routerinfo_t *router;
  609. for (i = 0; i < smartlist_len(sl); ++i) {
  610. router = smartlist_get(sl, i);
  611. if (router_is_unreliable(router, 1, 0)) {
  612. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  613. // router->nickname);
  614. smartlist_del(sl, i--);
  615. }
  616. }
  617. }
  618. #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
  619. /** Choose a random element of router list <b>sl</b>, weighted by
  620. * the advertised bandwidth of each router.
  621. */
  622. routerinfo_t *
  623. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  624. {
  625. int i;
  626. routerinfo_t *router;
  627. smartlist_t *bandwidths;
  628. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  629. uint32_t *p;
  630. /* First count the total bandwidth weight, and make a smartlist
  631. * of each value. */
  632. bandwidths = smartlist_create();
  633. for (i = 0; i < smartlist_len(sl); ++i) {
  634. router = smartlist_get(sl, i);
  635. this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
  636. router->bandwidthcapacity : router->bandwidthrate;
  637. /* if they claim something huge, don't believe it */
  638. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  639. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  640. p = tor_malloc(sizeof(uint32_t));
  641. *p = this_bw;
  642. smartlist_add(bandwidths, p);
  643. total_bw += this_bw;
  644. }
  645. if (!total_bw) {
  646. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  647. smartlist_free(bandwidths);
  648. return smartlist_choose(sl);
  649. }
  650. /* Second, choose a random value from the bandwidth weights. */
  651. rand_bw = crypto_pseudo_rand_int(total_bw);
  652. /* Last, count through sl until we get to the element we picked */
  653. tmp = 0;
  654. for (i=0; ; i++) {
  655. tor_assert(i < smartlist_len(sl));
  656. p = smartlist_get(bandwidths, i);
  657. tmp += *p;
  658. if (tmp >= rand_bw)
  659. break;
  660. }
  661. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  662. smartlist_free(bandwidths);
  663. return (routerinfo_t *)smartlist_get(sl, i);
  664. }
  665. /** Return a random running router from the routerlist. If any node
  666. * named in <b>preferred</b> is available, pick one of those. Never
  667. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  668. * <b>excludedsmartlist</b>, even if they are the only nodes
  669. * available. If <b>strict</b> is true, never pick any node besides
  670. * those in <b>preferred</b>.
  671. * If <b>need_uptime</b> is non-zero, don't return a router with less
  672. * than a minimum uptime.
  673. * If <b>need_capacity</b> is non-zero, weight your choice by the
  674. * advertised capacity of each router.
  675. */
  676. routerinfo_t *
  677. router_choose_random_node(const char *preferred,
  678. const char *excluded,
  679. smartlist_t *excludedsmartlist,
  680. int need_uptime, int need_capacity,
  681. int allow_unverified, int strict)
  682. {
  683. smartlist_t *sl, *excludednodes;
  684. routerinfo_t *choice;
  685. excludednodes = smartlist_create();
  686. add_nickname_list_to_smartlist(excludednodes,excluded,0);
  687. /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
  688. * since the user explicitly asked for these nodes. */
  689. sl = smartlist_create();
  690. add_nickname_list_to_smartlist(sl,preferred,1);
  691. smartlist_subtract(sl,excludednodes);
  692. if (excludedsmartlist)
  693. smartlist_subtract(sl,excludedsmartlist);
  694. choice = smartlist_choose(sl);
  695. smartlist_free(sl);
  696. if (!choice && !strict) {
  697. /* Then give up on our preferred choices: any node
  698. * will do that has the required attributes. */
  699. sl = smartlist_create();
  700. router_add_running_routers_to_smartlist(sl, allow_unverified,
  701. need_uptime, need_capacity);
  702. smartlist_subtract(sl,excludednodes);
  703. if (excludedsmartlist)
  704. smartlist_subtract(sl,excludedsmartlist);
  705. if (need_uptime)
  706. routerlist_sl_remove_unreliable_routers(sl);
  707. if (need_capacity)
  708. choice = routerlist_sl_choose_by_bandwidth(sl);
  709. else
  710. choice = smartlist_choose(sl);
  711. smartlist_free(sl);
  712. }
  713. smartlist_free(excludednodes);
  714. if (!choice)
  715. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  716. return choice;
  717. }
  718. /** Return true iff the digest of <b>router</b>'s identity key,
  719. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  720. * optionally prefixed with a single dollar sign). Return false if
  721. * <b>hexdigest</b> is malformed, or it doesn't match. */
  722. static INLINE int
  723. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  724. {
  725. char digest[DIGEST_LEN];
  726. tor_assert(hexdigest);
  727. if (hexdigest[0] == '$')
  728. ++hexdigest;
  729. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  730. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  731. return 0;
  732. return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
  733. }
  734. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  735. * (case-insensitive), or if <b>router's</b> identity key digest
  736. * matches a hexadecimal value stored in <b>nickname</b>. Return
  737. * false otherwise. */
  738. static int
  739. router_nickname_matches(routerinfo_t *router, const char *nickname)
  740. {
  741. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  742. return 1;
  743. return router_hex_digest_matches(router, nickname);
  744. }
  745. /** Return the router in our routerlist whose (case-insensitive)
  746. * nickname or (case-sensitive) hexadecimal key digest is
  747. * <b>nickname</b>. Return NULL if no such router is known.
  748. */
  749. routerinfo_t *
  750. router_get_by_nickname(const char *nickname)
  751. {
  752. int maybedigest;
  753. char digest[DIGEST_LEN];
  754. tor_assert(nickname);
  755. if (!routerlist)
  756. return NULL;
  757. if (nickname[0] == '$')
  758. return router_get_by_hexdigest(nickname);
  759. if (server_mode(get_options()) &&
  760. !strcasecmp(nickname, get_options()->Nickname))
  761. return router_get_my_routerinfo();
  762. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  763. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  764. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  765. {
  766. /* XXXX011 NM Should this restrict by Named rouers, or warn on
  767. * non-named routers, or something? */
  768. if (0 == strcasecmp(router->nickname, nickname) ||
  769. (maybedigest && 0 == memcmp(digest, router->identity_digest,
  770. DIGEST_LEN)))
  771. return router;
  772. });
  773. return NULL;
  774. }
  775. /** Return true iff <b>digest</b> is the digest of the identity key of
  776. * a trusted directory. */
  777. int
  778. router_digest_is_trusted_dir(const char *digest)
  779. {
  780. if (!trusted_dir_servers)
  781. return 0;
  782. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  783. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  784. return 0;
  785. }
  786. /** Return the router in our routerlist whose hexadecimal key digest
  787. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  788. routerinfo_t *
  789. router_get_by_hexdigest(const char *hexdigest)
  790. {
  791. char digest[DIGEST_LEN];
  792. tor_assert(hexdigest);
  793. if (!routerlist)
  794. return NULL;
  795. if (hexdigest[0]=='$')
  796. ++hexdigest;
  797. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  798. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  799. return NULL;
  800. return router_get_by_digest(digest);
  801. }
  802. /** Return the router in our routerlist whose 20-byte key digest
  803. * is <b>digest</b>. Return NULL if no such router is known. */
  804. routerinfo_t *
  805. router_get_by_digest(const char *digest)
  806. {
  807. tor_assert(digest);
  808. if (!routerlist) return NULL;
  809. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t*, router,
  810. {
  811. if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
  812. return router;
  813. });
  814. return NULL;
  815. }
  816. /** Set *<b>prouterlist</b> to the current list of all known routers. */
  817. void
  818. router_get_routerlist(routerlist_t **prouterlist)
  819. {
  820. *prouterlist = routerlist;
  821. }
  822. /** Free all storage held by <b>router</b>. */
  823. void
  824. routerinfo_free(routerinfo_t *router)
  825. {
  826. if (!router)
  827. return;
  828. tor_free(router->signed_descriptor);
  829. tor_free(router->address);
  830. tor_free(router->nickname);
  831. tor_free(router->platform);
  832. tor_free(router->contact_info);
  833. if (router->onion_pkey)
  834. crypto_free_pk_env(router->onion_pkey);
  835. if (router->identity_pkey)
  836. crypto_free_pk_env(router->identity_pkey);
  837. if (router->declared_family) {
  838. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  839. smartlist_free(router->declared_family);
  840. }
  841. addr_policy_free(router->exit_policy);
  842. tor_free(router);
  843. }
  844. /** Allocate a fresh copy of <b>router</b> */
  845. routerinfo_t *
  846. routerinfo_copy(const routerinfo_t *router)
  847. {
  848. routerinfo_t *r;
  849. addr_policy_t **e, *tmp;
  850. r = tor_malloc(sizeof(routerinfo_t));
  851. memcpy(r, router, sizeof(routerinfo_t));
  852. r->address = tor_strdup(r->address);
  853. r->nickname = tor_strdup(r->nickname);
  854. r->platform = tor_strdup(r->platform);
  855. if (r->signed_descriptor)
  856. r->signed_descriptor = tor_strdup(r->signed_descriptor);
  857. if (r->onion_pkey)
  858. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  859. if (r->identity_pkey)
  860. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  861. e = &r->exit_policy;
  862. while (*e) {
  863. tmp = tor_malloc(sizeof(addr_policy_t));
  864. memcpy(tmp,*e,sizeof(addr_policy_t));
  865. *e = tmp;
  866. (*e)->string = tor_strdup((*e)->string);
  867. e = & ((*e)->next);
  868. }
  869. if (r->declared_family) {
  870. r->declared_family = smartlist_create();
  871. SMARTLIST_FOREACH(router->declared_family, const char *, s,
  872. smartlist_add(r->declared_family, tor_strdup(s)));
  873. }
  874. return r;
  875. }
  876. /** Free all storage held by a routerlist <b>rl</b> */
  877. void
  878. routerlist_free(routerlist_t *rl)
  879. {
  880. tor_assert(rl);
  881. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  882. routerinfo_free(r));
  883. smartlist_free(rl->routers);
  884. tor_free(rl);
  885. }
  886. /** Free all memory held by the rouerlist module */
  887. void
  888. routerlist_free_all(void)
  889. {
  890. if (routerlist)
  891. routerlist_free(routerlist);
  892. routerlist = NULL;
  893. if (warned_nicknames) {
  894. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  895. smartlist_free(warned_nicknames);
  896. warned_nicknames = NULL;
  897. }
  898. if (trusted_dir_servers) {
  899. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  900. { tor_free(ds->address); tor_free(ds); });
  901. smartlist_free(trusted_dir_servers);
  902. trusted_dir_servers = NULL;
  903. }
  904. if (networkstatus_list) {
  905. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  906. networkstatus_free(ns));
  907. smartlist_free(networkstatus_list);
  908. networkstatus_list = NULL;
  909. }
  910. if (routerstatus_list) {
  911. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  912. local_routerstatus_free(rs));
  913. smartlist_free(routerstatus_list);
  914. routerstatus_list = NULL;
  915. }
  916. }
  917. /** Free all storage held by the routerstatus object <b>rs</b>. */
  918. void
  919. routerstatus_free(routerstatus_t *rs)
  920. {
  921. tor_free(rs);
  922. }
  923. /** Free all storage held by the local_routerstatus object <b>rs</b>. */
  924. static void
  925. local_routerstatus_free(local_routerstatus_t *rs)
  926. {
  927. tor_free(rs);
  928. }
  929. /** Free all storage held by the networkstatus object <b>ns</b>. */
  930. void
  931. networkstatus_free(networkstatus_t *ns)
  932. {
  933. tor_free(ns->source_address);
  934. tor_free(ns->contact);
  935. if (ns->signing_key)
  936. crypto_free_pk_env(ns->signing_key);
  937. tor_free(ns->client_versions);
  938. tor_free(ns->server_versions);
  939. if (ns->entries) {
  940. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
  941. smartlist_free(ns->entries);
  942. }
  943. tor_free(ns);
  944. }
  945. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  946. void
  947. router_mark_as_down(const char *digest)
  948. {
  949. routerinfo_t *router;
  950. tor_assert(digest);
  951. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  952. if (!memcmp(d->digest, digest, DIGEST_LEN))
  953. d->is_running = 0);
  954. router = router_get_by_digest(digest);
  955. if (!router) /* we don't seem to know about him in the first place */
  956. return;
  957. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  958. if (router_is_me(router) && !we_are_hibernating())
  959. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  960. router->is_running = 0;
  961. }
  962. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  963. * older entries (if any) with the same key. Note: Callers should not hold
  964. * their pointers to <b>router</b> if this function fails; <b>router</b>
  965. * will either be inserted into the routerlist or freed.
  966. *
  967. * Returns >= 0 if the router was added; less than 0 if it was not.
  968. *
  969. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  970. * describing the reason for not liking the routerinfo.
  971. *
  972. * If the return value is less than -1, there was a problem with the
  973. * routerinfo. If the return value is equal to -1, then the routerinfo was
  974. * fine, but out-of-date. If the return value is equal to 1, the
  975. * routerinfo was accepted, but we should notify the generator of the
  976. * descriptor using the message *<b>msg</b>.
  977. *
  978. * This function should be called *after*
  979. * routers_update_status_from_networkstatus; subsequenctly, you should call
  980. * router_rebuild_store and control_event_descriptors_changed.
  981. *
  982. * XXXX never replace your own descriptor.
  983. */
  984. int
  985. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  986. int from_cache)
  987. {
  988. int i;
  989. char id_digest[DIGEST_LEN];
  990. int authdir = get_options()->AuthoritativeDir;
  991. int authdir_verified = 0;
  992. tor_assert(msg);
  993. if (!routerlist) {
  994. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  995. routerlist->routers = smartlist_create();
  996. }
  997. crypto_pk_get_digest(router->identity_pkey, id_digest);
  998. if (authdir) {
  999. if (authdir_wants_to_reject_router(router, msg))
  1000. return -2;
  1001. authdir_verified = router->is_verified;
  1002. }
  1003. /* If we have a router with this name, and the identity key is the same,
  1004. * choose the newer one. If the identity key has changed, drop the router.
  1005. */
  1006. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1007. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  1008. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  1009. if (router->published_on <= old_router->published_on) {
  1010. /* Same key, but old */
  1011. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  1012. router->nickname);
  1013. routerinfo_free(router);
  1014. *msg = "Router descriptor was not new.";
  1015. return -1;
  1016. } else {
  1017. /* Same key, new. */
  1018. int unreachable = 0;
  1019. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  1020. router->nickname, old_router->nickname,
  1021. hex_str(id_digest,DIGEST_LEN));
  1022. if (router->addr == old_router->addr &&
  1023. router->or_port == old_router->or_port) {
  1024. /* these carry over when the address and orport are unchanged.*/
  1025. router->last_reachable = old_router->last_reachable;
  1026. router->testing_since = old_router->testing_since;
  1027. router->num_unreachable_notifications =
  1028. old_router->num_unreachable_notifications;
  1029. }
  1030. if (authdir &&
  1031. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  1032. if (router->num_unreachable_notifications >= 3) {
  1033. unreachable = 1;
  1034. log_fn(LOG_NOTICE, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
  1035. router->nickname, router->contact_info ? router->contact_info : "",
  1036. router->platform ? router->platform : "");
  1037. } else {
  1038. log_fn(LOG_INFO,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
  1039. router->num_unreachable_notifications++;
  1040. }
  1041. }
  1042. routerinfo_free(old_router);
  1043. smartlist_set(routerlist->routers, i, router);
  1044. if (!from_cache)
  1045. router_append_to_journal(router->signed_descriptor,
  1046. router->signed_descriptor_len);
  1047. directory_set_dirty();
  1048. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1049. authdir_verified ? "Verified server updated" :
  1050. "Unverified server updated. (Have you sent us your key fingerprint?)";
  1051. return unreachable ? 1 : 0;
  1052. }
  1053. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1054. /* nicknames match, keys don't. */
  1055. if (router->is_named) {
  1056. /* The new verified router replaces the old one; remove the
  1057. * old one. And carry on to the end of the list, in case
  1058. * there are more old unverified routers with this nickname
  1059. */
  1060. /* mark-for-close connections using the old key, so we can
  1061. * make new ones with the new key.
  1062. */
  1063. connection_t *conn;
  1064. while ((conn = connection_get_by_identity_digest(
  1065. old_router->identity_digest, CONN_TYPE_OR))) {
  1066. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
  1067. old_router->nickname);
  1068. connection_mark_for_close(conn);
  1069. }
  1070. routerinfo_free(old_router);
  1071. smartlist_del_keeporder(routerlist->routers, i--);
  1072. } else if (old_router->is_named) {
  1073. /* Can't replace a verified router with an unverified one. */
  1074. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  1075. router->nickname);
  1076. routerinfo_free(router);
  1077. *msg = "Already have verified router with same nickname and different key.";
  1078. return -2;
  1079. }
  1080. }
  1081. }
  1082. /* We haven't seen a router with this name before. Add it to the end of
  1083. * the list. */
  1084. smartlist_add(routerlist->routers, router);
  1085. if (!from_cache)
  1086. router_append_to_journal(router->signed_descriptor,
  1087. router->signed_descriptor_len);
  1088. directory_set_dirty();
  1089. return 0;
  1090. }
  1091. /** Remove any routers from the routerlist that are more than <b>age</b>
  1092. * seconds old.
  1093. */
  1094. void
  1095. routerlist_remove_old_routers(int age)
  1096. {
  1097. int i;
  1098. time_t cutoff;
  1099. routerinfo_t *router;
  1100. if (!routerlist)
  1101. return;
  1102. cutoff = time(NULL) - age;
  1103. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1104. router = smartlist_get(routerlist->routers, i);
  1105. if (router->published_on <= cutoff) {
  1106. /* Too old. Remove it. */
  1107. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  1108. routerinfo_free(router);
  1109. smartlist_del(routerlist->routers, i--);
  1110. }
  1111. }
  1112. }
  1113. /**
  1114. * Code to parse a single router descriptor and insert it into the
  1115. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1116. * descriptor was well-formed but could not be added; and 1 if the
  1117. * descriptor was added.
  1118. *
  1119. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1120. * *<b>msg</b> a static string describing the reason for refusing the
  1121. * descriptor.
  1122. *
  1123. * This is used only by the controller.
  1124. */
  1125. int
  1126. router_load_single_router(const char *s, const char **msg)
  1127. {
  1128. routerinfo_t *ri;
  1129. tor_assert(msg);
  1130. *msg = NULL;
  1131. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  1132. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  1133. *msg = "Couldn't parse router descriptor.";
  1134. return -1;
  1135. }
  1136. if (router_is_me(ri)) {
  1137. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  1138. *msg = "Router's identity key matches mine.";
  1139. routerinfo_free(ri);
  1140. return 0;
  1141. }
  1142. /* XXXX011 update router status from networkstatus!! */
  1143. if (router_add_to_routerlist(ri, msg, 0)<0) {
  1144. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  1145. *msg?*msg:"(No message).");
  1146. /* we've already assigned to *msg now, and ri is already freed */
  1147. return 0;
  1148. } else {
  1149. smartlist_t *changed = smartlist_create();
  1150. smartlist_add(changed, ri);
  1151. control_event_descriptors_changed(changed);
  1152. smartlist_free(changed);
  1153. }
  1154. log_fn(LOG_DEBUG, "Added router to list");
  1155. return 1;
  1156. }
  1157. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1158. * routers into our directory. If <b>from_cache</b> is false, the routers
  1159. * have come from the network: cache them.
  1160. *
  1161. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1162. * uppercased identity fingerprints. Do not update any router whose
  1163. * fingerprint is not on the list; after updating a router, remove its
  1164. * fingerprint from the list.
  1165. */
  1166. void
  1167. router_load_routers_from_string(const char *s, int from_cache,
  1168. smartlist_t *requested_fingerprints)
  1169. {
  1170. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1171. char fp[HEX_DIGEST_LEN+1];
  1172. const char *msg;
  1173. router_parse_list_from_string(&s, routers);
  1174. routers_update_status_from_networkstatus(routers, !from_cache);
  1175. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1176. {
  1177. base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
  1178. if (requested_fingerprints) {
  1179. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1180. smartlist_string_remove(requested_fingerprints, fp);
  1181. } else {
  1182. char *requested =
  1183. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1184. log_fn(LOG_WARN, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1185. tor_free(requested);
  1186. routerinfo_free(ri);
  1187. continue;
  1188. }
  1189. }
  1190. if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
  1191. smartlist_add(changed, ri);
  1192. });
  1193. control_event_descriptors_changed(changed);
  1194. router_rebuild_store(0);
  1195. smartlist_free(routers);
  1196. smartlist_free(changed);
  1197. }
  1198. /** Helper: return a newly allocated string containing the name of the filename
  1199. * where we plan to cache <b>ns</b>. */
  1200. static char *
  1201. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1202. {
  1203. const char *datadir = get_options()->DataDirectory;
  1204. size_t len = strlen(datadir)+64;
  1205. char fp[HEX_DIGEST_LEN+1];
  1206. char *fn = tor_malloc(len+1);
  1207. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1208. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1209. return fn;
  1210. }
  1211. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1212. * publication date. */
  1213. static int
  1214. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1215. {
  1216. const networkstatus_t *a = *_a, *b = *_b;
  1217. if (a->published_on < b->published_on)
  1218. return -1;
  1219. else if (a->published_on > b->published_on)
  1220. return 1;
  1221. else
  1222. return 0;
  1223. }
  1224. /** How far in the future do we allow a network-status to get before removing
  1225. * it? (seconds) */
  1226. #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
  1227. /** Given a string <b>s</b> containing a network status that we received at
  1228. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1229. * store it, and put it into our cache is necessary.
  1230. *
  1231. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1232. * own networkstatus_t (if we're a directory server).
  1233. *
  1234. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1235. * cache.
  1236. *
  1237. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1238. * uppercased identity fingerprints. Do not update any networkstatus whose
  1239. * fingerprint is not on the list; after updating a networkstatus, remove its
  1240. * fingerprint from the list.
  1241. *
  1242. * Return 0 on success, -1 on failure.
  1243. *
  1244. * Callers should make sure that routers_update_all_from_networkstatus() is
  1245. * invoked after this function succeeds.
  1246. */
  1247. int
  1248. router_set_networkstatus(const char *s, time_t arrived_at,
  1249. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1250. {
  1251. networkstatus_t *ns;
  1252. int i, found;
  1253. time_t now;
  1254. int skewed = 0;
  1255. trusted_dir_server_t *trusted_dir;
  1256. char fp[HEX_DIGEST_LEN+1];
  1257. char published[ISO_TIME_LEN+1];
  1258. ns = networkstatus_parse_from_string(s);
  1259. if (!ns) {
  1260. log_fn(LOG_WARN, "Couldn't parse network status.");
  1261. return -1;
  1262. }
  1263. if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  1264. log_fn(LOG_INFO, "Network status was signed, but not by an authoritative directory we recognize.");
  1265. networkstatus_free(ns);
  1266. return -1;
  1267. }
  1268. now = time(NULL);
  1269. if (arrived_at > now)
  1270. arrived_at = now;
  1271. ns->received_on = arrived_at;
  1272. format_iso_time(published, ns->published_on);
  1273. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1274. log_fn(LOG_WARN, "Network status was published in the future (%s GMT). Somebody is skewed here: check your clock. Not caching.", published);
  1275. skewed = 1;
  1276. }
  1277. if (!networkstatus_list)
  1278. networkstatus_list = smartlist_create();
  1279. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1280. /* Don't replace our own networkstatus when we get it from somebody else. */
  1281. networkstatus_free(ns);
  1282. return 0;
  1283. }
  1284. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1285. if (requested_fingerprints) {
  1286. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1287. smartlist_string_remove(requested_fingerprints, fp);
  1288. } else {
  1289. char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1290. log_fn(LOG_WARN, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1291. tor_free(requested);
  1292. return 0;
  1293. }
  1294. }
  1295. if (source != NS_FROM_CACHE)
  1296. trusted_dir->n_networkstatus_failures = 0;
  1297. found = 0;
  1298. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  1299. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  1300. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  1301. if (!memcmp(old_ns->networkstatus_digest,
  1302. ns->networkstatus_digest, DIGEST_LEN)) {
  1303. /* Same one we had before. */
  1304. networkstatus_free(ns);
  1305. log_fn(LOG_NOTICE,
  1306. "Dropping network-status from %s:%d (published %s); already have it.",
  1307. trusted_dir->address, trusted_dir->dir_port, published);
  1308. if (old_ns->received_on < arrived_at) {
  1309. if (source != NS_FROM_CACHE) {
  1310. char *fn = networkstatus_get_cache_filename(old_ns);
  1311. /* We use mtime to tell when it arrived, so update that. */
  1312. touch_file(fn);
  1313. tor_free(fn);
  1314. }
  1315. old_ns->received_on = arrived_at;
  1316. }
  1317. return 0;
  1318. } else if (old_ns->published_on >= ns->published_on) {
  1319. char old_published[ISO_TIME_LEN+1];
  1320. format_iso_time(old_published, old_ns->published_on);
  1321. log_fn(LOG_NOTICE,
  1322. "Dropping network-status from %s:%d (published %s);"
  1323. " we have a newer one (published %s) for this authority.",
  1324. trusted_dir->address, trusted_dir->dir_port, published,
  1325. old_published);
  1326. networkstatus_free(ns);
  1327. return 0;
  1328. } else {
  1329. networkstatus_free(old_ns);
  1330. smartlist_set(networkstatus_list, i, ns);
  1331. found = 1;
  1332. break;
  1333. }
  1334. }
  1335. }
  1336. if (!found)
  1337. smartlist_add(networkstatus_list, ns);
  1338. /*XXXX011 downgrade to INFO NM */
  1339. log_fn(LOG_NOTICE, "Setting networkstatus %s %s:%d (published %s)",
  1340. source == NS_FROM_CACHE?"cached from":
  1341. (source==NS_FROM_DIR?"downloaded from":"generated for"),
  1342. trusted_dir->address, trusted_dir->dir_port, published);
  1343. networkstatus_list_has_changed = 1;
  1344. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  1345. if (source != NS_FROM_CACHE && !skewed) {
  1346. char *fn = networkstatus_get_cache_filename(ns);
  1347. if (write_str_to_file(fn, s, 0)<0) {
  1348. log_fn(LOG_NOTICE, "Couldn't write cached network status to \"%s\"", fn);
  1349. }
  1350. tor_free(fn);
  1351. }
  1352. networkstatus_list_update_recent(now);
  1353. if (get_options()->DirPort && !skewed)
  1354. dirserv_set_cached_networkstatus_v2(s, fp, ns->published_on);
  1355. return 0;
  1356. }
  1357. /** How old do we allow a network-status to get before removing it completely? */
  1358. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  1359. /** Remove all very-old network_status_t objects from memory and from the
  1360. * disk cache. */
  1361. void
  1362. networkstatus_list_clean(time_t now)
  1363. {
  1364. int i;
  1365. if (!networkstatus_list)
  1366. return;
  1367. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  1368. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  1369. char *fname = NULL;;
  1370. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  1371. continue;
  1372. /* Okay, this one is too old. Remove it from the list, and delete it
  1373. * from the cache. */
  1374. smartlist_del(networkstatus_list, i--);
  1375. fname = networkstatus_get_cache_filename(ns);
  1376. if (file_status(fname) == FN_FILE) {
  1377. log_fn(LOG_INFO, "Removing too-old networkstatus in %s", fname);
  1378. unlink(fname);
  1379. }
  1380. tor_free(fname);
  1381. if (get_options()->DirPort) {
  1382. char fp[HEX_DIGEST_LEN+1];
  1383. base16_encode(fp, sizeof(fp), ns->identity_digest, DIGEST_LEN);
  1384. dirserv_set_cached_networkstatus_v2(NULL, fp, 0);
  1385. }
  1386. networkstatus_free(ns);
  1387. }
  1388. }
  1389. /** Helper for bsearching a list of routerstatus_t pointers.*/
  1390. static int
  1391. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  1392. {
  1393. const char *key = _key;
  1394. const routerstatus_t *rs = *_member;
  1395. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  1396. }
  1397. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  1398. * NULL if none was found. */
  1399. static routerstatus_t *
  1400. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  1401. {
  1402. return smartlist_bsearch(ns->entries, digest,
  1403. _compare_digest_to_routerstatus_entry);
  1404. }
  1405. /** Return the consensus view of the status of the router whose digest is
  1406. * <b>digest</b>, or NULL if we don't know about any such router. */
  1407. local_routerstatus_t *
  1408. router_get_combined_status_by_digest(const char *digest)
  1409. {
  1410. if (!routerstatus_list)
  1411. return NULL;
  1412. return smartlist_bsearch(routerstatus_list, digest,
  1413. _compare_digest_to_routerstatus_entry);
  1414. }
  1415. /* XXXX These should be configurable, perhaps? NM */
  1416. #define AUTHORITY_NS_CACHE_INTERVAL 10*60
  1417. #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
  1418. /** We are a directory server, and so cache network_status documents.
  1419. * Initiate downloads as needed to update them. For authorities, this means
  1420. * asking each trusted directory for its network-status. For caches, this means
  1421. * asking a random authority for all network-statuses.
  1422. */
  1423. void
  1424. update_networkstatus_cache_downloads(time_t now)
  1425. {
  1426. static time_t last_downloaded = 0;
  1427. int authority = authdir_mode(get_options());
  1428. int interval =
  1429. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  1430. /*XXXXX NM we should retry on failure. */
  1431. if (last_downloaded + interval >= now)
  1432. return;
  1433. if (!trusted_dir_servers)
  1434. return;
  1435. last_downloaded = now;
  1436. if (authority) {
  1437. /* An authority launches a separate connection for everybody. */
  1438. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1439. {
  1440. char resource[HEX_DIGEST_LEN+6];
  1441. if (router_digest_is_me(ds->digest))
  1442. continue;
  1443. if (connection_get_by_type_addr_port_purpose(
  1444. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  1445. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  1446. /* We are already fetching this one. */
  1447. continue;
  1448. }
  1449. strlcpy(resource, "fp/", sizeof(resource));
  1450. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  1451. strlcat(resource, ".z", sizeof(resource));
  1452. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
  1453. });
  1454. } else {
  1455. /* A non-authority cache launches one connection to a random authority. */
  1456. /* (Check whether we're currently fetching network-status objects.) */
  1457. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  1458. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1459. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  1460. }
  1461. }
  1462. /*XXXX Should these be configurable? NM*/
  1463. /** How old (in seconds) can a network-status be before we try replacing it? */
  1464. #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
  1465. /** How long (in seconds) does a client wait after getting a network status
  1466. * before downloading the next in sequence? */
  1467. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  1468. /* How many times do we allow a networkstatus download to fail before we
  1469. * assume that the authority isn't publishing? */
  1470. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  1471. /** We are not a directory cache or authority. Update our network-status list
  1472. * by launching a new directory fetch for enough network-status documents "as
  1473. * necessary". See function comments for implementation details.
  1474. */
  1475. void
  1476. update_networkstatus_client_downloads(time_t now)
  1477. {
  1478. int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
  1479. int most_recent_idx = -1;
  1480. trusted_dir_server_t *most_recent = NULL;
  1481. time_t most_recent_received = 0;
  1482. char *resource, *cp;
  1483. size_t resource_len;
  1484. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  1485. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1486. return;
  1487. /* This is a little tricky. We want to download enough network-status
  1488. * objects so that we have at least half of them under
  1489. * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
  1490. * *one* if the most recent one's publication time is under
  1491. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  1492. */
  1493. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  1494. return;
  1495. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  1496. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1497. {
  1498. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  1499. if (!ns)
  1500. continue;
  1501. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  1502. --n_running_dirservers;
  1503. continue;
  1504. }
  1505. if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
  1506. ++n_live;
  1507. if (!most_recent || ns->received_on > most_recent_received) {
  1508. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  1509. most_recent = ds;
  1510. most_recent_received = ns->received_on;
  1511. }
  1512. });
  1513. /* Download enough so we have at least half live, but no more than all the
  1514. * trusted dirservers we know.
  1515. */
  1516. if (n_live < (n_dirservers/2)+1)
  1517. needed = (n_dirservers/2)+1-n_live;
  1518. if (needed > n_running_dirservers)
  1519. needed = n_running_dirservers;
  1520. if (needed)
  1521. /* XXXX011 Downgrade to info NM */
  1522. log_fn(LOG_NOTICE, "For %d/%d running directory servers, we have %d live"
  1523. " network-status documents. Downloading %d.",
  1524. n_running_dirservers, n_dirservers, n_live, needed);
  1525. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  1526. if (n_running_dirservers &&
  1527. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
  1528. const char *addr = most_recent?most_recent->address:"nobody";
  1529. int port = most_recent?most_recent->dir_port:0;
  1530. log_fn(LOG_NOTICE, "Our most recent network-status document (from %s:%d) "
  1531. "is %d seconds old; downloading another.",
  1532. addr, port, (int)(now-most_recent_received));
  1533. needed = 1;
  1534. }
  1535. if (!needed)
  1536. return;
  1537. /* If no networkstatus was found, choose a dirserver at random as "most
  1538. * recent". */
  1539. if (most_recent_idx<0)
  1540. most_recent_idx = crypto_pseudo_rand_int(n_dirservers);
  1541. /* Build a request string for all the resources we want. */
  1542. resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
  1543. resource = tor_malloc(resource_len);
  1544. memcpy(resource, "fp/", 3);
  1545. cp = resource+3;
  1546. for (i = most_recent_idx+1; needed; ++i) {
  1547. trusted_dir_server_t *ds;
  1548. if (i >= n_dirservers)
  1549. i = 0;
  1550. ds = smartlist_get(trusted_dir_servers, i);
  1551. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
  1552. continue;
  1553. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1554. cp += HEX_DIGEST_LEN;
  1555. --needed;
  1556. if (needed)
  1557. *cp++ = '+';
  1558. }
  1559. memcpy(cp, ".z", 3);
  1560. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  1561. tor_free(resource);
  1562. }
  1563. /** Decide whether a given addr:port is definitely accepted,
  1564. * definitely rejected, probably accepted, or probably rejected by a
  1565. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1566. * target address. If <b>port</b> is 0, we don't know the port of the
  1567. * target address.
  1568. *
  1569. * For now, the algorithm is pretty simple: we look for definite and
  1570. * uncertain matches. The first definite match is what we guess; if
  1571. * it was preceded by no uncertain matches of the opposite policy,
  1572. * then the guess is definite; otherwise it is probable. (If we
  1573. * have a known addr and port, all matches are definite; if we have an
  1574. * unknown addr/port, any address/port ranges other than "all" are
  1575. * uncertain.)
  1576. *
  1577. * We could do better by assuming that some ranges never match typical
  1578. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1579. */
  1580. addr_policy_result_t
  1581. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1582. addr_policy_t *policy)
  1583. {
  1584. int maybe_reject = 0;
  1585. int maybe_accept = 0;
  1586. int match = 0;
  1587. int maybe = 0;
  1588. addr_policy_t *tmpe;
  1589. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1590. maybe = 0;
  1591. if (!addr) {
  1592. /* Address is unknown. */
  1593. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1594. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1595. /* The port definitely matches. */
  1596. if (tmpe->msk == 0) {
  1597. match = 1;
  1598. } else {
  1599. maybe = 1;
  1600. }
  1601. } else if (!port) {
  1602. /* The port maybe matches. */
  1603. maybe = 1;
  1604. }
  1605. } else {
  1606. /* Address is known */
  1607. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1608. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1609. /* Exact match for the policy */
  1610. match = 1;
  1611. } else if (!port) {
  1612. maybe = 1;
  1613. }
  1614. }
  1615. }
  1616. if (maybe) {
  1617. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1618. maybe_reject = 1;
  1619. else
  1620. maybe_accept = 1;
  1621. }
  1622. if (match) {
  1623. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1624. /* If we already hit a clause that might trigger a 'reject', than we
  1625. * can't be sure of this certain 'accept'.*/
  1626. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1627. } else {
  1628. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1629. }
  1630. }
  1631. }
  1632. /* accept all by default. */
  1633. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1634. }
  1635. /** Return 1 if all running sufficiently-stable routers will reject
  1636. * addr:port, return 0 if any might accept it. */
  1637. int
  1638. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1639. int need_uptime)
  1640. {
  1641. addr_policy_result_t r;
  1642. if (!routerlist) return 1;
  1643. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1644. {
  1645. if (router->is_running &&
  1646. !router_is_unreliable(router, need_uptime, 0)) {
  1647. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1648. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1649. return 0; /* this one could be ok. good enough. */
  1650. }
  1651. });
  1652. return 1; /* all will reject. */
  1653. }
  1654. /**
  1655. * If <b>policy</b> implicitly allows connections to any port in the
  1656. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1657. * part of the policy that allows it, and return 1. Else return 0.
  1658. *
  1659. * A policy allows an IP:Port combination <em>implicitly</em> if
  1660. * it is included in a *: pattern, or in a fallback pattern.
  1661. */
  1662. static int
  1663. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1664. uint32_t addr, uint32_t mask,
  1665. addr_policy_t **policy_out)
  1666. {
  1667. uint32_t addr2;
  1668. tor_assert(policy_out);
  1669. addr &= mask;
  1670. addr2 = addr | ~mask;
  1671. for (; policy; policy=policy->next) {
  1672. /* Does this policy cover all of the address range we're looking at? */
  1673. /* Boolean logic time: range X is contained in range Y if, for
  1674. * each bit B, all possible values of B in X are values of B in Y.
  1675. * In "addr", we have every fixed bit set to its value, and every
  1676. * free bit set to 0. In "addr2", we have every fixed bit set to
  1677. * its value, and every free bit set to 1. So if addr and addr2 are
  1678. * both in the policy, the range is covered by the policy.
  1679. */
  1680. uint32_t p_addr = policy->addr & policy->msk;
  1681. if (p_addr == (addr & policy->msk) &&
  1682. p_addr == (addr2 & policy->msk) &&
  1683. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1684. return 0;
  1685. }
  1686. /* Does this policy cover some of the address range we're looking at? */
  1687. /* Boolean logic time: range X and range Y intersect if there is
  1688. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1689. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1690. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1691. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1692. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1693. */
  1694. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1695. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1696. *policy_out = policy;
  1697. return 1;
  1698. }
  1699. }
  1700. *policy_out = NULL;
  1701. return 1;
  1702. }
  1703. /** If <b>policy</b> implicitly allows connections to any port on
  1704. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1705. * true. Else return false.
  1706. **/
  1707. int
  1708. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1709. int warn)
  1710. {
  1711. addr_policy_t *p;
  1712. int r=0,i;
  1713. static struct {
  1714. uint32_t addr; uint32_t mask; const char *network;
  1715. } private_networks[] = {
  1716. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1717. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1718. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1719. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1720. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1721. { 0,0,NULL},
  1722. };
  1723. for (i=0; private_networks[i].addr; ++i) {
  1724. p = NULL;
  1725. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1726. if (policy_includes_addr_mask_implicitly(
  1727. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1728. if (warn)
  1729. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1730. p?p->string:"(default)",
  1731. private_networks[i].network);
  1732. r = 1;
  1733. }
  1734. }
  1735. return r;
  1736. }
  1737. /** Return true iff <b>router</b> does not permit exit streams.
  1738. */
  1739. int
  1740. router_exit_policy_rejects_all(routerinfo_t *router)
  1741. {
  1742. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1743. == ADDR_POLICY_REJECTED;
  1744. }
  1745. /** Add to the list of authorized directory servers one at
  1746. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  1747. * <b>address</b> is NULL, add ourself. */
  1748. void
  1749. add_trusted_dir_server(const char *address, uint16_t port, const char *digest,
  1750. int supports_v1)
  1751. {
  1752. trusted_dir_server_t *ent;
  1753. uint32_t a;
  1754. char *hostname = NULL;
  1755. if (!trusted_dir_servers)
  1756. trusted_dir_servers = smartlist_create();
  1757. if (!address) { /* The address is us; we should guess. */
  1758. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  1759. log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
  1760. return;
  1761. }
  1762. } else {
  1763. if (tor_lookup_hostname(address, &a)) {
  1764. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1765. address);
  1766. return;
  1767. }
  1768. hostname = tor_strdup(address);
  1769. a = ntohl(a);
  1770. }
  1771. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  1772. ent->address = hostname;
  1773. ent->addr = a;
  1774. ent->dir_port = port;
  1775. ent->is_running = 1;
  1776. ent->supports_v1_protocol = supports_v1;
  1777. memcpy(ent->digest, digest, DIGEST_LEN);
  1778. smartlist_add(trusted_dir_servers, ent);
  1779. }
  1780. /** Remove all members from the list of trusted dir servers. */
  1781. void
  1782. clear_trusted_dir_servers(void)
  1783. {
  1784. if (trusted_dir_servers) {
  1785. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1786. { tor_free(ent->address); tor_free(ent); });
  1787. smartlist_clear(trusted_dir_servers);
  1788. } else {
  1789. trusted_dir_servers = smartlist_create();
  1790. }
  1791. }
  1792. /** Return the network status with a given identity digest. */
  1793. networkstatus_t *
  1794. networkstatus_get_by_digest(const char *digest)
  1795. {
  1796. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1797. {
  1798. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  1799. return ns;
  1800. });
  1801. return NULL;
  1802. }
  1803. /** If the network-status list has changed since the last time we called this
  1804. * function, update the status of every router from the network-status list.
  1805. */
  1806. void
  1807. routers_update_all_from_networkstatus(void)
  1808. {
  1809. #define SELF_OPINION_INTERVAL 90*60
  1810. static int have_warned_about_unverified_status = 0;
  1811. static int have_warned_about_old_version = 0;
  1812. static int have_warned_about_new_version = 0;
  1813. routerinfo_t *me;
  1814. time_t now;
  1815. if (!routerlist || !networkstatus_list ||
  1816. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  1817. return;
  1818. now = time(NULL);
  1819. if (networkstatus_list_has_changed)
  1820. routerstatus_list_update_from_networkstatus(now);
  1821. routers_update_status_from_networkstatus(routerlist->routers, 0);
  1822. me = router_get_my_routerinfo();
  1823. if (me && !have_warned_about_unverified_status) {
  1824. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
  1825. routerstatus_t *rs;
  1826. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1827. {
  1828. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  1829. continue;
  1830. ++n_recent;
  1831. if (!(rs = networkstatus_find_entry(ns, me->identity_digest)))
  1832. continue;
  1833. ++n_listing;
  1834. if (rs->is_valid)
  1835. ++n_valid;
  1836. if (rs->is_named)
  1837. ++n_named;
  1838. });
  1839. if (n_recent >= 2 && n_listing >= 2) {
  1840. if (n_valid <= n_recent/2) {
  1841. log_fn(LOG_WARN, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
  1842. n_recent-n_valid, n_recent);
  1843. have_warned_about_unverified_status = 1;
  1844. } else if (n_named <= n_recent/2) {
  1845. log_fn(LOG_WARN, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
  1846. n_recent-n_valid, n_recent);
  1847. have_warned_about_unverified_status = 1;
  1848. }
  1849. }
  1850. }
  1851. helper_nodes_set_status_from_directory();
  1852. if (!have_warned_about_old_version) {
  1853. int n_recent = 0;
  1854. int n_recommended = 0;
  1855. int is_server = server_mode(get_options());
  1856. version_status_t consensus = VS_RECOMMENDED;
  1857. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1858. {
  1859. version_status_t vs;
  1860. if (!ns->recommends_versions ||
  1861. ns->received_on + SELF_OPINION_INTERVAL < now )
  1862. continue;
  1863. vs = tor_version_is_obsolete(
  1864. VERSION, is_server ? ns->server_versions : ns->client_versions);
  1865. if (vs == VS_RECOMMENDED)
  1866. ++n_recommended;
  1867. if (n_recent++ == 0) {
  1868. consensus = vs;
  1869. } else if (consensus != vs) {
  1870. consensus = version_status_join(consensus, vs);
  1871. }
  1872. });
  1873. if (n_recent > 2 && n_recommended < n_recent/2) {
  1874. if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
  1875. if (!have_warned_about_new_version) {
  1876. log_fn(LOG_NOTICE, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
  1877. VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  1878. n_recent-n_recommended, n_recent);
  1879. have_warned_about_new_version = 1;
  1880. }
  1881. } else {
  1882. log_fn(LOG_NOTICE, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
  1883. VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
  1884. n_recent-n_recommended, n_recent);
  1885. have_warned_about_old_version = 1;
  1886. }
  1887. } else {
  1888. log_fn(LOG_INFO, "%d/%d recent directories think my version is ok.",
  1889. n_recommended, n_recent);
  1890. }
  1891. }
  1892. routerstatus_list_has_changed = 0;
  1893. }
  1894. /** Allow any network-status newer than this to influence our view of who's
  1895. * running. */
  1896. #define DEFAULT_RUNNING_INTERVAL 60*60
  1897. /** If possible, always allow at least this many network-statuses to influence
  1898. * our view of who's running. */
  1899. #define MIN_TO_INFLUENCE_RUNNING 3
  1900. /** Change the is_recent field of each member of networkstatus_list so that
  1901. * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
  1902. * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
  1903. * others are recent. Set networkstatus_list_has_changed if anything happeed.
  1904. */
  1905. void
  1906. networkstatus_list_update_recent(time_t now)
  1907. {
  1908. int n_statuses, n_recent, changed, i;
  1909. char published[ISO_TIME_LEN+1];
  1910. if (!networkstatus_list)
  1911. return;
  1912. n_statuses = smartlist_len(networkstatus_list);
  1913. n_recent = 0;
  1914. changed = 0;
  1915. for (i=n_statuses-1; i >= 0; --i) {
  1916. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  1917. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  1918. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  1919. if (!ns->is_recent) {
  1920. format_iso_time(published, ns->published_on);
  1921. log_fn(LOG_NOTICE,
  1922. "Networkstatus from %s:%d (published %s) is now \"recent\"",
  1923. ns->source_address, ns->source_dirport, published);
  1924. changed = 1;
  1925. }
  1926. ns->is_recent = 1;
  1927. ++n_recent;
  1928. } else {
  1929. if (ns->is_recent) {
  1930. format_iso_time(published, ns->published_on);
  1931. log_fn(LOG_NOTICE,
  1932. "Networkstatus from %s:%d (published %s) is no longer \"recent\"",
  1933. ns->source_address, ns->source_dirport, published);
  1934. changed = 1;
  1935. ns->is_recent = 0;
  1936. }
  1937. }
  1938. }
  1939. if (changed)
  1940. networkstatus_list_has_changed = 1;
  1941. }
  1942. /** Update our view of router status (as stored in routerstatus_list) from
  1943. * the current set of network status documents (as stored in networkstatus_list).
  1944. * Do nothing unless the network status list has changed since the last time
  1945. * this function was called.
  1946. */
  1947. static void
  1948. routerstatus_list_update_from_networkstatus(time_t now)
  1949. {
  1950. int n_trusted, n_statuses, n_recent=0, n_naming=0;
  1951. int n_distinct = 0;
  1952. int i;
  1953. int *index, *size;
  1954. networkstatus_t **networkstatus;
  1955. smartlist_t *result;
  1956. strmap_t *name_map;
  1957. char conflict[DIGEST_LEN];
  1958. networkstatus_list_update_recent(now);
  1959. if (!networkstatus_list_has_changed)
  1960. return;
  1961. if (!networkstatus_list)
  1962. networkstatus_list = smartlist_create();
  1963. if (!routerstatus_list)
  1964. routerstatus_list = smartlist_create();
  1965. if (!trusted_dir_servers)
  1966. trusted_dir_servers = smartlist_create();
  1967. n_trusted = smartlist_len(trusted_dir_servers);
  1968. n_statuses = smartlist_len(networkstatus_list);
  1969. if (n_statuses < (n_trusted/2)+1) {
  1970. /* Not enough statuses to adjust status. */
  1971. log_fn(LOG_NOTICE,"Not enough statuses to update router status list. (%d/%d)",
  1972. n_statuses, n_trusted);
  1973. return;
  1974. }
  1975. log_fn(LOG_NOTICE, "rebuilding router status list.");
  1976. index = tor_malloc(sizeof(int)*n_statuses);
  1977. size = tor_malloc(sizeof(int)*n_statuses);
  1978. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  1979. for (i = 0; i < n_statuses; ++i) {
  1980. index[i] = 0;
  1981. networkstatus[i] = smartlist_get(networkstatus_list, i);
  1982. size[i] = smartlist_len(networkstatus[i]->entries);
  1983. if (networkstatus[i]->binds_names)
  1984. ++n_naming;
  1985. if (networkstatus[i]->is_recent)
  1986. ++n_recent;
  1987. }
  1988. name_map = strmap_new();
  1989. memset(conflict, 0xff, sizeof(conflict));
  1990. for (i = 0; i < n_statuses; ++i) {
  1991. if (!networkstatus[i]->binds_names)
  1992. continue;
  1993. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  1994. {
  1995. const char *other_digest;
  1996. if (!rs->is_named)
  1997. continue;
  1998. other_digest = strmap_get_lc(name_map, rs->nickname);
  1999. if (!other_digest)
  2000. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  2001. else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  2002. other_digest != conflict) {
  2003. /*XXXX011 rate-limit this?*/
  2004. log_fn(LOG_WARN,
  2005. "Naming authorities disagree about which key goes with %s.",
  2006. rs->nickname);
  2007. strmap_set_lc(name_map, rs->nickname, conflict);
  2008. }
  2009. });
  2010. }
  2011. result = smartlist_create();
  2012. /* Iterate through all of the sorted routerstatus lists in step.
  2013. * Invariants:
  2014. * - For 0 <= i < n_statuses: index[i] is an index into
  2015. * networkstatus[i]->entries, which has size[i] elements.
  2016. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  2017. * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
  2018. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  2019. *
  2020. * (That is, the indices are always advanced past lower digest before
  2021. * higher.)
  2022. */
  2023. while (1) {
  2024. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  2025. const char *the_name = NULL;
  2026. local_routerstatus_t *rs_out, *rs_old;
  2027. routerstatus_t *rs, *most_recent;
  2028. networkstatus_t *ns;
  2029. const char *lowest = NULL;
  2030. /* Find out which of the digests appears first. */
  2031. for (i = 0; i < n_statuses; ++i) {
  2032. if (index[i] < size[i]) {
  2033. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  2034. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  2035. lowest = rs->identity_digest;
  2036. }
  2037. }
  2038. if (!lowest) {
  2039. /* We're out of routers. Great! */
  2040. break;
  2041. }
  2042. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  2043. * match "lowest" are next in order. Iterate over them, incrementing those
  2044. * index[i] as we go. */
  2045. ++n_distinct;
  2046. most_recent = NULL;
  2047. for (i = 0; i < n_statuses; ++i) {
  2048. if (index[i] >= size[i])
  2049. continue;
  2050. ns = networkstatus[i];
  2051. rs = smartlist_get(ns->entries, index[i]);
  2052. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  2053. continue;
  2054. ++index[i];
  2055. ++n_listing;
  2056. if (!most_recent || rs->published_on > most_recent->published_on)
  2057. most_recent = rs;
  2058. if (rs->is_named && ns->binds_names) {
  2059. if (!the_name)
  2060. the_name = rs->nickname;
  2061. if (!strcasecmp(rs->nickname, the_name)) {
  2062. ++n_named;
  2063. } else if (strcmp(the_name,"**mismatch**")) {
  2064. char hd[HEX_DIGEST_LEN+1];
  2065. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  2066. log_fn(LOG_WARN, "Naming authorities disagree about nicknames for $%s",
  2067. hd);
  2068. the_name = "**mismatch**";
  2069. }
  2070. }
  2071. if (rs->is_valid)
  2072. ++n_valid;
  2073. if (rs->is_running && ns->is_recent)
  2074. ++n_running;
  2075. }
  2076. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  2077. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  2078. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  2079. rs_out->n_download_failures = rs_old->n_download_failures;
  2080. rs_out->next_attempt_at = rs_old->next_attempt_at;
  2081. }
  2082. smartlist_add(result, rs_out);
  2083. log_fn(LOG_DEBUG, "Router '%s' is listed by %d/%d directories, "
  2084. "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
  2085. "think it's running.",
  2086. rs_out->status.nickname,
  2087. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  2088. n_running, n_recent);
  2089. rs_out->status.is_named = 0;
  2090. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  2091. const char *d = strmap_get_lc(name_map, the_name);
  2092. if (d && d != conflict)
  2093. rs_out->status.is_named = 1;
  2094. }
  2095. if (rs_out->status.is_named)
  2096. strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
  2097. rs_out->status.is_valid = n_valid > n_statuses/2;
  2098. rs_out->status.is_running = n_running > n_recent/2;
  2099. }
  2100. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2101. local_routerstatus_free(rs));
  2102. smartlist_free(routerstatus_list);
  2103. routerstatus_list = result;
  2104. tor_free(networkstatus);
  2105. tor_free(index);
  2106. tor_free(size);
  2107. strmap_free(name_map, NULL);
  2108. networkstatus_list_has_changed = 0;
  2109. routerstatus_list_has_changed = 1;
  2110. }
  2111. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  2112. * is_named, is_verified, and is_running fields according to our current
  2113. * networkstatus_t documents. */
  2114. void
  2115. routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures)
  2116. {
  2117. trusted_dir_server_t *ds;
  2118. local_routerstatus_t *rs;
  2119. or_options_t *options = get_options();
  2120. int authdir = options->AuthoritativeDir;
  2121. int namingdir = options->NamingAuthoritativeDir;
  2122. if (!routerstatus_list)
  2123. return;
  2124. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  2125. {
  2126. rs = router_get_combined_status_by_digest(router->identity_digest);
  2127. ds = router_get_trusteddirserver_by_digest(router->identity_digest);
  2128. if (!rs)
  2129. continue;
  2130. if (reset_failures) {
  2131. rs->n_download_failures = 0;
  2132. rs->next_attempt_at = 0;
  2133. }
  2134. if (!namingdir)
  2135. router->is_named = rs->status.is_named;
  2136. if (!authdir) {
  2137. /* If we're an authdir, don't believe others. */
  2138. router->is_verified = rs->status.is_valid;
  2139. router->is_running = rs->status.is_running;
  2140. if (router->is_running && ds) {
  2141. /* XXXX011 NM Hm. What about authorities? When do they reset
  2142. * n_networkstatus_failures? */
  2143. ds->n_networkstatus_failures = 0;
  2144. }
  2145. }
  2146. });
  2147. }
  2148. /** Return new list of ID fingerprints for superseded routers. A router is
  2149. * superseded if any network-status has a router with a different digest
  2150. * published more recently, or if it is listed in the network-status but not
  2151. * in the router list.
  2152. */
  2153. static smartlist_t *
  2154. router_list_downloadable(void)
  2155. {
  2156. #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
  2157. int n_conns, i, n_downloadable = 0;
  2158. int n_uptodate=0,n_skip_old=0;
  2159. connection_t **carray;
  2160. smartlist_t *superseded = smartlist_create();
  2161. smartlist_t *downloading;
  2162. time_t now = time(NULL);
  2163. int mirror = server_mode(get_options()) && get_options()->DirPort;
  2164. if (!routerstatus_list)
  2165. return superseded;
  2166. get_connection_array(&carray, &n_conns);
  2167. routerstatus_list_update_from_networkstatus(now);
  2168. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2169. {
  2170. if (rs->next_attempt_at < now) {
  2171. rs->should_download = 1;
  2172. ++n_downloadable;
  2173. } else {
  2174. /*
  2175. char fp[HEX_DIGEST_LEN+1];
  2176. base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
  2177. log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
  2178. (int)(rs->next_attempt_at-now));
  2179. */
  2180. rs->should_download = 0;
  2181. }
  2182. });
  2183. downloading = smartlist_create();
  2184. for (i = 0; i < n_conns; ++i) {
  2185. connection_t *conn = carray[i];
  2186. if (conn->type == CONN_TYPE_DIR &&
  2187. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  2188. !conn->marked_for_close) {
  2189. if (!strcmpstart(conn->requested_resource, "all"))
  2190. n_downloadable = 0;
  2191. dir_split_resource_into_fingerprints(conn->requested_resource,
  2192. downloading, NULL);
  2193. }
  2194. }
  2195. /*
  2196. log_fn(LOG_NOTICE, "%d downloads already in progress",
  2197. smartlist_len(downloading));
  2198. smartlist_sort_strings(downloading);
  2199. */
  2200. if (n_downloadable) {
  2201. SMARTLIST_FOREACH(downloading, const char *, dl,
  2202. {
  2203. char d[DIGEST_LEN];
  2204. local_routerstatus_t *rs;
  2205. base16_decode(d, DIGEST_LEN, dl, strlen(dl));
  2206. if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
  2207. rs->should_download = 0;
  2208. --n_downloadable;
  2209. // log_fn(LOG_NOTICE, "%s is in-progress; not fetching", dl);
  2210. }
  2211. });
  2212. }
  2213. SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
  2214. smartlist_free(downloading);
  2215. if (!n_downloadable)
  2216. return superseded;
  2217. if (routerlist) {
  2218. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  2219. {
  2220. local_routerstatus_t *rs;
  2221. if (!(rs = router_get_combined_status_by_digest(ri->identity_digest)) ||
  2222. !rs->should_download) {
  2223. // log_fn(LOG_NOTICE, "No status for %s", fp);
  2224. continue;
  2225. }
  2226. /* Change this "or" to be an "and" once dirs generate hashes right.
  2227. * Remove the version check once older versions are uncommon.
  2228. * XXXXX. NM */
  2229. if (!memcmp(ri->signed_descriptor_digest, rs->status.descriptor_digest,
  2230. DIGEST_LEN) ||
  2231. rs->status.published_on <= ri->published_on) {
  2232. ++n_uptodate;
  2233. rs->should_download = 0;
  2234. --n_downloadable;
  2235. } else if (!mirror &&
  2236. ri->platform &&
  2237. !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
  2238. ri->published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
  2239. /* Same digest, or date is up-to-date, or we have a comparatively recent
  2240. * server with an old version.
  2241. * No need to download it. */
  2242. // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
  2243. ++n_skip_old;
  2244. rs->should_download = 0;
  2245. --n_downloadable;
  2246. } /* else {
  2247. char t1[ISO_TIME_LEN+1];
  2248. char t2[ISO_TIME_LEN+1];
  2249. format_iso_time(t1, rs->satus.published_on);
  2250. format_iso_time(t2, ri->published_on);
  2251. log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
  2252. ri->nickname,
  2253. !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
  2254. DIGEST_LEN),
  2255. rs->published_on < ri->published_on,
  2256. t1, t2);
  2257. } */
  2258. });
  2259. }
  2260. if (n_skip_old)
  2261. log_fn(LOG_INFO, "Skipped %d updatable pre-0.1.1.6 servers.", n_skip_old);
  2262. if (!n_downloadable)
  2263. return superseded;
  2264. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2265. {
  2266. if (rs->should_download) {
  2267. char *fp = tor_malloc(HEX_DIGEST_LEN+1);
  2268. base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
  2269. smartlist_add(superseded, fp);
  2270. }
  2271. });
  2272. return superseded;
  2273. }
  2274. /** Initiate new router downloads as needed.
  2275. *
  2276. * We only allow one router descriptor download at a time.
  2277. * If we have less than two network-status documents, we ask
  2278. * a directory for "all descriptors."
  2279. * Otherwise, we ask for all descriptors that we think are different
  2280. * from what we have.
  2281. */
  2282. void
  2283. update_router_descriptor_downloads(time_t now)
  2284. {
  2285. #define MAX_DL_PER_REQUEST 128
  2286. #define MIN_DL_PER_REQUEST 4
  2287. #define MIN_REQUESTS 3
  2288. #define MAX_DL_TO_DELAY 16
  2289. #define MAX_INTERVAL_WITHOUT_REQUEST 10*60
  2290. smartlist_t *downloadable = NULL;
  2291. int get_all = 0;
  2292. int mirror = server_mode(get_options()) && get_options()->DirPort;
  2293. static time_t last_download_attempted = 0;
  2294. if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
  2295. get_all = 1;
  2296. if (get_all) {
  2297. log_fn(LOG_NOTICE, "Launching request for all routers");
  2298. last_download_attempted = now;
  2299. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
  2300. return;
  2301. }
  2302. downloadable = router_list_downloadable();
  2303. if (smartlist_len(downloadable) >= MAX_DL_TO_DELAY ||
  2304. (smartlist_len(downloadable) &&
  2305. (mirror ||
  2306. last_download_attempted + MAX_INTERVAL_WITHOUT_REQUEST < now))) {
  2307. int i, j, n, n_per_request=MAX_DL_PER_REQUEST;
  2308. size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
  2309. char *resource = tor_malloc(r_len);
  2310. n = smartlist_len(downloadable);
  2311. if (! mirror) {
  2312. n_per_request = (n+MIN_REQUESTS-1) / MIN_REQUESTS;
  2313. if (n_per_request > MAX_DL_PER_REQUEST)
  2314. n_per_request = MAX_DL_PER_REQUEST;
  2315. if (n_per_request < MIN_DL_PER_REQUEST)
  2316. n_per_request = MIN_DL_PER_REQUEST;
  2317. }
  2318. log_fn(LOG_NOTICE, "Launching %d request%s for %d router%s, %d at a time",
  2319. (n+n_per_request-1)/n_per_request, n>n_per_request?"s":"",
  2320. n, n>1?"s":"", n_per_request);
  2321. for (i=0; i < n; i += n_per_request) {
  2322. char *cp = resource;
  2323. memcpy(resource, "fp/", 3);
  2324. cp = resource + 3;
  2325. for (j=i; j < i+n_per_request && j < n; ++j) {
  2326. memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
  2327. cp += HEX_DIGEST_LEN;
  2328. *cp++ = '+';
  2329. }
  2330. memcpy(cp-1, ".z", 3);
  2331. last_download_attempted = now;
  2332. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
  2333. }
  2334. tor_free(resource);
  2335. }
  2336. SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
  2337. smartlist_free(downloadable);
  2338. }
  2339. /** Return true iff we have enough networkstatus and router information to
  2340. * start building circuits. Right now, this means "at least 2 networkstatus
  2341. * documents, and at least 1/4 of expected routers." */
  2342. int
  2343. router_have_minimum_dir_info(void)
  2344. {
  2345. int tot = 0, avg;
  2346. if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
  2347. !routerlist)
  2348. return 0;
  2349. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2350. tot += smartlist_len(ns->entries));
  2351. avg = tot / smartlist_len(networkstatus_list);
  2352. return smartlist_len(routerlist->routers) > (avg/4);
  2353. }
  2354. /** Reset the descriptor download failure count on all routers, so that we
  2355. * can retry any long-failed routers immediately.
  2356. */
  2357. void
  2358. router_reset_descriptor_download_failures(void)
  2359. {
  2360. if (!routerstatus_list)
  2361. return;
  2362. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2363. {
  2364. rs->n_download_failures = 0;
  2365. rs->next_attempt_at = 0;
  2366. });
  2367. }