routerlist.c 112 KB

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