routerlist.c 128 KB

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