routerlist.c 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerlist_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file routerlist.c
  10. * \brief Code to
  11. * maintain and access the global list of routerinfos for known
  12. * servers.
  13. **/
  14. #include "or.h"
  15. /****************************************************************************/
  16. /* static function prototypes */
  17. static routerstatus_t *router_pick_directory_server_impl(int requireother,
  18. int fascistfirewall,
  19. int for_v2_directory);
  20. static routerstatus_t *router_pick_trusteddirserver_impl(
  21. int need_v1_authority, int requireother, int fascistfirewall);
  22. static void mark_all_trusteddirservers_up(void);
  23. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  24. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  25. static void routerstatus_list_update_from_networkstatus(time_t now);
  26. static void local_routerstatus_free(local_routerstatus_t *rs);
  27. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  28. static void update_networkstatus_cache_downloads(time_t now);
  29. static void update_networkstatus_client_downloads(time_t now);
  30. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  31. static void routerlist_assert_ok(routerlist_t *rl);
  32. static int have_tried_downloading_all_statuses(int n_failures);
  33. static routerstatus_t *networkstatus_find_entry(networkstatus_t *ns,
  34. const char *digest);
  35. static local_routerstatus_t *router_get_combined_status_by_nickname(
  36. const char *nickname,
  37. int warn_if_unnamed);
  38. static void update_router_have_minimum_dir_info(void);
  39. static void router_dir_info_changed(void);
  40. /****************************************************************************/
  41. /** Global list of a trusted_dir_server_t object for each trusted directory
  42. * server. */
  43. static smartlist_t *trusted_dir_servers = NULL;
  44. /** Global list of all of the routers that we know about. */
  45. static routerlist_t *routerlist = NULL;
  46. /** Global list of all of the current network_status documents that we know
  47. * about. This list is kept sorted by published_on. */
  48. static smartlist_t *networkstatus_list = NULL;
  49. /** Global list of local_routerstatus_t for each router, known or unknown.
  50. * Kept sorted by digest. */
  51. static smartlist_t *routerstatus_list = NULL;
  52. /** Map from lowercase nickname to digest of named server, if any. */
  53. static strmap_t *named_server_map = NULL;
  54. /** True iff any member of networkstatus_list has changed since the last time
  55. * we called routerstatus_list_update_from_networkstatus(). */
  56. static int networkstatus_list_has_changed = 0;
  57. /** True iff any element of routerstatus_list has changed since the last
  58. * time we called routers_update_all_from_networkstatus().*/
  59. static int routerstatus_list_has_changed = 0;
  60. /** List of strings for nicknames we've already warned about and that are
  61. * still unknown / unavailable. */
  62. static smartlist_t *warned_nicknames = NULL;
  63. /** List of strings for nicknames or fingerprints we've already warned about
  64. * and that are still conflicted. */
  65. static smartlist_t *warned_conflicts = NULL;
  66. /** The last time we tried to download any routerdesc, or 0 for "never". We
  67. * use this to rate-limit download attempts when the number of routerdescs to
  68. * download is low. */
  69. static time_t last_routerdesc_download_attempted = 0;
  70. /** The last time we tried to download a networkstatus, or 0 for "never". We
  71. * use this to rate-limit download attempts for directory caches (including
  72. * mirrors). Clients don't use this now. */
  73. static time_t last_networkstatus_download_attempted = 0;
  74. /** True iff we have logged a warning about this OR not being valid or
  75. * not being named. */
  76. static int have_warned_about_invalid_status = 0;
  77. /** True iff we have logged a warning about this OR's version being older than
  78. * listed by the authorities */
  79. static int have_warned_about_old_version = 0;
  80. /** True iff we have logged a warning about this OR's version being newer than
  81. * listed by the authorities */
  82. static int have_warned_about_new_version = 0;
  83. /** Repopulate our list of network_status_t objects from the list cached on
  84. * disk. Return 0 on success, -1 on failure. */
  85. int
  86. router_reload_networkstatus(void)
  87. {
  88. char filename[512];
  89. struct stat st;
  90. smartlist_t *entries;
  91. char *s;
  92. tor_assert(get_options()->DataDirectory);
  93. if (!networkstatus_list)
  94. networkstatus_list = smartlist_create();
  95. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  96. get_options()->DataDirectory);
  97. entries = tor_listdir(filename);
  98. SMARTLIST_FOREACH(entries, const char *, fn, {
  99. char buf[DIGEST_LEN];
  100. if (strlen(fn) != HEX_DIGEST_LEN ||
  101. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  102. log_info(LD_DIR,
  103. "Skipping cached-status file with unexpected name \"%s\"",fn);
  104. continue;
  105. }
  106. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  107. get_options()->DataDirectory, fn);
  108. s = read_file_to_str(filename, 0);
  109. if (s) {
  110. stat(filename, &st);
  111. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  112. log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
  113. }
  114. tor_free(s);
  115. }
  116. });
  117. SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
  118. smartlist_free(entries);
  119. networkstatus_list_clean(time(NULL));
  120. routers_update_all_from_networkstatus();
  121. return 0;
  122. }
  123. /* Router descriptor storage.
  124. *
  125. * Routerdescs are stored in a big file, named "cached-routers". As new
  126. * routerdescs arrive, we append them to a journal file named
  127. * "cached-routers.new".
  128. *
  129. * From time to time, we replace "cached-routers" with a new file containing
  130. * only the live, non-superseded descriptors, and clear cached-routers.new.
  131. *
  132. * On startup, we read both files.
  133. */
  134. /** The size of the router log, in bytes. */
  135. static size_t router_journal_len = 0;
  136. /** The size of the router store, in bytes. */
  137. static size_t router_store_len = 0;
  138. /** Total bytes dropped since last rebuild. */
  139. static size_t router_bytes_dropped = 0;
  140. /** Helper: return 1 iff the router log is so big we want to rebuild the
  141. * store. */
  142. static int
  143. router_should_rebuild_store(void)
  144. {
  145. if (router_store_len > (1<<16))
  146. return (router_journal_len > router_store_len / 2 ||
  147. router_bytes_dropped > router_store_len / 2);
  148. else
  149. return router_journal_len > (1<<15);
  150. }
  151. /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
  152. * journal. */
  153. static int
  154. router_append_to_journal(signed_descriptor_t *desc)
  155. {
  156. or_options_t *options = get_options();
  157. size_t fname_len = strlen(options->DataDirectory)+32;
  158. char *fname = tor_malloc(fname_len);
  159. const char *body = signed_descriptor_get_body(desc);
  160. size_t len = desc->signed_descriptor_len;
  161. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  162. options->DataDirectory);
  163. tor_assert(len == strlen(body));
  164. if (append_bytes_to_file(fname, body, len, 1)) {
  165. log_warn(LD_FS, "Unable to store router descriptor");
  166. tor_free(fname);
  167. return -1;
  168. }
  169. desc->saved_location = SAVED_IN_JOURNAL;
  170. desc->saved_offset = router_journal_len;
  171. tor_free(fname);
  172. router_journal_len += len;
  173. return 0;
  174. }
  175. static int
  176. _compare_old_routers_by_age(const void **_a, const void **_b)
  177. {
  178. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  179. return r1->published_on - r2->published_on;
  180. }
  181. static int
  182. _compare_routers_by_age(const void **_a, const void **_b)
  183. {
  184. const routerinfo_t *r1 = *_a, *r2 = *_b;
  185. return r1->cache_info.published_on - r2->cache_info.published_on;
  186. }
  187. /** If the journal is too long, or if <b>force</b> is true, then atomically
  188. * replace the router store with the routers currently in our routerlist, and
  189. * clear the journal. Return 0 on success, -1 on failure.
  190. */
  191. static int
  192. router_rebuild_store(int force)
  193. {
  194. size_t len = 0;
  195. or_options_t *options;
  196. size_t fname_len;
  197. smartlist_t *chunk_list = NULL;
  198. char *fname = NULL;
  199. int r = -1, i;
  200. off_t offset = 0;
  201. smartlist_t *old_routers, *routers;
  202. if (!force && !router_should_rebuild_store())
  203. return 0;
  204. if (!routerlist)
  205. return 0;
  206. /* Don't save deadweight. */
  207. routerlist_remove_old_routers();
  208. log_info(LD_DIR, "Rebuilding router descriptor cache");
  209. options = get_options();
  210. fname_len = strlen(options->DataDirectory)+32;
  211. fname = tor_malloc(fname_len);
  212. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  213. chunk_list = smartlist_create();
  214. old_routers = smartlist_create();
  215. smartlist_add_all(old_routers, routerlist->old_routers);
  216. smartlist_sort(old_routers, _compare_old_routers_by_age);
  217. routers = smartlist_create();
  218. smartlist_add_all(routers, routerlist->routers);
  219. smartlist_sort(routers, _compare_routers_by_age);
  220. for (i = 0; i < 2; ++i) {
  221. smartlist_t *lst = smartlist_create();
  222. /* We sort the routers by age to enhance locality on disk. */
  223. if (i==0)
  224. lst = old_routers;
  225. else
  226. lst = routers;
  227. /* Now, add the appropriate members to chunk_list */
  228. SMARTLIST_FOREACH(lst, void *, ptr,
  229. {
  230. signed_descriptor_t *sd = (i==0) ?
  231. ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
  232. sized_chunk_t *c;
  233. const char *body = signed_descriptor_get_body(sd);
  234. if (!body) {
  235. log_warn(LD_BUG, "Bug! No descriptor available for router.");
  236. smartlist_free(lst);
  237. goto done;
  238. }
  239. c = tor_malloc(sizeof(sized_chunk_t));
  240. c->bytes = body;
  241. c->len = sd->signed_descriptor_len;
  242. smartlist_add(chunk_list, c);
  243. });
  244. }
  245. if (write_chunks_to_file(fname, chunk_list, 1)<0) {
  246. log_warn(LD_FS, "Error writing router store to disk.");
  247. goto done;
  248. }
  249. /* Our mmap is now invalid. */
  250. if (routerlist->mmap_descriptors) {
  251. tor_munmap_file(routerlist->mmap_descriptors);
  252. routerlist->mmap_descriptors = tor_mmap_file(fname);
  253. if (! routerlist->mmap_descriptors)
  254. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  255. }
  256. offset = 0;
  257. for (i = 0; i < 2; ++i) {
  258. smartlist_t *lst = (i == 0) ? old_routers : routers;
  259. SMARTLIST_FOREACH(lst, void *, ptr,
  260. {
  261. signed_descriptor_t *sd = (i==0) ?
  262. ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
  263. sd->saved_location = SAVED_IN_CACHE;
  264. if (routerlist->mmap_descriptors) {
  265. tor_free(sd->signed_descriptor_body); // sets it to null
  266. sd->saved_offset = offset;
  267. }
  268. offset += sd->signed_descriptor_len;
  269. signed_descriptor_get_body(sd);
  270. });
  271. }
  272. smartlist_free(old_routers);
  273. smartlist_free(routers);
  274. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  275. options->DataDirectory);
  276. write_str_to_file(fname, "", 1);
  277. r = 0;
  278. router_store_len = len;
  279. router_journal_len = 0;
  280. router_bytes_dropped = 0;
  281. done:
  282. tor_free(fname);
  283. if (chunk_list) {
  284. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  285. smartlist_free(chunk_list);
  286. }
  287. return r;
  288. }
  289. /* Load all cached router descriptors from the store. Return 0 on success and
  290. * -1 on failure.
  291. */
  292. int
  293. router_reload_router_list(void)
  294. {
  295. or_options_t *options = get_options();
  296. size_t fname_len = strlen(options->DataDirectory)+32;
  297. char *fname = tor_malloc(fname_len), *contents;
  298. struct stat st;
  299. if (!routerlist)
  300. router_get_routerlist(); /* mallocs and inits it in place */
  301. router_journal_len = router_store_len = 0;
  302. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  303. if (routerlist->mmap_descriptors) /* get rid of it first */
  304. tor_munmap_file(routerlist->mmap_descriptors);
  305. routerlist->mmap_descriptors = tor_mmap_file(fname);
  306. if (routerlist->mmap_descriptors) {
  307. router_store_len = routerlist->mmap_descriptors->size;
  308. router_load_routers_from_string(routerlist->mmap_descriptors->data,
  309. SAVED_IN_CACHE, NULL);
  310. }
  311. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  312. options->DataDirectory);
  313. contents = read_file_to_str(fname, 1);
  314. if (contents) {
  315. stat(fname, &st);
  316. router_load_routers_from_string(contents,
  317. SAVED_IN_JOURNAL, NULL);
  318. tor_free(contents);
  319. }
  320. tor_free(fname);
  321. if (router_journal_len) {
  322. /* Always clear the journal on startup.*/
  323. router_rebuild_store(1);
  324. } else {
  325. /* Don't cache expired routers. (This is in an else because
  326. * router_rebuild_store() also calls remove_old_routers().) */
  327. routerlist_remove_old_routers();
  328. }
  329. return 0;
  330. }
  331. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  332. * known trusted dirservers. Callers must not modify the list or its
  333. * contents.
  334. */
  335. smartlist_t *
  336. router_get_trusted_dir_servers(void)
  337. {
  338. if (!trusted_dir_servers)
  339. trusted_dir_servers = smartlist_create();
  340. return trusted_dir_servers;
  341. }
  342. /** Try to find a running dirserver. If there are no running dirservers
  343. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  344. * set all the authoritative ones as running again, and pick one;
  345. * if there are then no dirservers at all in our routerlist,
  346. * reload the routerlist and try one last time. If for_runningrouters is
  347. * true, then only pick a dirserver that can answer runningrouters queries
  348. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  349. * Don't pick an authority if any non-authority is viable.
  350. * Other args are as in router_pick_directory_server_impl().
  351. */
  352. routerstatus_t *
  353. router_pick_directory_server(int requireother,
  354. int fascistfirewall,
  355. int for_v2_directory,
  356. int retry_if_no_servers)
  357. {
  358. routerstatus_t *choice;
  359. if (!routerlist)
  360. return NULL;
  361. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  362. for_v2_directory);
  363. if (choice || !retry_if_no_servers)
  364. return choice;
  365. log_info(LD_DIR,
  366. "No reachable router entries for dirservers. "
  367. "Trying them all again.");
  368. /* mark all authdirservers as up again */
  369. mark_all_trusteddirservers_up();
  370. /* try again */
  371. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  372. for_v2_directory);
  373. if (choice)
  374. return choice;
  375. log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
  376. fascistfirewall ? "reachable" : "known");
  377. if (router_reload_router_list()) {
  378. return NULL;
  379. }
  380. /* give it one last try */
  381. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  382. for_v2_directory);
  383. return choice;
  384. }
  385. /** Return the trusted_dir_server_t for the directory authority whose identity
  386. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  387. */
  388. trusted_dir_server_t *
  389. router_get_trusteddirserver_by_digest(const char *digest)
  390. {
  391. if (!trusted_dir_servers)
  392. return NULL;
  393. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  394. {
  395. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  396. return ds;
  397. });
  398. return NULL;
  399. }
  400. /** Try to find a running trusted dirserver. If there are no running
  401. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  402. * set them all as running again, and try again.
  403. * If <b>need_v1_authority</b> is set, return only trusted servers
  404. * that are authorities for the V1 directory protocol.
  405. * Other args are as in router_pick_trusteddirserver_impl().
  406. */
  407. routerstatus_t *
  408. router_pick_trusteddirserver(int need_v1_authority,
  409. int requireother,
  410. int fascistfirewall,
  411. int retry_if_no_servers)
  412. {
  413. routerstatus_t *choice;
  414. choice = router_pick_trusteddirserver_impl(need_v1_authority,
  415. requireother, fascistfirewall);
  416. if (choice || !retry_if_no_servers)
  417. return choice;
  418. log_info(LD_DIR,
  419. "No trusted dirservers are reachable. Trying them all again.");
  420. mark_all_trusteddirservers_up();
  421. return router_pick_trusteddirserver_impl(need_v1_authority,
  422. requireother, fascistfirewall);
  423. }
  424. /** Pick a random running valid directory server/mirror from our
  425. * routerlist. Don't pick an authority if any non-authorities are viable.
  426. * If <b>fascistfirewall</b>,
  427. * make sure the router we pick is allowed by our firewall options.
  428. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  429. * choose a directory server new enough to support the v2 directory
  430. * functionality.
  431. */
  432. static routerstatus_t *
  433. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  434. int for_v2_directory)
  435. {
  436. routerstatus_t *result;
  437. smartlist_t *sl;
  438. smartlist_t *trusted;
  439. if (!routerstatus_list)
  440. return NULL;
  441. /* Find all the running dirservers we know about. */
  442. sl = smartlist_create();
  443. trusted = smartlist_create();
  444. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, _local_status,
  445. {
  446. routerstatus_t *status = &(_local_status->status);
  447. int is_trusted;
  448. if (!status->is_running || !status->dir_port || !status->is_valid)
  449. continue;
  450. if (requireother && router_digest_is_me(status->identity_digest))
  451. continue;
  452. if (fascistfirewall) {
  453. if (!fascist_firewall_allows_address_dir(status->addr, status->dir_port))
  454. continue;
  455. }
  456. is_trusted = router_digest_is_trusted_dir(status->identity_digest);
  457. if (for_v2_directory && !(status->is_v2_dir || is_trusted))
  458. continue;
  459. smartlist_add(is_trusted ? trusted : sl, status);
  460. });
  461. if (smartlist_len(sl))
  462. result = smartlist_choose(sl);
  463. else
  464. result = smartlist_choose(trusted);
  465. smartlist_free(sl);
  466. smartlist_free(trusted);
  467. return result;
  468. }
  469. /** Choose randomly from among the trusted dirservers that are up. If
  470. * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
  471. * firewall options. If <b>requireother</b>, it cannot be us. If
  472. * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
  473. * system.
  474. */
  475. static routerstatus_t *
  476. router_pick_trusteddirserver_impl(int need_v1_authority,
  477. int requireother, int fascistfirewall)
  478. {
  479. smartlist_t *sl;
  480. routerinfo_t *me;
  481. routerstatus_t *rs;
  482. sl = smartlist_create();
  483. me = router_get_my_routerinfo();
  484. if (!trusted_dir_servers)
  485. return NULL;
  486. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  487. {
  488. if (!d->is_running) continue;
  489. if (need_v1_authority && !d->is_v1_authority)
  490. continue;
  491. if (requireother && me && router_digest_is_me(d->digest))
  492. continue;
  493. if (fascistfirewall) {
  494. if (!fascist_firewall_allows_address_dir(d->addr, d->dir_port))
  495. continue;
  496. }
  497. smartlist_add(sl, &d->fake_status);
  498. });
  499. rs = smartlist_choose(sl);
  500. smartlist_free(sl);
  501. return rs;
  502. }
  503. /** Go through and mark the authoritative dirservers as up. */
  504. static void
  505. mark_all_trusteddirservers_up(void)
  506. {
  507. if (routerlist) {
  508. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  509. if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
  510. router->dir_port > 0) {
  511. router->is_running = 1;
  512. });
  513. }
  514. if (trusted_dir_servers) {
  515. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  516. {
  517. local_routerstatus_t *rs;
  518. dir->is_running = 1;
  519. dir->n_networkstatus_failures = 0;
  520. rs = router_get_combined_status_by_digest(dir->digest);
  521. if (rs)
  522. rs->status.is_running = 1;
  523. });
  524. }
  525. last_networkstatus_download_attempted = 0;
  526. router_dir_info_changed();
  527. }
  528. /** Reset all internal variables used to count failed downloads of network
  529. * status objects. */
  530. void
  531. router_reset_status_download_failures(void)
  532. {
  533. mark_all_trusteddirservers_up();
  534. }
  535. /** Look through the routerlist and identify routers that
  536. * advertise the same /16 network address as <b>router</b>.
  537. * Add each of them to <b>sl</b>.
  538. */
  539. static void
  540. routerlist_add_network_family(smartlist_t *sl, routerinfo_t *router)
  541. {
  542. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  543. {
  544. if (router != r &&
  545. (router->addr & 0xffff0000) == (r->addr & 0xffff0000))
  546. smartlist_add(sl, r);
  547. });
  548. }
  549. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  550. * This is used to make sure we don't pick siblings in a single path.
  551. */
  552. void
  553. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  554. {
  555. routerinfo_t *r;
  556. config_line_t *cl;
  557. /* First, add any routers with similar network addresses.
  558. * XXX It's possible this will be really expensive; we'll see. */
  559. routerlist_add_network_family(sl, router);
  560. if (!router->declared_family)
  561. return;
  562. /* Add every r such that router declares familyness with r, and r
  563. * declares familyhood with router. */
  564. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  565. {
  566. if (!(r = router_get_by_nickname(n, 0)))
  567. continue;
  568. if (!r->declared_family)
  569. continue;
  570. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  571. {
  572. if (router_nickname_matches(router, n2))
  573. smartlist_add(sl, r);
  574. });
  575. });
  576. /* If the user declared any families locally, honor those too. */
  577. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  578. if (router_nickname_is_in_list(router, cl->value)) {
  579. add_nickname_list_to_smartlist(sl, cl->value, 0, 1, 1);
  580. }
  581. }
  582. }
  583. /** Given a comma-and-whitespace separated list of nicknames, see which
  584. * nicknames in <b>list</b> name routers in our routerlist that are
  585. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  586. */
  587. void
  588. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
  589. int must_be_running,
  590. int warn_if_down, int warn_if_unnamed)
  591. {
  592. routerinfo_t *router;
  593. smartlist_t *nickname_list;
  594. int have_dir_info = router_have_minimum_dir_info();
  595. if (!list)
  596. return; /* nothing to do */
  597. tor_assert(sl);
  598. nickname_list = smartlist_create();
  599. if (!warned_nicknames)
  600. warned_nicknames = smartlist_create();
  601. smartlist_split_string(nickname_list, list, ",",
  602. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  603. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  604. int warned;
  605. if (!is_legal_nickname_or_hexdigest(nick)) {
  606. log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
  607. continue;
  608. }
  609. router = router_get_by_nickname(nick, warn_if_unnamed);
  610. warned = smartlist_string_isin(warned_nicknames, nick);
  611. if (router) {
  612. if (!must_be_running || router->is_running) {
  613. smartlist_add(sl,router);
  614. if (warned)
  615. smartlist_string_remove(warned_nicknames, nick);
  616. } else {
  617. if (!warned) {
  618. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
  619. "Nickname list includes '%s' which is known but down.",nick);
  620. smartlist_add(warned_nicknames, tor_strdup(nick));
  621. }
  622. }
  623. } else if (!router_get_combined_status_by_nickname(nick,warn_if_unnamed)) {
  624. if (!warned) {
  625. log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
  626. "Nickname list includes '%s' which isn't a known router.",nick);
  627. smartlist_add(warned_nicknames, tor_strdup(nick));
  628. }
  629. }
  630. });
  631. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  632. smartlist_free(nickname_list);
  633. }
  634. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  635. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  636. */
  637. static int
  638. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  639. {
  640. smartlist_t *nickname_list;
  641. int v = 0;
  642. if (!list)
  643. return 0; /* definitely not */
  644. tor_assert(router);
  645. nickname_list = smartlist_create();
  646. smartlist_split_string(nickname_list, list, ",",
  647. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  648. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  649. if (router_nickname_matches(router, cp)) {v=1;break;});
  650. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  651. smartlist_free(nickname_list);
  652. return v;
  653. }
  654. /** Add every router from our routerlist that is currently running to
  655. * <b>sl</b>, so that we can pick a node for a circuit.
  656. */
  657. static void
  658. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
  659. int need_uptime, int need_capacity,
  660. int need_guard)
  661. {
  662. if (!routerlist)
  663. return;
  664. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  665. {
  666. if (router->is_running &&
  667. router->purpose == ROUTER_PURPOSE_GENERAL &&
  668. (router->is_valid ||
  669. /* XXX this next part is wrong and should be fixed one day -RD */
  670. (allow_invalid &&
  671. !router_is_unreliable(router, need_uptime,
  672. need_capacity, need_guard)))) {
  673. /* If it's running, and either it's valid or we're ok picking
  674. * invalid routers and this one is suitable.
  675. */
  676. smartlist_add(sl, router);
  677. }
  678. });
  679. }
  680. /** Look through the routerlist until we find a router that has my key.
  681. Return it. */
  682. routerinfo_t *
  683. routerlist_find_my_routerinfo(void)
  684. {
  685. if (!routerlist)
  686. return NULL;
  687. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  688. {
  689. if (router_is_me(router))
  690. return router;
  691. });
  692. return NULL;
  693. }
  694. /** Find a router that's up, that has this IP address, and
  695. * that allows exit to this address:port, or return NULL if there
  696. * isn't a good one.
  697. */
  698. routerinfo_t *
  699. router_find_exact_exit_enclave(const char *address, uint16_t port)
  700. {
  701. uint32_t addr;
  702. struct in_addr in;
  703. if (!tor_inet_aton(address, &in))
  704. return NULL; /* it's not an IP already */
  705. addr = ntohl(in.s_addr);
  706. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  707. {
  708. if (router->is_running &&
  709. router->addr == addr &&
  710. compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  711. ADDR_POLICY_ACCEPTED)
  712. return router;
  713. });
  714. return NULL;
  715. }
  716. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  717. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  718. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  719. * bandwidth.
  720. */
  721. int
  722. router_is_unreliable(routerinfo_t *router, int need_uptime,
  723. int need_capacity, int need_guard)
  724. {
  725. if (need_uptime && !router->is_stable)
  726. return 1;
  727. if (need_capacity && !router->is_fast)
  728. return 1;
  729. if (need_guard && !router->is_possible_guard)
  730. return 1;
  731. return 0;
  732. }
  733. /** Remove from routerlist <b>sl</b> all routers that are not
  734. * sufficiently stable. */
  735. static void
  736. routerlist_sl_remove_unreliable_routers(smartlist_t *sl, int need_uptime,
  737. int need_capacity, int need_guard)
  738. {
  739. int i;
  740. routerinfo_t *router;
  741. for (i = 0; i < smartlist_len(sl); ++i) {
  742. router = smartlist_get(sl, i);
  743. if (router_is_unreliable(router, need_uptime,
  744. need_capacity, need_guard)) {
  745. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  746. // router->nickname);
  747. smartlist_del(sl, i--);
  748. }
  749. }
  750. }
  751. /** Return the smaller of the router's configured BandwidthRate
  752. * and its advertised capacity. */
  753. uint32_t
  754. router_get_advertised_bandwidth(routerinfo_t *router)
  755. {
  756. if (router->bandwidthcapacity < router->bandwidthrate)
  757. return router->bandwidthcapacity;
  758. return router->bandwidthrate;
  759. }
  760. #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
  761. /** Choose a random element of router list <b>sl</b>, weighted by
  762. * the advertised bandwidth of each router.
  763. */
  764. routerinfo_t *
  765. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  766. {
  767. int i;
  768. routerinfo_t *router;
  769. smartlist_t *bandwidths;
  770. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  771. uint32_t *p;
  772. /* First count the total bandwidth weight, and make a smartlist
  773. * of each value. */
  774. bandwidths = smartlist_create();
  775. for (i = 0; i < smartlist_len(sl); ++i) {
  776. router = smartlist_get(sl, i);
  777. this_bw = router_get_advertised_bandwidth(router);
  778. /* if they claim something huge, don't believe it */
  779. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  780. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  781. p = tor_malloc(sizeof(uint32_t));
  782. *p = this_bw;
  783. smartlist_add(bandwidths, p);
  784. total_bw += this_bw;
  785. }
  786. if (!total_bw) {
  787. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  788. smartlist_free(bandwidths);
  789. return smartlist_choose(sl);
  790. }
  791. /* Second, choose a random value from the bandwidth weights. */
  792. rand_bw = crypto_rand_int(total_bw);
  793. /* Last, count through sl until we get to the element we picked */
  794. tmp = 0;
  795. for (i=0; ; i++) {
  796. tor_assert(i < smartlist_len(sl));
  797. p = smartlist_get(bandwidths, i);
  798. tmp += *p;
  799. if (tmp >= rand_bw)
  800. break;
  801. }
  802. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  803. smartlist_free(bandwidths);
  804. return (routerinfo_t *)smartlist_get(sl, i);
  805. }
  806. /** Return a random running router from the routerlist. If any node
  807. * named in <b>preferred</b> is available, pick one of those. Never
  808. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  809. * <b>excludedsmartlist</b>, even if they are the only nodes
  810. * available. If <b>strict</b> is true, never pick any node besides
  811. * those in <b>preferred</b>.
  812. * If <b>need_uptime</b> is non-zero and any router has more than
  813. * a minimum uptime, return one of those.
  814. * If <b>need_capacity</b> is non-zero, weight your choice by the
  815. * advertised capacity of each router.
  816. */
  817. routerinfo_t *
  818. router_choose_random_node(const char *preferred,
  819. const char *excluded,
  820. smartlist_t *excludedsmartlist,
  821. int need_uptime, int need_capacity,
  822. int need_guard,
  823. int allow_invalid, int strict)
  824. {
  825. smartlist_t *sl, *excludednodes;
  826. routerinfo_t *choice = NULL;
  827. excludednodes = smartlist_create();
  828. add_nickname_list_to_smartlist(excludednodes,excluded,0,0,1);
  829. /* Try the preferred nodes first. Ignore need_uptime and need_capacity
  830. * and need_guard, since the user explicitly asked for these nodes. */
  831. if (preferred) {
  832. sl = smartlist_create();
  833. add_nickname_list_to_smartlist(sl,preferred,1,1,1);
  834. smartlist_subtract(sl,excludednodes);
  835. if (excludedsmartlist)
  836. smartlist_subtract(sl,excludedsmartlist);
  837. choice = smartlist_choose(sl);
  838. smartlist_free(sl);
  839. }
  840. if (!choice && !strict) {
  841. /* Then give up on our preferred choices: any node
  842. * will do that has the required attributes. */
  843. sl = smartlist_create();
  844. router_add_running_routers_to_smartlist(sl, allow_invalid,
  845. need_uptime, need_capacity,
  846. need_guard);
  847. smartlist_subtract(sl,excludednodes);
  848. if (excludedsmartlist)
  849. smartlist_subtract(sl,excludedsmartlist);
  850. routerlist_sl_remove_unreliable_routers(sl, need_uptime,
  851. need_capacity, need_guard);
  852. if (need_capacity)
  853. choice = routerlist_sl_choose_by_bandwidth(sl);
  854. else
  855. choice = smartlist_choose(sl);
  856. smartlist_free(sl);
  857. if (!choice && (need_uptime || need_capacity || need_guard)) {
  858. /* try once more -- recurse but with fewer restrictions. */
  859. log_info(LD_CIRC,
  860. "We couldn't find any live%s%s%s routers; falling back "
  861. "to list of all routers.",
  862. need_capacity?", fast":"",
  863. need_uptime?", stable":"",
  864. need_guard?", guard":"");
  865. choice = router_choose_random_node(
  866. NULL, excluded, excludedsmartlist, 0, 0, 0, allow_invalid, 0);
  867. }
  868. }
  869. smartlist_free(excludednodes);
  870. if (!choice)
  871. log_warn(LD_CIRC,
  872. "No available nodes when trying to choose node. Failing.");
  873. return choice;
  874. }
  875. /** Return true iff the digest of <b>router</b>'s identity key,
  876. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  877. * optionally prefixed with a single dollar sign). Return false if
  878. * <b>hexdigest</b> is malformed, or it doesn't match. */
  879. static INLINE int
  880. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  881. {
  882. char digest[DIGEST_LEN];
  883. tor_assert(hexdigest);
  884. if (hexdigest[0] == '$')
  885. ++hexdigest;
  886. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  887. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  888. return 0;
  889. return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
  890. }
  891. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  892. * (case-insensitive), or if <b>router's</b> identity key digest
  893. * matches a hexadecimal value stored in <b>nickname</b>. Return
  894. * false otherwise. */
  895. static int
  896. router_nickname_matches(routerinfo_t *router, const char *nickname)
  897. {
  898. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  899. return 1;
  900. return router_hex_digest_matches(router, nickname);
  901. }
  902. /** Return the router in our routerlist whose (case-insensitive)
  903. * nickname or (case-sensitive) hexadecimal key digest is
  904. * <b>nickname</b>. Return NULL if no such router is known.
  905. */
  906. routerinfo_t *
  907. router_get_by_nickname(const char *nickname, int warn_if_unnamed)
  908. {
  909. int maybedigest;
  910. char digest[DIGEST_LEN];
  911. routerinfo_t *best_match=NULL;
  912. int n_matches = 0;
  913. char *named_digest = NULL;
  914. tor_assert(nickname);
  915. if (!routerlist)
  916. return NULL;
  917. if (nickname[0] == '$')
  918. return router_get_by_hexdigest(nickname);
  919. if (server_mode(get_options()) &&
  920. !strcasecmp(nickname, get_options()->Nickname))
  921. return router_get_my_routerinfo();
  922. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  923. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  924. if (named_server_map &&
  925. (named_digest = strmap_get_lc(named_server_map, nickname))) {
  926. return digestmap_get(routerlist->identity_map, named_digest);
  927. }
  928. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  929. {
  930. if (!strcasecmp(router->nickname, nickname)) {
  931. ++n_matches;
  932. if (n_matches <= 1 || router->is_running)
  933. best_match = router;
  934. } else if (maybedigest &&
  935. !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
  936. ) {
  937. return router;
  938. }
  939. });
  940. if (best_match) {
  941. if (warn_if_unnamed && n_matches > 1) {
  942. smartlist_t *fps = smartlist_create();
  943. int any_unwarned = 0;
  944. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  945. {
  946. local_routerstatus_t *rs;
  947. char *desc;
  948. size_t dlen;
  949. char fp[HEX_DIGEST_LEN+1];
  950. if (strcasecmp(router->nickname, nickname))
  951. continue;
  952. rs = router_get_combined_status_by_digest(
  953. router->cache_info.identity_digest);
  954. if (rs && !rs->name_lookup_warned) {
  955. rs->name_lookup_warned = 1;
  956. any_unwarned = 1;
  957. }
  958. base16_encode(fp, sizeof(fp),
  959. router->cache_info.identity_digest, DIGEST_LEN);
  960. dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
  961. desc = tor_malloc(dlen);
  962. tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
  963. fp, router->address, router->or_port);
  964. smartlist_add(fps, desc);
  965. });
  966. if (any_unwarned) {
  967. char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
  968. log_warn(LD_CONFIG,
  969. "There are multiple matches for the nickname \"%s\","
  970. " but none is listed as named by the directory authorities. "
  971. "Choosing one arbitrarily. If you meant one in particular, "
  972. "you should say %s.", nickname, alternatives);
  973. tor_free(alternatives);
  974. }
  975. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  976. smartlist_free(fps);
  977. } else if (warn_if_unnamed) {
  978. local_routerstatus_t *rs = router_get_combined_status_by_digest(
  979. best_match->cache_info.identity_digest);
  980. if (rs && !rs->name_lookup_warned) {
  981. char fp[HEX_DIGEST_LEN+1];
  982. base16_encode(fp, sizeof(fp),
  983. best_match->cache_info.identity_digest, DIGEST_LEN);
  984. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
  985. "directory authorities do not have a binding for this nickname. "
  986. "To make sure you get the same server in the future, refer to "
  987. "it by key, as \"$%s\".", nickname, fp);
  988. rs->name_lookup_warned = 1;
  989. }
  990. }
  991. return best_match;
  992. }
  993. return NULL;
  994. }
  995. /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
  996. * return 1. If we do, ask tor_version_as_new_as() for the answer.
  997. */
  998. int
  999. router_digest_version_as_new_as(const char *digest, const char *cutoff)
  1000. {
  1001. routerinfo_t *router = router_get_by_digest(digest);
  1002. if (!router)
  1003. return 1;
  1004. return tor_version_as_new_as(router->platform, cutoff);
  1005. }
  1006. /** Return true iff <b>digest</b> is the digest of the identity key of
  1007. * a trusted directory. */
  1008. int
  1009. router_digest_is_trusted_dir(const char *digest)
  1010. {
  1011. if (!trusted_dir_servers)
  1012. return 0;
  1013. if (get_options()->AuthoritativeDir &&
  1014. router_digest_is_me(digest))
  1015. return 1;
  1016. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1017. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  1018. return 0;
  1019. }
  1020. /** Return the router in our routerlist whose hexadecimal key digest
  1021. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  1022. routerinfo_t *
  1023. router_get_by_hexdigest(const char *hexdigest)
  1024. {
  1025. char digest[DIGEST_LEN];
  1026. tor_assert(hexdigest);
  1027. if (!routerlist)
  1028. return NULL;
  1029. if (hexdigest[0]=='$')
  1030. ++hexdigest;
  1031. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  1032. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  1033. return NULL;
  1034. return router_get_by_digest(digest);
  1035. }
  1036. /** Return the router in our routerlist whose 20-byte key digest
  1037. * is <b>digest</b>. Return NULL if no such router is known. */
  1038. routerinfo_t *
  1039. router_get_by_digest(const char *digest)
  1040. {
  1041. tor_assert(digest);
  1042. if (!routerlist) return NULL;
  1043. // routerlist_assert_ok(routerlist);
  1044. return digestmap_get(routerlist->identity_map, digest);
  1045. }
  1046. /** Return the router in our routerlist whose 20-byte descriptor
  1047. * is <b>digest</b>. Return NULL if no such router is known. */
  1048. signed_descriptor_t *
  1049. router_get_by_descriptor_digest(const char *digest)
  1050. {
  1051. tor_assert(digest);
  1052. if (!routerlist) return NULL;
  1053. return digestmap_get(routerlist->desc_digest_map, digest);
  1054. }
  1055. /* DOCDOC Not always nul-terminated. */
  1056. const char *
  1057. signed_descriptor_get_body(signed_descriptor_t *desc)
  1058. {
  1059. const char *r;
  1060. size_t len = desc->signed_descriptor_len;
  1061. tor_assert(len > 32);
  1062. if (desc->saved_location == SAVED_IN_CACHE && routerlist &&
  1063. routerlist->mmap_descriptors) {
  1064. tor_assert(desc->saved_offset + len <= routerlist->mmap_descriptors->size);
  1065. r = routerlist->mmap_descriptors->data + desc->saved_offset;
  1066. } else {
  1067. r = desc->signed_descriptor_body;
  1068. }
  1069. tor_assert(r);
  1070. tor_assert(!memcmp("router ", r, 7));
  1071. #if 0
  1072. tor_assert(!memcmp("\n-----END SIGNATURE-----\n",
  1073. r + len - 25, 25));
  1074. #endif
  1075. return r;
  1076. }
  1077. /** Return the current list of all known routers. */
  1078. routerlist_t *
  1079. router_get_routerlist(void)
  1080. {
  1081. if (!routerlist) {
  1082. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  1083. routerlist->routers = smartlist_create();
  1084. routerlist->old_routers = smartlist_create();
  1085. routerlist->identity_map = digestmap_new();
  1086. routerlist->desc_digest_map = digestmap_new();
  1087. }
  1088. return routerlist;
  1089. }
  1090. /** Free all storage held by <b>router</b>. */
  1091. void
  1092. routerinfo_free(routerinfo_t *router)
  1093. {
  1094. if (!router)
  1095. return;
  1096. tor_free(router->cache_info.signed_descriptor_body);
  1097. tor_free(router->address);
  1098. tor_free(router->nickname);
  1099. tor_free(router->platform);
  1100. tor_free(router->contact_info);
  1101. if (router->onion_pkey)
  1102. crypto_free_pk_env(router->onion_pkey);
  1103. if (router->identity_pkey)
  1104. crypto_free_pk_env(router->identity_pkey);
  1105. if (router->declared_family) {
  1106. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  1107. smartlist_free(router->declared_family);
  1108. }
  1109. addr_policy_free(router->exit_policy);
  1110. tor_free(router);
  1111. }
  1112. /** Release storage held by <b>sd</b>. */
  1113. static void
  1114. signed_descriptor_free(signed_descriptor_t *sd)
  1115. {
  1116. tor_free(sd->signed_descriptor_body);
  1117. tor_free(sd);
  1118. }
  1119. /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
  1120. */
  1121. static signed_descriptor_t *
  1122. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  1123. {
  1124. signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  1125. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  1126. ri->cache_info.signed_descriptor_body = NULL;
  1127. routerinfo_free(ri);
  1128. return sd;
  1129. }
  1130. /** Free all storage held by a routerlist <b>rl</b> */
  1131. void
  1132. routerlist_free(routerlist_t *rl)
  1133. {
  1134. tor_assert(rl);
  1135. digestmap_free(rl->identity_map, NULL);
  1136. digestmap_free(rl->desc_digest_map, NULL);
  1137. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1138. routerinfo_free(r));
  1139. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  1140. signed_descriptor_free(sd));
  1141. smartlist_free(rl->routers);
  1142. smartlist_free(rl->old_routers);
  1143. if (routerlist->mmap_descriptors)
  1144. tor_munmap_file(routerlist->mmap_descriptors);
  1145. tor_free(rl);
  1146. router_dir_info_changed();
  1147. }
  1148. void
  1149. dump_routerlist_mem_usage(int severity)
  1150. {
  1151. uint64_t livedescs = 0;
  1152. uint64_t olddescs = 0;
  1153. if (!routerlist)
  1154. return;
  1155. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  1156. livedescs += r->cache_info.signed_descriptor_len);
  1157. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  1158. olddescs += sd->signed_descriptor_len);
  1159. log(severity, LD_GENERAL,
  1160. "In %d live descriptors: "U64_FORMAT" bytes. "
  1161. "In %d old descriptors: "U64_FORMAT" bytes.",
  1162. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  1163. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  1164. }
  1165. /** Return the greatest number of routerdescs we'll hold for any given router.
  1166. */
  1167. static int
  1168. max_descriptors_per_router(void)
  1169. {
  1170. int n_authorities = 0;
  1171. if (trusted_dir_servers)
  1172. n_authorities = smartlist_len(trusted_dir_servers);
  1173. return (n_authorities < 5) ? 5 : n_authorities;
  1174. }
  1175. /** Return non-zero if we have a lot of extra descriptors in our
  1176. * routerlist, and should get rid of some of them. Else return 0.
  1177. *
  1178. * We should be careful to not return true too eagerly, since we
  1179. * could churn. By using "+1" below, we make sure this function
  1180. * only returns true at most every smartlist_len(rl-\>routers)
  1181. * new descriptors.
  1182. */
  1183. static INLINE int
  1184. routerlist_is_overfull(routerlist_t *rl)
  1185. {
  1186. return smartlist_len(rl->old_routers) >
  1187. smartlist_len(rl->routers)*(max_descriptors_per_router()+1);
  1188. }
  1189. static INLINE int
  1190. _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
  1191. {
  1192. if (idx < 0 || smartlist_get(sl, idx) != ri) {
  1193. idx = -1;
  1194. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  1195. if (r == ri) {
  1196. idx = r_sl_idx;
  1197. break;
  1198. });
  1199. }
  1200. return idx;
  1201. }
  1202. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  1203. * as needed. */
  1204. static void
  1205. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  1206. {
  1207. digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  1208. digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
  1209. &(ri->cache_info));
  1210. smartlist_add(rl->routers, ri);
  1211. ri->routerlist_index = smartlist_len(rl->routers) - 1;
  1212. router_dir_info_changed();
  1213. // routerlist_assert_ok(rl);
  1214. }
  1215. static void
  1216. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  1217. {
  1218. if (get_options()->DirPort &&
  1219. !digestmap_get(rl->desc_digest_map,
  1220. ri->cache_info.signed_descriptor_digest)) {
  1221. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  1222. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1223. smartlist_add(rl->old_routers, sd);
  1224. ri->routerlist_index = -1;
  1225. } else {
  1226. routerinfo_free(ri);
  1227. }
  1228. // routerlist_assert_ok(rl);
  1229. }
  1230. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  1231. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  1232. * idx) == ri, we don't need to do a linear search over the list to decide
  1233. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  1234. * the list, if any exists. <b>ri</b> is freed. */
  1235. void
  1236. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
  1237. {
  1238. routerinfo_t *ri_tmp;
  1239. idx = _routerlist_find_elt(rl->routers, ri, idx);
  1240. if (idx < 0)
  1241. return;
  1242. ri->routerlist_index = -1;
  1243. smartlist_del(rl->routers, idx);
  1244. if (idx < smartlist_len(rl->routers)) {
  1245. routerinfo_t *r = smartlist_get(rl->routers, idx);
  1246. r->routerlist_index = idx;
  1247. }
  1248. ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
  1249. router_dir_info_changed();
  1250. tor_assert(ri_tmp == ri);
  1251. if (make_old && get_options()->DirPort) {
  1252. signed_descriptor_t *sd;
  1253. sd = signed_descriptor_from_routerinfo(ri);
  1254. smartlist_add(rl->old_routers, sd);
  1255. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1256. } else {
  1257. ri_tmp = digestmap_remove(rl->desc_digest_map,
  1258. ri->cache_info.signed_descriptor_digest);
  1259. tor_assert(ri_tmp == ri);
  1260. router_bytes_dropped += ri->cache_info.signed_descriptor_len;
  1261. routerinfo_free(ri);
  1262. }
  1263. // routerlist_assert_ok(rl);
  1264. }
  1265. static void
  1266. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  1267. {
  1268. signed_descriptor_t *sd_tmp;
  1269. idx = _routerlist_find_elt(rl->old_routers, sd, idx);
  1270. if (idx < 0)
  1271. return;
  1272. smartlist_del(rl->old_routers, idx);
  1273. sd_tmp = digestmap_remove(rl->desc_digest_map,
  1274. sd->signed_descriptor_digest);
  1275. tor_assert(sd_tmp == sd);
  1276. router_bytes_dropped += sd->signed_descriptor_len;
  1277. signed_descriptor_free(sd);
  1278. // routerlist_assert_ok(rl);
  1279. }
  1280. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  1281. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  1282. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  1283. * search over the list to decide which to remove. We put ri_new in the same
  1284. * index as ri_old, if possible. ri is freed as appropriate. */
  1285. static void
  1286. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  1287. routerinfo_t *ri_new, int idx, int make_old)
  1288. {
  1289. tor_assert(ri_old != ri_new);
  1290. idx = _routerlist_find_elt(rl->routers, ri_old, idx);
  1291. router_dir_info_changed();
  1292. if (idx >= 0) {
  1293. smartlist_set(rl->routers, idx, ri_new);
  1294. ri_old->routerlist_index = -1;
  1295. ri_new->routerlist_index = idx;
  1296. } else {
  1297. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  1298. routerlist_insert(rl, ri_new);
  1299. return;
  1300. }
  1301. if (memcmp(ri_old->cache_info.identity_digest,
  1302. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  1303. /* digests don't match; digestmap_set won't replace */
  1304. digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  1305. }
  1306. digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
  1307. digestmap_set(rl->desc_digest_map,
  1308. ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
  1309. if (make_old && get_options()->DirPort) {
  1310. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  1311. smartlist_add(rl->old_routers, sd);
  1312. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1313. } else {
  1314. if (memcmp(ri_old->cache_info.signed_descriptor_digest,
  1315. ri_new->cache_info.signed_descriptor_digest,
  1316. DIGEST_LEN)) {
  1317. /* digests don't match; digestmap_set didn't replace */
  1318. digestmap_remove(rl->desc_digest_map,
  1319. ri_old->cache_info.signed_descriptor_digest);
  1320. }
  1321. routerinfo_free(ri_old);
  1322. }
  1323. // routerlist_assert_ok(rl);
  1324. }
  1325. /** Free all memory held by the routerlist module. */
  1326. void
  1327. routerlist_free_all(void)
  1328. {
  1329. if (routerlist)
  1330. routerlist_free(routerlist);
  1331. routerlist = NULL;
  1332. if (warned_nicknames) {
  1333. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1334. smartlist_free(warned_nicknames);
  1335. warned_nicknames = NULL;
  1336. }
  1337. if (warned_conflicts) {
  1338. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1339. smartlist_free(warned_conflicts);
  1340. warned_conflicts = NULL;
  1341. }
  1342. if (trusted_dir_servers) {
  1343. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1344. trusted_dir_server_free(ds));
  1345. smartlist_free(trusted_dir_servers);
  1346. trusted_dir_servers = NULL;
  1347. }
  1348. if (networkstatus_list) {
  1349. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1350. networkstatus_free(ns));
  1351. smartlist_free(networkstatus_list);
  1352. networkstatus_list = NULL;
  1353. }
  1354. if (routerstatus_list) {
  1355. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1356. local_routerstatus_free(rs));
  1357. smartlist_free(routerstatus_list);
  1358. routerstatus_list = NULL;
  1359. }
  1360. if (named_server_map) {
  1361. strmap_free(named_server_map, _tor_free);
  1362. }
  1363. }
  1364. /** Free all storage held by the routerstatus object <b>rs</b>. */
  1365. void
  1366. routerstatus_free(routerstatus_t *rs)
  1367. {
  1368. tor_free(rs);
  1369. }
  1370. /** Free all storage held by the local_routerstatus object <b>rs</b>. */
  1371. static void
  1372. local_routerstatus_free(local_routerstatus_t *rs)
  1373. {
  1374. tor_free(rs);
  1375. }
  1376. /** Free all storage held by the networkstatus object <b>ns</b>. */
  1377. void
  1378. networkstatus_free(networkstatus_t *ns)
  1379. {
  1380. tor_free(ns->source_address);
  1381. tor_free(ns->contact);
  1382. if (ns->signing_key)
  1383. crypto_free_pk_env(ns->signing_key);
  1384. tor_free(ns->client_versions);
  1385. tor_free(ns->server_versions);
  1386. if (ns->entries) {
  1387. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1388. routerstatus_free(rs));
  1389. smartlist_free(ns->entries);
  1390. }
  1391. tor_free(ns);
  1392. }
  1393. /** Forget that we have issued any router-related warnings, so that we'll
  1394. * warn again if we see the same errors. */
  1395. void
  1396. routerlist_reset_warnings(void)
  1397. {
  1398. if (!warned_nicknames)
  1399. warned_nicknames = smartlist_create();
  1400. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1401. smartlist_clear(warned_nicknames); /* now the list is empty. */
  1402. if (!warned_conflicts)
  1403. warned_conflicts = smartlist_create();
  1404. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1405. smartlist_clear(warned_conflicts); /* now the list is empty. */
  1406. if (!routerstatus_list)
  1407. routerstatus_list = smartlist_create();
  1408. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1409. rs->name_lookup_warned = 0);
  1410. have_warned_about_invalid_status = 0;
  1411. have_warned_about_old_version = 0;
  1412. have_warned_about_new_version = 0;
  1413. }
  1414. /** Mark the router with ID <b>digest</b> as running or non-running
  1415. * in our routerlist. */
  1416. void
  1417. router_set_status(const char *digest, int up)
  1418. {
  1419. routerinfo_t *router;
  1420. local_routerstatus_t *status;
  1421. tor_assert(digest);
  1422. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  1423. if (!memcmp(d->digest, digest, DIGEST_LEN))
  1424. d->is_running = up);
  1425. router = router_get_by_digest(digest);
  1426. if (router) {
  1427. log_debug(LD_DIR,"Marking router '%s' as %s.",
  1428. router->nickname, up ? "up" : "down");
  1429. if (!up && router_is_me(router) && !we_are_hibernating())
  1430. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  1431. "addresses reachable?");
  1432. router->is_running = up;
  1433. }
  1434. status = router_get_combined_status_by_digest(digest);
  1435. if (status) {
  1436. status->status.is_running = up;
  1437. }
  1438. router_dir_info_changed();
  1439. }
  1440. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  1441. * older entries (if any) with the same key. Note: Callers should not hold
  1442. * their pointers to <b>router</b> if this function fails; <b>router</b>
  1443. * will either be inserted into the routerlist or freed.
  1444. *
  1445. * Returns >= 0 if the router was added; less than 0 if it was not.
  1446. *
  1447. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  1448. * describing the reason for not liking the routerinfo.
  1449. *
  1450. * If the return value is less than -1, there was a problem with the
  1451. * routerinfo. If the return value is equal to -1, then the routerinfo was
  1452. * fine, but out-of-date. If the return value is equal to 1, the
  1453. * routerinfo was accepted, but we should notify the generator of the
  1454. * descriptor using the message *<b>msg</b>.
  1455. *
  1456. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  1457. * <b>from_fetch</b>, we received it in response to a request we made.
  1458. * (If both are false, that means it was uploaded to us as an auth dir
  1459. * server or via the controller.)
  1460. *
  1461. * This function should be called *after*
  1462. * routers_update_status_from_networkstatus; subsequently, you should call
  1463. * router_rebuild_store and control_event_descriptors_changed.
  1464. */
  1465. int
  1466. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  1467. int from_cache, int from_fetch)
  1468. {
  1469. const char *id_digest;
  1470. int authdir = get_options()->AuthoritativeDir;
  1471. int authdir_believes_valid = 0;
  1472. routerinfo_t *old_router;
  1473. tor_assert(msg);
  1474. if (!routerlist)
  1475. router_get_routerlist();
  1476. if (!networkstatus_list)
  1477. networkstatus_list = smartlist_create();
  1478. id_digest = router->cache_info.identity_digest;
  1479. /* Make sure that we haven't already got this exact descriptor. */
  1480. if (digestmap_get(routerlist->desc_digest_map,
  1481. router->cache_info.signed_descriptor_digest)) {
  1482. log_info(LD_DIR,
  1483. "Dropping descriptor that we already have for router '%s'",
  1484. router->nickname);
  1485. *msg = "Router descriptor was not new.";
  1486. routerinfo_free(router);
  1487. return -1;
  1488. }
  1489. if (routerlist_is_overfull(routerlist))
  1490. routerlist_remove_old_routers();
  1491. if (authdir) {
  1492. if (authdir_wants_to_reject_router(router, msg,
  1493. !from_cache && !from_fetch)) {
  1494. tor_assert(*msg);
  1495. routerinfo_free(router);
  1496. return -2;
  1497. }
  1498. authdir_believes_valid = router->is_valid;
  1499. } else if (from_fetch) {
  1500. /* Only check the descriptor digest against the network statuses when
  1501. * we are receiving in response to a fetch. */
  1502. if (!signed_desc_digest_is_recognized(&router->cache_info)) {
  1503. log_warn(LD_DIR, "Dropping unrecognized descriptor for router '%s'",
  1504. router->nickname);
  1505. *msg = "Router descriptor is not referenced by any network-status.";
  1506. routerinfo_free(router);
  1507. return -1;
  1508. }
  1509. }
  1510. /* We no longer need a router with this descriptor digest. */
  1511. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1512. {
  1513. routerstatus_t *rs =
  1514. networkstatus_find_entry(ns, router->cache_info.identity_digest);
  1515. if (rs && !memcmp(rs->descriptor_digest,
  1516. router->cache_info.signed_descriptor_digest,
  1517. DIGEST_LEN))
  1518. rs->need_to_mirror = 0;
  1519. });
  1520. /* If we have a router with the same identity key, choose the newer one. */
  1521. old_router = digestmap_get(routerlist->identity_map,
  1522. router->cache_info.identity_digest);
  1523. if (old_router) {
  1524. int pos = old_router->routerlist_index;
  1525. tor_assert(smartlist_get(routerlist->routers, pos) == old_router);
  1526. if (router->cache_info.published_on <=
  1527. old_router->cache_info.published_on) {
  1528. /* Same key, but old */
  1529. log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
  1530. router->nickname);
  1531. /* Only journal this desc if we'll be serving it. */
  1532. if (!from_cache && get_options()->DirPort)
  1533. router_append_to_journal(&router->cache_info);
  1534. routerlist_insert_old(routerlist, router);
  1535. *msg = "Router descriptor was not new.";
  1536. return -1;
  1537. } else {
  1538. /* Same key, new. */
  1539. int unreachable = 0;
  1540. log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
  1541. router->nickname, old_router->nickname,
  1542. hex_str(id_digest,DIGEST_LEN));
  1543. if (router->addr == old_router->addr &&
  1544. router->or_port == old_router->or_port) {
  1545. /* these carry over when the address and orport are unchanged.*/
  1546. router->last_reachable = old_router->last_reachable;
  1547. router->testing_since = old_router->testing_since;
  1548. router->num_unreachable_notifications =
  1549. old_router->num_unreachable_notifications;
  1550. }
  1551. if (authdir && !from_cache && !from_fetch &&
  1552. router_have_minimum_dir_info() &&
  1553. dirserv_thinks_router_is_blatantly_unreachable(router,
  1554. time(NULL))) {
  1555. if (router->num_unreachable_notifications >= 3) {
  1556. unreachable = 1;
  1557. log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
  1558. "(ContactInfo '%s', platform '%s').",
  1559. router->nickname,
  1560. router->contact_info ? router->contact_info : "",
  1561. router->platform ? router->platform : "");
  1562. } else {
  1563. log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
  1564. "descriptors were thought to be unreachable.",
  1565. router->nickname, router->num_unreachable_notifications);
  1566. router->num_unreachable_notifications++;
  1567. }
  1568. }
  1569. routerlist_replace(routerlist, old_router, router, pos, 1);
  1570. if (!from_cache) {
  1571. router_append_to_journal(&router->cache_info);
  1572. }
  1573. directory_set_dirty();
  1574. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1575. authdir_believes_valid ? "Valid server updated" :
  1576. ("Invalid server updated. (This dirserver is marking your "
  1577. "server as unapproved.)");
  1578. return unreachable ? 1 : 0;
  1579. }
  1580. }
  1581. #if 0
  1582. /* XXXX This block is slow, and could be smarter. All it does is ensure
  1583. * that if we have a named server called "Foo", we will never have another
  1584. * server called "Foo." router_get_by_nickname() already knows to prefer
  1585. * named routers, so the problem only arises when there is a named router
  1586. * called 'foo', but we don't have it. If, instead, we kept a
  1587. * name-to-identity-key mapping for each named router in the networkstatus
  1588. * list, we could eliminate this block.
  1589. *
  1590. * Hm. perhaps we should; I don't see how this code is non-broken wrt named
  1591. * routers. -NM
  1592. */
  1593. /* If the identity key has changed, and one of the
  1594. * routers is named, drop the unnamed ones. (If more than one are named,
  1595. * drop the old ones.)
  1596. */
  1597. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1598. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  1599. if (!memcmp(router->cache_info.identity_digest,
  1600. old_router->cache_info.identity_digest, DIGEST_LEN)) {
  1601. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1602. /* nicknames match, keys don't. */
  1603. if (router->is_named) {
  1604. /* The new named router replaces the old one; remove the
  1605. * old one. And carry on to the end of the list, in case
  1606. * there are more old unnamed routers with this nickname.
  1607. */
  1608. /* mark-for-close connections using the old key, so we can
  1609. * make new ones with the new key.
  1610. */
  1611. or_connection_t *conn;
  1612. while ((conn = connection_or_get_by_identity_digest(
  1613. old_router->cache_info.identity_digest))) {
  1614. log_info(LD_DIR,"Closing conn to router '%s'; there is now a named "
  1615. "router with that name.",
  1616. old_router->nickname);
  1617. connection_mark_for_close(TO_CONN(conn));
  1618. }
  1619. routerlist_remove(routerlist, old_router, i--, 0);
  1620. } else if (old_router->is_named) {
  1621. /* Can't replace a named router with an unnamed one. */
  1622. log_debug(LD_DIR, "Skipping unnamed entry for named router '%s'",
  1623. router->nickname);
  1624. routerinfo_free(router);
  1625. *msg =
  1626. "Already have named router with same nickname and different key.";
  1627. return -2;
  1628. }
  1629. }
  1630. }
  1631. #endif
  1632. /* We haven't seen a router with this name before. Add it to the end of
  1633. * the list. */
  1634. routerlist_insert(routerlist, router);
  1635. if (!from_cache)
  1636. router_append_to_journal(&router->cache_info);
  1637. directory_set_dirty();
  1638. return 0;
  1639. }
  1640. static int
  1641. _compare_old_routers_by_identity(const void **_a, const void **_b)
  1642. {
  1643. int i;
  1644. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  1645. if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  1646. return i;
  1647. return r1->published_on - r2->published_on;
  1648. }
  1649. struct duration_idx_t {
  1650. int duration;
  1651. int idx;
  1652. int old;
  1653. };
  1654. static int
  1655. _compare_duration_idx(const void *_d1, const void *_d2)
  1656. {
  1657. const struct duration_idx_t *d1 = _d1;
  1658. const struct duration_idx_t *d2 = _d2;
  1659. return d1->duration - d2->duration;
  1660. }
  1661. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  1662. * must contain routerinfo_t with the same identity and with publication time
  1663. * in ascending order. Remove members from this range until there are no more
  1664. * than max_descriptors_per_router() remaining. Start by removing the oldest
  1665. * members from before <b>cutoff</b>, then remove members which were current
  1666. * for the lowest amount of time. The order of members of old_routers at
  1667. * indices <b>lo</b> or higher may be changed.
  1668. */
  1669. static void
  1670. routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
  1671. digestmap_t *retain)
  1672. {
  1673. int i, n = hi-lo+1, n_extra;
  1674. int n_rmv = 0;
  1675. struct duration_idx_t *lifespans;
  1676. uint8_t *rmv, *must_keep;
  1677. smartlist_t *lst = routerlist->old_routers;
  1678. #if 1
  1679. const char *ident;
  1680. tor_assert(hi < smartlist_len(lst));
  1681. tor_assert(lo <= hi);
  1682. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  1683. for (i = lo+1; i <= hi; ++i) {
  1684. signed_descriptor_t *r = smartlist_get(lst, i);
  1685. tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
  1686. }
  1687. #endif
  1688. /* Check whether we need to do anything at all. */
  1689. n_extra = n - max_descriptors_per_router();
  1690. if (n_extra <= 0)
  1691. return;
  1692. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  1693. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  1694. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  1695. /* Set lifespans to contain the lifespan and index of each server. */
  1696. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  1697. for (i = lo; i <= hi; ++i) {
  1698. signed_descriptor_t *r = smartlist_get(lst, i);
  1699. signed_descriptor_t *r_next;
  1700. lifespans[i-lo].idx = i;
  1701. if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
  1702. must_keep[i-lo] = 1;
  1703. }
  1704. if (i < hi) {
  1705. r_next = smartlist_get(lst, i+1);
  1706. tor_assert(r->published_on <= r_next->published_on);
  1707. lifespans[i-lo].duration = (r_next->published_on - r->published_on);
  1708. } else {
  1709. r_next = NULL;
  1710. lifespans[i-lo].duration = INT_MAX;
  1711. }
  1712. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  1713. ++n_rmv;
  1714. lifespans[i-lo].old = 1;
  1715. rmv[i-lo] = 1;
  1716. }
  1717. }
  1718. if (n_rmv < n_extra) {
  1719. /**
  1720. * We aren't removing enough servers for being old. Sort lifespans by
  1721. * the duration of liveness, and remove the ones we're not already going to
  1722. * remove based on how long they were alive.
  1723. **/
  1724. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  1725. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  1726. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  1727. rmv[lifespans[i].idx-lo] = 1;
  1728. ++n_rmv;
  1729. }
  1730. }
  1731. }
  1732. for (i = hi; i >= lo; --i) {
  1733. if (rmv[i-lo])
  1734. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  1735. }
  1736. tor_free(must_keep);
  1737. tor_free(rmv);
  1738. tor_free(lifespans);
  1739. }
  1740. /** Deactivate any routers from the routerlist that are more than
  1741. * ROUTER_MAX_AGE seconds old; remove old routers from the list of
  1742. * cached routers if we have too many.
  1743. */
  1744. void
  1745. routerlist_remove_old_routers(void)
  1746. {
  1747. int i, hi=-1;
  1748. const char *cur_id = NULL;
  1749. time_t now = time(NULL);
  1750. time_t cutoff;
  1751. routerinfo_t *router;
  1752. signed_descriptor_t *sd;
  1753. digestmap_t *retain;
  1754. or_options_t *options = get_options();
  1755. if (!routerlist || !networkstatus_list)
  1756. return;
  1757. retain = digestmap_new();
  1758. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1759. if (options->DirPort) {
  1760. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1761. {
  1762. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1763. if (rs->published_on >= cutoff)
  1764. digestmap_set(retain, rs->descriptor_digest, (void*)1));
  1765. });
  1766. }
  1767. cutoff = now - ROUTER_MAX_AGE;
  1768. /* Remove too-old members of routerlist->routers. */
  1769. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1770. router = smartlist_get(routerlist->routers, i);
  1771. if (router->cache_info.published_on <= cutoff &&
  1772. !digestmap_get(retain, router->cache_info.signed_descriptor_digest)) {
  1773. /* Too old. Remove it. */
  1774. log_info(LD_DIR,
  1775. "Forgetting obsolete (too old) routerinfo for router '%s'",
  1776. router->nickname);
  1777. routerlist_remove(routerlist, router, i--, 1);
  1778. }
  1779. }
  1780. /* Remove far-too-old members of routerlist->old_routers. */
  1781. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1782. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  1783. sd = smartlist_get(routerlist->old_routers, i);
  1784. if (sd->published_on <= cutoff &&
  1785. !digestmap_get(retain, sd->signed_descriptor_digest)) {
  1786. /* Too old. Remove it. */
  1787. routerlist_remove_old(routerlist, sd, i--);
  1788. }
  1789. }
  1790. /* Now we're looking at routerlist->old_routers for extraneous
  1791. * members. (We'd keep all the members if we could, but we'd like to save
  1792. * space.) First, check whether we have too many router descriptors, total.
  1793. * We're okay with having too many for some given router, so long as the
  1794. * total number doesn't approach max_descriptors_per_router()*len(router).
  1795. */
  1796. if (smartlist_len(routerlist->old_routers) <
  1797. smartlist_len(routerlist->routers) * (max_descriptors_per_router() - 1))
  1798. goto done;
  1799. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  1800. /* Iterate through the list from back to front, so when we remove descriptors
  1801. * we don't mess up groups we haven't gotten to. */
  1802. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  1803. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  1804. if (!cur_id) {
  1805. cur_id = r->identity_digest;
  1806. hi = i;
  1807. }
  1808. if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
  1809. routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
  1810. cur_id = r->identity_digest;
  1811. hi = i;
  1812. }
  1813. }
  1814. if (hi>=0)
  1815. routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
  1816. routerlist_assert_ok(routerlist);
  1817. done:
  1818. digestmap_free(retain, NULL);
  1819. }
  1820. /**
  1821. * Code to parse a single router descriptor and insert it into the
  1822. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1823. * descriptor was well-formed but could not be added; and 1 if the
  1824. * descriptor was added.
  1825. *
  1826. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1827. * *<b>msg</b> a static string describing the reason for refusing the
  1828. * descriptor.
  1829. *
  1830. * This is used only by the controller.
  1831. */
  1832. int
  1833. router_load_single_router(const char *s, uint8_t purpose, const char **msg)
  1834. {
  1835. routerinfo_t *ri;
  1836. int r;
  1837. smartlist_t *lst;
  1838. tor_assert(msg);
  1839. *msg = NULL;
  1840. if (!(ri = router_parse_entry_from_string(s, NULL, 1))) {
  1841. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  1842. *msg = "Couldn't parse router descriptor.";
  1843. return -1;
  1844. }
  1845. ri->purpose = purpose;
  1846. if (router_is_me(ri)) {
  1847. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  1848. *msg = "Router's identity key matches mine.";
  1849. routerinfo_free(ri);
  1850. return 0;
  1851. }
  1852. lst = smartlist_create();
  1853. smartlist_add(lst, ri);
  1854. routers_update_status_from_networkstatus(lst, 0);
  1855. if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
  1856. /* we've already assigned to *msg now, and ri is already freed */
  1857. tor_assert(*msg);
  1858. if (r < -1)
  1859. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  1860. smartlist_free(lst);
  1861. return 0;
  1862. } else {
  1863. control_event_descriptors_changed(lst);
  1864. smartlist_free(lst);
  1865. log_debug(LD_DIR, "Added router to list");
  1866. return 1;
  1867. }
  1868. }
  1869. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1870. * routers into our directory. If <b>from_cache</b> is false, the routers
  1871. * are in response to a query to the network: cache them.
  1872. *
  1873. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1874. * uppercased identity fingerprints. Do not update any router whose
  1875. * fingerprint is not on the list; after updating a router, remove its
  1876. * fingerprint from the list.
  1877. * DOCDOC saved_location
  1878. */
  1879. void
  1880. router_load_routers_from_string(const char *s, saved_location_t saved_location,
  1881. smartlist_t *requested_fingerprints)
  1882. {
  1883. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1884. char fp[HEX_DIGEST_LEN+1];
  1885. const char *msg;
  1886. int from_cache = (saved_location != SAVED_NOWHERE);
  1887. router_parse_list_from_string(&s, routers, saved_location);
  1888. routers_update_status_from_networkstatus(routers, !from_cache);
  1889. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  1890. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1891. {
  1892. base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
  1893. DIGEST_LEN);
  1894. if (requested_fingerprints) {
  1895. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1896. smartlist_string_remove(requested_fingerprints, fp);
  1897. } else {
  1898. char *requested =
  1899. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1900. log_warn(LD_DIR,
  1901. "We received a router descriptor with a fingerprint (%s) "
  1902. "that we never requested. (We asked for: %s.) Dropping.",
  1903. fp, requested);
  1904. tor_free(requested);
  1905. routerinfo_free(ri);
  1906. continue;
  1907. }
  1908. }
  1909. if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
  1910. smartlist_add(changed, ri);
  1911. });
  1912. if (smartlist_len(changed))
  1913. control_event_descriptors_changed(changed);
  1914. routerlist_assert_ok(routerlist);
  1915. router_rebuild_store(0);
  1916. smartlist_free(routers);
  1917. smartlist_free(changed);
  1918. }
  1919. /** Helper: return a newly allocated string containing the name of the filename
  1920. * where we plan to cache <b>ns</b>. */
  1921. static char *
  1922. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1923. {
  1924. const char *datadir = get_options()->DataDirectory;
  1925. size_t len = strlen(datadir)+64;
  1926. char fp[HEX_DIGEST_LEN+1];
  1927. char *fn = tor_malloc(len+1);
  1928. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1929. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1930. return fn;
  1931. }
  1932. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1933. * publication date. */
  1934. static int
  1935. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1936. {
  1937. const networkstatus_t *a = *_a, *b = *_b;
  1938. if (a->published_on < b->published_on)
  1939. return -1;
  1940. else if (a->published_on > b->published_on)
  1941. return 1;
  1942. else
  1943. return 0;
  1944. }
  1945. /** Add the parsed neworkstatus in <b>ns</b> (with original document in
  1946. * <b>s</b> to the disk cache (and the in-memory directory server cache) as
  1947. * appropriate. */
  1948. static int
  1949. add_networkstatus_to_cache(const char *s,
  1950. networkstatus_source_t source,
  1951. networkstatus_t *ns)
  1952. {
  1953. if (source != NS_FROM_CACHE) {
  1954. char *fn = networkstatus_get_cache_filename(ns);
  1955. if (write_str_to_file(fn, s, 0)<0) {
  1956. log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
  1957. }
  1958. tor_free(fn);
  1959. }
  1960. if (get_options()->DirPort)
  1961. dirserv_set_cached_networkstatus_v2(s,
  1962. ns->identity_digest,
  1963. ns->published_on);
  1964. return 0;
  1965. }
  1966. /** How far in the future do we allow a network-status to get before removing
  1967. * it? (seconds) */
  1968. #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
  1969. /** Given a string <b>s</b> containing a network status that we received at
  1970. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1971. * store it, and put it into our cache as necessary.
  1972. *
  1973. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1974. * own networkstatus_t (if we're an authoritative directory server).
  1975. *
  1976. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1977. * cache.
  1978. *
  1979. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1980. * uppercased identity fingerprints. Do not update any networkstatus whose
  1981. * fingerprint is not on the list; after updating a networkstatus, remove its
  1982. * fingerprint from the list.
  1983. *
  1984. * Return 0 on success, -1 on failure.
  1985. *
  1986. * Callers should make sure that routers_update_all_from_networkstatus() is
  1987. * invoked after this function succeeds.
  1988. */
  1989. int
  1990. router_set_networkstatus(const char *s, time_t arrived_at,
  1991. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1992. {
  1993. networkstatus_t *ns;
  1994. int i, found;
  1995. time_t now;
  1996. int skewed = 0;
  1997. trusted_dir_server_t *trusted_dir = NULL;
  1998. const char *source_desc = NULL;
  1999. char fp[HEX_DIGEST_LEN+1];
  2000. char published[ISO_TIME_LEN+1];
  2001. ns = networkstatus_parse_from_string(s);
  2002. if (!ns) {
  2003. log_warn(LD_DIR, "Couldn't parse network status.");
  2004. return -1;
  2005. }
  2006. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  2007. if (!(trusted_dir =
  2008. router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  2009. log_info(LD_DIR, "Network status was signed, but not by an authoritative "
  2010. "directory we recognize.");
  2011. if (!get_options()->DirPort) {
  2012. networkstatus_free(ns);
  2013. return 0;
  2014. }
  2015. source_desc = fp;
  2016. } else {
  2017. source_desc = trusted_dir->description;
  2018. }
  2019. now = time(NULL);
  2020. if (arrived_at > now)
  2021. arrived_at = now;
  2022. ns->received_on = arrived_at;
  2023. format_iso_time(published, ns->published_on);
  2024. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  2025. log_warn(LD_GENERAL, "Network status from %s was published in the future "
  2026. "(%s GMT). Somebody is skewed here: check your clock. "
  2027. "Not caching.",
  2028. source_desc, published);
  2029. skewed = 1;
  2030. }
  2031. if (!networkstatus_list)
  2032. networkstatus_list = smartlist_create();
  2033. if ( (source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) &&
  2034. router_digest_is_me(ns->identity_digest)) {
  2035. /* Don't replace our own networkstatus when we get it from somebody else.*/
  2036. networkstatus_free(ns);
  2037. return 0;
  2038. }
  2039. if (requested_fingerprints) {
  2040. if (smartlist_string_isin(requested_fingerprints, fp)) {
  2041. smartlist_string_remove(requested_fingerprints, fp);
  2042. } else {
  2043. char *requested =
  2044. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  2045. if (source != NS_FROM_DIR_ALL) {
  2046. log_warn(LD_DIR,
  2047. "We received a network status with a fingerprint (%s) that we "
  2048. "never requested. (We asked for: %s.) Dropping.",
  2049. fp, requested);
  2050. tor_free(requested);
  2051. return 0;
  2052. }
  2053. }
  2054. }
  2055. if (!trusted_dir) {
  2056. if (!skewed && get_options()->DirPort) {
  2057. /* We got a non-trusted networkstatus, and we're a directory cache.
  2058. * This means that we asked an authority, and it told us about another
  2059. * authority we didn't recognize. */
  2060. log_info(LD_DIR,
  2061. "We do not recognize authority (%s) but we are willing "
  2062. "to cache it", fp);
  2063. add_networkstatus_to_cache(s, source, ns);
  2064. networkstatus_free(ns);
  2065. }
  2066. return 0;
  2067. }
  2068. if (source != NS_FROM_CACHE && trusted_dir)
  2069. trusted_dir->n_networkstatus_failures = 0;
  2070. found = 0;
  2071. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  2072. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  2073. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  2074. if (!memcmp(old_ns->networkstatus_digest,
  2075. ns->networkstatus_digest, DIGEST_LEN)) {
  2076. /* Same one we had before. */
  2077. networkstatus_free(ns);
  2078. log_info(LD_DIR,
  2079. "Not replacing network-status from %s (published %s); "
  2080. "we already have it.",
  2081. trusted_dir->description, published);
  2082. if (old_ns->received_on < arrived_at) {
  2083. if (source != NS_FROM_CACHE) {
  2084. char *fn = networkstatus_get_cache_filename(old_ns);
  2085. /* We use mtime to tell when it arrived, so update that. */
  2086. touch_file(fn);
  2087. tor_free(fn);
  2088. }
  2089. old_ns->received_on = arrived_at;
  2090. }
  2091. return 0;
  2092. } else if (old_ns->published_on >= ns->published_on) {
  2093. char old_published[ISO_TIME_LEN+1];
  2094. format_iso_time(old_published, old_ns->published_on);
  2095. log_info(LD_DIR,
  2096. "Not replacing network-status from %s (published %s);"
  2097. " we have a newer one (published %s) for this authority.",
  2098. trusted_dir->description, published,
  2099. old_published);
  2100. networkstatus_free(ns);
  2101. return 0;
  2102. } else {
  2103. networkstatus_free(old_ns);
  2104. smartlist_set(networkstatus_list, i, ns);
  2105. found = 1;
  2106. break;
  2107. }
  2108. }
  2109. }
  2110. if (!found)
  2111. smartlist_add(networkstatus_list, ns);
  2112. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  2113. {
  2114. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  2115. rs->need_to_mirror = 1;
  2116. });
  2117. log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
  2118. source == NS_FROM_CACHE?"cached from":
  2119. ((source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) ?
  2120. "downloaded from":"generated for"),
  2121. trusted_dir->description, published);
  2122. networkstatus_list_has_changed = 1;
  2123. router_dir_info_changed();
  2124. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  2125. if (!skewed)
  2126. add_networkstatus_to_cache(s, source, ns);
  2127. networkstatus_list_update_recent(now);
  2128. return 0;
  2129. }
  2130. /** How old do we allow a network-status to get before removing it
  2131. * completely? */
  2132. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  2133. /** Remove all very-old network_status_t objects from memory and from the
  2134. * disk cache. */
  2135. void
  2136. networkstatus_list_clean(time_t now)
  2137. {
  2138. int i;
  2139. if (!networkstatus_list)
  2140. return;
  2141. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  2142. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2143. char *fname = NULL;;
  2144. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  2145. continue;
  2146. /* Okay, this one is too old. Remove it from the list, and delete it
  2147. * from the cache. */
  2148. smartlist_del(networkstatus_list, i--);
  2149. fname = networkstatus_get_cache_filename(ns);
  2150. if (file_status(fname) == FN_FILE) {
  2151. log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
  2152. unlink(fname);
  2153. }
  2154. tor_free(fname);
  2155. if (get_options()->DirPort) {
  2156. dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
  2157. }
  2158. networkstatus_free(ns);
  2159. router_dir_info_changed();
  2160. }
  2161. }
  2162. /** Helper for bsearching a list of routerstatus_t pointers.*/
  2163. static int
  2164. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  2165. {
  2166. const char *key = _key;
  2167. const routerstatus_t *rs = *_member;
  2168. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  2169. }
  2170. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  2171. * NULL if none was found. */
  2172. static routerstatus_t *
  2173. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  2174. {
  2175. return smartlist_bsearch(ns->entries, digest,
  2176. _compare_digest_to_routerstatus_entry);
  2177. }
  2178. /** Return the consensus view of the status of the router whose digest is
  2179. * <b>digest</b>, or NULL if we don't know about any such router. */
  2180. local_routerstatus_t *
  2181. router_get_combined_status_by_digest(const char *digest)
  2182. {
  2183. if (!routerstatus_list)
  2184. return NULL;
  2185. return smartlist_bsearch(routerstatus_list, digest,
  2186. _compare_digest_to_routerstatus_entry);
  2187. }
  2188. static local_routerstatus_t *
  2189. router_get_combined_status_by_nickname(const char *nickname,
  2190. int warn_if_unnamed)
  2191. {
  2192. char digest[DIGEST_LEN];
  2193. local_routerstatus_t *best=NULL;
  2194. smartlist_t *matches=NULL;
  2195. if (!routerstatus_list || !nickname)
  2196. return NULL;
  2197. if (nickname[0] == '$') {
  2198. if (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))<0)
  2199. return NULL;
  2200. return router_get_combined_status_by_digest(digest);
  2201. } else if (strlen(nickname) == HEX_DIGEST_LEN &&
  2202. (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))==0)) {
  2203. return router_get_combined_status_by_digest(digest);
  2204. }
  2205. matches = smartlist_create();
  2206. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
  2207. {
  2208. if (!strcasecmp(lrs->status.nickname, nickname)) {
  2209. if (lrs->status.is_named) {
  2210. smartlist_free(matches);
  2211. return lrs;
  2212. } else {
  2213. smartlist_add(matches, lrs);
  2214. best = lrs;
  2215. }
  2216. }
  2217. });
  2218. if (smartlist_len(matches)>1 && warn_if_unnamed) {
  2219. int any_unwarned=0;
  2220. SMARTLIST_FOREACH(matches, local_routerstatus_t *, lrs,
  2221. {
  2222. if (! lrs->name_lookup_warned) {
  2223. lrs->name_lookup_warned=1;
  2224. any_unwarned=1;
  2225. }
  2226. });
  2227. if (any_unwarned) {
  2228. log_warn(LD_CONFIG,"There are multiple matches for the nickname \"%s\",",
  2229. " but none is listed as named by the directory authorites. "
  2230. "Choosing one arbitrarily.");
  2231. }
  2232. } else if (warn_if_unnamed && best && !best->name_lookup_warned) {
  2233. char fp[HEX_DIGEST_LEN+1];
  2234. base16_encode(fp, sizeof(fp),
  2235. best->status.identity_digest, DIGEST_LEN);
  2236. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
  2237. "directory authorities do not have a binding for this nickname. "
  2238. "To make sure you get the same server in the future, refer to "
  2239. "it by key, as \"$%s\".", nickname, fp);
  2240. best->name_lookup_warned = 1;
  2241. }
  2242. smartlist_free(matches);
  2243. return best;
  2244. }
  2245. /** Return true iff any networkstatus includes a descriptor whose digest
  2246. * is that of <b>desc</b>. */
  2247. static int
  2248. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  2249. {
  2250. routerstatus_t *rs;
  2251. if (!networkstatus_list)
  2252. return 0;
  2253. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2254. {
  2255. if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
  2256. continue;
  2257. if (!memcmp(rs->descriptor_digest,
  2258. desc->signed_descriptor_digest, DIGEST_LEN))
  2259. return 1;
  2260. });
  2261. return 0;
  2262. }
  2263. /** How frequently do directory authorities re-download fresh networkstatus
  2264. * documents? */
  2265. #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
  2266. /** How frequently do non-authority directory caches re-download fresh
  2267. * networkstatus documents? */
  2268. #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
  2269. /** We are a directory server, and so cache network_status documents.
  2270. * Initiate downloads as needed to update them. For authorities, this means
  2271. * asking each trusted directory for its network-status. For caches, this
  2272. * means asking a random authority for all network-statuses.
  2273. */
  2274. static void
  2275. update_networkstatus_cache_downloads(time_t now)
  2276. {
  2277. int authority = authdir_mode(get_options());
  2278. int interval =
  2279. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  2280. if (last_networkstatus_download_attempted + interval >= now)
  2281. return;
  2282. if (!trusted_dir_servers)
  2283. return;
  2284. last_networkstatus_download_attempted = now;
  2285. if (authority) {
  2286. /* An authority launches a separate connection for everybody. */
  2287. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2288. {
  2289. char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
  2290. if (router_digest_is_me(ds->digest))
  2291. continue;
  2292. if (connection_get_by_type_addr_port_purpose(
  2293. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  2294. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  2295. /* We are already fetching this one. */
  2296. continue;
  2297. }
  2298. strlcpy(resource, "fp/", sizeof(resource));
  2299. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  2300. strlcat(resource, ".z", sizeof(resource));
  2301. directory_initiate_command_routerstatus(
  2302. &ds->fake_status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
  2303. 0, /* Not private */
  2304. resource,
  2305. NULL, 0 /* No payload. */);
  2306. });
  2307. } else {
  2308. /* A non-authority cache launches one connection to a random authority. */
  2309. /* (Check whether we're currently fetching network-status objects.) */
  2310. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  2311. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2312. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  2313. }
  2314. }
  2315. /** How long (in seconds) does a client wait after getting a network status
  2316. * before downloading the next in sequence? */
  2317. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  2318. /* How many times do we allow a networkstatus download to fail before we
  2319. * assume that the authority isn't publishing? */
  2320. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  2321. /** We are not a directory cache or authority. Update our network-status list
  2322. * by launching a new directory fetch for enough network-status documents "as
  2323. * necessary". See function comments for implementation details.
  2324. */
  2325. static void
  2326. update_networkstatus_client_downloads(time_t now)
  2327. {
  2328. int n_live = 0, n_dirservers, n_running_dirservers, needed = 0;
  2329. int fetch_latest = 0;
  2330. int most_recent_idx = -1;
  2331. trusted_dir_server_t *most_recent = NULL;
  2332. time_t most_recent_received = 0;
  2333. char *resource, *cp;
  2334. size_t resource_len;
  2335. smartlist_t *missing;
  2336. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  2337. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2338. return;
  2339. /* This is a little tricky. We want to download enough network-status
  2340. * objects so that we have all of them under
  2341. * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
  2342. * *one* if the most recent one's publication time is under
  2343. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  2344. */
  2345. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  2346. return;
  2347. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  2348. missing = smartlist_create();
  2349. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2350. {
  2351. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  2352. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2353. --n_running_dirservers;
  2354. continue;
  2355. }
  2356. if (ns && ns->published_on > now-NETWORKSTATUS_MAX_AGE)
  2357. ++n_live;
  2358. else
  2359. smartlist_add(missing, ds->digest);
  2360. if (ns && (!most_recent || ns->received_on > most_recent_received)) {
  2361. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  2362. most_recent = ds;
  2363. most_recent_received = ns->received_on;
  2364. }
  2365. });
  2366. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  2367. if (!smartlist_len(missing) &&
  2368. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL) {
  2369. log_info(LD_DIR, "Our most recent network-status document (from %s) "
  2370. "is %d seconds old; downloading another.",
  2371. most_recent?most_recent->description:"nobody",
  2372. (int)(now-most_recent_received));
  2373. fetch_latest = 1;
  2374. needed = 1;
  2375. } else if (smartlist_len(missing)) {
  2376. log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
  2377. " network-status documents. Downloading %d.",
  2378. n_running_dirservers, n_dirservers, n_live,
  2379. smartlist_len(missing));
  2380. needed = smartlist_len(missing);
  2381. } else {
  2382. smartlist_free(missing);
  2383. return;
  2384. }
  2385. /* If no networkstatus was found, choose a dirserver at random as "most
  2386. * recent". */
  2387. if (most_recent_idx<0)
  2388. most_recent_idx = crypto_rand_int(n_dirservers);
  2389. if (fetch_latest) {
  2390. int i;
  2391. int n_failed = 0;
  2392. for (i = most_recent_idx + 1; 1; ++i) {
  2393. trusted_dir_server_t *ds;
  2394. if (i >= n_dirservers)
  2395. i = 0;
  2396. ds = smartlist_get(trusted_dir_servers, i);
  2397. if (n_failed < n_dirservers &&
  2398. ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2399. ++n_failed;
  2400. continue;
  2401. }
  2402. smartlist_add(missing, ds->digest);
  2403. break;
  2404. }
  2405. }
  2406. /* Build a request string for all the resources we want. */
  2407. resource_len = smartlist_len(missing) * (HEX_DIGEST_LEN+1) + 6;
  2408. resource = tor_malloc(resource_len);
  2409. memcpy(resource, "fp/", 3);
  2410. cp = resource+3;
  2411. smartlist_sort_digests(missing);
  2412. needed = smartlist_len(missing);
  2413. SMARTLIST_FOREACH(missing, const char *, d,
  2414. {
  2415. base16_encode(cp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  2416. cp += HEX_DIGEST_LEN;
  2417. --needed;
  2418. if (needed)
  2419. *cp++ = '+';
  2420. });
  2421. memcpy(cp, ".z", 3);
  2422. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  2423. tor_free(resource);
  2424. smartlist_free(missing);
  2425. }
  2426. /** Launch requests for networkstatus documents as appropriate. */
  2427. void
  2428. update_networkstatus_downloads(time_t now)
  2429. {
  2430. or_options_t *options = get_options();
  2431. if (options->DirPort)
  2432. update_networkstatus_cache_downloads(now);
  2433. else
  2434. update_networkstatus_client_downloads(now);
  2435. }
  2436. /** Return 1 if all running sufficiently-stable routers will reject
  2437. * addr:port, return 0 if any might accept it. */
  2438. int
  2439. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  2440. int need_uptime)
  2441. {
  2442. addr_policy_result_t r;
  2443. if (!routerlist) return 1;
  2444. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  2445. {
  2446. if (router->is_running &&
  2447. !router_is_unreliable(router, need_uptime, 0, 0)) {
  2448. r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
  2449. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2450. return 0; /* this one could be ok. good enough. */
  2451. }
  2452. });
  2453. return 1; /* all will reject. */
  2454. }
  2455. /** Return true iff <b>router</b> does not permit exit streams.
  2456. */
  2457. int
  2458. router_exit_policy_rejects_all(routerinfo_t *router)
  2459. {
  2460. return compare_addr_to_addr_policy(0, 0, router->exit_policy)
  2461. == ADDR_POLICY_REJECTED;
  2462. }
  2463. /** Add to the list of authorized directory servers one at
  2464. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  2465. * <b>address</b> is NULL, add ourself. */
  2466. void
  2467. add_trusted_dir_server(const char *nickname, const char *address,
  2468. uint16_t port, const char *digest, int is_v1_authority)
  2469. {
  2470. trusted_dir_server_t *ent;
  2471. uint32_t a;
  2472. char *hostname = NULL;
  2473. size_t dlen;
  2474. if (!trusted_dir_servers)
  2475. trusted_dir_servers = smartlist_create();
  2476. if (!address) { /* The address is us; we should guess. */
  2477. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  2478. log_warn(LD_CONFIG,
  2479. "Couldn't find a suitable address when adding ourself as a "
  2480. "trusted directory server.");
  2481. return;
  2482. }
  2483. } else {
  2484. if (tor_lookup_hostname(address, &a)) {
  2485. log_warn(LD_CONFIG,
  2486. "Unable to lookup address for directory server at '%s'",
  2487. address);
  2488. return;
  2489. }
  2490. hostname = tor_strdup(address);
  2491. a = ntohl(a);
  2492. }
  2493. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  2494. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  2495. ent->address = hostname;
  2496. ent->addr = a;
  2497. ent->dir_port = port;
  2498. ent->is_running = 1;
  2499. ent->is_v1_authority = is_v1_authority;
  2500. memcpy(ent->digest, digest, DIGEST_LEN);
  2501. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  2502. ent->description = tor_malloc(dlen);
  2503. if (nickname)
  2504. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  2505. nickname, hostname, (int)port);
  2506. else
  2507. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  2508. hostname, (int)port);
  2509. ent->fake_status.addr = ent->addr;
  2510. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  2511. if (nickname)
  2512. strlcpy(ent->fake_status.nickname, nickname,
  2513. sizeof(ent->fake_status.nickname));
  2514. else
  2515. ent->fake_status.nickname[0] = '\0';
  2516. ent->fake_status.dir_port = ent->dir_port;
  2517. smartlist_add(trusted_dir_servers, ent);
  2518. router_dir_info_changed();
  2519. }
  2520. /** Free storage held in <b>ds</b> */
  2521. void
  2522. trusted_dir_server_free(trusted_dir_server_t *ds)
  2523. {
  2524. tor_free(ds->nickname);
  2525. tor_free(ds->description);
  2526. tor_free(ds->address);
  2527. tor_free(ds);
  2528. }
  2529. /** Remove all members from the list of trusted dir servers. */
  2530. void
  2531. clear_trusted_dir_servers(void)
  2532. {
  2533. if (trusted_dir_servers) {
  2534. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2535. trusted_dir_server_free(ent));
  2536. smartlist_clear(trusted_dir_servers);
  2537. } else {
  2538. trusted_dir_servers = smartlist_create();
  2539. }
  2540. router_dir_info_changed();
  2541. }
  2542. /** Return 1 if any trusted dir server supports v1 directories,
  2543. * else return 0. */
  2544. int
  2545. any_trusted_dir_is_v1_authority(void)
  2546. {
  2547. if (trusted_dir_servers)
  2548. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2549. if (ent->is_v1_authority) return 1);
  2550. return 0;
  2551. }
  2552. /** Return the network status with a given identity digest. */
  2553. networkstatus_t *
  2554. networkstatus_get_by_digest(const char *digest)
  2555. {
  2556. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2557. {
  2558. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  2559. return ns;
  2560. });
  2561. return NULL;
  2562. }
  2563. /** We believe networkstatuses more recent than this when they tell us that
  2564. * our server is broken, invalid, obsolete, etc. */
  2565. #define SELF_OPINION_INTERVAL (90*60)
  2566. /** Return a string naming the versions of Tor recommended by
  2567. * more than half the versioning networkstatuses. */
  2568. static char *
  2569. compute_recommended_versions(time_t now, int client)
  2570. {
  2571. int n_seen;
  2572. char *current;
  2573. smartlist_t *combined, *recommended;
  2574. int n_versioning;
  2575. char *result;
  2576. (void) now; /* right now, we consider *all* ors. */
  2577. if (!networkstatus_list)
  2578. return tor_strdup("<none>");
  2579. combined = smartlist_create();
  2580. n_versioning = 0;
  2581. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2582. {
  2583. const char *vers;
  2584. smartlist_t *versions;
  2585. if (! ns->recommends_versions)
  2586. continue;
  2587. n_versioning++;
  2588. vers = client ? ns->client_versions : ns->server_versions;
  2589. if (!vers)
  2590. continue;
  2591. versions = smartlist_create();
  2592. smartlist_split_string(versions, vers, ",",
  2593. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2594. sort_version_list(versions, 1);
  2595. smartlist_add_all(combined, versions);
  2596. smartlist_free(versions);
  2597. });
  2598. sort_version_list(combined, 0);
  2599. current = NULL;
  2600. n_seen = 0;
  2601. recommended = smartlist_create();
  2602. SMARTLIST_FOREACH(combined, char *, cp,
  2603. {
  2604. if (current && !strcmp(cp, current)) {
  2605. ++n_seen;
  2606. } else {
  2607. if (n_seen >= n_versioning/2 && current)
  2608. smartlist_add(recommended, current);
  2609. n_seen = 0;
  2610. current = cp;
  2611. }
  2612. });
  2613. if (n_seen >= n_versioning/2 && current)
  2614. smartlist_add(recommended, current);
  2615. result = smartlist_join_strings(recommended, ", ", 0, NULL);
  2616. SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
  2617. smartlist_free(combined);
  2618. smartlist_free(recommended);
  2619. return result;
  2620. }
  2621. /** If the network-status list has changed since the last time we called this
  2622. * function, update the status of every routerinfo from the network-status
  2623. * list.
  2624. */
  2625. void
  2626. routers_update_all_from_networkstatus(void)
  2627. {
  2628. routerinfo_t *me;
  2629. time_t now;
  2630. if (!routerlist || !networkstatus_list ||
  2631. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  2632. return;
  2633. router_dir_info_changed();
  2634. now = time(NULL);
  2635. if (networkstatus_list_has_changed)
  2636. routerstatus_list_update_from_networkstatus(now);
  2637. routers_update_status_from_networkstatus(routerlist->routers, 0);
  2638. me = router_get_my_routerinfo();
  2639. if (me && !have_warned_about_invalid_status &&
  2640. have_tried_downloading_all_statuses(4)) {
  2641. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0, n_naming = 0;
  2642. routerstatus_t *rs;
  2643. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2644. {
  2645. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  2646. continue;
  2647. ++n_recent;
  2648. if (ns->binds_names)
  2649. ++n_naming;
  2650. if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
  2651. continue;
  2652. ++n_listing;
  2653. if (rs->is_valid)
  2654. ++n_valid;
  2655. if (rs->is_named)
  2656. ++n_named;
  2657. });
  2658. if (n_listing) {
  2659. if (n_valid <= n_listing/2) {
  2660. log_info(LD_GENERAL,
  2661. "%d/%d recent statements from directory authorities list us "
  2662. "as unapproved. Are you misconfigured?",
  2663. n_listing-n_valid, n_listing);
  2664. have_warned_about_invalid_status = 1;
  2665. } else if (n_naming && !n_named) {
  2666. log_info(LD_GENERAL, "0/%d name-binding directory authorities "
  2667. "recognize your nickname. Please consider sending your "
  2668. "nickname and identity fingerprint to the tor-ops.",
  2669. n_naming);
  2670. have_warned_about_invalid_status = 1;
  2671. }
  2672. }
  2673. }
  2674. entry_guards_set_status_from_directory();
  2675. if (!have_warned_about_old_version &&
  2676. have_tried_downloading_all_statuses(4)) {
  2677. int n_versioning = 0;
  2678. int n_recommended = 0;
  2679. int is_server = server_mode(get_options());
  2680. version_status_t consensus = VS_RECOMMENDED;
  2681. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2682. {
  2683. version_status_t vs;
  2684. if (!ns->recommends_versions)
  2685. continue;
  2686. vs = tor_version_is_obsolete(
  2687. VERSION, is_server ? ns->server_versions : ns->client_versions);
  2688. if (vs == VS_RECOMMENDED)
  2689. ++n_recommended;
  2690. if (n_versioning++ == 0) {
  2691. consensus = vs;
  2692. } else if (consensus != vs) {
  2693. consensus = version_status_join(consensus, vs);
  2694. }
  2695. });
  2696. if (n_versioning && n_recommended <= n_versioning/2) {
  2697. if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
  2698. if (!have_warned_about_new_version) {
  2699. char *rec = compute_recommended_versions(now, !is_server);
  2700. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  2701. "recommended version%s, according to %d/%d network "
  2702. "statuses. Versions recommended by more than %d "
  2703. "authorit%s are: %s",
  2704. VERSION,
  2705. consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  2706. n_versioning-n_recommended, n_versioning, n_versioning/2,
  2707. n_versioning/2 > 1 ? "ies" : "y", rec);
  2708. have_warned_about_new_version = 1;
  2709. tor_free(rec);
  2710. }
  2711. } else {
  2712. char *rec = compute_recommended_versions(now, !is_server);
  2713. log_warn(LD_GENERAL, "Please upgrade! "
  2714. "This version of Tor (%s) is %s, according to "
  2715. "%d/%d network statuses. Versions recommended by "
  2716. "at least %d authorit%s are: %s",
  2717. VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
  2718. n_versioning-n_recommended, n_versioning, n_versioning/2,
  2719. n_versioning/2 > 1 ? "ies" : "y", rec);
  2720. have_warned_about_old_version = 1;
  2721. tor_free(rec);
  2722. }
  2723. } else {
  2724. log_info(LD_GENERAL, "%d/%d statements from "
  2725. "directory authorities say my version is ok.",
  2726. n_recommended, n_versioning);
  2727. }
  2728. }
  2729. routerstatus_list_has_changed = 0;
  2730. }
  2731. /** Allow any network-status newer than this to influence our view of who's
  2732. * running. */
  2733. #define DEFAULT_RUNNING_INTERVAL (60*60)
  2734. /** If possible, always allow at least this many network-statuses to influence
  2735. * our view of who's running. */
  2736. #define MIN_TO_INFLUENCE_RUNNING 3
  2737. /** Change the is_recent field of each member of networkstatus_list so that
  2738. * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
  2739. * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
  2740. * others are recent. Set networkstatus_list_has_changed if anything happened.
  2741. */
  2742. void
  2743. networkstatus_list_update_recent(time_t now)
  2744. {
  2745. int n_statuses, n_recent, changed, i;
  2746. char published[ISO_TIME_LEN+1];
  2747. if (!networkstatus_list)
  2748. return;
  2749. n_statuses = smartlist_len(networkstatus_list);
  2750. n_recent = 0;
  2751. changed = 0;
  2752. for (i=n_statuses-1; i >= 0; --i) {
  2753. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2754. trusted_dir_server_t *ds =
  2755. router_get_trusteddirserver_by_digest(ns->identity_digest);
  2756. const char *src = ds?ds->description:ns->source_address;
  2757. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  2758. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  2759. if (!ns->is_recent) {
  2760. format_iso_time(published, ns->published_on);
  2761. log_info(LD_DIR,
  2762. "Networkstatus from %s (published %s) is now \"recent\"",
  2763. src, published);
  2764. changed = 1;
  2765. }
  2766. ns->is_recent = 1;
  2767. ++n_recent;
  2768. } else {
  2769. if (ns->is_recent) {
  2770. format_iso_time(published, ns->published_on);
  2771. log_info(LD_DIR,
  2772. "Networkstatus from %s (published %s) is "
  2773. "no longer \"recent\"",
  2774. src, published);
  2775. changed = 1;
  2776. ns->is_recent = 0;
  2777. }
  2778. }
  2779. }
  2780. if (changed) {
  2781. networkstatus_list_has_changed = 1;
  2782. router_dir_info_changed();
  2783. }
  2784. }
  2785. /** Helper for routerstatus_list_update_from_networkstatus: remember how many
  2786. * authorities recommend a given descriptor digest. */
  2787. typedef struct {
  2788. routerstatus_t *rs;
  2789. int count;
  2790. } desc_digest_count_t;
  2791. /** Update our view of router status (as stored in routerstatus_list) from the
  2792. * current set of network status documents (as stored in networkstatus_list).
  2793. * Do nothing unless the network status list has changed since the last time
  2794. * this function was called.
  2795. */
  2796. static void
  2797. routerstatus_list_update_from_networkstatus(time_t now)
  2798. {
  2799. or_options_t *options = get_options();
  2800. int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
  2801. int i, j, warned;
  2802. int *index, *size;
  2803. networkstatus_t **networkstatus;
  2804. smartlist_t *result;
  2805. strmap_t *name_map;
  2806. char conflict[DIGEST_LEN]; /* Sentinel value */
  2807. desc_digest_count_t *digest_counts = NULL;
  2808. /* compute which network statuses will have a vote now */
  2809. networkstatus_list_update_recent(now);
  2810. router_dir_info_changed();
  2811. if (!networkstatus_list_has_changed)
  2812. return;
  2813. if (!networkstatus_list)
  2814. networkstatus_list = smartlist_create();
  2815. if (!routerstatus_list)
  2816. routerstatus_list = smartlist_create();
  2817. if (!trusted_dir_servers)
  2818. trusted_dir_servers = smartlist_create();
  2819. if (!warned_conflicts)
  2820. warned_conflicts = smartlist_create();
  2821. n_trusted = smartlist_len(trusted_dir_servers);
  2822. n_statuses = smartlist_len(networkstatus_list);
  2823. if (n_statuses <= n_trusted/2) {
  2824. /* Not enough statuses to adjust status. */
  2825. log_info(LD_DIR,
  2826. "Not enough statuses to update router status list. (%d/%d)",
  2827. n_statuses, n_trusted);
  2828. return;
  2829. }
  2830. log_info(LD_DIR, "Rebuilding router status list.");
  2831. index = tor_malloc(sizeof(int)*n_statuses);
  2832. size = tor_malloc(sizeof(int)*n_statuses);
  2833. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  2834. for (i = 0; i < n_statuses; ++i) {
  2835. index[i] = 0;
  2836. networkstatus[i] = smartlist_get(networkstatus_list, i);
  2837. size[i] = smartlist_len(networkstatus[i]->entries);
  2838. if (networkstatus[i]->binds_names)
  2839. ++n_naming;
  2840. if (networkstatus[i]->is_recent)
  2841. ++n_recent;
  2842. }
  2843. /** Iterate over all entries in all networkstatuses, and build
  2844. * name_map as a map from lc nickname to identity digest. If there
  2845. * is a conflict on that nickname, map the lc nickname to conflict.
  2846. */
  2847. name_map = strmap_new();
  2848. /* Clear the global map... */
  2849. if (named_server_map)
  2850. strmap_free(named_server_map, _tor_free);
  2851. named_server_map = strmap_new();
  2852. memset(conflict, 0xff, sizeof(conflict));
  2853. for (i = 0; i < n_statuses; ++i) {
  2854. if (!networkstatus[i]->binds_names)
  2855. continue;
  2856. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  2857. {
  2858. const char *other_digest;
  2859. if (!rs->is_named)
  2860. continue;
  2861. other_digest = strmap_get_lc(name_map, rs->nickname);
  2862. warned = smartlist_string_isin(warned_conflicts, rs->nickname);
  2863. if (!other_digest) {
  2864. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  2865. strmap_set_lc(named_server_map, rs->nickname,
  2866. tor_memdup(rs->identity_digest, DIGEST_LEN));
  2867. if (warned)
  2868. smartlist_string_remove(warned_conflicts, rs->nickname);
  2869. } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  2870. other_digest != conflict) {
  2871. if (!warned) {
  2872. char *d;
  2873. int should_warn = options->DirPort && options->AuthoritativeDir;
  2874. char fp1[HEX_DIGEST_LEN+1];
  2875. char fp2[HEX_DIGEST_LEN+1];
  2876. base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
  2877. base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
  2878. log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
  2879. "Naming authorities disagree about which key goes with %s. "
  2880. "($%s vs $%s)",
  2881. rs->nickname, fp1, fp2);
  2882. strmap_set_lc(name_map, rs->nickname, conflict);
  2883. d = strmap_remove_lc(named_server_map, rs->nickname);
  2884. tor_free(d);
  2885. smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
  2886. }
  2887. } else {
  2888. if (warned)
  2889. smartlist_string_remove(warned_conflicts, rs->nickname);
  2890. }
  2891. });
  2892. }
  2893. result = smartlist_create();
  2894. digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
  2895. /* Iterate through all of the sorted routerstatus lists in lockstep.
  2896. * Invariants:
  2897. * - For 0 <= i < n_statuses: index[i] is an index into
  2898. * networkstatus[i]->entries, which has size[i] elements.
  2899. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  2900. * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
  2901. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  2902. *
  2903. * (That is, the indices are always advanced past lower digest before
  2904. * higher.)
  2905. */
  2906. while (1) {
  2907. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  2908. int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0;
  2909. int n_desc_digests=0, highest_count=0;
  2910. const char *the_name = NULL;
  2911. local_routerstatus_t *rs_out, *rs_old;
  2912. routerstatus_t *rs, *most_recent;
  2913. networkstatus_t *ns;
  2914. const char *lowest = NULL;
  2915. /* Find out which of the digests appears first. */
  2916. for (i = 0; i < n_statuses; ++i) {
  2917. if (index[i] < size[i]) {
  2918. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  2919. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  2920. lowest = rs->identity_digest;
  2921. }
  2922. }
  2923. if (!lowest) {
  2924. /* We're out of routers. Great! */
  2925. break;
  2926. }
  2927. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  2928. * match "lowest" are next in order. Iterate over them, incrementing those
  2929. * index[i] as we go. */
  2930. for (i = 0; i < n_statuses; ++i) {
  2931. if (index[i] >= size[i])
  2932. continue;
  2933. ns = networkstatus[i];
  2934. rs = smartlist_get(ns->entries, index[i]);
  2935. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  2936. continue;
  2937. /* At this point, we know that we're looking at a routersatus with
  2938. * identity "lowest".
  2939. */
  2940. ++index[i];
  2941. ++n_listing;
  2942. /* Should we name this router? Only if all the names from naming
  2943. * authorities match. */
  2944. if (rs->is_named && ns->binds_names) {
  2945. if (!the_name)
  2946. the_name = rs->nickname;
  2947. if (!strcasecmp(rs->nickname, the_name)) {
  2948. ++n_named;
  2949. } else if (strcmp(the_name,"**mismatch**")) {
  2950. char hd[HEX_DIGEST_LEN+1];
  2951. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  2952. if (! smartlist_string_isin(warned_conflicts, hd)) {
  2953. log_warn(LD_DIR,
  2954. "Naming authorities disagree about nicknames for $%s "
  2955. "(\"%s\" vs \"%s\")",
  2956. hd, the_name, rs->nickname);
  2957. smartlist_add(warned_conflicts, tor_strdup(hd));
  2958. }
  2959. the_name = "**mismatch**";
  2960. }
  2961. }
  2962. /* Keep a running count of how often which descriptor digests
  2963. * appear. */
  2964. for (j = 0; j < n_desc_digests; ++j) {
  2965. if (!memcmp(rs->descriptor_digest,
  2966. digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
  2967. if (++digest_counts[j].count > highest_count)
  2968. highest_count = digest_counts[j].count;
  2969. goto found;
  2970. }
  2971. }
  2972. digest_counts[n_desc_digests].rs = rs;
  2973. digest_counts[n_desc_digests].count = 1;
  2974. if (!highest_count)
  2975. highest_count = 1;
  2976. ++n_desc_digests;
  2977. found:
  2978. /* Now tally up the easily-tallied flags. */
  2979. if (rs->is_valid)
  2980. ++n_valid;
  2981. if (rs->is_running && ns->is_recent)
  2982. ++n_running;
  2983. if (rs->is_exit)
  2984. ++n_exit;
  2985. if (rs->is_fast)
  2986. ++n_fast;
  2987. if (rs->is_possible_guard)
  2988. ++n_guard;
  2989. if (rs->is_stable)
  2990. ++n_stable;
  2991. if (rs->is_v2_dir)
  2992. ++n_v2_dir;
  2993. }
  2994. /* Go over the descriptor digests and figure out which descriptor we
  2995. * want. */
  2996. most_recent = NULL;
  2997. for (i = 0; i < n_desc_digests; ++i) {
  2998. /* If any digest appears twice or more, ignore those that don't.*/
  2999. if (highest_count >= 2 && digest_counts[i].count < 2)
  3000. continue;
  3001. if (!most_recent ||
  3002. digest_counts[i].rs->published_on > most_recent->published_on)
  3003. most_recent = digest_counts[i].rs;
  3004. }
  3005. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  3006. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  3007. /* Copy status info about this router, if we had any before. */
  3008. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  3009. if (!memcmp(rs_out->status.descriptor_digest,
  3010. most_recent->descriptor_digest, DIGEST_LEN)) {
  3011. rs_out->n_download_failures = rs_old->n_download_failures;
  3012. rs_out->next_attempt_at = rs_old->next_attempt_at;
  3013. }
  3014. rs_out->name_lookup_warned = rs_old->name_lookup_warned;
  3015. }
  3016. smartlist_add(result, rs_out);
  3017. log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
  3018. "named by %d/%d, validated by %d/%d, and %d/%d recent "
  3019. "directories think it's running.",
  3020. rs_out->status.nickname,
  3021. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  3022. n_running, n_recent);
  3023. rs_out->status.is_named = 0;
  3024. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  3025. const char *d = strmap_get_lc(name_map, the_name);
  3026. if (d && d != conflict)
  3027. rs_out->status.is_named = 1;
  3028. if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
  3029. smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
  3030. }
  3031. if (rs_out->status.is_named)
  3032. strlcpy(rs_out->status.nickname, the_name,
  3033. sizeof(rs_out->status.nickname));
  3034. rs_out->status.is_valid = n_valid > n_statuses/2;
  3035. rs_out->status.is_running = n_running > n_recent/2;
  3036. rs_out->status.is_exit = n_exit > n_statuses/2;
  3037. rs_out->status.is_fast = n_fast > n_statuses/2;
  3038. rs_out->status.is_possible_guard = n_guard > n_statuses/2;
  3039. rs_out->status.is_stable = n_stable > n_statuses/2;
  3040. rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
  3041. }
  3042. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3043. local_routerstatus_free(rs));
  3044. smartlist_free(routerstatus_list);
  3045. routerstatus_list = result;
  3046. tor_free(networkstatus);
  3047. tor_free(index);
  3048. tor_free(size);
  3049. tor_free(digest_counts);
  3050. strmap_free(name_map, NULL);
  3051. networkstatus_list_has_changed = 0;
  3052. routerstatus_list_has_changed = 1;
  3053. }
  3054. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  3055. * is_named, is_valid, and is_running fields according to our current
  3056. * networkstatus_t documents. */
  3057. void
  3058. routers_update_status_from_networkstatus(smartlist_t *routers,
  3059. int reset_failures)
  3060. {
  3061. trusted_dir_server_t *ds;
  3062. local_routerstatus_t *rs;
  3063. or_options_t *options = get_options();
  3064. int authdir = options->AuthoritativeDir;
  3065. int namingdir = options->AuthoritativeDir &&
  3066. options->NamingAuthoritativeDir;
  3067. if (!routerstatus_list)
  3068. return;
  3069. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  3070. {
  3071. const char *digest = router->cache_info.identity_digest;
  3072. rs = router_get_combined_status_by_digest(digest);
  3073. ds = router_get_trusteddirserver_by_digest(digest);
  3074. if (!rs)
  3075. continue;
  3076. if (!namingdir)
  3077. router->is_named = rs->status.is_named;
  3078. if (!authdir) {
  3079. /* If we're not an authdir, believe others. */
  3080. router->is_valid = rs->status.is_valid;
  3081. router->is_running = rs->status.is_running;
  3082. router->is_fast = rs->status.is_fast;
  3083. router->is_stable = rs->status.is_stable;
  3084. router->is_possible_guard = rs->status.is_possible_guard;
  3085. }
  3086. if (router->is_running && ds) {
  3087. ds->n_networkstatus_failures = 0;
  3088. }
  3089. if (reset_failures) {
  3090. rs->n_download_failures = 0;
  3091. rs->next_attempt_at = 0;
  3092. }
  3093. });
  3094. router_dir_info_changed();
  3095. }
  3096. /** For every router descriptor we are currently downloading by descriptor
  3097. * digest, set result[d] to 1. */
  3098. static void
  3099. list_pending_descriptor_downloads(digestmap_t *result)
  3100. {
  3101. const char *prefix = "d/";
  3102. size_t p_len = strlen(prefix);
  3103. int i, n_conns;
  3104. connection_t **carray;
  3105. smartlist_t *tmp = smartlist_create();
  3106. tor_assert(result);
  3107. get_connection_array(&carray, &n_conns);
  3108. for (i = 0; i < n_conns; ++i) {
  3109. connection_t *conn = carray[i];
  3110. if (conn->type == CONN_TYPE_DIR &&
  3111. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  3112. !conn->marked_for_close) {
  3113. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3114. if (!strcmpstart(resource, prefix))
  3115. dir_split_resource_into_fingerprints(resource + p_len,
  3116. tmp, NULL, 1, 0);
  3117. }
  3118. }
  3119. SMARTLIST_FOREACH(tmp, char *, d,
  3120. {
  3121. digestmap_set(result, d, (void*)1);
  3122. tor_free(d);
  3123. });
  3124. smartlist_free(tmp);
  3125. }
  3126. /** Launch downloads for all the descriptors whose digests are listed
  3127. * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
  3128. * If <b>source</b> is given, download from <b>source</b>; otherwise,
  3129. * download from an appropriate random directory server.
  3130. */
  3131. static void
  3132. initiate_descriptor_downloads(routerstatus_t *source,
  3133. smartlist_t *digests,
  3134. int lo, int hi)
  3135. {
  3136. int i, n = hi-lo;
  3137. char *resource, *cp;
  3138. size_t r_len;
  3139. if (n <= 0)
  3140. return;
  3141. if (lo < 0)
  3142. lo = 0;
  3143. if (hi > smartlist_len(digests))
  3144. hi = smartlist_len(digests);
  3145. r_len = 8 + (HEX_DIGEST_LEN+1)*n;
  3146. cp = resource = tor_malloc(r_len);
  3147. memcpy(cp, "d/", 2);
  3148. cp += 2;
  3149. for (i = lo; i < hi; ++i) {
  3150. base16_encode(cp, r_len-(cp-resource),
  3151. smartlist_get(digests,i), DIGEST_LEN);
  3152. cp += HEX_DIGEST_LEN;
  3153. *cp++ = '+';
  3154. }
  3155. memcpy(cp-1, ".z", 3);
  3156. if (source) {
  3157. /* We know which authority we want. */
  3158. directory_initiate_command_routerstatus(source,
  3159. DIR_PURPOSE_FETCH_SERVERDESC,
  3160. 0, /* not private */
  3161. resource, NULL, 0);
  3162. } else {
  3163. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  3164. resource,
  3165. 1);
  3166. }
  3167. tor_free(resource);
  3168. }
  3169. /** Clients don't download any descriptor this recent, since it will probably
  3170. * not have propageted to enough caches. */
  3171. #define ESTIMATED_PROPAGATION_TIME (10*60)
  3172. /** Return 0 if this routerstatus is obsolete, too new, isn't
  3173. * running, or otherwise not a descriptor that we would make any
  3174. * use of even if we had it. Else return 1. */
  3175. static INLINE int
  3176. client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
  3177. {
  3178. if (!rs->is_running && !options->FetchUselessDescriptors) {
  3179. /* If we had this router descriptor, we wouldn't even bother using it.
  3180. * But, if we want to have a complete list, fetch it anyway. */
  3181. return 0;
  3182. }
  3183. if (rs->published_on + ROUTER_MAX_AGE < now) {
  3184. /* This one is too old to consider. */
  3185. return 0;
  3186. }
  3187. if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
  3188. /* Most caches probably don't have this descriptor yet. */
  3189. return 0;
  3190. }
  3191. return 1;
  3192. }
  3193. /** Return new list of ID fingerprints for routers that we (as a client) would
  3194. * like to download.
  3195. */
  3196. static smartlist_t *
  3197. router_list_client_downloadable(void)
  3198. {
  3199. int n_downloadable = 0;
  3200. smartlist_t *downloadable = smartlist_create();
  3201. digestmap_t *downloading;
  3202. time_t now = time(NULL);
  3203. /* these are just used for logging */
  3204. int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_wouldnt_use = 0;
  3205. or_options_t *options = get_options();
  3206. if (!routerstatus_list)
  3207. return downloadable;
  3208. downloading = digestmap_new();
  3209. list_pending_descriptor_downloads(downloading);
  3210. routerstatus_list_update_from_networkstatus(now);
  3211. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3212. {
  3213. routerinfo_t *ri;
  3214. if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
  3215. /* We have the 'best' descriptor for this router. */
  3216. ++n_uptodate;
  3217. } else if (!client_would_use_router(&rs->status, now, options)) {
  3218. /* We wouldn't want this descriptor even if we got it. */
  3219. ++n_wouldnt_use;
  3220. } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
  3221. /* We're downloading this one now. */
  3222. ++n_in_progress;
  3223. } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
  3224. ri->cache_info.published_on > rs->status.published_on) {
  3225. /* Oddly, we have a descriptor more recent than the 'best' one, but it
  3226. was once best. So that's okay. */
  3227. ++n_uptodate;
  3228. } else if (rs->next_attempt_at > now) {
  3229. /* We failed too recently to try again. */
  3230. ++n_not_ready;
  3231. } else {
  3232. /* Okay, time to try it. */
  3233. smartlist_add(downloadable, rs->status.descriptor_digest);
  3234. ++n_downloadable;
  3235. }
  3236. });
  3237. #if 0
  3238. log_info(LD_DIR,
  3239. "%d router descriptors are downloadable. "
  3240. "%d are in progress. %d are up-to-date. "
  3241. "%d are non-useful. %d failed too recently to retry.",
  3242. n_downloadable, n_in_progress, n_uptodate,
  3243. n_wouldnt_use, n_not_ready);
  3244. #endif
  3245. digestmap_free(downloading, NULL);
  3246. return downloadable;
  3247. }
  3248. /** Initiate new router downloads as needed, using the strategy for
  3249. * non-directory-servers.
  3250. *
  3251. * We only allow one router descriptor download at a time.
  3252. * If we have less than two network-status documents, we ask
  3253. * a directory for "all descriptors."
  3254. * Otherwise, we ask for all descriptors that we think are different
  3255. * from what we have.
  3256. */
  3257. static void
  3258. update_router_descriptor_client_downloads(time_t now)
  3259. {
  3260. /* Max amount of hashes to download per request.
  3261. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3262. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3263. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3264. * So use 96 because it's a nice number.
  3265. */
  3266. #define MAX_DL_PER_REQUEST 96
  3267. /** Don't split our requests so finely that we are requesting fewer than
  3268. * this number per server. */
  3269. #define MIN_DL_PER_REQUEST 4
  3270. /** To prevent a single screwy cache from confusing us by selective reply,
  3271. * try to split our requests into at least this this many requests. */
  3272. #define MIN_REQUESTS 3
  3273. /** If we want fewer than this many descriptors, wait until we
  3274. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3275. * passed. */
  3276. #define MAX_DL_TO_DELAY 16
  3277. /** When directory clients have only a few servers to request, they batch
  3278. * them until they have more, or until this amount of time has passed. */
  3279. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3280. smartlist_t *downloadable = NULL;
  3281. int should_delay, n_downloadable;
  3282. or_options_t *options = get_options();
  3283. if (options->DirPort) {
  3284. log_warn(LD_BUG,
  3285. "Called router_descriptor_client_downloads() on a dir mirror?");
  3286. }
  3287. if (rep_hist_circbuilding_dormant(now)) {
  3288. log_info(LD_CIRC, "Skipping descriptor downloads: we haven't needed "
  3289. "any circuits lately.");
  3290. return;
  3291. }
  3292. if (networkstatus_list && smartlist_len(networkstatus_list) <=
  3293. smartlist_len(trusted_dir_servers)/2) {
  3294. log_info(LD_DIR,
  3295. "Not enough networkstatus documents to launch requests.");
  3296. }
  3297. downloadable = router_list_client_downloadable();
  3298. n_downloadable = smartlist_len(downloadable);
  3299. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3300. log_debug(LD_DIR,
  3301. "There are enough downloadable routerdescs to launch requests.");
  3302. should_delay = 0;
  3303. } else if (n_downloadable == 0) {
  3304. // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
  3305. should_delay = 1;
  3306. } else {
  3307. should_delay = (last_routerdesc_download_attempted +
  3308. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3309. if (!should_delay) {
  3310. if (last_routerdesc_download_attempted) {
  3311. log_info(LD_DIR,
  3312. "There are not many downloadable routerdescs, but we've "
  3313. "been waiting long enough (%d seconds). Downloading.",
  3314. (int)(now-last_routerdesc_download_attempted));
  3315. } else {
  3316. log_info(LD_DIR,
  3317. "There are not many downloadable routerdescs, but we haven't "
  3318. "tried downloading descriptors recently. Downloading.");
  3319. }
  3320. }
  3321. }
  3322. if (! should_delay) {
  3323. int i, n_per_request;
  3324. n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
  3325. if (n_per_request > MAX_DL_PER_REQUEST)
  3326. n_per_request = MAX_DL_PER_REQUEST;
  3327. if (n_per_request < MIN_DL_PER_REQUEST)
  3328. n_per_request = MIN_DL_PER_REQUEST;
  3329. log_info(LD_DIR,
  3330. "Launching %d request%s for %d router%s, %d at a time",
  3331. (n_downloadable+n_per_request-1)/n_per_request,
  3332. n_downloadable>n_per_request?"s":"",
  3333. n_downloadable, n_downloadable>1?"s":"", n_per_request);
  3334. smartlist_sort_digests(downloadable);
  3335. for (i=0; i < n_downloadable; i += n_per_request) {
  3336. initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
  3337. }
  3338. last_routerdesc_download_attempted = now;
  3339. }
  3340. smartlist_free(downloadable);
  3341. }
  3342. /** Launch downloads for router status as needed, using the strategy used by
  3343. * authorities and caches: download every descriptor we don't have but would
  3344. * serve from a random authoritiy that lists it. */
  3345. static void
  3346. update_router_descriptor_cache_downloads(time_t now)
  3347. {
  3348. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3349. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3350. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3351. int i, j, n;
  3352. int n_download;
  3353. or_options_t *options = get_options();
  3354. (void) now;
  3355. if (!options->DirPort) {
  3356. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
  3357. "on a non-dir-mirror?");
  3358. }
  3359. if (!networkstatus_list || !smartlist_len(networkstatus_list))
  3360. return;
  3361. map = digestmap_new();
  3362. n = smartlist_len(networkstatus_list);
  3363. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3364. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3365. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3366. * downloading. */
  3367. list_pending_descriptor_downloads(map);
  3368. /* For the digest of every descriptor that we don't have, and that we aren't
  3369. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3370. * about that descriptor, and we haven't already failed to get that
  3371. * descriptor from the corresponding authority.
  3372. */
  3373. n_download = 0;
  3374. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3375. {
  3376. smartlist_t *dl = smartlist_create();
  3377. downloadable[ns_sl_idx] = dl;
  3378. download_from[ns_sl_idx] = smartlist_create();
  3379. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  3380. {
  3381. if (!rs->need_to_mirror)
  3382. continue;
  3383. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3384. log_warn(LD_BUG,
  3385. "Bug: We have a router descriptor, but need_to_mirror=1.");
  3386. rs->need_to_mirror = 0;
  3387. continue;
  3388. }
  3389. if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
  3390. rs->need_to_mirror = 0;
  3391. continue;
  3392. }
  3393. if (digestmap_get(map, rs->descriptor_digest)) {
  3394. /* We're downloading it already. */
  3395. continue;
  3396. } else {
  3397. /* We could download it from this guy. */
  3398. smartlist_add(dl, rs->descriptor_digest);
  3399. ++n_download;
  3400. }
  3401. });
  3402. });
  3403. /* At random, assign descriptors to authorities such that:
  3404. * - if d is a member of some downloadable[x], d is a member of some
  3405. * download_from[y]. (Everything we want to download, we try to download
  3406. * from somebody.)
  3407. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3408. * (We only try to download descriptors from authorities who claim to have
  3409. * them.)
  3410. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3411. * (We don't try to download anything from two authorities concurrently.)
  3412. */
  3413. while (n_download) {
  3414. int which_ns = crypto_rand_int(n);
  3415. smartlist_t *dl = downloadable[which_ns];
  3416. int idx;
  3417. char *d;
  3418. tor_assert(dl);
  3419. if (!smartlist_len(dl))
  3420. continue;
  3421. idx = crypto_rand_int(smartlist_len(dl));
  3422. d = smartlist_get(dl, idx);
  3423. if (! digestmap_get(map, d)) {
  3424. smartlist_add(download_from[which_ns], d);
  3425. digestmap_set(map, d, (void*) 1);
  3426. }
  3427. smartlist_del(dl, idx);
  3428. --n_download;
  3429. }
  3430. /* Now, we can actually launch our requests. */
  3431. for (i=0; i<n; ++i) {
  3432. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  3433. trusted_dir_server_t *ds =
  3434. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3435. smartlist_t *dl = download_from[i];
  3436. if (!ds) {
  3437. log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
  3438. continue;
  3439. }
  3440. if (! smartlist_len(dl))
  3441. continue;
  3442. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3443. smartlist_len(dl), ds->nickname);
  3444. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3445. initiate_descriptor_downloads(&(ds->fake_status), dl, j,
  3446. j+MAX_DL_PER_REQUEST);
  3447. }
  3448. }
  3449. for (i=0; i<n; ++i) {
  3450. smartlist_free(download_from[i]);
  3451. smartlist_free(downloadable[i]);
  3452. }
  3453. tor_free(download_from);
  3454. tor_free(downloadable);
  3455. digestmap_free(map,NULL);
  3456. }
  3457. /** Launch downloads for router status as needed. */
  3458. void
  3459. update_router_descriptor_downloads(time_t now)
  3460. {
  3461. or_options_t *options = get_options();
  3462. if (options->DirPort) {
  3463. update_router_descriptor_cache_downloads(now);
  3464. } else {
  3465. update_router_descriptor_client_downloads(now);
  3466. }
  3467. }
  3468. static int
  3469. routerstatus_count_usable_entries(smartlist_t *entries)
  3470. {
  3471. int count = 0;
  3472. time_t now = time(NULL);
  3473. or_options_t *options = get_options();
  3474. SMARTLIST_FOREACH(entries, routerstatus_t *, rs,
  3475. if (client_would_use_router(rs, now, options)) count++);
  3476. return count;
  3477. }
  3478. static int have_min_dir_info = 0;
  3479. static int need_to_update_have_min_dir_info = 1;
  3480. /** Return true iff we have enough networkstatus and router information to
  3481. * start building circuits. Right now, this means "more than half the
  3482. * networkstatus documents, and at least 1/4 of expected routers." */
  3483. //XXX should consider whether we have enough exiting nodes here.
  3484. int
  3485. router_have_minimum_dir_info(void)
  3486. {
  3487. if (need_to_update_have_min_dir_info) {
  3488. update_router_have_minimum_dir_info();
  3489. need_to_update_have_min_dir_info = 0;
  3490. }
  3491. return have_min_dir_info;
  3492. }
  3493. /** DOCDOC
  3494. * Must change when authorities change, networkstatuses change, or list of
  3495. * routerdescs changes, or number of running routers changes.
  3496. */
  3497. static void
  3498. router_dir_info_changed(void)
  3499. {
  3500. need_to_update_have_min_dir_info = 1;
  3501. }
  3502. /** DOCDOC */
  3503. static void
  3504. update_router_have_minimum_dir_info(void)
  3505. {
  3506. int tot = 0, num_running = 0;
  3507. int n_ns, n_authorities, res, avg;
  3508. if (!networkstatus_list || !routerlist) {
  3509. res = 0;
  3510. goto done;
  3511. }
  3512. n_authorities = smartlist_len(trusted_dir_servers);
  3513. n_ns = smartlist_len(networkstatus_list);
  3514. if (n_ns<=n_authorities/2) {
  3515. log_info(LD_DIR,
  3516. "We have %d of %d network statuses, and we want "
  3517. "more than %d.", n_ns, n_authorities, n_authorities/2);
  3518. res = 0;
  3519. goto done;
  3520. }
  3521. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3522. tot += routerstatus_count_usable_entries(ns->entries));
  3523. avg = tot / n_ns;
  3524. if (!routerstatus_list)
  3525. routerstatus_list = smartlist_create();
  3526. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3527. {
  3528. if (rs->status.is_running)
  3529. num_running++;
  3530. });
  3531. res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
  3532. done:
  3533. if (res && !have_min_dir_info) {
  3534. log(LOG_NOTICE, LD_DIR,
  3535. "We now have enough directory information to build circuits.");
  3536. }
  3537. if (!res && have_min_dir_info) {
  3538. log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
  3539. "enough to build circuits.%s",
  3540. num_running > 2 ? "" : " (Not enough servers seem reachable -- "
  3541. "is your network connection down?)");
  3542. }
  3543. need_to_update_have_min_dir_info = 0;
  3544. have_min_dir_info = res;
  3545. }
  3546. /** Return true iff we have downloaded, or attempted to download at least
  3547. * n_failures times, a network status for each authority. */
  3548. static int
  3549. have_tried_downloading_all_statuses(int n_failures)
  3550. {
  3551. if (!trusted_dir_servers)
  3552. return 0;
  3553. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  3554. {
  3555. /* If we don't have the status, and we haven't failed to get the status,
  3556. * we haven't tried to get the status. */
  3557. if (!networkstatus_get_by_digest(ds->digest) &&
  3558. ds->n_networkstatus_failures <= n_failures)
  3559. return 0;
  3560. });
  3561. return 1;
  3562. }
  3563. /** Reset the descriptor download failure count on all routers, so that we
  3564. * can retry any long-failed routers immediately.
  3565. */
  3566. void
  3567. router_reset_descriptor_download_failures(void)
  3568. {
  3569. if (!routerstatus_list)
  3570. return;
  3571. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3572. {
  3573. rs->n_download_failures = 0;
  3574. rs->next_attempt_at = 0;
  3575. });
  3576. tor_assert(networkstatus_list);
  3577. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3578. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  3579. {
  3580. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  3581. rs->need_to_mirror = 1;
  3582. }));
  3583. last_routerdesc_download_attempted = 0;
  3584. }
  3585. /** Any changes in a router descriptor's publication time larger than this are
  3586. * automatically non-cosmetic. */
  3587. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  3588. /** We allow uptime to vary from how much it ought to be by this much. */
  3589. #define ROUTER_ALLOW_UPTIME_DRIFT (30*60)
  3590. /** Return true iff the only differences between r1 and r2 are such that
  3591. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  3592. */
  3593. int
  3594. router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
  3595. {
  3596. time_t r1pub, r2pub;
  3597. tor_assert(r1 && r2);
  3598. /* r1 should be the one that was published first. */
  3599. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  3600. routerinfo_t *ri_tmp = r2;
  3601. r2 = r1;
  3602. r1 = ri_tmp;
  3603. }
  3604. /* If any key fields differ, they're different. */
  3605. if (strcasecmp(r1->address, r2->address) ||
  3606. strcasecmp(r1->nickname, r2->nickname) ||
  3607. r1->or_port != r2->or_port ||
  3608. r1->dir_port != r2->dir_port ||
  3609. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  3610. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  3611. strcasecmp(r1->platform, r2->platform) ||
  3612. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  3613. (!r1->contact_info && r2->contact_info) ||
  3614. (r1->contact_info && r2->contact_info &&
  3615. strcasecmp(r1->contact_info, r2->contact_info)) ||
  3616. r1->is_hibernating != r2->is_hibernating ||
  3617. r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
  3618. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  3619. return 0;
  3620. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  3621. return 0;
  3622. if (r1->declared_family && r2->declared_family) {
  3623. int i, n;
  3624. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  3625. return 0;
  3626. n = smartlist_len(r1->declared_family);
  3627. for (i=0; i < n; ++i) {
  3628. if (strcasecmp(smartlist_get(r1->declared_family, i),
  3629. smartlist_get(r2->declared_family, i)))
  3630. return 0;
  3631. }
  3632. }
  3633. /* Did bandwidth change a lot? */
  3634. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  3635. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  3636. return 0;
  3637. /* Did more than 12 hours pass? */
  3638. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  3639. < r2->cache_info.published_on)
  3640. return 0;
  3641. /* Did uptime fail to increase by approximately the amount we would think,
  3642. * give or take 30 minutes? */
  3643. r1pub = r1->cache_info.published_on;
  3644. r2pub = r2->cache_info.published_on;
  3645. if (abs(r2->uptime - (r1->uptime + (r2pub - r1pub)))
  3646. > ROUTER_ALLOW_UPTIME_DRIFT)
  3647. return 0;
  3648. /* Otherwise, the difference is cosmetic. */
  3649. return 1;
  3650. }
  3651. static void
  3652. routerlist_assert_ok(routerlist_t *rl)
  3653. {
  3654. digestmap_iter_t *iter;
  3655. routerinfo_t *r2;
  3656. signed_descriptor_t *sd2;
  3657. if (!routerlist)
  3658. return;
  3659. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  3660. {
  3661. r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
  3662. tor_assert(r == r2);
  3663. sd2 = digestmap_get(rl->desc_digest_map,
  3664. r->cache_info.signed_descriptor_digest);
  3665. tor_assert(&(r->cache_info) == sd2);
  3666. tor_assert(r->routerlist_index == r_sl_idx);
  3667. });
  3668. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  3669. {
  3670. r2 = digestmap_get(rl->identity_map, sd->identity_digest);
  3671. tor_assert(sd != &(r2->cache_info));
  3672. sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  3673. tor_assert(sd == sd2);
  3674. });
  3675. iter = digestmap_iter_init(rl->identity_map);
  3676. while (!digestmap_iter_done(iter)) {
  3677. const char *d;
  3678. void *_r;
  3679. routerinfo_t *r;
  3680. digestmap_iter_get(iter, &d, &_r);
  3681. r = _r;
  3682. tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
  3683. iter = digestmap_iter_next(rl->identity_map, iter);
  3684. }
  3685. iter = digestmap_iter_init(rl->desc_digest_map);
  3686. while (!digestmap_iter_done(iter)) {
  3687. const char *d;
  3688. void *_sd;
  3689. signed_descriptor_t *sd;
  3690. digestmap_iter_get(iter, &d, &_sd);
  3691. sd = _sd;
  3692. tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
  3693. iter = digestmap_iter_next(rl->desc_digest_map, iter);
  3694. }
  3695. }
  3696. /** Allocate and return a new string representing the contact info
  3697. * and platform string for <b>router</b>,
  3698. * surrounded by quotes and using standard C escapes.
  3699. *
  3700. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  3701. * thread. Also, each call invalidates the last-returned value, so don't
  3702. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  3703. */
  3704. const char *
  3705. esc_router_info(routerinfo_t *router)
  3706. {
  3707. static char *info;
  3708. char *esc_contact, *esc_platform;
  3709. size_t len;
  3710. if (info)
  3711. tor_free(info);
  3712. esc_contact = esc_for_log(router->contact_info);
  3713. esc_platform = esc_for_log(router->platform);
  3714. len = strlen(esc_contact)+strlen(esc_platform)+32;
  3715. info = tor_malloc(len);
  3716. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  3717. esc_platform);
  3718. tor_free(esc_contact);
  3719. tor_free(esc_platform);
  3720. return info;
  3721. }