routerlist.c 111 KB

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