routerlist.c 122 KB

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