routerlist.c 97 KB

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