routerlist.c 112 KB

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