routerlist.c 112 KB

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