routerlist.c 129 KB

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