routerlist.c 112 KB

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