routerlist.c 122 KB

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