routerlist.c 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerlist.c
  8. * \brief Code to
  9. * maintain and access the global list of routerinfos for known
  10. * servers.
  11. *
  12. * A "routerinfo_t" object represents a single self-signed router
  13. * descriptor, as generated by a Tor relay in order to tell the rest of
  14. * the world about its keys, address, and capabilities. An
  15. * "extrainfo_t" object represents an adjunct "extra-info" object,
  16. * certified by a corresponding router descriptor, reporting more
  17. * information about the relay that nearly all users will not need.
  18. *
  19. * Most users will not use router descriptors for most relays. Instead,
  20. * they use the information in microdescriptors and in the consensus
  21. * networkstatus.
  22. *
  23. * Right now, routerinfo_t objects are used in these ways:
  24. * <ul>
  25. * <li>By clients, in order to learn about bridge keys and capabilities.
  26. * (Bridges aren't listed in the consensus networkstatus, so they
  27. * can't have microdescriptors.)
  28. * <li>By relays, since relays want more information about other relays
  29. * than they can learn from microdescriptors. (TODO: Is this still true?)
  30. * <li>By authorities, which receive them and use them to generate the
  31. * consensus and the microdescriptors.
  32. * <li>By all directory caches, which download them in case somebody
  33. * else wants them.
  34. * </ul>
  35. *
  36. * Routerinfos are mostly created by parsing them from a string, in
  37. * routerparse.c. We store them to disk on receiving them, and
  38. * periodically discard the ones we don't need. On restarting, we
  39. * re-read them from disk. (This also applies to extrainfo documents, if
  40. * we are configured to fetch them.)
  41. *
  42. * In order to keep our list of routerinfos up-to-date, we periodically
  43. * check whether there are any listed in the latest consensus (or in the
  44. * votes from other authorities, if we are an authority) that we don't
  45. * have. (This also applies to extrainfo documents, if we are
  46. * configured to fetch them.)
  47. *
  48. * Almost nothing in Tor should use a routerinfo_t to refer directly to
  49. * a relay; instead, almost everything should use node_t (implemented in
  50. * nodelist.c), which provides a common interface to routerinfo_t,
  51. * routerstatus_t, and microdescriptor_t.
  52. *
  53. * <br>
  54. *
  55. * This module also has some of the functions used for choosing random
  56. * nodes according to different rules and weights. Historically, they
  57. * were all in this module. Now, they are spread across this module,
  58. * nodelist.c, and networkstatus.c. (TODO: Fix that.)
  59. **/
  60. #define ROUTERLIST_PRIVATE
  61. #include "core/or/or.h"
  62. #include "app/config/config.h"
  63. #include "core/mainloop/connection.h"
  64. #include "core/mainloop/mainloop.h"
  65. #include "core/or/policies.h"
  66. #include "feature/client/bridges.h"
  67. #include "feature/control/control.h"
  68. #include "feature/dirauth/authmode.h"
  69. #include "feature/dirauth/process_descs.h"
  70. #include "feature/dirauth/reachability.h"
  71. #include "feature/dircache/dirserv.h"
  72. #include "feature/dirclient/dirclient.h"
  73. #include "feature/dirclient/dlstatus.h"
  74. #include "feature/dircommon/directory.h"
  75. #include "feature/nodelist/authcert.h"
  76. #include "feature/nodelist/describe.h"
  77. #include "feature/nodelist/dirlist.h"
  78. #include "feature/nodelist/microdesc.h"
  79. #include "feature/nodelist/networkstatus.h"
  80. #include "feature/nodelist/node_select.h"
  81. #include "feature/nodelist/nodelist.h"
  82. #include "feature/nodelist/routerinfo.h"
  83. #include "feature/nodelist/routerlist.h"
  84. #include "feature/dirparse/routerparse.h"
  85. #include "feature/nodelist/routerset.h"
  86. #include "feature/nodelist/torcert.h"
  87. #include "feature/relay/routermode.h"
  88. #include "feature/stats/rephist.h"
  89. #include "lib/crypt_ops/crypto_format.h"
  90. #include "lib/crypt_ops/crypto_rand.h"
  91. #include "feature/dircommon/dir_connection_st.h"
  92. #include "feature/dirclient/dir_server_st.h"
  93. #include "feature/nodelist/document_signature_st.h"
  94. #include "feature/nodelist/extrainfo_st.h"
  95. #include "feature/nodelist/networkstatus_st.h"
  96. #include "feature/nodelist/networkstatus_voter_info_st.h"
  97. #include "feature/nodelist/node_st.h"
  98. #include "feature/nodelist/routerinfo_st.h"
  99. #include "feature/nodelist/routerlist_st.h"
  100. #include "feature/nodelist/vote_routerstatus_st.h"
  101. #include "lib/crypt_ops/digestset.h"
  102. #ifdef HAVE_SYS_STAT_H
  103. #include <sys/stat.h>
  104. #endif
  105. // #define DEBUG_ROUTERLIST
  106. /****************************************************************************/
  107. /* Typed wrappers for different digestmap types; used to avoid type
  108. * confusion. */
  109. DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
  110. DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
  111. DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
  112. #define SDMAP_FOREACH(map, keyvar, valvar) \
  113. DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
  114. valvar)
  115. #define RIMAP_FOREACH(map, keyvar, valvar) \
  116. DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
  117. #define EIMAP_FOREACH(map, keyvar, valvar) \
  118. DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
  119. #define eimap_free(map, fn) MAP_FREE_AND_NULL(eimap, (map), (fn))
  120. #define rimap_free(map, fn) MAP_FREE_AND_NULL(rimap, (map), (fn))
  121. #define sdmap_free(map, fn) MAP_FREE_AND_NULL(sdmap, (map), (fn))
  122. /* static function prototypes */
  123. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  124. static const char *signed_descriptor_get_body_impl(
  125. const signed_descriptor_t *desc,
  126. int with_annotations);
  127. static void launch_dummy_descriptor_download_as_needed(time_t now,
  128. const or_options_t *options);
  129. /****************************************************************************/
  130. /** Global list of all of the routers that we know about. */
  131. static routerlist_t *routerlist = NULL;
  132. /** List of strings for nicknames we've already warned about and that are
  133. * still unknown / unavailable. */
  134. static smartlist_t *warned_nicknames = NULL;
  135. /** The last time we tried to download any routerdesc, or 0 for "never". We
  136. * use this to rate-limit download attempts when the number of routerdescs to
  137. * download is low. */
  138. static time_t last_descriptor_download_attempted = 0;
  139. /* Router descriptor storage.
  140. *
  141. * Routerdescs are stored in a big file, named "cached-descriptors". As new
  142. * routerdescs arrive, we append them to a journal file named
  143. * "cached-descriptors.new".
  144. *
  145. * From time to time, we replace "cached-descriptors" with a new file
  146. * containing only the live, non-superseded descriptors, and clear
  147. * cached-descriptors.new.
  148. *
  149. * On startup, we read both files.
  150. */
  151. /** Helper: return 1 iff the router log is so big we want to rebuild the
  152. * store. */
  153. static int
  154. router_should_rebuild_store(desc_store_t *store)
  155. {
  156. if (store->store_len > (1<<16))
  157. return (store->journal_len > store->store_len / 2 ||
  158. store->bytes_dropped > store->store_len / 2);
  159. else
  160. return store->journal_len > (1<<15);
  161. }
  162. /** Return the desc_store_t in <b>rl</b> that should be used to store
  163. * <b>sd</b>. */
  164. static inline desc_store_t *
  165. desc_get_store(routerlist_t *rl, const signed_descriptor_t *sd)
  166. {
  167. if (sd->is_extrainfo)
  168. return &rl->extrainfo_store;
  169. else
  170. return &rl->desc_store;
  171. }
  172. /** Add the signed_descriptor_t in <b>desc</b> to the router
  173. * journal; change its saved_location to SAVED_IN_JOURNAL and set its
  174. * offset appropriately. */
  175. static int
  176. signed_desc_append_to_journal(signed_descriptor_t *desc,
  177. desc_store_t *store)
  178. {
  179. char *fname = get_cachedir_fname_suffix(store->fname_base, ".new");
  180. const char *body = signed_descriptor_get_body_impl(desc,1);
  181. size_t len = desc->signed_descriptor_len + desc->annotations_len;
  182. if (append_bytes_to_file(fname, body, len, 1)) {
  183. log_warn(LD_FS, "Unable to store router descriptor");
  184. tor_free(fname);
  185. return -1;
  186. }
  187. desc->saved_location = SAVED_IN_JOURNAL;
  188. tor_free(fname);
  189. desc->saved_offset = store->journal_len;
  190. store->journal_len += len;
  191. return 0;
  192. }
  193. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  194. * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
  195. * the signed_descriptor_t* in *<b>b</b>. */
  196. static int
  197. compare_signed_descriptors_by_age_(const void **_a, const void **_b)
  198. {
  199. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  200. return (int)(r1->published_on - r2->published_on);
  201. }
  202. #define RRS_FORCE 1
  203. #define RRS_DONT_REMOVE_OLD 2
  204. /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
  205. * <b>flags</b>, then atomically replace the saved router store with the
  206. * routers currently in our routerlist, and clear the journal. Unless
  207. * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
  208. * rebuilding the store. Return 0 on success, -1 on failure.
  209. */
  210. static int
  211. router_rebuild_store(int flags, desc_store_t *store)
  212. {
  213. smartlist_t *chunk_list = NULL;
  214. char *fname = NULL, *fname_tmp = NULL;
  215. int r = -1;
  216. off_t offset = 0;
  217. smartlist_t *signed_descriptors = NULL;
  218. int nocache=0;
  219. size_t total_expected_len = 0;
  220. int had_any;
  221. int force = flags & RRS_FORCE;
  222. if (!force && !router_should_rebuild_store(store)) {
  223. r = 0;
  224. goto done;
  225. }
  226. if (!routerlist) {
  227. r = 0;
  228. goto done;
  229. }
  230. if (store->type == EXTRAINFO_STORE)
  231. had_any = !eimap_isempty(routerlist->extra_info_map);
  232. else
  233. had_any = (smartlist_len(routerlist->routers)+
  234. smartlist_len(routerlist->old_routers))>0;
  235. /* Don't save deadweight. */
  236. if (!(flags & RRS_DONT_REMOVE_OLD))
  237. routerlist_remove_old_routers();
  238. log_info(LD_DIR, "Rebuilding %s cache", store->description);
  239. fname = get_cachedir_fname(store->fname_base);
  240. fname_tmp = get_cachedir_fname_suffix(store->fname_base, ".tmp");
  241. chunk_list = smartlist_new();
  242. /* We sort the routers by age to enhance locality on disk. */
  243. signed_descriptors = smartlist_new();
  244. if (store->type == EXTRAINFO_STORE) {
  245. eimap_iter_t *iter;
  246. for (iter = eimap_iter_init(routerlist->extra_info_map);
  247. !eimap_iter_done(iter);
  248. iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
  249. const char *key;
  250. extrainfo_t *ei;
  251. eimap_iter_get(iter, &key, &ei);
  252. smartlist_add(signed_descriptors, &ei->cache_info);
  253. }
  254. } else {
  255. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  256. smartlist_add(signed_descriptors, sd));
  257. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  258. smartlist_add(signed_descriptors, &ri->cache_info));
  259. }
  260. smartlist_sort(signed_descriptors, compare_signed_descriptors_by_age_);
  261. /* Now, add the appropriate members to chunk_list */
  262. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  263. sized_chunk_t *c;
  264. const char *body = signed_descriptor_get_body_impl(sd, 1);
  265. if (!body) {
  266. log_warn(LD_BUG, "No descriptor available for router.");
  267. goto done;
  268. }
  269. if (sd->do_not_cache) {
  270. ++nocache;
  271. continue;
  272. }
  273. c = tor_malloc(sizeof(sized_chunk_t));
  274. c->bytes = body;
  275. c->len = sd->signed_descriptor_len + sd->annotations_len;
  276. total_expected_len += c->len;
  277. smartlist_add(chunk_list, c);
  278. } SMARTLIST_FOREACH_END(sd);
  279. if (write_chunks_to_file(fname_tmp, chunk_list, 1, 1)<0) {
  280. log_warn(LD_FS, "Error writing router store to disk.");
  281. goto done;
  282. }
  283. /* Our mmap is now invalid. */
  284. if (store->mmap) {
  285. int res = tor_munmap_file(store->mmap);
  286. store->mmap = NULL;
  287. if (res != 0) {
  288. log_warn(LD_FS, "Unable to munmap route store in %s", fname);
  289. }
  290. }
  291. if (replace_file(fname_tmp, fname)<0) {
  292. log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
  293. goto done;
  294. }
  295. errno = 0;
  296. store->mmap = tor_mmap_file(fname);
  297. if (! store->mmap) {
  298. if (errno == ERANGE) {
  299. /* empty store.*/
  300. if (total_expected_len) {
  301. log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
  302. " but when we went to mmap it, it was empty!", fname);
  303. } else if (had_any) {
  304. log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
  305. "okay if we're just starting up after a long time. "
  306. "Otherwise, it's a bug.", fname);
  307. }
  308. } else {
  309. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  310. }
  311. }
  312. log_info(LD_DIR, "Reconstructing pointers into cache");
  313. offset = 0;
  314. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  315. if (sd->do_not_cache)
  316. continue;
  317. sd->saved_location = SAVED_IN_CACHE;
  318. if (store->mmap) {
  319. tor_free(sd->signed_descriptor_body); // sets it to null
  320. sd->saved_offset = offset;
  321. }
  322. offset += sd->signed_descriptor_len + sd->annotations_len;
  323. signed_descriptor_get_body(sd); /* reconstruct and assert */
  324. } SMARTLIST_FOREACH_END(sd);
  325. tor_free(fname);
  326. fname = get_cachedir_fname_suffix(store->fname_base, ".new");
  327. write_str_to_file(fname, "", 1);
  328. r = 0;
  329. store->store_len = (size_t) offset;
  330. store->journal_len = 0;
  331. store->bytes_dropped = 0;
  332. done:
  333. smartlist_free(signed_descriptors);
  334. tor_free(fname);
  335. tor_free(fname_tmp);
  336. if (chunk_list) {
  337. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  338. smartlist_free(chunk_list);
  339. }
  340. return r;
  341. }
  342. /** Helper: Reload a cache file and its associated journal, setting metadata
  343. * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
  344. * else reload the router descriptor store. */
  345. static int
  346. router_reload_router_list_impl(desc_store_t *store)
  347. {
  348. char *fname = NULL, *contents = NULL;
  349. struct stat st;
  350. int extrainfo = (store->type == EXTRAINFO_STORE);
  351. store->journal_len = store->store_len = 0;
  352. fname = get_cachedir_fname(store->fname_base);
  353. if (store->mmap) {
  354. /* get rid of it first */
  355. int res = tor_munmap_file(store->mmap);
  356. store->mmap = NULL;
  357. if (res != 0) {
  358. log_warn(LD_FS, "Failed to munmap %s", fname);
  359. tor_free(fname);
  360. return -1;
  361. }
  362. }
  363. store->mmap = tor_mmap_file(fname);
  364. if (store->mmap) {
  365. store->store_len = store->mmap->size;
  366. if (extrainfo)
  367. router_load_extrainfo_from_string(store->mmap->data,
  368. store->mmap->data+store->mmap->size,
  369. SAVED_IN_CACHE, NULL, 0);
  370. else
  371. router_load_routers_from_string(store->mmap->data,
  372. store->mmap->data+store->mmap->size,
  373. SAVED_IN_CACHE, NULL, 0, NULL);
  374. }
  375. tor_free(fname);
  376. fname = get_cachedir_fname_suffix(store->fname_base, ".new");
  377. /* don't load empty files - we wouldn't get any data, even if we tried */
  378. if (file_status(fname) == FN_FILE)
  379. contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  380. if (contents) {
  381. if (extrainfo)
  382. router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
  383. NULL, 0);
  384. else
  385. router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
  386. NULL, 0, NULL);
  387. store->journal_len = (size_t) st.st_size;
  388. tor_free(contents);
  389. }
  390. tor_free(fname);
  391. if (store->journal_len) {
  392. /* Always clear the journal on startup.*/
  393. router_rebuild_store(RRS_FORCE, store);
  394. } else if (!extrainfo) {
  395. /* Don't cache expired routers. (This is in an else because
  396. * router_rebuild_store() also calls remove_old_routers().) */
  397. routerlist_remove_old_routers();
  398. }
  399. return 0;
  400. }
  401. /** Load all cached router descriptors and extra-info documents from the
  402. * store. Return 0 on success and -1 on failure.
  403. */
  404. int
  405. router_reload_router_list(void)
  406. {
  407. routerlist_t *rl = router_get_routerlist();
  408. if (router_reload_router_list_impl(&rl->desc_store))
  409. return -1;
  410. if (router_reload_router_list_impl(&rl->extrainfo_store))
  411. return -1;
  412. return 0;
  413. }
  414. /* When iterating through the routerlist, can OR address/port preference
  415. * and reachability checks be skipped?
  416. */
  417. int
  418. router_skip_or_reachability(const or_options_t *options, int try_ip_pref)
  419. {
  420. /* Servers always have and prefer IPv4.
  421. * And if clients are checking against the firewall for reachability only,
  422. * but there's no firewall, don't bother checking */
  423. return server_mode(options) || (!try_ip_pref && !firewall_is_fascist_or());
  424. }
  425. /* When iterating through the routerlist, can Dir address/port preference
  426. * and reachability checks be skipped?
  427. */
  428. int
  429. router_skip_dir_reachability(const or_options_t *options, int try_ip_pref)
  430. {
  431. /* Servers always have and prefer IPv4.
  432. * And if clients are checking against the firewall for reachability only,
  433. * but there's no firewall, don't bother checking */
  434. return server_mode(options) || (!try_ip_pref && !firewall_is_fascist_dir());
  435. }
  436. /** Return true iff r1 and r2 have the same address and OR port. */
  437. int
  438. routers_have_same_or_addrs(const routerinfo_t *r1, const routerinfo_t *r2)
  439. {
  440. return r1->addr == r2->addr && r1->or_port == r2->or_port &&
  441. tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) &&
  442. r1->ipv6_orport == r2->ipv6_orport;
  443. }
  444. /** Add every suitable node from our nodelist to <b>sl</b>, so that
  445. * we can pick a node for a circuit.
  446. */
  447. void
  448. router_add_running_nodes_to_smartlist(smartlist_t *sl, int need_uptime,
  449. int need_capacity, int need_guard,
  450. int need_desc, int pref_addr,
  451. int direct_conn)
  452. {
  453. const int check_reach = !router_skip_or_reachability(get_options(),
  454. pref_addr);
  455. /* XXXX MOVE */
  456. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  457. if (!node->is_running || !node->is_valid)
  458. continue;
  459. if (need_desc && !node_has_preferred_descriptor(node, direct_conn))
  460. continue;
  461. if (node->ri && node->ri->purpose != ROUTER_PURPOSE_GENERAL)
  462. continue;
  463. if (node_is_unreliable(node, need_uptime, need_capacity, need_guard))
  464. continue;
  465. /* Don't choose nodes if we are certain they can't do EXTEND2 cells */
  466. if (node->rs && !routerstatus_version_supports_extend2_cells(node->rs, 1))
  467. continue;
  468. /* Don't choose nodes if we are certain they can't do ntor. */
  469. if ((node->ri || node->md) && !node_has_curve25519_onion_key(node))
  470. continue;
  471. /* Choose a node with an OR address that matches the firewall rules */
  472. if (direct_conn && check_reach &&
  473. !fascist_firewall_allows_node(node,
  474. FIREWALL_OR_CONNECTION,
  475. pref_addr))
  476. continue;
  477. smartlist_add(sl, (void *)node);
  478. } SMARTLIST_FOREACH_END(node);
  479. }
  480. /** Look through the routerlist until we find a router that has my key.
  481. Return it. */
  482. const routerinfo_t *
  483. routerlist_find_my_routerinfo(void)
  484. {
  485. if (!routerlist)
  486. return NULL;
  487. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  488. {
  489. if (router_is_me(router))
  490. return router;
  491. });
  492. return NULL;
  493. }
  494. /** Return the smaller of the router's configured BandwidthRate
  495. * and its advertised capacity. */
  496. uint32_t
  497. router_get_advertised_bandwidth(const routerinfo_t *router)
  498. {
  499. if (router->bandwidthcapacity < router->bandwidthrate)
  500. return router->bandwidthcapacity;
  501. return router->bandwidthrate;
  502. }
  503. /** Do not weight any declared bandwidth more than this much when picking
  504. * routers by bandwidth. */
  505. #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
  506. /** Return the smaller of the router's configured BandwidthRate
  507. * and its advertised capacity, capped by max-believe-bw. */
  508. uint32_t
  509. router_get_advertised_bandwidth_capped(const routerinfo_t *router)
  510. {
  511. uint32_t result = router->bandwidthcapacity;
  512. if (result > router->bandwidthrate)
  513. result = router->bandwidthrate;
  514. if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
  515. result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
  516. return result;
  517. }
  518. /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
  519. * Return 0 on success, -1 on failure. Store the result into the
  520. * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
  521. * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
  522. * at <b>nickname_out</b>.
  523. *
  524. * The recognized format is:
  525. * HexName = Dollar? HexDigest NamePart?
  526. * Dollar = '?'
  527. * HexDigest = HexChar*20
  528. * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
  529. * NamePart = QualChar Name
  530. * QualChar = '=' | '~'
  531. * Name = NameChar*(1..MAX_NICKNAME_LEN)
  532. * NameChar = Any ASCII alphanumeric character
  533. */
  534. int
  535. hex_digest_nickname_decode(const char *hexdigest,
  536. char *digest_out,
  537. char *nickname_qualifier_char_out,
  538. char *nickname_out)
  539. {
  540. size_t len;
  541. tor_assert(hexdigest);
  542. if (hexdigest[0] == '$')
  543. ++hexdigest;
  544. len = strlen(hexdigest);
  545. if (len < HEX_DIGEST_LEN) {
  546. return -1;
  547. } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
  548. hexdigest[HEX_DIGEST_LEN] == '~') &&
  549. len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
  550. *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
  551. strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
  552. } else if (len == HEX_DIGEST_LEN) {
  553. ;
  554. } else {
  555. return -1;
  556. }
  557. if (base16_decode(digest_out, DIGEST_LEN,
  558. hexdigest, HEX_DIGEST_LEN) != DIGEST_LEN)
  559. return -1;
  560. return 0;
  561. }
  562. /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
  563. * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
  564. * (which is optionally prefixed with a single dollar sign). Return false if
  565. * <b>hexdigest</b> is malformed, or it doesn't match. */
  566. int
  567. hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest,
  568. const char *nickname)
  569. {
  570. char digest[DIGEST_LEN];
  571. char nn_char='\0';
  572. char nn_buf[MAX_NICKNAME_LEN+1];
  573. if (hex_digest_nickname_decode(hexdigest, digest, &nn_char, nn_buf) == -1)
  574. return 0;
  575. if (nn_char == '=') {
  576. return 0;
  577. }
  578. if (nn_char == '~') {
  579. if (!nickname) // XXX This seems wrong. -NM
  580. return 0;
  581. if (strcasecmp(nn_buf, nickname))
  582. return 0;
  583. }
  584. return tor_memeq(digest, identity_digest, DIGEST_LEN);
  585. }
  586. /** If hexdigest is correctly formed, base16_decode it into
  587. * digest, which must have DIGEST_LEN space in it.
  588. * Return 0 on success, -1 on failure.
  589. */
  590. int
  591. hexdigest_to_digest(const char *hexdigest, char *digest)
  592. {
  593. if (hexdigest[0]=='$')
  594. ++hexdigest;
  595. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  596. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN)
  597. return -1;
  598. return 0;
  599. }
  600. /** As router_get_by_id_digest,but return a pointer that you're allowed to
  601. * modify */
  602. routerinfo_t *
  603. router_get_mutable_by_digest(const char *digest)
  604. {
  605. tor_assert(digest);
  606. if (!routerlist) return NULL;
  607. // routerlist_assert_ok(routerlist);
  608. return rimap_get(routerlist->identity_map, digest);
  609. }
  610. /** Return the router in our routerlist whose 20-byte key digest
  611. * is <b>digest</b>. Return NULL if no such router is known. */
  612. const routerinfo_t *
  613. router_get_by_id_digest(const char *digest)
  614. {
  615. return router_get_mutable_by_digest(digest);
  616. }
  617. /** Return the router in our routerlist whose 20-byte descriptor
  618. * is <b>digest</b>. Return NULL if no such router is known. */
  619. signed_descriptor_t *
  620. router_get_by_descriptor_digest(const char *digest)
  621. {
  622. tor_assert(digest);
  623. if (!routerlist) return NULL;
  624. return sdmap_get(routerlist->desc_digest_map, digest);
  625. }
  626. /** Return the signed descriptor for the router in our routerlist whose
  627. * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
  628. * is known. */
  629. MOCK_IMPL(signed_descriptor_t *,
  630. router_get_by_extrainfo_digest,(const char *digest))
  631. {
  632. tor_assert(digest);
  633. if (!routerlist) return NULL;
  634. return sdmap_get(routerlist->desc_by_eid_map, digest);
  635. }
  636. /** Return the signed descriptor for the extrainfo_t in our routerlist whose
  637. * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
  638. * document is known. */
  639. MOCK_IMPL(signed_descriptor_t *,
  640. extrainfo_get_by_descriptor_digest,(const char *digest))
  641. {
  642. extrainfo_t *ei;
  643. tor_assert(digest);
  644. if (!routerlist) return NULL;
  645. ei = eimap_get(routerlist->extra_info_map, digest);
  646. return ei ? &ei->cache_info : NULL;
  647. }
  648. /** Return a pointer to the signed textual representation of a descriptor.
  649. * The returned string is not guaranteed to be NUL-terminated: the string's
  650. * length will be in desc-\>signed_descriptor_len.
  651. *
  652. * If <b>with_annotations</b> is set, the returned string will include
  653. * the annotations
  654. * (if any) preceding the descriptor. This will increase the length of the
  655. * string by desc-\>annotations_len.
  656. *
  657. * The caller must not free the string returned.
  658. */
  659. static const char *
  660. signed_descriptor_get_body_impl(const signed_descriptor_t *desc,
  661. int with_annotations)
  662. {
  663. const char *r = NULL;
  664. size_t len = desc->signed_descriptor_len;
  665. off_t offset = desc->saved_offset;
  666. if (with_annotations)
  667. len += desc->annotations_len;
  668. else
  669. offset += desc->annotations_len;
  670. tor_assert(len > 32);
  671. if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
  672. desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
  673. if (store && store->mmap) {
  674. tor_assert(desc->saved_offset + len <= store->mmap->size);
  675. r = store->mmap->data + offset;
  676. } else if (store) {
  677. log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
  678. "mmaped in our cache. Is another process running in our data "
  679. "directory? Exiting.");
  680. exit(1); // XXXX bad exit: should recover.
  681. }
  682. }
  683. if (!r) /* no mmap, or not in cache. */
  684. r = desc->signed_descriptor_body +
  685. (with_annotations ? 0 : desc->annotations_len);
  686. tor_assert(r);
  687. if (!with_annotations) {
  688. if (fast_memcmp("router ", r, 7) && fast_memcmp("extra-info ", r, 11)) {
  689. char *cp = tor_strndup(r, 64);
  690. log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
  691. "Is another process running in our data directory? Exiting.",
  692. desc, escaped(cp));
  693. exit(1); // XXXX bad exit: should recover.
  694. }
  695. }
  696. return r;
  697. }
  698. /** Return a pointer to the signed textual representation of a descriptor.
  699. * The returned string is not guaranteed to be NUL-terminated: the string's
  700. * length will be in desc-\>signed_descriptor_len.
  701. *
  702. * The caller must not free the string returned.
  703. */
  704. const char *
  705. signed_descriptor_get_body(const signed_descriptor_t *desc)
  706. {
  707. return signed_descriptor_get_body_impl(desc, 0);
  708. }
  709. /** As signed_descriptor_get_body(), but points to the beginning of the
  710. * annotations section rather than the beginning of the descriptor. */
  711. const char *
  712. signed_descriptor_get_annotations(const signed_descriptor_t *desc)
  713. {
  714. return signed_descriptor_get_body_impl(desc, 1);
  715. }
  716. /** Return the current list of all known routers. */
  717. routerlist_t *
  718. router_get_routerlist(void)
  719. {
  720. if (PREDICT_UNLIKELY(!routerlist)) {
  721. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  722. routerlist->routers = smartlist_new();
  723. routerlist->old_routers = smartlist_new();
  724. routerlist->identity_map = rimap_new();
  725. routerlist->desc_digest_map = sdmap_new();
  726. routerlist->desc_by_eid_map = sdmap_new();
  727. routerlist->extra_info_map = eimap_new();
  728. routerlist->desc_store.fname_base = "cached-descriptors";
  729. routerlist->extrainfo_store.fname_base = "cached-extrainfo";
  730. routerlist->desc_store.type = ROUTER_STORE;
  731. routerlist->extrainfo_store.type = EXTRAINFO_STORE;
  732. routerlist->desc_store.description = "router descriptors";
  733. routerlist->extrainfo_store.description = "extra-info documents";
  734. }
  735. return routerlist;
  736. }
  737. /** Free all storage held by <b>router</b>. */
  738. void
  739. routerinfo_free_(routerinfo_t *router)
  740. {
  741. if (!router)
  742. return;
  743. tor_free(router->cache_info.signed_descriptor_body);
  744. tor_free(router->nickname);
  745. tor_free(router->platform);
  746. tor_free(router->protocol_list);
  747. tor_free(router->contact_info);
  748. if (router->onion_pkey)
  749. tor_free(router->onion_pkey);
  750. tor_free(router->onion_curve25519_pkey);
  751. if (router->identity_pkey)
  752. crypto_pk_free(router->identity_pkey);
  753. tor_cert_free(router->cache_info.signing_key_cert);
  754. if (router->declared_family) {
  755. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  756. smartlist_free(router->declared_family);
  757. }
  758. addr_policy_list_free(router->exit_policy);
  759. short_policy_free(router->ipv6_exit_policy);
  760. memset(router, 77, sizeof(routerinfo_t));
  761. tor_free(router);
  762. }
  763. /** Release all storage held by <b>extrainfo</b> */
  764. void
  765. extrainfo_free_(extrainfo_t *extrainfo)
  766. {
  767. if (!extrainfo)
  768. return;
  769. tor_cert_free(extrainfo->cache_info.signing_key_cert);
  770. tor_free(extrainfo->cache_info.signed_descriptor_body);
  771. tor_free(extrainfo->pending_sig);
  772. memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  773. tor_free(extrainfo);
  774. }
  775. #define signed_descriptor_free(val) \
  776. FREE_AND_NULL(signed_descriptor_t, signed_descriptor_free_, (val))
  777. /** Release storage held by <b>sd</b>. */
  778. static void
  779. signed_descriptor_free_(signed_descriptor_t *sd)
  780. {
  781. if (!sd)
  782. return;
  783. tor_free(sd->signed_descriptor_body);
  784. tor_cert_free(sd->signing_key_cert);
  785. memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
  786. tor_free(sd);
  787. }
  788. /** Reset the given signed descriptor <b>sd</b> by freeing the allocated
  789. * memory inside the object and by zeroing its content. */
  790. static void
  791. signed_descriptor_reset(signed_descriptor_t *sd)
  792. {
  793. tor_assert(sd);
  794. tor_free(sd->signed_descriptor_body);
  795. tor_cert_free(sd->signing_key_cert);
  796. memset(sd, 0, sizeof(*sd));
  797. }
  798. /** Copy src into dest, and steal all references inside src so that when
  799. * we free src, we don't mess up dest. */
  800. static void
  801. signed_descriptor_move(signed_descriptor_t *dest,
  802. signed_descriptor_t *src)
  803. {
  804. tor_assert(dest != src);
  805. /* Cleanup destination object before overwriting it.*/
  806. signed_descriptor_reset(dest);
  807. memcpy(dest, src, sizeof(signed_descriptor_t));
  808. src->signed_descriptor_body = NULL;
  809. src->signing_key_cert = NULL;
  810. dest->routerlist_index = -1;
  811. }
  812. /** Extract a signed_descriptor_t from a general routerinfo, and free the
  813. * routerinfo.
  814. */
  815. static signed_descriptor_t *
  816. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  817. {
  818. signed_descriptor_t *sd;
  819. tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
  820. sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  821. signed_descriptor_move(sd, &ri->cache_info);
  822. routerinfo_free(ri);
  823. return sd;
  824. }
  825. /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
  826. static void
  827. extrainfo_free_void(void *e)
  828. {
  829. extrainfo_free_(e);
  830. }
  831. /** Free all storage held by a routerlist <b>rl</b>. */
  832. void
  833. routerlist_free_(routerlist_t *rl)
  834. {
  835. if (!rl)
  836. return;
  837. rimap_free(rl->identity_map, NULL);
  838. sdmap_free(rl->desc_digest_map, NULL);
  839. sdmap_free(rl->desc_by_eid_map, NULL);
  840. eimap_free(rl->extra_info_map, extrainfo_free_void);
  841. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  842. routerinfo_free(r));
  843. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  844. signed_descriptor_free(sd));
  845. smartlist_free(rl->routers);
  846. smartlist_free(rl->old_routers);
  847. if (rl->desc_store.mmap) {
  848. int res = tor_munmap_file(rl->desc_store.mmap);
  849. if (res != 0) {
  850. log_warn(LD_FS, "Failed to munmap routerlist->desc_store.mmap");
  851. }
  852. }
  853. if (rl->extrainfo_store.mmap) {
  854. int res = tor_munmap_file(rl->extrainfo_store.mmap);
  855. if (res != 0) {
  856. log_warn(LD_FS, "Failed to munmap routerlist->extrainfo_store.mmap");
  857. }
  858. }
  859. tor_free(rl);
  860. }
  861. /** Log information about how much memory is being used for routerlist,
  862. * at log level <b>severity</b>. */
  863. void
  864. dump_routerlist_mem_usage(int severity)
  865. {
  866. uint64_t livedescs = 0;
  867. uint64_t olddescs = 0;
  868. if (!routerlist)
  869. return;
  870. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  871. livedescs += r->cache_info.signed_descriptor_len);
  872. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  873. olddescs += sd->signed_descriptor_len);
  874. tor_log(severity, LD_DIR,
  875. "In %d live descriptors: %"PRIu64" bytes. "
  876. "In %d old descriptors: %"PRIu64" bytes.",
  877. smartlist_len(routerlist->routers), (livedescs),
  878. smartlist_len(routerlist->old_routers), (olddescs));
  879. }
  880. /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
  881. * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
  882. * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
  883. * is not in <b>sl</b>. */
  884. static inline int
  885. routerlist_find_elt_(smartlist_t *sl, void *ri, int idx)
  886. {
  887. if (idx < 0) {
  888. idx = -1;
  889. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  890. if (r == ri) {
  891. idx = r_sl_idx;
  892. break;
  893. });
  894. } else {
  895. tor_assert(idx < smartlist_len(sl));
  896. tor_assert(smartlist_get(sl, idx) == ri);
  897. };
  898. return idx;
  899. }
  900. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  901. * as needed. There must be no previous member of <b>rl</b> with the same
  902. * identity digest as <b>ri</b>: If there is, call routerlist_replace
  903. * instead.
  904. */
  905. static void
  906. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  907. {
  908. routerinfo_t *ri_old;
  909. signed_descriptor_t *sd_old;
  910. {
  911. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  912. tor_assert(ri_generated != ri);
  913. }
  914. tor_assert(ri->cache_info.routerlist_index == -1);
  915. ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  916. tor_assert(!ri_old);
  917. sd_old = sdmap_set(rl->desc_digest_map,
  918. ri->cache_info.signed_descriptor_digest,
  919. &(ri->cache_info));
  920. if (sd_old) {
  921. int idx = sd_old->routerlist_index;
  922. sd_old->routerlist_index = -1;
  923. smartlist_del(rl->old_routers, idx);
  924. if (idx < smartlist_len(rl->old_routers)) {
  925. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  926. d->routerlist_index = idx;
  927. }
  928. rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
  929. sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
  930. signed_descriptor_free(sd_old);
  931. }
  932. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  933. sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
  934. &ri->cache_info);
  935. smartlist_add(rl->routers, ri);
  936. ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
  937. nodelist_set_routerinfo(ri, NULL);
  938. router_dir_info_changed();
  939. #ifdef DEBUG_ROUTERLIST
  940. routerlist_assert_ok(rl);
  941. #endif
  942. }
  943. /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
  944. * corresponding router in rl-\>routers or rl-\>old_routers. Return the status
  945. * of inserting <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
  946. MOCK_IMPL(STATIC was_router_added_t,
  947. extrainfo_insert,(routerlist_t *rl, extrainfo_t *ei, int warn_if_incompatible))
  948. {
  949. was_router_added_t r;
  950. const char *compatibility_error_msg;
  951. routerinfo_t *ri = rimap_get(rl->identity_map,
  952. ei->cache_info.identity_digest);
  953. signed_descriptor_t *sd =
  954. sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
  955. extrainfo_t *ei_tmp;
  956. const int severity = warn_if_incompatible ? LOG_WARN : LOG_INFO;
  957. {
  958. extrainfo_t *ei_generated = router_get_my_extrainfo();
  959. tor_assert(ei_generated != ei);
  960. }
  961. if (!ri) {
  962. /* This router is unknown; we can't even verify the signature. Give up.*/
  963. r = ROUTER_NOT_IN_CONSENSUS;
  964. goto done;
  965. }
  966. if (! sd) {
  967. /* The extrainfo router doesn't have a known routerdesc to attach it to.
  968. * This just won't work. */;
  969. static ratelim_t no_sd_ratelim = RATELIM_INIT(1800);
  970. r = ROUTER_BAD_EI;
  971. log_fn_ratelim(&no_sd_ratelim, severity, LD_BUG,
  972. "No entry found in extrainfo map.");
  973. goto done;
  974. }
  975. if (tor_memneq(ei->cache_info.signed_descriptor_digest,
  976. sd->extra_info_digest, DIGEST_LEN)) {
  977. static ratelim_t digest_mismatch_ratelim = RATELIM_INIT(1800);
  978. /* The sd we got from the map doesn't match the digest we used to look
  979. * it up. This makes no sense. */
  980. r = ROUTER_BAD_EI;
  981. log_fn_ratelim(&digest_mismatch_ratelim, severity, LD_BUG,
  982. "Mismatch in digest in extrainfo map.");
  983. goto done;
  984. }
  985. if (routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei, sd,
  986. &compatibility_error_msg)) {
  987. char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
  988. r = (ri->cache_info.extrainfo_is_bogus) ?
  989. ROUTER_BAD_EI : ROUTER_NOT_IN_CONSENSUS;
  990. base16_encode(d1, sizeof(d1), ri->cache_info.identity_digest, DIGEST_LEN);
  991. base16_encode(d2, sizeof(d2), ei->cache_info.identity_digest, DIGEST_LEN);
  992. log_fn(severity,LD_DIR,
  993. "router info incompatible with extra info (ri id: %s, ei id %s, "
  994. "reason: %s)", d1, d2, compatibility_error_msg);
  995. goto done;
  996. }
  997. /* Okay, if we make it here, we definitely have a router corresponding to
  998. * this extrainfo. */
  999. ei_tmp = eimap_set(rl->extra_info_map,
  1000. ei->cache_info.signed_descriptor_digest,
  1001. ei);
  1002. r = ROUTER_ADDED_SUCCESSFULLY;
  1003. if (ei_tmp) {
  1004. rl->extrainfo_store.bytes_dropped +=
  1005. ei_tmp->cache_info.signed_descriptor_len;
  1006. extrainfo_free(ei_tmp);
  1007. }
  1008. done:
  1009. if (r != ROUTER_ADDED_SUCCESSFULLY)
  1010. extrainfo_free(ei);
  1011. #ifdef DEBUG_ROUTERLIST
  1012. routerlist_assert_ok(rl);
  1013. #endif
  1014. return r;
  1015. }
  1016. #define should_cache_old_descriptors() \
  1017. directory_caches_dir_info(get_options())
  1018. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  1019. * a copy of router <b>ri</b> yet, add it to the list of old (not
  1020. * recommended but still served) descriptors. Else free it. */
  1021. static void
  1022. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  1023. {
  1024. {
  1025. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  1026. tor_assert(ri_generated != ri);
  1027. }
  1028. tor_assert(ri->cache_info.routerlist_index == -1);
  1029. if (should_cache_old_descriptors() &&
  1030. ri->purpose == ROUTER_PURPOSE_GENERAL &&
  1031. !sdmap_get(rl->desc_digest_map,
  1032. ri->cache_info.signed_descriptor_digest)) {
  1033. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  1034. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1035. smartlist_add(rl->old_routers, sd);
  1036. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  1037. if (!tor_digest_is_zero(sd->extra_info_digest))
  1038. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  1039. } else {
  1040. routerinfo_free(ri);
  1041. }
  1042. #ifdef DEBUG_ROUTERLIST
  1043. routerlist_assert_ok(rl);
  1044. #endif
  1045. }
  1046. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  1047. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  1048. * idx) == ri, we don't need to do a linear search over the list to decide
  1049. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  1050. * the list, if any exists. <b>ri</b> is freed.
  1051. *
  1052. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  1053. * it to rl-&gt;old_routers. */
  1054. void
  1055. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
  1056. {
  1057. routerinfo_t *ri_tmp;
  1058. extrainfo_t *ei_tmp;
  1059. int idx = ri->cache_info.routerlist_index;
  1060. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  1061. tor_assert(smartlist_get(rl->routers, idx) == ri);
  1062. nodelist_remove_routerinfo(ri);
  1063. /* make sure the rephist module knows that it's not running */
  1064. rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
  1065. ri->cache_info.routerlist_index = -1;
  1066. smartlist_del(rl->routers, idx);
  1067. if (idx < smartlist_len(rl->routers)) {
  1068. routerinfo_t *r = smartlist_get(rl->routers, idx);
  1069. r->cache_info.routerlist_index = idx;
  1070. }
  1071. ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  1072. router_dir_info_changed();
  1073. tor_assert(ri_tmp == ri);
  1074. if (make_old && should_cache_old_descriptors() &&
  1075. ri->purpose == ROUTER_PURPOSE_GENERAL) {
  1076. signed_descriptor_t *sd;
  1077. sd = signed_descriptor_from_routerinfo(ri);
  1078. smartlist_add(rl->old_routers, sd);
  1079. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  1080. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1081. if (!tor_digest_is_zero(sd->extra_info_digest))
  1082. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  1083. } else {
  1084. signed_descriptor_t *sd_tmp;
  1085. sd_tmp = sdmap_remove(rl->desc_digest_map,
  1086. ri->cache_info.signed_descriptor_digest);
  1087. tor_assert(sd_tmp == &(ri->cache_info));
  1088. rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
  1089. ei_tmp = eimap_remove(rl->extra_info_map,
  1090. ri->cache_info.extra_info_digest);
  1091. if (ei_tmp) {
  1092. rl->extrainfo_store.bytes_dropped +=
  1093. ei_tmp->cache_info.signed_descriptor_len;
  1094. extrainfo_free(ei_tmp);
  1095. }
  1096. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  1097. sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
  1098. routerinfo_free(ri);
  1099. }
  1100. #ifdef DEBUG_ROUTERLIST
  1101. routerlist_assert_ok(rl);
  1102. #endif
  1103. }
  1104. /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
  1105. * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
  1106. * <b>sd</b>. */
  1107. static void
  1108. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  1109. {
  1110. signed_descriptor_t *sd_tmp;
  1111. extrainfo_t *ei_tmp;
  1112. desc_store_t *store;
  1113. if (idx == -1) {
  1114. idx = sd->routerlist_index;
  1115. }
  1116. tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
  1117. /* XXXX edmanm's bridge relay triggered the following assert while
  1118. * running 0.2.0.12-alpha. If anybody triggers this again, see if we
  1119. * can get a backtrace. */
  1120. tor_assert(smartlist_get(rl->old_routers, idx) == sd);
  1121. tor_assert(idx == sd->routerlist_index);
  1122. sd->routerlist_index = -1;
  1123. smartlist_del(rl->old_routers, idx);
  1124. if (idx < smartlist_len(rl->old_routers)) {
  1125. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  1126. d->routerlist_index = idx;
  1127. }
  1128. sd_tmp = sdmap_remove(rl->desc_digest_map,
  1129. sd->signed_descriptor_digest);
  1130. tor_assert(sd_tmp == sd);
  1131. store = desc_get_store(rl, sd);
  1132. if (store)
  1133. store->bytes_dropped += sd->signed_descriptor_len;
  1134. ei_tmp = eimap_remove(rl->extra_info_map,
  1135. sd->extra_info_digest);
  1136. if (ei_tmp) {
  1137. rl->extrainfo_store.bytes_dropped +=
  1138. ei_tmp->cache_info.signed_descriptor_len;
  1139. extrainfo_free(ei_tmp);
  1140. }
  1141. if (!tor_digest_is_zero(sd->extra_info_digest))
  1142. sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
  1143. signed_descriptor_free(sd);
  1144. #ifdef DEBUG_ROUTERLIST
  1145. routerlist_assert_ok(rl);
  1146. #endif
  1147. }
  1148. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  1149. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  1150. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  1151. * search over the list to decide which to remove. We put ri_new in the same
  1152. * index as ri_old, if possible. ri is freed as appropriate.
  1153. *
  1154. * If should_cache_descriptors() is true, instead of deleting the router,
  1155. * we add it to rl-&gt;old_routers. */
  1156. static void
  1157. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  1158. routerinfo_t *ri_new)
  1159. {
  1160. int idx;
  1161. int same_descriptors;
  1162. routerinfo_t *ri_tmp;
  1163. extrainfo_t *ei_tmp;
  1164. {
  1165. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  1166. tor_assert(ri_generated != ri_new);
  1167. }
  1168. tor_assert(ri_old != ri_new);
  1169. tor_assert(ri_new->cache_info.routerlist_index == -1);
  1170. idx = ri_old->cache_info.routerlist_index;
  1171. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  1172. tor_assert(smartlist_get(rl->routers, idx) == ri_old);
  1173. {
  1174. routerinfo_t *ri_old_tmp=NULL;
  1175. nodelist_set_routerinfo(ri_new, &ri_old_tmp);
  1176. tor_assert(ri_old == ri_old_tmp);
  1177. }
  1178. router_dir_info_changed();
  1179. if (idx >= 0) {
  1180. smartlist_set(rl->routers, idx, ri_new);
  1181. ri_old->cache_info.routerlist_index = -1;
  1182. ri_new->cache_info.routerlist_index = idx;
  1183. /* Check that ri_old is not in rl->routers anymore: */
  1184. tor_assert( routerlist_find_elt_(rl->routers, ri_old, -1) == -1 );
  1185. } else {
  1186. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  1187. routerlist_insert(rl, ri_new);
  1188. return;
  1189. }
  1190. if (tor_memneq(ri_old->cache_info.identity_digest,
  1191. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  1192. /* digests don't match; digestmap_set won't replace */
  1193. rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  1194. }
  1195. ri_tmp = rimap_set(rl->identity_map,
  1196. ri_new->cache_info.identity_digest, ri_new);
  1197. tor_assert(!ri_tmp || ri_tmp == ri_old);
  1198. sdmap_set(rl->desc_digest_map,
  1199. ri_new->cache_info.signed_descriptor_digest,
  1200. &(ri_new->cache_info));
  1201. if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
  1202. sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
  1203. &ri_new->cache_info);
  1204. }
  1205. same_descriptors = tor_memeq(ri_old->cache_info.signed_descriptor_digest,
  1206. ri_new->cache_info.signed_descriptor_digest,
  1207. DIGEST_LEN);
  1208. if (should_cache_old_descriptors() &&
  1209. ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
  1210. !same_descriptors) {
  1211. /* ri_old is going to become a signed_descriptor_t and go into
  1212. * old_routers */
  1213. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  1214. smartlist_add(rl->old_routers, sd);
  1215. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  1216. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1217. if (!tor_digest_is_zero(sd->extra_info_digest))
  1218. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  1219. } else {
  1220. /* We're dropping ri_old. */
  1221. if (!same_descriptors) {
  1222. /* digests don't match; The sdmap_set above didn't replace */
  1223. sdmap_remove(rl->desc_digest_map,
  1224. ri_old->cache_info.signed_descriptor_digest);
  1225. if (tor_memneq(ri_old->cache_info.extra_info_digest,
  1226. ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
  1227. ei_tmp = eimap_remove(rl->extra_info_map,
  1228. ri_old->cache_info.extra_info_digest);
  1229. if (ei_tmp) {
  1230. rl->extrainfo_store.bytes_dropped +=
  1231. ei_tmp->cache_info.signed_descriptor_len;
  1232. extrainfo_free(ei_tmp);
  1233. }
  1234. }
  1235. if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
  1236. sdmap_remove(rl->desc_by_eid_map,
  1237. ri_old->cache_info.extra_info_digest);
  1238. }
  1239. }
  1240. rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
  1241. routerinfo_free(ri_old);
  1242. }
  1243. #ifdef DEBUG_ROUTERLIST
  1244. routerlist_assert_ok(rl);
  1245. #endif
  1246. }
  1247. /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
  1248. * it as a fresh routerinfo_t. */
  1249. static routerinfo_t *
  1250. routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
  1251. {
  1252. routerinfo_t *ri;
  1253. const char *body;
  1254. body = signed_descriptor_get_annotations(sd);
  1255. ri = router_parse_entry_from_string(body,
  1256. body+sd->signed_descriptor_len+sd->annotations_len,
  1257. 0, 1, NULL, NULL);
  1258. if (!ri)
  1259. return NULL;
  1260. signed_descriptor_move(&ri->cache_info, sd);
  1261. routerlist_remove_old(rl, sd, -1);
  1262. return ri;
  1263. }
  1264. /** Free all memory held by the routerlist module.
  1265. * Note: Calling routerlist_free_all() should always be paired with
  1266. * a call to nodelist_free_all(). These should only be called during
  1267. * cleanup.
  1268. */
  1269. void
  1270. routerlist_free_all(void)
  1271. {
  1272. routerlist_t *rl = routerlist;
  1273. routerlist = NULL; // Prevent internals of routerlist_free() from using
  1274. // routerlist.
  1275. routerlist_free(rl);
  1276. dirlist_free_all();
  1277. if (warned_nicknames) {
  1278. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1279. smartlist_free(warned_nicknames);
  1280. warned_nicknames = NULL;
  1281. }
  1282. authcert_free_all();
  1283. }
  1284. /** Forget that we have issued any router-related warnings, so that we'll
  1285. * warn again if we see the same errors. */
  1286. void
  1287. routerlist_reset_warnings(void)
  1288. {
  1289. if (!warned_nicknames)
  1290. warned_nicknames = smartlist_new();
  1291. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1292. smartlist_clear(warned_nicknames); /* now the list is empty. */
  1293. networkstatus_reset_warnings();
  1294. }
  1295. /** Return 1 if the signed descriptor of this router is older than
  1296. * <b>seconds</b> seconds. Otherwise return 0. */
  1297. MOCK_IMPL(int,
  1298. router_descriptor_is_older_than,(const routerinfo_t *router, int seconds))
  1299. {
  1300. return router->cache_info.published_on < approx_time() - seconds;
  1301. }
  1302. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  1303. * older entries (if any) with the same key. Note: Callers should not hold
  1304. * their pointers to <b>router</b> if this function fails; <b>router</b>
  1305. * will either be inserted into the routerlist or freed. Similarly, even
  1306. * if this call succeeds, they should not hold their pointers to
  1307. * <b>router</b> after subsequent calls with other routerinfo's -- they
  1308. * might cause the original routerinfo to get freed.
  1309. *
  1310. * Returns the status for the operation. Might set *<b>msg</b> if it wants
  1311. * the poster of the router to know something.
  1312. *
  1313. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  1314. * <b>from_fetch</b>, we received it in response to a request we made.
  1315. * (If both are false, that means it was uploaded to us as an auth dir
  1316. * server or via the controller.)
  1317. *
  1318. * This function should be called *after*
  1319. * routers_update_status_from_consensus_networkstatus; subsequently, you
  1320. * should call router_rebuild_store and routerlist_descriptors_added.
  1321. */
  1322. was_router_added_t
  1323. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  1324. int from_cache, int from_fetch)
  1325. {
  1326. const char *id_digest;
  1327. const or_options_t *options = get_options();
  1328. int authdir = authdir_mode_handles_descs(options, router->purpose);
  1329. int authdir_believes_valid = 0;
  1330. routerinfo_t *old_router;
  1331. networkstatus_t *consensus =
  1332. networkstatus_get_latest_consensus_by_flavor(FLAV_NS);
  1333. int in_consensus = 0;
  1334. tor_assert(msg);
  1335. if (!routerlist)
  1336. router_get_routerlist();
  1337. id_digest = router->cache_info.identity_digest;
  1338. old_router = router_get_mutable_by_digest(id_digest);
  1339. /* Make sure that it isn't expired. */
  1340. if (router->cert_expiration_time < approx_time()) {
  1341. routerinfo_free(router);
  1342. *msg = "Some certs on this router are expired.";
  1343. return ROUTER_CERTS_EXPIRED;
  1344. }
  1345. /* Make sure that we haven't already got this exact descriptor. */
  1346. if (sdmap_get(routerlist->desc_digest_map,
  1347. router->cache_info.signed_descriptor_digest)) {
  1348. /* If we have this descriptor already and the new descriptor is a bridge
  1349. * descriptor, replace it. If we had a bridge descriptor before and the
  1350. * new one is not a bridge descriptor, don't replace it. */
  1351. /* Only members of routerlist->identity_map can be bridges; we don't
  1352. * put bridges in old_routers. */
  1353. const int was_bridge = old_router &&
  1354. old_router->purpose == ROUTER_PURPOSE_BRIDGE;
  1355. if (routerinfo_is_a_configured_bridge(router) &&
  1356. router->purpose == ROUTER_PURPOSE_BRIDGE &&
  1357. !was_bridge) {
  1358. log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
  1359. "descriptor for router %s",
  1360. router_describe(router));
  1361. } else {
  1362. log_info(LD_DIR,
  1363. "Dropping descriptor that we already have for router %s",
  1364. router_describe(router));
  1365. *msg = "Router descriptor was not new.";
  1366. routerinfo_free(router);
  1367. return ROUTER_IS_ALREADY_KNOWN;
  1368. }
  1369. }
  1370. if (authdir) {
  1371. if (authdir_wants_to_reject_router(router, msg,
  1372. !from_cache && !from_fetch,
  1373. &authdir_believes_valid)) {
  1374. tor_assert(*msg);
  1375. routerinfo_free(router);
  1376. return ROUTER_AUTHDIR_REJECTS;
  1377. }
  1378. } else if (from_fetch) {
  1379. /* Only check the descriptor digest against the network statuses when
  1380. * we are receiving in response to a fetch. */
  1381. if (!signed_desc_digest_is_recognized(&router->cache_info) &&
  1382. !routerinfo_is_a_configured_bridge(router)) {
  1383. /* We asked for it, so some networkstatus must have listed it when we
  1384. * did. Save it if we're a cache in case somebody else asks for it. */
  1385. log_info(LD_DIR,
  1386. "Received a no-longer-recognized descriptor for router %s",
  1387. router_describe(router));
  1388. *msg = "Router descriptor is not referenced by any network-status.";
  1389. /* Only journal this desc if we want to keep old descriptors */
  1390. if (!from_cache && should_cache_old_descriptors())
  1391. signed_desc_append_to_journal(&router->cache_info,
  1392. &routerlist->desc_store);
  1393. routerlist_insert_old(routerlist, router);
  1394. return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
  1395. }
  1396. }
  1397. /* We no longer need a router with this descriptor digest. */
  1398. if (consensus) {
  1399. routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
  1400. consensus, id_digest);
  1401. if (rs && tor_memeq(rs->descriptor_digest,
  1402. router->cache_info.signed_descriptor_digest,
  1403. DIGEST_LEN)) {
  1404. in_consensus = 1;
  1405. }
  1406. }
  1407. if (router->purpose == ROUTER_PURPOSE_GENERAL &&
  1408. consensus && !in_consensus && !authdir) {
  1409. /* If it's a general router not listed in the consensus, then don't
  1410. * consider replacing the latest router with it. */
  1411. if (!from_cache && should_cache_old_descriptors())
  1412. signed_desc_append_to_journal(&router->cache_info,
  1413. &routerlist->desc_store);
  1414. routerlist_insert_old(routerlist, router);
  1415. *msg = "Skipping router descriptor: not in consensus.";
  1416. return ROUTER_NOT_IN_CONSENSUS;
  1417. }
  1418. /* If we're reading a bridge descriptor from our cache, and we don't
  1419. * recognize it as one of our currently configured bridges, drop the
  1420. * descriptor. Otherwise we could end up using it as one of our entry
  1421. * guards even if it isn't in our Bridge config lines. */
  1422. if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
  1423. !authdir_mode_bridge(options) &&
  1424. !routerinfo_is_a_configured_bridge(router)) {
  1425. log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
  1426. "no bridge configured at that address.",
  1427. safe_str_client(router_describe(router)));
  1428. *msg = "Router descriptor was not a configured bridge.";
  1429. routerinfo_free(router);
  1430. return ROUTER_WAS_NOT_WANTED;
  1431. }
  1432. /* If we have a router with the same identity key, choose the newer one. */
  1433. if (old_router) {
  1434. if (!in_consensus && (router->cache_info.published_on <=
  1435. old_router->cache_info.published_on)) {
  1436. /* Same key, but old. This one is not listed in the consensus. */
  1437. log_debug(LD_DIR, "Not-new descriptor for router %s",
  1438. router_describe(router));
  1439. /* Only journal this desc if we'll be serving it. */
  1440. if (!from_cache && should_cache_old_descriptors())
  1441. signed_desc_append_to_journal(&router->cache_info,
  1442. &routerlist->desc_store);
  1443. routerlist_insert_old(routerlist, router);
  1444. *msg = "Router descriptor was not new.";
  1445. return ROUTER_IS_ALREADY_KNOWN;
  1446. } else {
  1447. /* Same key, and either new, or listed in the consensus. */
  1448. log_debug(LD_DIR, "Replacing entry for router %s",
  1449. router_describe(router));
  1450. routerlist_replace(routerlist, old_router, router);
  1451. if (!from_cache) {
  1452. signed_desc_append_to_journal(&router->cache_info,
  1453. &routerlist->desc_store);
  1454. }
  1455. *msg = authdir_believes_valid ? "Valid server updated" :
  1456. ("Invalid server updated. (This dirserver is marking your "
  1457. "server as unapproved.)");
  1458. return ROUTER_ADDED_SUCCESSFULLY;
  1459. }
  1460. }
  1461. if (!in_consensus && from_cache &&
  1462. router_descriptor_is_older_than(router, OLD_ROUTER_DESC_MAX_AGE)) {
  1463. *msg = "Router descriptor was really old.";
  1464. routerinfo_free(router);
  1465. return ROUTER_WAS_TOO_OLD;
  1466. }
  1467. /* We haven't seen a router with this identity before. Add it to the end of
  1468. * the list. */
  1469. routerlist_insert(routerlist, router);
  1470. if (!from_cache) {
  1471. signed_desc_append_to_journal(&router->cache_info,
  1472. &routerlist->desc_store);
  1473. }
  1474. return ROUTER_ADDED_SUCCESSFULLY;
  1475. }
  1476. /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
  1477. * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
  1478. * we actually inserted it, ROUTER_BAD_EI otherwise.
  1479. */
  1480. was_router_added_t
  1481. router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
  1482. int from_cache, int from_fetch)
  1483. {
  1484. was_router_added_t inserted;
  1485. (void)from_fetch;
  1486. if (msg) *msg = NULL;
  1487. /*XXXX Do something with msg */
  1488. inserted = extrainfo_insert(router_get_routerlist(), ei, !from_cache);
  1489. if (WRA_WAS_ADDED(inserted) && !from_cache)
  1490. signed_desc_append_to_journal(&ei->cache_info,
  1491. &routerlist->extrainfo_store);
  1492. return inserted;
  1493. }
  1494. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  1495. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  1496. * to, or later than that of *<b>b</b>. */
  1497. static int
  1498. compare_old_routers_by_identity_(const void **_a, const void **_b)
  1499. {
  1500. int i;
  1501. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  1502. if ((i = fast_memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  1503. return i;
  1504. return (int)(r1->published_on - r2->published_on);
  1505. }
  1506. /** Internal type used to represent how long an old descriptor was valid,
  1507. * where it appeared in the list of old descriptors, and whether it's extra
  1508. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  1509. struct duration_idx_t {
  1510. int duration;
  1511. int idx;
  1512. int old;
  1513. };
  1514. /** Sorting helper: compare two duration_idx_t by their duration. */
  1515. static int
  1516. compare_duration_idx_(const void *_d1, const void *_d2)
  1517. {
  1518. const struct duration_idx_t *d1 = _d1;
  1519. const struct duration_idx_t *d2 = _d2;
  1520. return d1->duration - d2->duration;
  1521. }
  1522. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  1523. * must contain routerinfo_t with the same identity and with publication time
  1524. * in ascending order. Remove members from this range until there are no more
  1525. * than max_descriptors_per_router() remaining. Start by removing the oldest
  1526. * members from before <b>cutoff</b>, then remove members which were current
  1527. * for the lowest amount of time. The order of members of old_routers at
  1528. * indices <b>lo</b> or higher may be changed.
  1529. */
  1530. static void
  1531. routerlist_remove_old_cached_routers_with_id(time_t now,
  1532. time_t cutoff, int lo, int hi,
  1533. digestset_t *retain)
  1534. {
  1535. int i, n = hi-lo+1;
  1536. unsigned n_extra, n_rmv = 0;
  1537. struct duration_idx_t *lifespans;
  1538. uint8_t *rmv, *must_keep;
  1539. smartlist_t *lst = routerlist->old_routers;
  1540. #if 1
  1541. const char *ident;
  1542. tor_assert(hi < smartlist_len(lst));
  1543. tor_assert(lo <= hi);
  1544. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  1545. for (i = lo+1; i <= hi; ++i) {
  1546. signed_descriptor_t *r = smartlist_get(lst, i);
  1547. tor_assert(tor_memeq(ident, r->identity_digest, DIGEST_LEN));
  1548. }
  1549. #endif /* 1 */
  1550. /* Check whether we need to do anything at all. */
  1551. {
  1552. int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
  1553. if (n <= mdpr)
  1554. return;
  1555. n_extra = n - mdpr;
  1556. }
  1557. lifespans = tor_calloc(n, sizeof(struct duration_idx_t));
  1558. rmv = tor_calloc(n, sizeof(uint8_t));
  1559. must_keep = tor_calloc(n, sizeof(uint8_t));
  1560. /* Set lifespans to contain the lifespan and index of each server. */
  1561. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  1562. for (i = lo; i <= hi; ++i) {
  1563. signed_descriptor_t *r = smartlist_get(lst, i);
  1564. signed_descriptor_t *r_next;
  1565. lifespans[i-lo].idx = i;
  1566. if (r->last_listed_as_valid_until >= now ||
  1567. (retain && digestset_probably_contains(retain,
  1568. r->signed_descriptor_digest))) {
  1569. must_keep[i-lo] = 1;
  1570. }
  1571. if (i < hi) {
  1572. r_next = smartlist_get(lst, i+1);
  1573. tor_assert(r->published_on <= r_next->published_on);
  1574. lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
  1575. } else {
  1576. r_next = NULL;
  1577. lifespans[i-lo].duration = INT_MAX;
  1578. }
  1579. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  1580. ++n_rmv;
  1581. lifespans[i-lo].old = 1;
  1582. rmv[i-lo] = 1;
  1583. }
  1584. }
  1585. if (n_rmv < n_extra) {
  1586. /**
  1587. * We aren't removing enough servers for being old. Sort lifespans by
  1588. * the duration of liveness, and remove the ones we're not already going to
  1589. * remove based on how long they were alive.
  1590. **/
  1591. qsort(lifespans, n, sizeof(struct duration_idx_t), compare_duration_idx_);
  1592. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  1593. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  1594. rmv[lifespans[i].idx-lo] = 1;
  1595. ++n_rmv;
  1596. }
  1597. }
  1598. }
  1599. i = hi;
  1600. do {
  1601. if (rmv[i-lo])
  1602. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  1603. } while (--i >= lo);
  1604. tor_free(must_keep);
  1605. tor_free(rmv);
  1606. tor_free(lifespans);
  1607. }
  1608. /** Deactivate any routers from the routerlist that are more than
  1609. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  1610. * remove old routers from the list of cached routers if we have too many.
  1611. */
  1612. void
  1613. routerlist_remove_old_routers(void)
  1614. {
  1615. int i, hi=-1;
  1616. const char *cur_id = NULL;
  1617. time_t now = time(NULL);
  1618. time_t cutoff;
  1619. routerinfo_t *router;
  1620. signed_descriptor_t *sd;
  1621. digestset_t *retain;
  1622. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  1623. trusted_dirs_remove_old_certs();
  1624. if (!routerlist || !consensus)
  1625. return;
  1626. // routerlist_assert_ok(routerlist);
  1627. /* We need to guess how many router descriptors we will wind up wanting to
  1628. retain, so that we can be sure to allocate a large enough Bloom filter
  1629. to hold the digest set. Overestimating is fine; underestimating is bad.
  1630. */
  1631. {
  1632. /* We'll probably retain everything in the consensus. */
  1633. int n_max_retain = smartlist_len(consensus->routerstatus_list);
  1634. retain = digestset_new(n_max_retain);
  1635. }
  1636. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1637. /* Retain anything listed in the consensus. */
  1638. if (consensus) {
  1639. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  1640. if (rs->published_on >= cutoff)
  1641. digestset_add(retain, rs->descriptor_digest));
  1642. }
  1643. /* If we have a consensus, we should consider pruning current routers that
  1644. * are too old and that nobody recommends. (If we don't have a consensus,
  1645. * then we should get one before we decide to kill routers.) */
  1646. if (consensus) {
  1647. cutoff = now - ROUTER_MAX_AGE;
  1648. /* Remove too-old unrecommended members of routerlist->routers. */
  1649. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1650. router = smartlist_get(routerlist->routers, i);
  1651. if (router->cache_info.published_on <= cutoff &&
  1652. router->cache_info.last_listed_as_valid_until < now &&
  1653. !digestset_probably_contains(retain,
  1654. router->cache_info.signed_descriptor_digest)) {
  1655. /* Too old: remove it. (If we're a cache, just move it into
  1656. * old_routers.) */
  1657. log_info(LD_DIR,
  1658. "Forgetting obsolete (too old) routerinfo for router %s",
  1659. router_describe(router));
  1660. routerlist_remove(routerlist, router, 1, now);
  1661. i--;
  1662. }
  1663. }
  1664. }
  1665. //routerlist_assert_ok(routerlist);
  1666. /* Remove far-too-old members of routerlist->old_routers. */
  1667. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1668. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  1669. sd = smartlist_get(routerlist->old_routers, i);
  1670. if (sd->published_on <= cutoff &&
  1671. sd->last_listed_as_valid_until < now &&
  1672. !digestset_probably_contains(retain, sd->signed_descriptor_digest)) {
  1673. /* Too old. Remove it. */
  1674. routerlist_remove_old(routerlist, sd, i--);
  1675. }
  1676. }
  1677. //routerlist_assert_ok(routerlist);
  1678. log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
  1679. smartlist_len(routerlist->routers),
  1680. smartlist_len(routerlist->old_routers));
  1681. /* Now we might have to look at routerlist->old_routers for extraneous
  1682. * members. (We'd keep all the members if we could, but we need to save
  1683. * space.) First, check whether we have too many router descriptors, total.
  1684. * We're okay with having too many for some given router, so long as the
  1685. * total number doesn't approach max_descriptors_per_router()*len(router).
  1686. */
  1687. if (smartlist_len(routerlist->old_routers) <
  1688. smartlist_len(routerlist->routers))
  1689. goto done;
  1690. /* Sort by identity, then fix indices. */
  1691. smartlist_sort(routerlist->old_routers, compare_old_routers_by_identity_);
  1692. /* Fix indices. */
  1693. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  1694. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  1695. r->routerlist_index = i;
  1696. }
  1697. /* Iterate through the list from back to front, so when we remove descriptors
  1698. * we don't mess up groups we haven't gotten to. */
  1699. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  1700. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  1701. if (!cur_id) {
  1702. cur_id = r->identity_digest;
  1703. hi = i;
  1704. }
  1705. if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
  1706. routerlist_remove_old_cached_routers_with_id(now,
  1707. cutoff, i+1, hi, retain);
  1708. cur_id = r->identity_digest;
  1709. hi = i;
  1710. }
  1711. }
  1712. if (hi>=0)
  1713. routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
  1714. //routerlist_assert_ok(routerlist);
  1715. done:
  1716. digestset_free(retain);
  1717. router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
  1718. router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
  1719. }
  1720. /** We just added a new set of descriptors. Take whatever extra steps
  1721. * we need. */
  1722. void
  1723. routerlist_descriptors_added(smartlist_t *sl, int from_cache)
  1724. {
  1725. tor_assert(sl);
  1726. control_event_descriptors_changed(sl);
  1727. SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
  1728. if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
  1729. learned_bridge_descriptor(ri, from_cache);
  1730. if (ri->needs_retest_if_added) {
  1731. ri->needs_retest_if_added = 0;
  1732. dirserv_single_reachability_test(approx_time(), ri);
  1733. }
  1734. } SMARTLIST_FOREACH_END(ri);
  1735. }
  1736. /**
  1737. * Code to parse a single router descriptor and insert it into the
  1738. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1739. * descriptor was well-formed but could not be added; and 1 if the
  1740. * descriptor was added.
  1741. *
  1742. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1743. * *<b>msg</b> a static string describing the reason for refusing the
  1744. * descriptor.
  1745. *
  1746. * This is used only by the controller.
  1747. */
  1748. int
  1749. router_load_single_router(const char *s, uint8_t purpose, int cache,
  1750. const char **msg)
  1751. {
  1752. routerinfo_t *ri;
  1753. was_router_added_t r;
  1754. smartlist_t *lst;
  1755. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  1756. tor_assert(msg);
  1757. *msg = NULL;
  1758. tor_snprintf(annotation_buf, sizeof(annotation_buf),
  1759. "@source controller\n"
  1760. "@purpose %s\n", router_purpose_to_string(purpose));
  1761. if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0,
  1762. annotation_buf, NULL))) {
  1763. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  1764. *msg = "Couldn't parse router descriptor.";
  1765. return -1;
  1766. }
  1767. tor_assert(ri->purpose == purpose);
  1768. if (router_is_me(ri)) {
  1769. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  1770. *msg = "Router's identity key matches mine.";
  1771. routerinfo_free(ri);
  1772. return 0;
  1773. }
  1774. if (!cache) /* obey the preference of the controller */
  1775. ri->cache_info.do_not_cache = 1;
  1776. lst = smartlist_new();
  1777. smartlist_add(lst, ri);
  1778. routers_update_status_from_consensus_networkstatus(lst, 0);
  1779. r = router_add_to_routerlist(ri, msg, 0, 0);
  1780. if (!WRA_WAS_ADDED(r)) {
  1781. /* we've already assigned to *msg now, and ri is already freed */
  1782. tor_assert(*msg);
  1783. if (r == ROUTER_AUTHDIR_REJECTS)
  1784. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  1785. smartlist_free(lst);
  1786. return 0;
  1787. } else {
  1788. routerlist_descriptors_added(lst, 0);
  1789. smartlist_free(lst);
  1790. log_debug(LD_DIR, "Added router to list");
  1791. return 1;
  1792. }
  1793. }
  1794. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1795. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  1796. * are in response to a query to the network: cache them by adding them to
  1797. * the journal.
  1798. *
  1799. * Return the number of routers actually added.
  1800. *
  1801. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1802. * uppercased fingerprints. Do not update any router whose
  1803. * fingerprint is not on the list; after updating a router, remove its
  1804. * fingerprint from the list.
  1805. *
  1806. * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
  1807. * are descriptor digests. Otherwise they are identity digests.
  1808. */
  1809. int
  1810. router_load_routers_from_string(const char *s, const char *eos,
  1811. saved_location_t saved_location,
  1812. smartlist_t *requested_fingerprints,
  1813. int descriptor_digests,
  1814. const char *prepend_annotations)
  1815. {
  1816. smartlist_t *routers = smartlist_new(), *changed = smartlist_new();
  1817. char fp[HEX_DIGEST_LEN+1];
  1818. const char *msg;
  1819. int from_cache = (saved_location != SAVED_NOWHERE);
  1820. int allow_annotations = (saved_location != SAVED_NOWHERE);
  1821. int any_changed = 0;
  1822. smartlist_t *invalid_digests = smartlist_new();
  1823. router_parse_list_from_string(&s, eos, routers, saved_location, 0,
  1824. allow_annotations, prepend_annotations,
  1825. invalid_digests);
  1826. routers_update_status_from_consensus_networkstatus(routers, !from_cache);
  1827. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  1828. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  1829. was_router_added_t r;
  1830. char d[DIGEST_LEN];
  1831. if (requested_fingerprints) {
  1832. base16_encode(fp, sizeof(fp), descriptor_digests ?
  1833. ri->cache_info.signed_descriptor_digest :
  1834. ri->cache_info.identity_digest,
  1835. DIGEST_LEN);
  1836. if (smartlist_contains_string(requested_fingerprints, fp)) {
  1837. smartlist_string_remove(requested_fingerprints, fp);
  1838. } else {
  1839. char *requested =
  1840. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1841. log_warn(LD_DIR,
  1842. "We received a router descriptor with a fingerprint (%s) "
  1843. "that we never requested. (We asked for: %s.) Dropping.",
  1844. fp, requested);
  1845. tor_free(requested);
  1846. routerinfo_free(ri);
  1847. continue;
  1848. }
  1849. }
  1850. memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
  1851. r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
  1852. if (WRA_WAS_ADDED(r)) {
  1853. any_changed++;
  1854. smartlist_add(changed, ri);
  1855. routerlist_descriptors_added(changed, from_cache);
  1856. smartlist_clear(changed);
  1857. } else if (WRA_NEVER_DOWNLOADABLE(r)) {
  1858. download_status_t *dl_status;
  1859. dl_status = router_get_dl_status_by_descriptor_digest(d);
  1860. if (dl_status) {
  1861. log_info(LD_GENERAL, "Marking router %s as never downloadable",
  1862. hex_str(d, DIGEST_LEN));
  1863. download_status_mark_impossible(dl_status);
  1864. }
  1865. }
  1866. } SMARTLIST_FOREACH_END(ri);
  1867. SMARTLIST_FOREACH_BEGIN(invalid_digests, const uint8_t *, bad_digest) {
  1868. /* This digest is never going to be parseable. */
  1869. base16_encode(fp, sizeof(fp), (char*)bad_digest, DIGEST_LEN);
  1870. if (requested_fingerprints && descriptor_digests) {
  1871. if (! smartlist_contains_string(requested_fingerprints, fp)) {
  1872. /* But we didn't ask for it, so we should assume shennanegans. */
  1873. continue;
  1874. }
  1875. smartlist_string_remove(requested_fingerprints, fp);
  1876. }
  1877. download_status_t *dls;
  1878. dls = router_get_dl_status_by_descriptor_digest((char*)bad_digest);
  1879. if (dls) {
  1880. log_info(LD_GENERAL, "Marking router with descriptor %s as unparseable, "
  1881. "and therefore undownloadable", fp);
  1882. download_status_mark_impossible(dls);
  1883. }
  1884. } SMARTLIST_FOREACH_END(bad_digest);
  1885. SMARTLIST_FOREACH(invalid_digests, uint8_t *, d, tor_free(d));
  1886. smartlist_free(invalid_digests);
  1887. routerlist_assert_ok(routerlist);
  1888. if (any_changed)
  1889. router_rebuild_store(0, &routerlist->desc_store);
  1890. smartlist_free(routers);
  1891. smartlist_free(changed);
  1892. return any_changed;
  1893. }
  1894. /** Parse one or more extrainfos from <b>s</b> (ending immediately before
  1895. * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
  1896. * router_load_routers_from_string(). */
  1897. void
  1898. router_load_extrainfo_from_string(const char *s, const char *eos,
  1899. saved_location_t saved_location,
  1900. smartlist_t *requested_fingerprints,
  1901. int descriptor_digests)
  1902. {
  1903. smartlist_t *extrainfo_list = smartlist_new();
  1904. const char *msg;
  1905. int from_cache = (saved_location != SAVED_NOWHERE);
  1906. smartlist_t *invalid_digests = smartlist_new();
  1907. router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
  1908. NULL, invalid_digests);
  1909. log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
  1910. SMARTLIST_FOREACH_BEGIN(extrainfo_list, extrainfo_t *, ei) {
  1911. uint8_t d[DIGEST_LEN];
  1912. memcpy(d, ei->cache_info.signed_descriptor_digest, DIGEST_LEN);
  1913. was_router_added_t added =
  1914. router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
  1915. if (WRA_WAS_ADDED(added) && requested_fingerprints) {
  1916. char fp[HEX_DIGEST_LEN+1];
  1917. base16_encode(fp, sizeof(fp), descriptor_digests ?
  1918. ei->cache_info.signed_descriptor_digest :
  1919. ei->cache_info.identity_digest,
  1920. DIGEST_LEN);
  1921. smartlist_string_remove(requested_fingerprints, fp);
  1922. /* We silently let relays stuff us with extrainfos we didn't ask for,
  1923. * so long as we would have wanted them anyway. Since we always fetch
  1924. * all the extrainfos we want, and we never actually act on them
  1925. * inside Tor, this should be harmless. */
  1926. } else if (WRA_NEVER_DOWNLOADABLE(added)) {
  1927. signed_descriptor_t *sd = router_get_by_extrainfo_digest((char*)d);
  1928. if (sd) {
  1929. log_info(LD_GENERAL, "Marking extrainfo with descriptor %s as "
  1930. "unparseable, and therefore undownloadable",
  1931. hex_str((char*)d,DIGEST_LEN));
  1932. download_status_mark_impossible(&sd->ei_dl_status);
  1933. }
  1934. }
  1935. } SMARTLIST_FOREACH_END(ei);
  1936. SMARTLIST_FOREACH_BEGIN(invalid_digests, const uint8_t *, bad_digest) {
  1937. /* This digest is never going to be parseable. */
  1938. char fp[HEX_DIGEST_LEN+1];
  1939. base16_encode(fp, sizeof(fp), (char*)bad_digest, DIGEST_LEN);
  1940. if (requested_fingerprints) {
  1941. if (! smartlist_contains_string(requested_fingerprints, fp)) {
  1942. /* But we didn't ask for it, so we should assume shennanegans. */
  1943. continue;
  1944. }
  1945. smartlist_string_remove(requested_fingerprints, fp);
  1946. }
  1947. signed_descriptor_t *sd =
  1948. router_get_by_extrainfo_digest((char*)bad_digest);
  1949. if (sd) {
  1950. log_info(LD_GENERAL, "Marking extrainfo with descriptor %s as "
  1951. "unparseable, and therefore undownloadable", fp);
  1952. download_status_mark_impossible(&sd->ei_dl_status);
  1953. }
  1954. } SMARTLIST_FOREACH_END(bad_digest);
  1955. SMARTLIST_FOREACH(invalid_digests, uint8_t *, d, tor_free(d));
  1956. smartlist_free(invalid_digests);
  1957. routerlist_assert_ok(routerlist);
  1958. router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
  1959. smartlist_free(extrainfo_list);
  1960. }
  1961. /** Return true iff the latest ns-flavored consensus includes a descriptor
  1962. * whose digest is that of <b>desc</b>. */
  1963. static int
  1964. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  1965. {
  1966. const routerstatus_t *rs;
  1967. networkstatus_t *consensus = networkstatus_get_latest_consensus_by_flavor(
  1968. FLAV_NS);
  1969. if (consensus) {
  1970. rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
  1971. if (rs && tor_memeq(rs->descriptor_digest,
  1972. desc->signed_descriptor_digest, DIGEST_LEN))
  1973. return 1;
  1974. }
  1975. return 0;
  1976. }
  1977. /** Update downloads for router descriptors and/or microdescriptors as
  1978. * appropriate. */
  1979. void
  1980. update_all_descriptor_downloads(time_t now)
  1981. {
  1982. if (should_delay_dir_fetches(get_options(), NULL))
  1983. return;
  1984. update_router_descriptor_downloads(now);
  1985. update_microdesc_downloads(now);
  1986. launch_dummy_descriptor_download_as_needed(now, get_options());
  1987. }
  1988. /** Clear all our timeouts for fetching v3 directory stuff, and then
  1989. * give it all a try again. */
  1990. void
  1991. routerlist_retry_directory_downloads(time_t now)
  1992. {
  1993. (void)now;
  1994. log_debug(LD_GENERAL,
  1995. "In routerlist_retry_directory_downloads()");
  1996. router_reset_status_download_failures();
  1997. router_reset_descriptor_download_failures();
  1998. reschedule_directory_downloads();
  1999. }
  2000. /** Return true iff <b>router</b> does not permit exit streams.
  2001. */
  2002. int
  2003. router_exit_policy_rejects_all(const routerinfo_t *router)
  2004. {
  2005. return router->policy_is_reject_star;
  2006. }
  2007. /** For every current directory connection whose purpose is <b>purpose</b>,
  2008. * and where the resource being downloaded begins with <b>prefix</b>, split
  2009. * rest of the resource into base16 fingerprints (or base64 fingerprints if
  2010. * purpose==DIR_PURPOSE_FETCH_MICRODESC), decode them, and set the
  2011. * corresponding elements of <b>result</b> to a nonzero value.
  2012. */
  2013. void
  2014. list_pending_downloads(digestmap_t *result, digest256map_t *result256,
  2015. int purpose, const char *prefix)
  2016. {
  2017. const size_t p_len = strlen(prefix);
  2018. smartlist_t *tmp = smartlist_new();
  2019. smartlist_t *conns = get_connection_array();
  2020. int flags = DSR_HEX;
  2021. if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
  2022. flags = DSR_DIGEST256|DSR_BASE64;
  2023. tor_assert(result || result256);
  2024. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  2025. if (conn->type == CONN_TYPE_DIR &&
  2026. conn->purpose == purpose &&
  2027. !conn->marked_for_close) {
  2028. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  2029. if (!strcmpstart(resource, prefix))
  2030. dir_split_resource_into_fingerprints(resource + p_len,
  2031. tmp, NULL, flags);
  2032. }
  2033. } SMARTLIST_FOREACH_END(conn);
  2034. if (result) {
  2035. SMARTLIST_FOREACH(tmp, char *, d,
  2036. {
  2037. digestmap_set(result, d, (void*)1);
  2038. tor_free(d);
  2039. });
  2040. } else if (result256) {
  2041. SMARTLIST_FOREACH(tmp, uint8_t *, d,
  2042. {
  2043. digest256map_set(result256, d, (void*)1);
  2044. tor_free(d);
  2045. });
  2046. }
  2047. smartlist_free(tmp);
  2048. }
  2049. /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
  2050. * true) we are currently downloading by descriptor digest, set result[d] to
  2051. * (void*)1. */
  2052. static void
  2053. list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
  2054. {
  2055. int purpose =
  2056. extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
  2057. list_pending_downloads(result, NULL, purpose, "d/");
  2058. }
  2059. /** For every microdescriptor we are currently downloading by descriptor
  2060. * digest, set result[d] to (void*)1.
  2061. */
  2062. void
  2063. list_pending_microdesc_downloads(digest256map_t *result)
  2064. {
  2065. list_pending_downloads(NULL, result, DIR_PURPOSE_FETCH_MICRODESC, "d/");
  2066. }
  2067. /** Launch downloads for all the descriptors whose digests or digests256
  2068. * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
  2069. * range.) If <b>source</b> is given, download from <b>source</b>;
  2070. * otherwise, download from an appropriate random directory server.
  2071. */
  2072. MOCK_IMPL(STATIC void,
  2073. initiate_descriptor_downloads,(const routerstatus_t *source,
  2074. int purpose, smartlist_t *digests,
  2075. int lo, int hi, int pds_flags))
  2076. {
  2077. char *resource, *cp;
  2078. int digest_len, enc_digest_len;
  2079. const char *sep;
  2080. int b64_256;
  2081. smartlist_t *tmp;
  2082. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  2083. /* Microdescriptors are downloaded by "-"-separated base64-encoded
  2084. * 256-bit digests. */
  2085. digest_len = DIGEST256_LEN;
  2086. enc_digest_len = BASE64_DIGEST256_LEN + 1;
  2087. sep = "-";
  2088. b64_256 = 1;
  2089. } else {
  2090. digest_len = DIGEST_LEN;
  2091. enc_digest_len = HEX_DIGEST_LEN + 1;
  2092. sep = "+";
  2093. b64_256 = 0;
  2094. }
  2095. if (lo < 0)
  2096. lo = 0;
  2097. if (hi > smartlist_len(digests))
  2098. hi = smartlist_len(digests);
  2099. if (hi-lo <= 0)
  2100. return;
  2101. tmp = smartlist_new();
  2102. for (; lo < hi; ++lo) {
  2103. cp = tor_malloc(enc_digest_len);
  2104. if (b64_256) {
  2105. digest256_to_base64(cp, smartlist_get(digests, lo));
  2106. } else {
  2107. base16_encode(cp, enc_digest_len, smartlist_get(digests, lo),
  2108. digest_len);
  2109. }
  2110. smartlist_add(tmp, cp);
  2111. }
  2112. cp = smartlist_join_strings(tmp, sep, 0, NULL);
  2113. tor_asprintf(&resource, "d/%s.z", cp);
  2114. SMARTLIST_FOREACH(tmp, char *, cp1, tor_free(cp1));
  2115. smartlist_free(tmp);
  2116. tor_free(cp);
  2117. if (source) {
  2118. /* We know which authority or directory mirror we want. */
  2119. directory_request_t *req = directory_request_new(purpose);
  2120. directory_request_set_routerstatus(req, source);
  2121. directory_request_set_resource(req, resource);
  2122. directory_initiate_request(req);
  2123. directory_request_free(req);
  2124. } else {
  2125. directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
  2126. pds_flags, DL_WANT_ANY_DIRSERVER);
  2127. }
  2128. tor_free(resource);
  2129. }
  2130. /** Return the max number of hashes to put in a URL for a given request.
  2131. */
  2132. static int
  2133. max_dl_per_request(const or_options_t *options, int purpose)
  2134. {
  2135. /* Since squid does not like URLs >= 4096 bytes we limit it to 96.
  2136. * 4096 - strlen(http://[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535
  2137. * /tor/server/d/.z) == 4026
  2138. * 4026/41 (40 for the hash and 1 for the + that separates them) => 98
  2139. * So use 96 because it's a nice number.
  2140. *
  2141. * For microdescriptors, the calculation is
  2142. * 4096 - strlen(http://[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535
  2143. * /tor/micro/d/.z) == 4027
  2144. * 4027/44 (43 for the hash and 1 for the - that separates them) => 91
  2145. * So use 90 because it's a nice number.
  2146. */
  2147. int max = 96;
  2148. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  2149. max = 90;
  2150. }
  2151. /* If we're going to tunnel our connections, we can ask for a lot more
  2152. * in a request. */
  2153. if (directory_must_use_begindir(options)) {
  2154. max = 500;
  2155. }
  2156. return max;
  2157. }
  2158. /** Don't split our requests so finely that we are requesting fewer than
  2159. * this number per server. (Grouping more than this at once leads to
  2160. * diminishing returns.) */
  2161. #define MIN_DL_PER_REQUEST 32
  2162. /** To prevent a single screwy cache from confusing us by selective reply,
  2163. * try to split our requests into at least this many requests. */
  2164. #define MIN_REQUESTS 3
  2165. /** If we want fewer than this many descriptors, wait until we
  2166. * want more, or until TestingClientMaxIntervalWithoutRequest has passed. */
  2167. #define MAX_DL_TO_DELAY 16
  2168. /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
  2169. * router descriptor digests or microdescriptor digest256s in
  2170. * <b>downloadable</b>, decide whether to delay fetching until we have more.
  2171. * If we don't want to delay, launch one or more requests to the appropriate
  2172. * directory authorities.
  2173. */
  2174. void
  2175. launch_descriptor_downloads(int purpose,
  2176. smartlist_t *downloadable,
  2177. const routerstatus_t *source, time_t now)
  2178. {
  2179. const or_options_t *options = get_options();
  2180. const char *descname;
  2181. const int fetch_microdesc = (purpose == DIR_PURPOSE_FETCH_MICRODESC);
  2182. int n_downloadable = smartlist_len(downloadable);
  2183. int i, n_per_request, max_dl_per_req;
  2184. const char *req_plural = "", *rtr_plural = "";
  2185. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  2186. tor_assert(fetch_microdesc || purpose == DIR_PURPOSE_FETCH_SERVERDESC);
  2187. descname = fetch_microdesc ? "microdesc" : "routerdesc";
  2188. if (!n_downloadable)
  2189. return;
  2190. if (!directory_fetches_dir_info_early(options)) {
  2191. if (n_downloadable >= MAX_DL_TO_DELAY) {
  2192. log_debug(LD_DIR,
  2193. "There are enough downloadable %ss to launch requests.",
  2194. descname);
  2195. } else if (! router_have_minimum_dir_info()) {
  2196. log_debug(LD_DIR,
  2197. "We are only missing %d %ss, but we'll fetch anyway, since "
  2198. "we don't yet have enough directory info.",
  2199. n_downloadable, descname);
  2200. } else {
  2201. /* should delay */
  2202. if ((last_descriptor_download_attempted +
  2203. options->TestingClientMaxIntervalWithoutRequest) > now)
  2204. return;
  2205. if (last_descriptor_download_attempted) {
  2206. log_info(LD_DIR,
  2207. "There are not many downloadable %ss, but we've "
  2208. "been waiting long enough (%d seconds). Downloading.",
  2209. descname,
  2210. (int)(now-last_descriptor_download_attempted));
  2211. } else {
  2212. log_info(LD_DIR,
  2213. "There are not many downloadable %ss, but we haven't "
  2214. "tried downloading descriptors recently. Downloading.",
  2215. descname);
  2216. }
  2217. }
  2218. }
  2219. if (!authdir_mode(options)) {
  2220. /* If we wind up going to the authorities, we want to only open one
  2221. * connection to each authority at a time, so that we don't overload
  2222. * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
  2223. * regardless of whether we're a cache or not.
  2224. *
  2225. * Setting this flag can make initiate_descriptor_downloads() ignore
  2226. * requests. We need to make sure that we do in fact call
  2227. * update_router_descriptor_downloads() later on, once the connections
  2228. * have succeeded or failed.
  2229. */
  2230. pds_flags |= fetch_microdesc ?
  2231. PDS_NO_EXISTING_MICRODESC_FETCH :
  2232. PDS_NO_EXISTING_SERVERDESC_FETCH;
  2233. }
  2234. n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
  2235. max_dl_per_req = max_dl_per_request(options, purpose);
  2236. if (n_per_request > max_dl_per_req)
  2237. n_per_request = max_dl_per_req;
  2238. if (n_per_request < MIN_DL_PER_REQUEST) {
  2239. n_per_request = MIN(MIN_DL_PER_REQUEST, n_downloadable);
  2240. }
  2241. if (n_downloadable > n_per_request)
  2242. req_plural = rtr_plural = "s";
  2243. else if (n_downloadable > 1)
  2244. rtr_plural = "s";
  2245. log_info(LD_DIR,
  2246. "Launching %d request%s for %d %s%s, %d at a time",
  2247. CEIL_DIV(n_downloadable, n_per_request), req_plural,
  2248. n_downloadable, descname, rtr_plural, n_per_request);
  2249. smartlist_sort_digests(downloadable);
  2250. for (i=0; i < n_downloadable; i += n_per_request) {
  2251. initiate_descriptor_downloads(source, purpose,
  2252. downloadable, i, i+n_per_request,
  2253. pds_flags);
  2254. }
  2255. last_descriptor_download_attempted = now;
  2256. }
  2257. /** For any descriptor that we want that's currently listed in
  2258. * <b>consensus</b>, download it as appropriate. */
  2259. void
  2260. update_consensus_router_descriptor_downloads(time_t now, int is_vote,
  2261. networkstatus_t *consensus)
  2262. {
  2263. const or_options_t *options = get_options();
  2264. digestmap_t *map = NULL;
  2265. smartlist_t *no_longer_old = smartlist_new();
  2266. smartlist_t *downloadable = smartlist_new();
  2267. routerstatus_t *source = NULL;
  2268. int authdir = authdir_mode(options);
  2269. int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
  2270. n_inprogress=0, n_in_oldrouters=0;
  2271. if (directory_too_idle_to_fetch_descriptors(options, now))
  2272. goto done;
  2273. if (!consensus)
  2274. goto done;
  2275. if (is_vote) {
  2276. /* where's it from, so we know whom to ask for descriptors */
  2277. dir_server_t *ds;
  2278. networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
  2279. tor_assert(voter);
  2280. ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
  2281. if (ds)
  2282. source = &(ds->fake_status);
  2283. else
  2284. log_warn(LD_DIR, "couldn't lookup source from vote?");
  2285. }
  2286. map = digestmap_new();
  2287. list_pending_descriptor_downloads(map, 0);
  2288. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
  2289. routerstatus_t *rs =
  2290. is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
  2291. signed_descriptor_t *sd;
  2292. if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
  2293. const routerinfo_t *ri;
  2294. ++n_have;
  2295. if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
  2296. tor_memneq(ri->cache_info.signed_descriptor_digest,
  2297. sd->signed_descriptor_digest, DIGEST_LEN)) {
  2298. /* We have a descriptor with this digest, but either there is no
  2299. * entry in routerlist with the same ID (!ri), or there is one,
  2300. * but the identity digest differs (memneq).
  2301. */
  2302. smartlist_add(no_longer_old, sd);
  2303. ++n_in_oldrouters; /* We have it in old_routers. */
  2304. }
  2305. continue; /* We have it already. */
  2306. }
  2307. if (digestmap_get(map, rs->descriptor_digest)) {
  2308. ++n_inprogress;
  2309. continue; /* We have an in-progress download. */
  2310. }
  2311. if (!download_status_is_ready(&rs->dl_status, now)) {
  2312. ++n_delayed; /* Not ready for retry. */
  2313. continue;
  2314. }
  2315. if (authdir && dirserv_would_reject_router(rs)) {
  2316. ++n_would_reject;
  2317. continue; /* We would throw it out immediately. */
  2318. }
  2319. if (!we_want_to_fetch_flavor(options, consensus->flavor) &&
  2320. !client_would_use_router(rs, now)) {
  2321. ++n_wouldnt_use;
  2322. continue; /* We would never use it ourself. */
  2323. }
  2324. if (is_vote && source) {
  2325. char time_bufnew[ISO_TIME_LEN+1];
  2326. char time_bufold[ISO_TIME_LEN+1];
  2327. const routerinfo_t *oldrouter;
  2328. oldrouter = router_get_by_id_digest(rs->identity_digest);
  2329. format_iso_time(time_bufnew, rs->published_on);
  2330. if (oldrouter)
  2331. format_iso_time(time_bufold, oldrouter->cache_info.published_on);
  2332. log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
  2333. routerstatus_describe(rs),
  2334. time_bufnew,
  2335. oldrouter ? time_bufold : "none",
  2336. source->nickname, oldrouter ? "known" : "unknown");
  2337. }
  2338. smartlist_add(downloadable, rs->descriptor_digest);
  2339. } SMARTLIST_FOREACH_END(rsp);
  2340. if (!authdir_mode_v3(options)
  2341. && smartlist_len(no_longer_old)) {
  2342. routerlist_t *rl = router_get_routerlist();
  2343. log_info(LD_DIR, "%d router descriptors listed in consensus are "
  2344. "currently in old_routers; making them current.",
  2345. smartlist_len(no_longer_old));
  2346. SMARTLIST_FOREACH_BEGIN(no_longer_old, signed_descriptor_t *, sd) {
  2347. const char *msg;
  2348. was_router_added_t r;
  2349. time_t tmp_cert_expiration_time;
  2350. routerinfo_t *ri = routerlist_reparse_old(rl, sd);
  2351. if (!ri) {
  2352. log_warn(LD_BUG, "Failed to re-parse a router.");
  2353. continue;
  2354. }
  2355. /* need to remember for below, since add_to_routerlist may free. */
  2356. tmp_cert_expiration_time = ri->cert_expiration_time;
  2357. r = router_add_to_routerlist(ri, &msg, 1, 0);
  2358. if (WRA_WAS_OUTDATED(r)) {
  2359. log_warn(LD_DIR, "Couldn't add re-parsed router: %s. This isn't "
  2360. "usually a big deal, but you should make sure that your "
  2361. "clock and timezone are set correctly.",
  2362. msg?msg:"???");
  2363. if (r == ROUTER_CERTS_EXPIRED) {
  2364. char time_cons[ISO_TIME_LEN+1];
  2365. char time_cert_expires[ISO_TIME_LEN+1];
  2366. format_iso_time(time_cons, consensus->valid_after);
  2367. format_iso_time(time_cert_expires, tmp_cert_expiration_time);
  2368. log_warn(LD_DIR, " (I'm looking at a consensus from %s; This "
  2369. "router's certificates began expiring at %s.)",
  2370. time_cons, time_cert_expires);
  2371. }
  2372. }
  2373. } SMARTLIST_FOREACH_END(sd);
  2374. routerlist_assert_ok(rl);
  2375. }
  2376. log_info(LD_DIR,
  2377. "%d router descriptors downloadable. %d delayed; %d present "
  2378. "(%d of those were in old_routers); %d would_reject; "
  2379. "%d wouldnt_use; %d in progress.",
  2380. smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
  2381. n_would_reject, n_wouldnt_use, n_inprogress);
  2382. launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC,
  2383. downloadable, source, now);
  2384. digestmap_free(map, NULL);
  2385. done:
  2386. smartlist_free(downloadable);
  2387. smartlist_free(no_longer_old);
  2388. }
  2389. /** How often should we launch a server/authority request to be sure of getting
  2390. * a guess for our IP? */
  2391. /*XXXX+ this info should come from netinfo cells or something, or we should
  2392. * do this only when we aren't seeing incoming data. see bug 652. */
  2393. #define DUMMY_DOWNLOAD_INTERVAL (20*60)
  2394. /** As needed, launch a dummy router descriptor fetch to see if our
  2395. * address has changed. */
  2396. static void
  2397. launch_dummy_descriptor_download_as_needed(time_t now,
  2398. const or_options_t *options)
  2399. {
  2400. static time_t last_dummy_download = 0;
  2401. /* XXXX+ we could be smarter here; see notes on bug 652. */
  2402. /* If we're a server that doesn't have a configured address, we rely on
  2403. * directory fetches to learn when our address changes. So if we haven't
  2404. * tried to get any routerdescs in a long time, try a dummy fetch now. */
  2405. if (!options->Address &&
  2406. server_mode(options) &&
  2407. last_descriptor_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
  2408. last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
  2409. last_dummy_download = now;
  2410. /* XX/teor - do we want an authority here, because they are less likely
  2411. * to give us the wrong address? (See #17782)
  2412. * I'm leaving the previous behaviour intact, because I don't like
  2413. * the idea of some relays contacting an authority every 20 minutes. */
  2414. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  2415. ROUTER_PURPOSE_GENERAL, "authority.z",
  2416. PDS_RETRY_IF_NO_SERVERS,
  2417. DL_WANT_ANY_DIRSERVER);
  2418. }
  2419. }
  2420. /** Launch downloads for router status as needed. */
  2421. void
  2422. update_router_descriptor_downloads(time_t now)
  2423. {
  2424. const or_options_t *options = get_options();
  2425. if (should_delay_dir_fetches(options, NULL))
  2426. return;
  2427. if (!we_fetch_router_descriptors(options))
  2428. return;
  2429. update_consensus_router_descriptor_downloads(now, 0,
  2430. networkstatus_get_reasonably_live_consensus(now, FLAV_NS));
  2431. }
  2432. /** Launch extrainfo downloads as needed. */
  2433. void
  2434. update_extrainfo_downloads(time_t now)
  2435. {
  2436. const or_options_t *options = get_options();
  2437. routerlist_t *rl;
  2438. smartlist_t *wanted;
  2439. digestmap_t *pending;
  2440. int old_routers, i, max_dl_per_req;
  2441. int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0, n_bogus[2] = {0,0};
  2442. if (! options->DownloadExtraInfo)
  2443. return;
  2444. if (should_delay_dir_fetches(options, NULL))
  2445. return;
  2446. if (!router_have_minimum_dir_info())
  2447. return;
  2448. pending = digestmap_new();
  2449. list_pending_descriptor_downloads(pending, 1);
  2450. rl = router_get_routerlist();
  2451. wanted = smartlist_new();
  2452. for (old_routers = 0; old_routers < 2; ++old_routers) {
  2453. smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
  2454. for (i = 0; i < smartlist_len(lst); ++i) {
  2455. signed_descriptor_t *sd;
  2456. char *d;
  2457. if (old_routers)
  2458. sd = smartlist_get(lst, i);
  2459. else
  2460. sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
  2461. if (sd->is_extrainfo)
  2462. continue; /* This should never happen. */
  2463. if (old_routers && !router_get_by_id_digest(sd->identity_digest))
  2464. continue; /* Couldn't check the signature if we got it. */
  2465. if (sd->extrainfo_is_bogus)
  2466. continue;
  2467. d = sd->extra_info_digest;
  2468. if (tor_digest_is_zero(d)) {
  2469. ++n_no_ei;
  2470. continue;
  2471. }
  2472. if (eimap_get(rl->extra_info_map, d)) {
  2473. ++n_have;
  2474. continue;
  2475. }
  2476. if (!download_status_is_ready(&sd->ei_dl_status, now)) {
  2477. ++n_delay;
  2478. continue;
  2479. }
  2480. if (digestmap_get(pending, d)) {
  2481. ++n_pending;
  2482. continue;
  2483. }
  2484. const signed_descriptor_t *sd2 = router_get_by_extrainfo_digest(d);
  2485. if (sd2 != sd) {
  2486. if (sd2 != NULL) {
  2487. char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
  2488. char d3[HEX_DIGEST_LEN+1], d4[HEX_DIGEST_LEN+1];
  2489. base16_encode(d1, sizeof(d1), sd->identity_digest, DIGEST_LEN);
  2490. base16_encode(d2, sizeof(d2), sd2->identity_digest, DIGEST_LEN);
  2491. base16_encode(d3, sizeof(d3), d, DIGEST_LEN);
  2492. base16_encode(d4, sizeof(d3), sd2->extra_info_digest, DIGEST_LEN);
  2493. log_info(LD_DIR, "Found an entry in %s with mismatched "
  2494. "router_get_by_extrainfo_digest() value. This has ID %s "
  2495. "but the entry in the map has ID %s. This has EI digest "
  2496. "%s and the entry in the map has EI digest %s.",
  2497. old_routers?"old_routers":"routers",
  2498. d1, d2, d3, d4);
  2499. } else {
  2500. char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
  2501. base16_encode(d1, sizeof(d1), sd->identity_digest, DIGEST_LEN);
  2502. base16_encode(d2, sizeof(d2), d, DIGEST_LEN);
  2503. log_info(LD_DIR, "Found an entry in %s with NULL "
  2504. "router_get_by_extrainfo_digest() value. This has ID %s "
  2505. "and EI digest %s.",
  2506. old_routers?"old_routers":"routers",
  2507. d1, d2);
  2508. }
  2509. ++n_bogus[old_routers];
  2510. continue;
  2511. }
  2512. smartlist_add(wanted, d);
  2513. }
  2514. }
  2515. digestmap_free(pending, NULL);
  2516. log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
  2517. "with present ei, %d delaying, %d pending, %d downloadable, %d "
  2518. "bogus in routers, %d bogus in old_routers",
  2519. n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted),
  2520. n_bogus[0], n_bogus[1]);
  2521. smartlist_shuffle(wanted);
  2522. max_dl_per_req = max_dl_per_request(options, DIR_PURPOSE_FETCH_EXTRAINFO);
  2523. for (i = 0; i < smartlist_len(wanted); i += max_dl_per_req) {
  2524. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
  2525. wanted, i, i+max_dl_per_req,
  2526. PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
  2527. }
  2528. smartlist_free(wanted);
  2529. }
  2530. /** Reset the consensus and extra-info download failure count on all routers.
  2531. * When we get a new consensus,
  2532. * routers_update_status_from_consensus_networkstatus() will reset the
  2533. * download statuses on the descriptors in that consensus.
  2534. */
  2535. void
  2536. router_reset_descriptor_download_failures(void)
  2537. {
  2538. log_debug(LD_GENERAL,
  2539. "In router_reset_descriptor_download_failures()");
  2540. networkstatus_reset_download_failures();
  2541. last_descriptor_download_attempted = 0;
  2542. if (!routerlist)
  2543. return;
  2544. /* We want to download *all* extra-info descriptors, not just those in
  2545. * the consensus we currently have (or are about to have) */
  2546. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  2547. {
  2548. download_status_reset(&ri->cache_info.ei_dl_status);
  2549. });
  2550. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  2551. {
  2552. download_status_reset(&sd->ei_dl_status);
  2553. });
  2554. }
  2555. /** Any changes in a router descriptor's publication time larger than this are
  2556. * automatically non-cosmetic. */
  2557. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
  2558. /** We allow uptime to vary from how much it ought to be by this much. */
  2559. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  2560. /** Return true iff the only differences between r1 and r2 are such that
  2561. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  2562. */
  2563. int
  2564. router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
  2565. {
  2566. time_t r1pub, r2pub;
  2567. time_t time_difference;
  2568. tor_assert(r1 && r2);
  2569. /* r1 should be the one that was published first. */
  2570. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  2571. const routerinfo_t *ri_tmp = r2;
  2572. r2 = r1;
  2573. r1 = ri_tmp;
  2574. }
  2575. /* If any key fields differ, they're different. */
  2576. if (r1->addr != r2->addr ||
  2577. strcasecmp(r1->nickname, r2->nickname) ||
  2578. r1->or_port != r2->or_port ||
  2579. !tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) ||
  2580. r1->ipv6_orport != r2->ipv6_orport ||
  2581. r1->dir_port != r2->dir_port ||
  2582. r1->purpose != r2->purpose ||
  2583. r1->onion_pkey_len != r2->onion_pkey_len ||
  2584. !tor_memeq(r1->onion_pkey, r2->onion_pkey, r1->onion_pkey_len) ||
  2585. !crypto_pk_eq_keys(r1->identity_pkey, r2->identity_pkey) ||
  2586. strcasecmp(r1->platform, r2->platform) ||
  2587. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  2588. (!r1->contact_info && r2->contact_info) ||
  2589. (r1->contact_info && r2->contact_info &&
  2590. strcasecmp(r1->contact_info, r2->contact_info)) ||
  2591. r1->is_hibernating != r2->is_hibernating ||
  2592. ! addr_policies_eq(r1->exit_policy, r2->exit_policy) ||
  2593. (r1->supports_tunnelled_dir_requests !=
  2594. r2->supports_tunnelled_dir_requests))
  2595. return 0;
  2596. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  2597. return 0;
  2598. if (r1->declared_family && r2->declared_family) {
  2599. int i, n;
  2600. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  2601. return 0;
  2602. n = smartlist_len(r1->declared_family);
  2603. for (i=0; i < n; ++i) {
  2604. if (strcasecmp(smartlist_get(r1->declared_family, i),
  2605. smartlist_get(r2->declared_family, i)))
  2606. return 0;
  2607. }
  2608. }
  2609. /* Did bandwidth change a lot? */
  2610. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  2611. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  2612. return 0;
  2613. /* Did the bandwidthrate or bandwidthburst change? */
  2614. if ((r1->bandwidthrate != r2->bandwidthrate) ||
  2615. (r1->bandwidthburst != r2->bandwidthburst))
  2616. return 0;
  2617. /* Did more than 12 hours pass? */
  2618. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  2619. < r2->cache_info.published_on)
  2620. return 0;
  2621. /* Did uptime fail to increase by approximately the amount we would think,
  2622. * give or take some slop? */
  2623. r1pub = r1->cache_info.published_on;
  2624. r2pub = r2->cache_info.published_on;
  2625. time_difference = r2->uptime - (r1->uptime + (r2pub - r1pub));
  2626. if (time_difference < 0)
  2627. time_difference = - time_difference;
  2628. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  2629. time_difference > r1->uptime * .05 &&
  2630. time_difference > r2->uptime * .05)
  2631. return 0;
  2632. /* Otherwise, the difference is cosmetic. */
  2633. return 1;
  2634. }
  2635. /** Check whether <b>sd</b> describes a router descriptor compatible with the
  2636. * extrainfo document <b>ei</b>.
  2637. *
  2638. * <b>identity_pkey</b> (which must also be provided) is RSA1024 identity key
  2639. * for the router. We use it to check the signature of the extrainfo document,
  2640. * if it has not already been checked.
  2641. *
  2642. * If no router is compatible with <b>ei</b>, <b>ei</b> should be
  2643. * dropped. Return 0 for "compatible", return 1 for "reject, and inform
  2644. * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
  2645. * <b>msg</b> is present, set *<b>msg</b> to a description of the
  2646. * incompatibility (if any).
  2647. *
  2648. * Set the extrainfo_is_bogus field in <b>sd</b> if the digests matched
  2649. * but the extrainfo was nonetheless incompatible.
  2650. **/
  2651. int
  2652. routerinfo_incompatible_with_extrainfo(const crypto_pk_t *identity_pkey,
  2653. extrainfo_t *ei,
  2654. signed_descriptor_t *sd,
  2655. const char **msg)
  2656. {
  2657. int digest_matches, digest256_matches, r=1;
  2658. tor_assert(identity_pkey);
  2659. tor_assert(sd);
  2660. tor_assert(ei);
  2661. if (ei->bad_sig) {
  2662. if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
  2663. return 1;
  2664. }
  2665. digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
  2666. sd->extra_info_digest, DIGEST_LEN);
  2667. /* Set digest256_matches to 1 if the digest is correct, or if no
  2668. * digest256 was in the ri. */
  2669. digest256_matches = tor_memeq(ei->digest256,
  2670. sd->extra_info_digest256, DIGEST256_LEN);
  2671. digest256_matches |=
  2672. tor_mem_is_zero(sd->extra_info_digest256, DIGEST256_LEN);
  2673. /* The identity must match exactly to have been generated at the same time
  2674. * by the same router. */
  2675. if (tor_memneq(sd->identity_digest,
  2676. ei->cache_info.identity_digest,
  2677. DIGEST_LEN)) {
  2678. if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
  2679. goto err; /* different servers */
  2680. }
  2681. if (! tor_cert_opt_eq(sd->signing_key_cert,
  2682. ei->cache_info.signing_key_cert)) {
  2683. if (msg) *msg = "Extrainfo signing key cert didn't match routerinfo";
  2684. goto err; /* different servers */
  2685. }
  2686. if (ei->pending_sig) {
  2687. char signed_digest[128];
  2688. if (crypto_pk_public_checksig(identity_pkey,
  2689. signed_digest, sizeof(signed_digest),
  2690. ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
  2691. tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
  2692. DIGEST_LEN)) {
  2693. ei->bad_sig = 1;
  2694. tor_free(ei->pending_sig);
  2695. if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
  2696. goto err; /* Bad signature, or no match. */
  2697. }
  2698. ei->cache_info.send_unencrypted = sd->send_unencrypted;
  2699. tor_free(ei->pending_sig);
  2700. }
  2701. if (ei->cache_info.published_on < sd->published_on) {
  2702. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  2703. goto err;
  2704. } else if (ei->cache_info.published_on > sd->published_on) {
  2705. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  2706. r = -1;
  2707. goto err;
  2708. }
  2709. if (!digest256_matches && !digest_matches) {
  2710. if (msg) *msg = "Neither digest256 or digest matched "
  2711. "digest from routerdesc";
  2712. goto err;
  2713. }
  2714. if (!digest256_matches) {
  2715. if (msg) *msg = "Extrainfo digest did not match digest256 from routerdesc";
  2716. goto err; /* Digest doesn't match declared value. */
  2717. }
  2718. if (!digest_matches) {
  2719. if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
  2720. goto err; /* Digest doesn't match declared value. */
  2721. }
  2722. return 0;
  2723. err:
  2724. if (digest_matches) {
  2725. /* This signature was okay, and the digest was right: This is indeed the
  2726. * corresponding extrainfo. But insanely, it doesn't match the routerinfo
  2727. * that lists it. Don't try to fetch this one again. */
  2728. sd->extrainfo_is_bogus = 1;
  2729. }
  2730. return r;
  2731. }
  2732. /* Does ri have a valid ntor onion key?
  2733. * Valid ntor onion keys exist and have at least one non-zero byte. */
  2734. int
  2735. routerinfo_has_curve25519_onion_key(const routerinfo_t *ri)
  2736. {
  2737. if (!ri) {
  2738. return 0;
  2739. }
  2740. if (!ri->onion_curve25519_pkey) {
  2741. return 0;
  2742. }
  2743. if (tor_mem_is_zero((const char*)ri->onion_curve25519_pkey->public_key,
  2744. CURVE25519_PUBKEY_LEN)) {
  2745. return 0;
  2746. }
  2747. return 1;
  2748. }
  2749. /* Is rs running a tor version known to support EXTEND2 cells?
  2750. * If allow_unknown_versions is true, return true if we can't tell
  2751. * (from a versions line or a protocols line) whether it supports extend2
  2752. * cells.
  2753. * Otherwise, return false if the version is unknown. */
  2754. int
  2755. routerstatus_version_supports_extend2_cells(const routerstatus_t *rs,
  2756. int allow_unknown_versions)
  2757. {
  2758. if (!rs) {
  2759. return allow_unknown_versions;
  2760. }
  2761. if (!rs->pv.protocols_known) {
  2762. return allow_unknown_versions;
  2763. }
  2764. return rs->pv.supports_extend2_cells;
  2765. }
  2766. /** Assert that the internal representation of <b>rl</b> is
  2767. * self-consistent. */
  2768. void
  2769. routerlist_assert_ok(const routerlist_t *rl)
  2770. {
  2771. routerinfo_t *r2;
  2772. signed_descriptor_t *sd2;
  2773. if (!rl)
  2774. return;
  2775. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, r) {
  2776. r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
  2777. tor_assert(r == r2);
  2778. sd2 = sdmap_get(rl->desc_digest_map,
  2779. r->cache_info.signed_descriptor_digest);
  2780. tor_assert(&(r->cache_info) == sd2);
  2781. tor_assert(r->cache_info.routerlist_index == r_sl_idx);
  2782. /* XXXX
  2783. *
  2784. * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
  2785. * commenting this out is just a band-aid.
  2786. *
  2787. * The problem is that, although well-behaved router descriptors
  2788. * should never have the same value for their extra_info_digest, it's
  2789. * possible for ill-behaved routers to claim whatever they like there.
  2790. *
  2791. * The real answer is to trash desc_by_eid_map and instead have
  2792. * something that indicates for a given extra-info digest we want,
  2793. * what its download status is. We'll do that as a part of routerlist
  2794. * refactoring once consensus directories are in. For now,
  2795. * this rep violation is probably harmless: an adversary can make us
  2796. * reset our retry count for an extrainfo, but that's not the end
  2797. * of the world. Changing the representation in 0.2.0.x would just
  2798. * destabilize the codebase.
  2799. if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
  2800. signed_descriptor_t *sd3 =
  2801. sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
  2802. tor_assert(sd3 == &(r->cache_info));
  2803. }
  2804. */
  2805. } SMARTLIST_FOREACH_END(r);
  2806. SMARTLIST_FOREACH_BEGIN(rl->old_routers, signed_descriptor_t *, sd) {
  2807. r2 = rimap_get(rl->identity_map, sd->identity_digest);
  2808. tor_assert(!r2 || sd != &(r2->cache_info));
  2809. sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  2810. tor_assert(sd == sd2);
  2811. tor_assert(sd->routerlist_index == sd_sl_idx);
  2812. /* XXXX see above.
  2813. if (!tor_digest_is_zero(sd->extra_info_digest)) {
  2814. signed_descriptor_t *sd3 =
  2815. sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
  2816. tor_assert(sd3 == sd);
  2817. }
  2818. */
  2819. } SMARTLIST_FOREACH_END(sd);
  2820. RIMAP_FOREACH(rl->identity_map, d, r) {
  2821. tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
  2822. } DIGESTMAP_FOREACH_END;
  2823. SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
  2824. tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
  2825. } DIGESTMAP_FOREACH_END;
  2826. SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
  2827. tor_assert(!tor_digest_is_zero(d));
  2828. tor_assert(sd);
  2829. tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
  2830. } DIGESTMAP_FOREACH_END;
  2831. EIMAP_FOREACH(rl->extra_info_map, d, ei) {
  2832. signed_descriptor_t *sd;
  2833. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  2834. d, DIGEST_LEN));
  2835. sd = sdmap_get(rl->desc_by_eid_map,
  2836. ei->cache_info.signed_descriptor_digest);
  2837. // tor_assert(sd); // XXXX see above
  2838. if (sd) {
  2839. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  2840. sd->extra_info_digest, DIGEST_LEN));
  2841. }
  2842. } DIGESTMAP_FOREACH_END;
  2843. }
  2844. /** Allocate and return a new string representing the contact info
  2845. * and platform string for <b>router</b>,
  2846. * surrounded by quotes and using standard C escapes.
  2847. *
  2848. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  2849. * thread. Also, each call invalidates the last-returned value, so don't
  2850. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  2851. *
  2852. * If <b>router</b> is NULL, it just frees its internal memory and returns.
  2853. */
  2854. const char *
  2855. esc_router_info(const routerinfo_t *router)
  2856. {
  2857. static char *info=NULL;
  2858. char *esc_contact, *esc_platform;
  2859. tor_free(info);
  2860. if (!router)
  2861. return NULL; /* we're exiting; just free the memory we use */
  2862. esc_contact = esc_for_log(router->contact_info);
  2863. esc_platform = esc_for_log(router->platform);
  2864. tor_asprintf(&info, "Contact %s, Platform %s", esc_contact, esc_platform);
  2865. tor_free(esc_contact);
  2866. tor_free(esc_platform);
  2867. return info;
  2868. }
  2869. /** Helper for sorting: compare two routerinfos by their identity
  2870. * digest. */
  2871. static int
  2872. compare_routerinfo_by_id_digest_(const void **a, const void **b)
  2873. {
  2874. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  2875. return fast_memcmp(first->cache_info.identity_digest,
  2876. second->cache_info.identity_digest,
  2877. DIGEST_LEN);
  2878. }
  2879. /** Sort a list of routerinfo_t in ascending order of identity digest. */
  2880. void
  2881. routers_sort_by_identity(smartlist_t *routers)
  2882. {
  2883. smartlist_sort(routers, compare_routerinfo_by_id_digest_);
  2884. }
  2885. /** Called when we change a node set, or when we reload the geoip IPv4 list:
  2886. * recompute all country info in all configuration node sets and in the
  2887. * routerlist. */
  2888. void
  2889. refresh_all_country_info(void)
  2890. {
  2891. const or_options_t *options = get_options();
  2892. if (options->EntryNodes)
  2893. routerset_refresh_countries(options->EntryNodes);
  2894. if (options->ExitNodes)
  2895. routerset_refresh_countries(options->ExitNodes);
  2896. if (options->MiddleNodes)
  2897. routerset_refresh_countries(options->MiddleNodes);
  2898. if (options->ExcludeNodes)
  2899. routerset_refresh_countries(options->ExcludeNodes);
  2900. if (options->ExcludeExitNodes)
  2901. routerset_refresh_countries(options->ExcludeExitNodes);
  2902. if (options->ExcludeExitNodesUnion_)
  2903. routerset_refresh_countries(options->ExcludeExitNodesUnion_);
  2904. nodelist_refresh_countries();
  2905. }