routerlist.c 113 KB

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