routerlist.c 125 KB

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