routerlist.c 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerlist_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file routerlist.c
  10. * \brief Code to
  11. * maintain and access the global list of routerinfos for known
  12. * servers.
  13. **/
  14. #include "or.h"
  15. /****************************************************************************/
  16. /* static function prototypes */
  17. static routerstatus_t *router_pick_directory_server_impl(int requireother,
  18. int fascistfirewall,
  19. int for_v2_directory);
  20. static routerstatus_t *router_pick_trusteddirserver_impl(
  21. int need_v1_authority, int requireother, int fascistfirewall);
  22. static void mark_all_trusteddirservers_up(void);
  23. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  24. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  25. static void routerstatus_list_update_from_networkstatus(time_t now);
  26. static void local_routerstatus_free(local_routerstatus_t *rs);
  27. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  28. static void update_networkstatus_cache_downloads(time_t now);
  29. static void update_networkstatus_client_downloads(time_t now);
  30. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  31. static void routerlist_assert_ok(routerlist_t *rl);
  32. static int have_tried_downloading_all_statuses(int n_failures);
  33. static routerstatus_t *networkstatus_find_entry(networkstatus_t *ns,
  34. const char *digest);
  35. static local_routerstatus_t *router_get_combined_status_by_nickname(
  36. const char *nickname,
  37. int warn_if_unnamed);
  38. /****************************************************************************/
  39. /** Global list of a trusted_dir_server_t object for each trusted directory
  40. * server. */
  41. static smartlist_t *trusted_dir_servers = NULL;
  42. /** Global list of all of the routers that we know about. */
  43. static routerlist_t *routerlist = NULL;
  44. /** Global list of all of the current network_status documents that we know
  45. * about. This list is kept sorted by published_on. */
  46. static smartlist_t *networkstatus_list = NULL;
  47. /** Global list of local_routerstatus_t for each router, known or unknown. */
  48. static smartlist_t *routerstatus_list = NULL;
  49. /** True iff any member of networkstatus_list has changed since the last time
  50. * we called routerstatus_list_update_from_networkstatus(). */
  51. static int networkstatus_list_has_changed = 0;
  52. /** True iff any element of routerstatus_list has changed since the last
  53. * time we called routers_update_all_from_networkstatus().*/
  54. static int routerstatus_list_has_changed = 0;
  55. /** List of strings for nicknames we've already warned about and that are
  56. * still unknown / unavailable. */
  57. static smartlist_t *warned_nicknames = NULL;
  58. /** List of strings for nicknames or fingerprints we've already warned about
  59. * and that are still conflicted. */
  60. static smartlist_t *warned_conflicts = NULL;
  61. /** The last time we tried to download any routerdesc, or 0 for "never". We
  62. * use this to rate-limit download attempts when the number of routerdescs to
  63. * download is low. */
  64. static time_t last_routerdesc_download_attempted = 0;
  65. /** The last time we tried to download a networkstatus, or 0 for "never". We
  66. * use this to rate-limit download attempts for directory caches (including
  67. * mirrors). Clients don't use this now. */
  68. static time_t last_networkstatus_download_attempted = 0;
  69. /** True iff we have logged a warning about this OR not being valid or
  70. * not being named. */
  71. static int have_warned_about_invalid_status = 0;
  72. /** True iff we have logged a warning about this OR's version being older than
  73. * listed by the authorities */
  74. static int have_warned_about_old_version = 0;
  75. /** True iff we have logged a warning about this OR's version being newer than
  76. * listed by the authorities */
  77. static int have_warned_about_new_version = 0;
  78. /** Repopulate our list of network_status_t objects from the list cached on
  79. * disk. Return 0 on success, -1 on failure. */
  80. int
  81. router_reload_networkstatus(void)
  82. {
  83. char filename[512];
  84. struct stat st;
  85. smartlist_t *entries;
  86. char *s;
  87. tor_assert(get_options()->DataDirectory);
  88. if (!networkstatus_list)
  89. networkstatus_list = smartlist_create();
  90. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  91. get_options()->DataDirectory);
  92. entries = tor_listdir(filename);
  93. SMARTLIST_FOREACH(entries, const char *, fn, {
  94. char buf[DIGEST_LEN];
  95. if (strlen(fn) != HEX_DIGEST_LEN ||
  96. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  97. log_info(LD_DIR,
  98. "Skipping cached-status file with unexpected name \"%s\"",fn);
  99. continue;
  100. }
  101. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  102. get_options()->DataDirectory, fn);
  103. s = read_file_to_str(filename, 0);
  104. if (s) {
  105. stat(filename, &st);
  106. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  107. log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
  108. }
  109. tor_free(s);
  110. }
  111. });
  112. SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
  113. smartlist_free(entries);
  114. networkstatus_list_clean(time(NULL));
  115. routers_update_all_from_networkstatus();
  116. return 0;
  117. }
  118. /* Router descriptor storage.
  119. *
  120. * Routerdescs are stored in a big file, named "cached-routers". As new
  121. * routerdescs arrive, we append them to a journal file named
  122. * "cached-routers.new".
  123. *
  124. * From time to time, we replace "cached-routers" with a new file containing
  125. * only the live, non-superseded descriptors, and clear cached-routers.new.
  126. *
  127. * On startup, we read both files.
  128. */
  129. /** The size of the router log, in bytes. */
  130. static size_t router_journal_len = 0;
  131. /** The size of the router store, in bytes. */
  132. static size_t router_store_len = 0;
  133. /** Total bytes dropped since last rebuild. */
  134. static size_t router_bytes_dropped = 0;
  135. /** Helper: return 1 iff the router log is so big we want to rebuild the
  136. * store. */
  137. static int
  138. router_should_rebuild_store(void)
  139. {
  140. if (router_store_len > (1<<16))
  141. return (router_journal_len > router_store_len / 2 ||
  142. router_bytes_dropped > router_store_len / 2);
  143. else
  144. return router_journal_len > (1<<15);
  145. }
  146. /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
  147. * journal. */
  148. static int
  149. router_append_to_journal(signed_descriptor_t *desc)
  150. {
  151. or_options_t *options = get_options();
  152. size_t fname_len = strlen(options->DataDirectory)+32;
  153. char *fname = tor_malloc(fname_len);
  154. const char *body = signed_descriptor_get_body(desc);
  155. size_t len = desc->signed_descriptor_len;
  156. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  157. options->DataDirectory);
  158. tor_assert(len == strlen(body));
  159. if (append_bytes_to_file(fname, body, len, 0)) {
  160. log_warn(LD_FS, "Unable to store router descriptor");
  161. tor_free(fname);
  162. return -1;
  163. }
  164. desc->saved_location = SAVED_IN_JOURNAL;
  165. desc->saved_offset = router_journal_len;
  166. tor_free(fname);
  167. router_journal_len += len;
  168. return 0;
  169. }
  170. static int
  171. _compare_old_routers_by_age(const void **_a, const void **_b)
  172. {
  173. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  174. return r1->published_on - r2->published_on;
  175. }
  176. static int
  177. _compare_routers_by_age(const void **_a, const void **_b)
  178. {
  179. const routerinfo_t *r1 = *_a, *r2 = *_b;
  180. return r1->cache_info.published_on - r2->cache_info.published_on;
  181. }
  182. /** If the journal is too long, or if <b>force</b> is true, then atomically
  183. * replace the router store with the routers currently in our routerlist, and
  184. * clear the journal. Return 0 on success, -1 on failure.
  185. */
  186. static int
  187. router_rebuild_store(int force)
  188. {
  189. size_t len = 0;
  190. or_options_t *options;
  191. size_t fname_len;
  192. smartlist_t *chunk_list = NULL;
  193. char *fname = NULL;
  194. int r = -1, i;
  195. off_t offset = 0;
  196. smartlist_t *old_routers, *routers;
  197. if (!force && !router_should_rebuild_store())
  198. return 0;
  199. if (!routerlist)
  200. return 0;
  201. /* Don't save deadweight. */
  202. routerlist_remove_old_routers();
  203. log_info(LD_DIR, "Rebuilding router descriptor cache");
  204. options = get_options();
  205. fname_len = strlen(options->DataDirectory)+32;
  206. fname = tor_malloc(fname_len);
  207. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  208. chunk_list = smartlist_create();
  209. old_routers = smartlist_create();
  210. smartlist_add_all(old_routers, routerlist->old_routers);
  211. smartlist_sort(old_routers, _compare_old_routers_by_age);
  212. routers = smartlist_create();
  213. smartlist_add_all(routers, routerlist->routers);
  214. smartlist_sort(routers, _compare_routers_by_age);
  215. for (i = 0; i < 2; ++i) {
  216. smartlist_t *lst = smartlist_create();
  217. /* We sort the routers by age to enhance locality on disk. */
  218. if (i==0)
  219. lst = old_routers;
  220. else
  221. lst = routers;
  222. /* Now, add the appropriate members to chunk_list */
  223. SMARTLIST_FOREACH(lst, void *, ptr,
  224. {
  225. signed_descriptor_t *sd = (i==0) ?
  226. ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
  227. sized_chunk_t *c;
  228. const char *body = signed_descriptor_get_body(sd);
  229. if (!body) {
  230. log_warn(LD_BUG, "Bug! No descriptor available for router.");
  231. smartlist_free(lst);
  232. goto done;
  233. }
  234. c = tor_malloc(sizeof(sized_chunk_t));
  235. c->bytes = body;
  236. c->len = sd->signed_descriptor_len;
  237. smartlist_add(chunk_list, c);
  238. });
  239. }
  240. if (write_chunks_to_file(fname, chunk_list, 0)<0) {
  241. log_warn(LD_FS, "Error writing router store to disk.");
  242. goto done;
  243. }
  244. /* Our mmap is now invalid. */
  245. if (routerlist->mmap_descriptors) {
  246. tor_munmap_file(routerlist->mmap_descriptors,
  247. routerlist->mmap_descriptors_len);
  248. routerlist->mmap_descriptors =
  249. tor_mmap_file(fname, &routerlist->mmap_descriptors_len);
  250. if (! routerlist->mmap_descriptors)
  251. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  252. }
  253. offset = 0;
  254. for (i = 0; i < 2; ++i) {
  255. smartlist_t *lst = (i == 0) ? old_routers : routers;
  256. SMARTLIST_FOREACH(lst, void *, ptr,
  257. {
  258. signed_descriptor_t *sd = (i==0) ?
  259. ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
  260. sd->saved_location = SAVED_IN_CACHE;
  261. if (routerlist->mmap_descriptors) {
  262. tor_free(sd->signed_descriptor_body); // sets it to null
  263. }
  264. offset += sd->signed_descriptor_len;
  265. signed_descriptor_get_body(sd);
  266. });
  267. }
  268. smartlist_free(old_routers);
  269. smartlist_free(routers);
  270. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  271. options->DataDirectory);
  272. write_str_to_file(fname, "", 0);
  273. r = 0;
  274. router_store_len = len;
  275. router_journal_len = 0;
  276. router_bytes_dropped = 0;
  277. done:
  278. tor_free(fname);
  279. if (chunk_list) {
  280. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  281. smartlist_free(chunk_list);
  282. }
  283. return r;
  284. }
  285. /* Load all cached router descriptors from the store. Return 0 on success and
  286. * -1 on failure.
  287. */
  288. int
  289. router_reload_router_list(void)
  290. {
  291. or_options_t *options = get_options();
  292. size_t fname_len = strlen(options->DataDirectory)+32;
  293. char *fname = tor_malloc(fname_len), *contents;
  294. struct stat st;
  295. if (!routerlist)
  296. router_get_routerlist(); /* mallocs and inits it in place */
  297. router_journal_len = router_store_len = 0;
  298. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  299. routerlist->mmap_descriptors =
  300. tor_mmap_file(fname, &routerlist->mmap_descriptors_len);
  301. if (routerlist->mmap_descriptors) {
  302. router_store_len = routerlist->mmap_descriptors_len;
  303. router_load_routers_from_string(routerlist->mmap_descriptors,
  304. SAVED_IN_CACHE, NULL);
  305. }
  306. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  307. options->DataDirectory);
  308. contents = read_file_to_str(fname, 0);
  309. if (contents) {
  310. stat(fname, &st);
  311. router_load_routers_from_string(contents,
  312. SAVED_IN_JOURNAL, NULL);
  313. }
  314. tor_free(fname);
  315. if (router_journal_len) {
  316. /* Always clear the journal on startup.*/
  317. router_rebuild_store(1);
  318. } else {
  319. /* Don't cache expired routers. (This is in an else because
  320. * router_rebuild_store() also calls remove_old_routers().) */
  321. routerlist_remove_old_routers();
  322. }
  323. return 0;
  324. }
  325. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  326. * known trusted dirservers. Callers must not modify the list or its
  327. * contents.
  328. */
  329. smartlist_t *
  330. router_get_trusted_dir_servers(void)
  331. {
  332. if (!trusted_dir_servers)
  333. trusted_dir_servers = smartlist_create();
  334. return trusted_dir_servers;
  335. }
  336. /** Try to find a running dirserver. If there are no running dirservers
  337. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  338. * set all the authoritative ones as running again, and pick one;
  339. * if there are then no dirservers at all in our routerlist,
  340. * reload the routerlist and try one last time. If for_runningrouters is
  341. * true, then only pick a dirserver that can answer runningrouters queries
  342. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  343. * Don't pick an authority if any non-authority is viable.
  344. * Other args are as in router_pick_directory_server_impl().
  345. */
  346. routerstatus_t *
  347. router_pick_directory_server(int requireother,
  348. int fascistfirewall,
  349. int for_v2_directory,
  350. int retry_if_no_servers)
  351. {
  352. routerstatus_t *choice;
  353. if (!routerlist)
  354. return NULL;
  355. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  356. for_v2_directory);
  357. if (choice || !retry_if_no_servers)
  358. return choice;
  359. log_info(LD_DIR,
  360. "No reachable router entries for dirservers. "
  361. "Trying them all again.");
  362. /* mark all authdirservers as up again */
  363. mark_all_trusteddirservers_up();
  364. /* try again */
  365. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  366. for_v2_directory);
  367. if (choice)
  368. return choice;
  369. log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
  370. fascistfirewall ? "reachable" : "known");
  371. if (router_reload_router_list()) {
  372. return NULL;
  373. }
  374. /* give it one last try */
  375. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  376. for_v2_directory);
  377. return choice;
  378. }
  379. /** Return the trusted_dir_server_t for the directory authority whose identity
  380. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  381. */
  382. trusted_dir_server_t *
  383. router_get_trusteddirserver_by_digest(const char *digest)
  384. {
  385. if (!trusted_dir_servers)
  386. return NULL;
  387. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  388. {
  389. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  390. return ds;
  391. });
  392. return NULL;
  393. }
  394. /** Try to find a running trusted dirserver. If there are no running
  395. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  396. * set them all as running again, and try again.
  397. * If <b>need_v1_authority</b> is set, return only trusted servers
  398. * that are authorities for the V1 directory protocol.
  399. * Other args are as in router_pick_trusteddirserver_impl().
  400. */
  401. routerstatus_t *
  402. router_pick_trusteddirserver(int need_v1_authority,
  403. int requireother,
  404. int fascistfirewall,
  405. int retry_if_no_servers)
  406. {
  407. routerstatus_t *choice;
  408. choice = router_pick_trusteddirserver_impl(need_v1_authority,
  409. requireother, fascistfirewall);
  410. if (choice || !retry_if_no_servers)
  411. return choice;
  412. log_info(LD_DIR,
  413. "No trusted dirservers are reachable. Trying them all again.");
  414. mark_all_trusteddirservers_up();
  415. return router_pick_trusteddirserver_impl(need_v1_authority,
  416. requireother, fascistfirewall);
  417. }
  418. /** Pick a random running valid directory server/mirror from our
  419. * routerlist. Don't pick an authority if any non-authorities are viable.
  420. * If <b>fascistfirewall</b>,
  421. * make sure the router we pick is allowed by our firewall options.
  422. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  423. * choose a directory server new enough to support the v2 directory
  424. * functionality.
  425. */
  426. static routerstatus_t *
  427. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  428. int for_v2_directory)
  429. {
  430. routerstatus_t *result;
  431. smartlist_t *sl;
  432. smartlist_t *trusted;
  433. if (!routerstatus_list)
  434. return NULL;
  435. /* Find all the running dirservers we know about. */
  436. sl = smartlist_create();
  437. trusted = smartlist_create();
  438. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, _local_status,
  439. {
  440. routerstatus_t *status = &(_local_status->status);
  441. int is_trusted;
  442. if (!status->is_running || !status->dir_port || !status->is_valid)
  443. continue;
  444. if (requireother && router_digest_is_me(status->identity_digest))
  445. continue;
  446. if (fascistfirewall) {
  447. if (!fascist_firewall_allows_address_dir(status->addr, status->dir_port))
  448. continue;
  449. }
  450. is_trusted = router_digest_is_trusted_dir(status->identity_digest);
  451. if (for_v2_directory && !(status->is_v2_dir || is_trusted))
  452. continue;
  453. smartlist_add(is_trusted ? trusted : sl, status);
  454. });
  455. if (smartlist_len(sl))
  456. result = smartlist_choose(sl);
  457. else
  458. result = smartlist_choose(trusted);
  459. smartlist_free(sl);
  460. smartlist_free(trusted);
  461. return result;
  462. }
  463. /** Choose randomly from among the trusted dirservers that are up. If
  464. * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
  465. * firewall options. If <b>requireother</b>, it cannot be us. If
  466. * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
  467. * system.
  468. */
  469. static routerstatus_t *
  470. router_pick_trusteddirserver_impl(int need_v1_authority,
  471. int requireother, int fascistfirewall)
  472. {
  473. smartlist_t *sl;
  474. routerinfo_t *me;
  475. routerstatus_t *rs;
  476. sl = smartlist_create();
  477. me = router_get_my_routerinfo();
  478. if (!trusted_dir_servers)
  479. return NULL;
  480. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  481. {
  482. if (!d->is_running) continue;
  483. if (need_v1_authority && !d->is_v1_authority)
  484. continue;
  485. if (requireother && me && router_digest_is_me(d->digest))
  486. continue;
  487. if (fascistfirewall) {
  488. if (!fascist_firewall_allows_address_dir(d->addr, d->dir_port))
  489. continue;
  490. }
  491. smartlist_add(sl, &d->fake_status);
  492. });
  493. rs = smartlist_choose(sl);
  494. smartlist_free(sl);
  495. return rs;
  496. }
  497. /** Go through and mark the authoritative dirservers as up. */
  498. static void
  499. mark_all_trusteddirservers_up(void)
  500. {
  501. if (routerlist) {
  502. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  503. if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
  504. router->dir_port > 0) {
  505. router->is_running = 1;
  506. });
  507. }
  508. if (trusted_dir_servers) {
  509. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  510. {
  511. local_routerstatus_t *rs;
  512. dir->is_running = 1;
  513. dir->n_networkstatus_failures = 0;
  514. rs = router_get_combined_status_by_digest(dir->digest);
  515. if (rs)
  516. rs->status.is_running = 1;
  517. });
  518. }
  519. last_networkstatus_download_attempted = 0;
  520. }
  521. /** Reset all internal variables used to count failed downloads of network
  522. * status objects. */
  523. void
  524. router_reset_status_download_failures(void)
  525. {
  526. mark_all_trusteddirservers_up();
  527. }
  528. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  529. * This is used to make sure we don't pick siblings in a single path.
  530. */
  531. void
  532. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  533. {
  534. routerinfo_t *r;
  535. config_line_t *cl;
  536. if (!router->declared_family)
  537. return;
  538. /* Add every r such that router declares familyness with r, and r
  539. * declares familyhood with router. */
  540. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  541. {
  542. if (!(r = router_get_by_nickname(n, 0)))
  543. continue;
  544. if (!r->declared_family)
  545. continue;
  546. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  547. {
  548. if (router_nickname_matches(router, n2))
  549. smartlist_add(sl, r);
  550. });
  551. });
  552. /* If the user declared any families locally, honor those too. */
  553. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  554. if (router_nickname_is_in_list(router, cl->value)) {
  555. add_nickname_list_to_smartlist(sl, cl->value, 0, 1, 1);
  556. }
  557. }
  558. }
  559. /** Given a comma-and-whitespace separated list of nicknames, see which
  560. * nicknames in <b>list</b> name routers in our routerlist that are
  561. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  562. */
  563. void
  564. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
  565. int must_be_running,
  566. int warn_if_down, int warn_if_unnamed)
  567. {
  568. routerinfo_t *router;
  569. smartlist_t *nickname_list;
  570. int have_dir_info = router_have_minimum_dir_info();
  571. if (!list)
  572. return; /* nothing to do */
  573. tor_assert(sl);
  574. nickname_list = smartlist_create();
  575. if (!warned_nicknames)
  576. warned_nicknames = smartlist_create();
  577. smartlist_split_string(nickname_list, list, ",",
  578. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  579. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  580. int warned;
  581. if (!is_legal_nickname_or_hexdigest(nick)) {
  582. log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
  583. continue;
  584. }
  585. router = router_get_by_nickname(nick, warn_if_unnamed);
  586. warned = smartlist_string_isin(warned_nicknames, nick);
  587. if (router) {
  588. if (!must_be_running || router->is_running) {
  589. smartlist_add(sl,router);
  590. if (warned)
  591. smartlist_string_remove(warned_nicknames, nick);
  592. } else {
  593. if (!warned) {
  594. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
  595. "Nickname list includes '%s' which is known but down.",nick);
  596. smartlist_add(warned_nicknames, tor_strdup(nick));
  597. }
  598. }
  599. } else if (!router_get_combined_status_by_nickname(nick,warn_if_unnamed)) {
  600. if (!warned) {
  601. log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
  602. "Nickname list includes '%s' which isn't a known router.",nick);
  603. smartlist_add(warned_nicknames, tor_strdup(nick));
  604. }
  605. }
  606. });
  607. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  608. smartlist_free(nickname_list);
  609. }
  610. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  611. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  612. */
  613. static int
  614. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  615. {
  616. smartlist_t *nickname_list;
  617. int v = 0;
  618. if (!list)
  619. return 0; /* definitely not */
  620. tor_assert(router);
  621. nickname_list = smartlist_create();
  622. smartlist_split_string(nickname_list, list, ",",
  623. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  624. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  625. if (router_nickname_matches(router, cp)) {v=1;break;});
  626. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  627. smartlist_free(nickname_list);
  628. return v;
  629. }
  630. /** Add every router from our routerlist that is currently running to
  631. * <b>sl</b>, so that we can pick a node for a circuit.
  632. */
  633. static void
  634. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
  635. int need_uptime, int need_capacity,
  636. int need_guard)
  637. {
  638. if (!routerlist)
  639. return;
  640. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  641. {
  642. if (router->is_running &&
  643. router->purpose == ROUTER_PURPOSE_GENERAL &&
  644. (router->is_valid ||
  645. /* XXX this next part is wrong and should be fixed one day -RD */
  646. (allow_invalid &&
  647. !router_is_unreliable(router, need_uptime,
  648. need_capacity, need_guard)))) {
  649. /* If it's running, and either it's valid or we're ok picking
  650. * invalid routers and this one is suitable.
  651. */
  652. smartlist_add(sl, router);
  653. }
  654. });
  655. }
  656. /** Look through the routerlist until we find a router that has my key.
  657. Return it. */
  658. routerinfo_t *
  659. routerlist_find_my_routerinfo(void)
  660. {
  661. if (!routerlist)
  662. return NULL;
  663. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  664. {
  665. if (router_is_me(router))
  666. return router;
  667. });
  668. return NULL;
  669. }
  670. /** Find a router that's up, that has this IP address, and
  671. * that allows exit to this address:port, or return NULL if there
  672. * isn't a good one.
  673. */
  674. routerinfo_t *
  675. router_find_exact_exit_enclave(const char *address, uint16_t port)
  676. {
  677. uint32_t addr;
  678. struct in_addr in;
  679. if (!tor_inet_aton(address, &in))
  680. return NULL; /* it's not an IP already */
  681. addr = ntohl(in.s_addr);
  682. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  683. {
  684. if (router->is_running &&
  685. router->addr == addr &&
  686. compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  687. ADDR_POLICY_ACCEPTED)
  688. return router;
  689. });
  690. return NULL;
  691. }
  692. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  693. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  694. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  695. * bandwidth.
  696. */
  697. int
  698. router_is_unreliable(routerinfo_t *router, int need_uptime,
  699. int need_capacity, int need_guard)
  700. {
  701. if (need_uptime && !router->is_stable)
  702. return 1;
  703. if (need_capacity && !router->is_fast)
  704. return 1;
  705. if (need_guard && !router->is_possible_guard)
  706. return 1;
  707. return 0;
  708. }
  709. /** Remove from routerlist <b>sl</b> all routers that are not
  710. * sufficiently stable. */
  711. static void
  712. routerlist_sl_remove_unreliable_routers(smartlist_t *sl, int need_uptime,
  713. int need_capacity, int need_guard)
  714. {
  715. int i;
  716. routerinfo_t *router;
  717. for (i = 0; i < smartlist_len(sl); ++i) {
  718. router = smartlist_get(sl, i);
  719. if (router_is_unreliable(router, need_uptime,
  720. need_capacity, need_guard)) {
  721. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  722. // router->nickname);
  723. smartlist_del(sl, i--);
  724. }
  725. }
  726. }
  727. /** Return the smaller of the router's configured BandwidthRate
  728. * and its advertised capacity. */
  729. uint32_t
  730. router_get_advertised_bandwidth(routerinfo_t *router)
  731. {
  732. if (router->bandwidthcapacity < router->bandwidthrate)
  733. return router->bandwidthcapacity;
  734. return router->bandwidthrate;
  735. }
  736. #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
  737. /** Choose a random element of router list <b>sl</b>, weighted by
  738. * the advertised bandwidth of each router.
  739. */
  740. routerinfo_t *
  741. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  742. {
  743. int i;
  744. routerinfo_t *router;
  745. smartlist_t *bandwidths;
  746. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  747. uint32_t *p;
  748. /* First count the total bandwidth weight, and make a smartlist
  749. * of each value. */
  750. bandwidths = smartlist_create();
  751. for (i = 0; i < smartlist_len(sl); ++i) {
  752. router = smartlist_get(sl, i);
  753. this_bw = router_get_advertised_bandwidth(router);
  754. /* if they claim something huge, don't believe it */
  755. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  756. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  757. p = tor_malloc(sizeof(uint32_t));
  758. *p = this_bw;
  759. smartlist_add(bandwidths, p);
  760. total_bw += this_bw;
  761. }
  762. if (!total_bw) {
  763. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  764. smartlist_free(bandwidths);
  765. return smartlist_choose(sl);
  766. }
  767. /* Second, choose a random value from the bandwidth weights. */
  768. rand_bw = crypto_rand_int(total_bw);
  769. /* Last, count through sl until we get to the element we picked */
  770. tmp = 0;
  771. for (i=0; ; i++) {
  772. tor_assert(i < smartlist_len(sl));
  773. p = smartlist_get(bandwidths, i);
  774. tmp += *p;
  775. if (tmp >= rand_bw)
  776. break;
  777. }
  778. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  779. smartlist_free(bandwidths);
  780. return (routerinfo_t *)smartlist_get(sl, i);
  781. }
  782. /** Return a random running router from the routerlist. If any node
  783. * named in <b>preferred</b> is available, pick one of those. Never
  784. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  785. * <b>excludedsmartlist</b>, even if they are the only nodes
  786. * available. If <b>strict</b> is true, never pick any node besides
  787. * those in <b>preferred</b>.
  788. * If <b>need_uptime</b> is non-zero and any router has more than
  789. * a minimum uptime, return one of those.
  790. * If <b>need_capacity</b> is non-zero, weight your choice by the
  791. * advertised capacity of each router.
  792. */
  793. routerinfo_t *
  794. router_choose_random_node(const char *preferred,
  795. const char *excluded,
  796. smartlist_t *excludedsmartlist,
  797. int need_uptime, int need_capacity,
  798. int need_guard,
  799. int allow_invalid, int strict)
  800. {
  801. smartlist_t *sl, *excludednodes;
  802. routerinfo_t *choice = NULL;
  803. excludednodes = smartlist_create();
  804. add_nickname_list_to_smartlist(excludednodes,excluded,0,0,1);
  805. /* Try the preferred nodes first. Ignore need_uptime and need_capacity
  806. * and need_guard, since the user explicitly asked for these nodes. */
  807. if (preferred) {
  808. sl = smartlist_create();
  809. add_nickname_list_to_smartlist(sl,preferred,1,1,1);
  810. smartlist_subtract(sl,excludednodes);
  811. if (excludedsmartlist)
  812. smartlist_subtract(sl,excludedsmartlist);
  813. choice = smartlist_choose(sl);
  814. smartlist_free(sl);
  815. }
  816. if (!choice && !strict) {
  817. /* Then give up on our preferred choices: any node
  818. * will do that has the required attributes. */
  819. sl = smartlist_create();
  820. router_add_running_routers_to_smartlist(sl, allow_invalid,
  821. need_uptime, need_capacity,
  822. need_guard);
  823. smartlist_subtract(sl,excludednodes);
  824. if (excludedsmartlist)
  825. smartlist_subtract(sl,excludedsmartlist);
  826. routerlist_sl_remove_unreliable_routers(sl, need_uptime,
  827. need_capacity, need_guard);
  828. if (need_capacity)
  829. choice = routerlist_sl_choose_by_bandwidth(sl);
  830. else
  831. choice = smartlist_choose(sl);
  832. smartlist_free(sl);
  833. if (!choice && (need_uptime || need_capacity || need_guard)) {
  834. /* try once more -- recurse but with fewer restrictions. */
  835. log_info(LD_CIRC,
  836. "We couldn't find any live%s%s%s routers; falling back "
  837. "to list of all routers.",
  838. need_capacity?", fast":"",
  839. need_uptime?", stable":"",
  840. need_guard?", guard":"");
  841. choice = router_choose_random_node(
  842. NULL, excluded, excludedsmartlist, 0, 0, 0, allow_invalid, 0);
  843. }
  844. }
  845. smartlist_free(excludednodes);
  846. if (!choice)
  847. log_warn(LD_CIRC,
  848. "No available nodes when trying to choose node. Failing.");
  849. return choice;
  850. }
  851. /** Return true iff the digest of <b>router</b>'s identity key,
  852. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  853. * optionally prefixed with a single dollar sign). Return false if
  854. * <b>hexdigest</b> is malformed, or it doesn't match. */
  855. static INLINE int
  856. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  857. {
  858. char digest[DIGEST_LEN];
  859. tor_assert(hexdigest);
  860. if (hexdigest[0] == '$')
  861. ++hexdigest;
  862. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  863. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  864. return 0;
  865. return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
  866. }
  867. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  868. * (case-insensitive), or if <b>router's</b> identity key digest
  869. * matches a hexadecimal value stored in <b>nickname</b>. Return
  870. * false otherwise. */
  871. static int
  872. router_nickname_matches(routerinfo_t *router, const char *nickname)
  873. {
  874. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  875. return 1;
  876. return router_hex_digest_matches(router, nickname);
  877. }
  878. /** Return the router in our routerlist whose (case-insensitive)
  879. * nickname or (case-sensitive) hexadecimal key digest is
  880. * <b>nickname</b>. Return NULL if no such router is known.
  881. */
  882. routerinfo_t *
  883. router_get_by_nickname(const char *nickname, int warn_if_unnamed)
  884. {
  885. int maybedigest;
  886. char digest[DIGEST_LEN];
  887. routerinfo_t *best_match=NULL;
  888. int n_matches = 0;
  889. tor_assert(nickname);
  890. if (!routerlist)
  891. return NULL;
  892. if (nickname[0] == '$')
  893. return router_get_by_hexdigest(nickname);
  894. if (server_mode(get_options()) &&
  895. !strcasecmp(nickname, get_options()->Nickname))
  896. return router_get_my_routerinfo();
  897. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  898. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  899. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  900. {
  901. if (!strcasecmp(router->nickname, nickname)) {
  902. if (router->is_named)
  903. return router;
  904. else {
  905. ++n_matches;
  906. if (n_matches <= 1 || router->is_running)
  907. best_match = router;
  908. }
  909. } else if (maybedigest &&
  910. !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
  911. ) {
  912. return router;
  913. }
  914. });
  915. if (best_match) {
  916. if (warn_if_unnamed && n_matches > 1) {
  917. smartlist_t *fps = smartlist_create();
  918. int any_unwarned = 0;
  919. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  920. {
  921. local_routerstatus_t *rs;
  922. char *desc;
  923. size_t dlen;
  924. char fp[HEX_DIGEST_LEN+1];
  925. if (strcasecmp(router->nickname, nickname))
  926. continue;
  927. rs = router_get_combined_status_by_digest(
  928. router->cache_info.identity_digest);
  929. if (rs && !rs->name_lookup_warned) {
  930. rs->name_lookup_warned = 1;
  931. any_unwarned = 1;
  932. }
  933. base16_encode(fp, sizeof(fp),
  934. router->cache_info.identity_digest, DIGEST_LEN);
  935. dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
  936. desc = tor_malloc(dlen);
  937. tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
  938. fp, router->address, router->or_port);
  939. smartlist_add(fps, desc);
  940. });
  941. if (any_unwarned) {
  942. char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
  943. log_warn(LD_CONFIG,
  944. "There are multiple matches for the nickname \"%s\","
  945. " but none is listed as named by the directory authorities. "
  946. "Choosing one arbitrarily. If you meant one in particular, "
  947. "you should say %s.", nickname, alternatives);
  948. tor_free(alternatives);
  949. }
  950. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  951. smartlist_free(fps);
  952. } else if (warn_if_unnamed) {
  953. local_routerstatus_t *rs = router_get_combined_status_by_digest(
  954. best_match->cache_info.identity_digest);
  955. if (rs && !rs->name_lookup_warned) {
  956. char fp[HEX_DIGEST_LEN+1];
  957. base16_encode(fp, sizeof(fp),
  958. best_match->cache_info.identity_digest, DIGEST_LEN);
  959. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
  960. "directory authorities do not have a binding for this nickname. "
  961. "To make sure you get the same server in the future, refer to "
  962. "it by key, as \"$%s\".", nickname, fp);
  963. rs->name_lookup_warned = 1;
  964. }
  965. }
  966. return best_match;
  967. }
  968. return NULL;
  969. }
  970. /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
  971. * return 1. If we do, ask tor_version_as_new_as() for the answer.
  972. */
  973. int
  974. router_digest_version_as_new_as(const char *digest, const char *cutoff)
  975. {
  976. routerinfo_t *router = router_get_by_digest(digest);
  977. if (!router)
  978. return 1;
  979. return tor_version_as_new_as(router->platform, cutoff);
  980. }
  981. /** Return true iff <b>digest</b> is the digest of the identity key of
  982. * a trusted directory. */
  983. int
  984. router_digest_is_trusted_dir(const char *digest)
  985. {
  986. if (!trusted_dir_servers)
  987. return 0;
  988. if (get_options()->AuthoritativeDir &&
  989. router_digest_is_me(digest))
  990. return 1;
  991. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  992. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  993. return 0;
  994. }
  995. /** Return the router in our routerlist whose hexadecimal key digest
  996. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  997. routerinfo_t *
  998. router_get_by_hexdigest(const char *hexdigest)
  999. {
  1000. char digest[DIGEST_LEN];
  1001. tor_assert(hexdigest);
  1002. if (!routerlist)
  1003. return NULL;
  1004. if (hexdigest[0]=='$')
  1005. ++hexdigest;
  1006. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  1007. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  1008. return NULL;
  1009. return router_get_by_digest(digest);
  1010. }
  1011. /** Return the router in our routerlist whose 20-byte key digest
  1012. * is <b>digest</b>. Return NULL if no such router is known. */
  1013. routerinfo_t *
  1014. router_get_by_digest(const char *digest)
  1015. {
  1016. tor_assert(digest);
  1017. if (!routerlist) return NULL;
  1018. // routerlist_assert_ok(routerlist);
  1019. return digestmap_get(routerlist->identity_map, digest);
  1020. }
  1021. /** Return the router in our routerlist whose 20-byte descriptor
  1022. * is <b>digest</b>. Return NULL if no such router is known. */
  1023. signed_descriptor_t *
  1024. router_get_by_descriptor_digest(const char *digest)
  1025. {
  1026. tor_assert(digest);
  1027. if (!routerlist) return NULL;
  1028. return digestmap_get(routerlist->desc_digest_map, digest);
  1029. }
  1030. /* DOCDOC Not always nul-terminated. */
  1031. const char *
  1032. signed_descriptor_get_body(signed_descriptor_t *desc)
  1033. {
  1034. const char *r;
  1035. size_t len = desc->signed_descriptor_len;
  1036. tor_assert(len > 32);
  1037. if (desc->saved_location == SAVED_IN_CACHE && routerlist &&
  1038. routerlist->mmap_descriptors) {
  1039. tor_assert(desc->saved_offset + len <= routerlist->mmap_descriptors_len);
  1040. r = routerlist->mmap_descriptors + desc->saved_offset;
  1041. } else {
  1042. r = desc->signed_descriptor_body;
  1043. }
  1044. tor_assert(r);
  1045. tor_assert(!memcmp("router ", r, 7));
  1046. #if 0
  1047. tor_assert(!memcmp("\n-----END SIGNATURE-----\n",
  1048. r + len - 25, 25));
  1049. #endif
  1050. return r;
  1051. }
  1052. /** Return the current list of all known routers. */
  1053. routerlist_t *
  1054. router_get_routerlist(void)
  1055. {
  1056. if (!routerlist) {
  1057. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  1058. routerlist->routers = smartlist_create();
  1059. routerlist->old_routers = smartlist_create();
  1060. routerlist->identity_map = digestmap_new();
  1061. routerlist->desc_digest_map = digestmap_new();
  1062. }
  1063. return routerlist;
  1064. }
  1065. /** Free all storage held by <b>router</b>. */
  1066. void
  1067. routerinfo_free(routerinfo_t *router)
  1068. {
  1069. if (!router)
  1070. return;
  1071. tor_free(router->cache_info.signed_descriptor_body);
  1072. tor_free(router->address);
  1073. tor_free(router->nickname);
  1074. tor_free(router->platform);
  1075. tor_free(router->contact_info);
  1076. if (router->onion_pkey)
  1077. crypto_free_pk_env(router->onion_pkey);
  1078. if (router->identity_pkey)
  1079. crypto_free_pk_env(router->identity_pkey);
  1080. if (router->declared_family) {
  1081. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  1082. smartlist_free(router->declared_family);
  1083. }
  1084. addr_policy_free(router->exit_policy);
  1085. tor_free(router);
  1086. }
  1087. /** Release storage held by <b>sd</b>. */
  1088. static void
  1089. signed_descriptor_free(signed_descriptor_t *sd)
  1090. {
  1091. tor_free(sd->signed_descriptor_body);
  1092. tor_free(sd);
  1093. }
  1094. /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
  1095. */
  1096. static signed_descriptor_t *
  1097. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  1098. {
  1099. signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  1100. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  1101. ri->cache_info.signed_descriptor_body = NULL;
  1102. routerinfo_free(ri);
  1103. return sd;
  1104. }
  1105. /** Free all storage held by a routerlist <b>rl</b> */
  1106. void
  1107. routerlist_free(routerlist_t *rl)
  1108. {
  1109. tor_assert(rl);
  1110. digestmap_free(rl->identity_map, NULL);
  1111. digestmap_free(rl->desc_digest_map, NULL);
  1112. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1113. routerinfo_free(r));
  1114. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  1115. signed_descriptor_free(sd));
  1116. smartlist_free(rl->routers);
  1117. smartlist_free(rl->old_routers);
  1118. tor_free(rl);
  1119. }
  1120. void
  1121. dump_routerlist_mem_usage(int severity)
  1122. {
  1123. uint64_t livedescs = 0;
  1124. uint64_t olddescs = 0;
  1125. if (!routerlist)
  1126. return;
  1127. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  1128. livedescs += r->cache_info.signed_descriptor_len);
  1129. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  1130. olddescs += sd->signed_descriptor_len);
  1131. log(severity, LD_GENERAL,
  1132. "In %d live descriptors: "U64_FORMAT" bytes. "
  1133. "In %d old descriptors: "U64_FORMAT" bytes.",
  1134. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  1135. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  1136. }
  1137. /** Return the greatest number of routerdescs we'll hold for any given router.
  1138. */
  1139. static int
  1140. max_descriptors_per_router(void)
  1141. {
  1142. int n_authorities = 0;
  1143. if (trusted_dir_servers)
  1144. n_authorities = smartlist_len(trusted_dir_servers);
  1145. return (n_authorities < 5) ? 5 : n_authorities;
  1146. }
  1147. /** Return non-zero if we have a lot of extra descriptors in our
  1148. * routerlist, and should get rid of some of them. Else return 0.
  1149. *
  1150. * We should be careful to not return true too eagerly, since we
  1151. * could churn. By using "+1" below, we make sure this function
  1152. * only returns true at most every smartlist_len(rl-\>routers)
  1153. * new descriptors.
  1154. */
  1155. static INLINE int
  1156. routerlist_is_overfull(routerlist_t *rl)
  1157. {
  1158. return smartlist_len(rl->old_routers) >
  1159. smartlist_len(rl->routers)*(max_descriptors_per_router()+1);
  1160. }
  1161. static INLINE int
  1162. _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
  1163. {
  1164. if (idx < 0 || smartlist_get(sl, idx) != ri) {
  1165. idx = -1;
  1166. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  1167. if (r == ri) {
  1168. idx = r_sl_idx;
  1169. break;
  1170. });
  1171. }
  1172. return idx;
  1173. }
  1174. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  1175. * as needed. */
  1176. static void
  1177. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  1178. {
  1179. digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  1180. digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
  1181. &(ri->cache_info));
  1182. smartlist_add(rl->routers, ri);
  1183. // routerlist_assert_ok(rl);
  1184. }
  1185. static void
  1186. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  1187. {
  1188. if (get_options()->DirPort &&
  1189. !digestmap_get(rl->desc_digest_map,
  1190. ri->cache_info.signed_descriptor_digest)) {
  1191. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  1192. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1193. smartlist_add(rl->old_routers, sd);
  1194. } else {
  1195. routerinfo_free(ri);
  1196. }
  1197. // routerlist_assert_ok(rl);
  1198. }
  1199. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  1200. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  1201. * idx) == ri, we don't need to do a linear search over the list to decide
  1202. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  1203. * the list, if any exists. <b>ri</b> is freed. */
  1204. void
  1205. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
  1206. {
  1207. routerinfo_t *ri_tmp;
  1208. idx = _routerlist_find_elt(rl->routers, ri, idx);
  1209. if (idx < 0)
  1210. return;
  1211. smartlist_del(rl->routers, idx);
  1212. ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
  1213. tor_assert(ri_tmp == ri);
  1214. if (make_old && get_options()->DirPort) {
  1215. signed_descriptor_t *sd;
  1216. sd = signed_descriptor_from_routerinfo(ri);
  1217. smartlist_add(rl->old_routers, sd);
  1218. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1219. } else {
  1220. ri_tmp = digestmap_remove(rl->desc_digest_map,
  1221. ri->cache_info.signed_descriptor_digest);
  1222. tor_assert(ri_tmp == ri);
  1223. router_bytes_dropped += ri->cache_info.signed_descriptor_len;
  1224. routerinfo_free(ri);
  1225. }
  1226. // routerlist_assert_ok(rl);
  1227. }
  1228. static void
  1229. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  1230. {
  1231. signed_descriptor_t *sd_tmp;
  1232. idx = _routerlist_find_elt(rl->old_routers, sd, idx);
  1233. if (idx < 0)
  1234. return;
  1235. smartlist_del(rl->old_routers, idx);
  1236. sd_tmp = digestmap_remove(rl->desc_digest_map,
  1237. sd->signed_descriptor_digest);
  1238. tor_assert(sd_tmp == sd);
  1239. router_bytes_dropped += sd->signed_descriptor_len;
  1240. signed_descriptor_free(sd);
  1241. // routerlist_assert_ok(rl);
  1242. }
  1243. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  1244. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  1245. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  1246. * search over the list to decide which to remove. We put ri_new in the same
  1247. * index as ri_old, if possible. ri is freed as appropriate. */
  1248. static void
  1249. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  1250. routerinfo_t *ri_new, int idx, int make_old)
  1251. {
  1252. tor_assert(ri_old != ri_new);
  1253. idx = _routerlist_find_elt(rl->routers, ri_old, idx);
  1254. if (idx >= 0) {
  1255. smartlist_set(rl->routers, idx, ri_new);
  1256. } else {
  1257. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  1258. routerlist_insert(rl, ri_new);
  1259. return;
  1260. }
  1261. if (memcmp(ri_old->cache_info.identity_digest,
  1262. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  1263. /* digests don't match; digestmap_set won't replace */
  1264. digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  1265. }
  1266. digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
  1267. digestmap_set(rl->desc_digest_map,
  1268. ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
  1269. if (make_old && get_options()->DirPort) {
  1270. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  1271. smartlist_add(rl->old_routers, sd);
  1272. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1273. } else {
  1274. if (memcmp(ri_old->cache_info.signed_descriptor_digest,
  1275. ri_new->cache_info.signed_descriptor_digest,
  1276. DIGEST_LEN)) {
  1277. /* digests don't match; digestmap_set didn't replace */
  1278. digestmap_remove(rl->desc_digest_map,
  1279. ri_old->cache_info.signed_descriptor_digest);
  1280. }
  1281. routerinfo_free(ri_old);
  1282. }
  1283. // routerlist_assert_ok(rl);
  1284. }
  1285. /** Free all memory held by the routerlist module. */
  1286. void
  1287. routerlist_free_all(void)
  1288. {
  1289. if (routerlist)
  1290. routerlist_free(routerlist);
  1291. routerlist = NULL;
  1292. if (warned_nicknames) {
  1293. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1294. smartlist_free(warned_nicknames);
  1295. warned_nicknames = NULL;
  1296. }
  1297. if (warned_conflicts) {
  1298. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1299. smartlist_free(warned_conflicts);
  1300. warned_conflicts = NULL;
  1301. }
  1302. if (trusted_dir_servers) {
  1303. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1304. trusted_dir_server_free(ds));
  1305. smartlist_free(trusted_dir_servers);
  1306. trusted_dir_servers = NULL;
  1307. }
  1308. if (networkstatus_list) {
  1309. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1310. networkstatus_free(ns));
  1311. smartlist_free(networkstatus_list);
  1312. networkstatus_list = NULL;
  1313. }
  1314. if (routerstatus_list) {
  1315. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1316. local_routerstatus_free(rs));
  1317. smartlist_free(routerstatus_list);
  1318. routerstatus_list = NULL;
  1319. }
  1320. }
  1321. /** Free all storage held by the routerstatus object <b>rs</b>. */
  1322. void
  1323. routerstatus_free(routerstatus_t *rs)
  1324. {
  1325. tor_free(rs);
  1326. }
  1327. /** Free all storage held by the local_routerstatus object <b>rs</b>. */
  1328. static void
  1329. local_routerstatus_free(local_routerstatus_t *rs)
  1330. {
  1331. tor_free(rs);
  1332. }
  1333. /** Free all storage held by the networkstatus object <b>ns</b>. */
  1334. void
  1335. networkstatus_free(networkstatus_t *ns)
  1336. {
  1337. tor_free(ns->source_address);
  1338. tor_free(ns->contact);
  1339. if (ns->signing_key)
  1340. crypto_free_pk_env(ns->signing_key);
  1341. tor_free(ns->client_versions);
  1342. tor_free(ns->server_versions);
  1343. if (ns->entries) {
  1344. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1345. routerstatus_free(rs));
  1346. smartlist_free(ns->entries);
  1347. }
  1348. tor_free(ns);
  1349. }
  1350. /** Forget that we have issued any router-related warnings, so that we'll
  1351. * warn again if we see the same errors. */
  1352. void
  1353. routerlist_reset_warnings(void)
  1354. {
  1355. if (!warned_nicknames)
  1356. warned_nicknames = smartlist_create();
  1357. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1358. smartlist_clear(warned_nicknames); /* now the list is empty. */
  1359. if (!warned_conflicts)
  1360. warned_conflicts = smartlist_create();
  1361. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1362. smartlist_clear(warned_conflicts); /* now the list is empty. */
  1363. if (!routerstatus_list)
  1364. routerstatus_list = smartlist_create();
  1365. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1366. rs->name_lookup_warned = 0);
  1367. have_warned_about_invalid_status = 0;
  1368. have_warned_about_old_version = 0;
  1369. have_warned_about_new_version = 0;
  1370. }
  1371. /** Mark the router with ID <b>digest</b> as running or non-running
  1372. * in our routerlist. */
  1373. void
  1374. router_set_status(const char *digest, int up)
  1375. {
  1376. routerinfo_t *router;
  1377. local_routerstatus_t *status;
  1378. tor_assert(digest);
  1379. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  1380. if (!memcmp(d->digest, digest, DIGEST_LEN))
  1381. d->is_running = up);
  1382. router = router_get_by_digest(digest);
  1383. if (router) {
  1384. log_debug(LD_DIR,"Marking router '%s' as %s.",
  1385. router->nickname, up ? "up" : "down");
  1386. if (!up && router_is_me(router) && !we_are_hibernating())
  1387. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  1388. "addresses reachable?");
  1389. router->is_running = up;
  1390. }
  1391. status = router_get_combined_status_by_digest(digest);
  1392. if (status) {
  1393. status->status.is_running = up;
  1394. }
  1395. }
  1396. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  1397. * older entries (if any) with the same key. Note: Callers should not hold
  1398. * their pointers to <b>router</b> if this function fails; <b>router</b>
  1399. * will either be inserted into the routerlist or freed.
  1400. *
  1401. * Returns >= 0 if the router was added; less than 0 if it was not.
  1402. *
  1403. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  1404. * describing the reason for not liking the routerinfo.
  1405. *
  1406. * If the return value is less than -1, there was a problem with the
  1407. * routerinfo. If the return value is equal to -1, then the routerinfo was
  1408. * fine, but out-of-date. If the return value is equal to 1, the
  1409. * routerinfo was accepted, but we should notify the generator of the
  1410. * descriptor using the message *<b>msg</b>.
  1411. *
  1412. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  1413. * <b>from_fetch</b>, we received it in response to a request we made.
  1414. * (If both are false, that means it was uploaded to us as an auth dir
  1415. * server or via the controller.)
  1416. *
  1417. * This function should be called *after*
  1418. * routers_update_status_from_networkstatus; subsequently, you should call
  1419. * router_rebuild_store and control_event_descriptors_changed.
  1420. */
  1421. int
  1422. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  1423. int from_cache, int from_fetch)
  1424. {
  1425. int i;
  1426. const char *id_digest;
  1427. int authdir = get_options()->AuthoritativeDir;
  1428. int authdir_believes_valid = 0;
  1429. tor_assert(msg);
  1430. if (!routerlist)
  1431. router_get_routerlist();
  1432. if (!networkstatus_list)
  1433. networkstatus_list = smartlist_create();
  1434. id_digest = router->cache_info.identity_digest;
  1435. /* Make sure that we haven't already got this exact descriptor. */
  1436. if (digestmap_get(routerlist->desc_digest_map,
  1437. router->cache_info.signed_descriptor_digest)) {
  1438. log_info(LD_DIR,
  1439. "Dropping descriptor that we already have for router '%s'",
  1440. router->nickname);
  1441. *msg = "Router descriptor was not new.";
  1442. routerinfo_free(router);
  1443. return -1;
  1444. }
  1445. if (routerlist_is_overfull(routerlist))
  1446. routerlist_remove_old_routers();
  1447. if (authdir) {
  1448. if (authdir_wants_to_reject_router(router, msg,
  1449. !from_cache && !from_fetch)) {
  1450. tor_assert(*msg);
  1451. routerinfo_free(router);
  1452. return -2;
  1453. }
  1454. authdir_believes_valid = router->is_valid;
  1455. } else if (from_fetch) {
  1456. /* Only check the descriptor digest against the network statuses when
  1457. * we are receiving in response to a fetch. */
  1458. if (!signed_desc_digest_is_recognized(&router->cache_info)) {
  1459. log_warn(LD_DIR, "Dropping unrecognized descriptor for router '%s'",
  1460. router->nickname);
  1461. *msg = "Router descriptor is not referenced by any network-status.";
  1462. routerinfo_free(router);
  1463. return -1;
  1464. }
  1465. }
  1466. /* We no longer need a router with this descriptor digest. */
  1467. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1468. {
  1469. routerstatus_t *rs =
  1470. networkstatus_find_entry(ns, router->cache_info.identity_digest);
  1471. if (rs && !memcmp(rs->descriptor_digest,
  1472. router->cache_info.signed_descriptor_digest,
  1473. DIGEST_LEN))
  1474. rs->need_to_mirror = 0;
  1475. });
  1476. /* If we have a router with this name, and the identity key is the same,
  1477. * choose the newer one. If the identity key has changed, and one of the
  1478. * routers is named, drop the unnamed ones. (If more than one are named,
  1479. * drop the old ones.)
  1480. */
  1481. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1482. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  1483. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  1484. if (router->cache_info.published_on <=
  1485. old_router->cache_info.published_on) {
  1486. /* Same key, but old */
  1487. log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
  1488. router->nickname);
  1489. /* Only journal this desc if we'll be serving it. */
  1490. if (!from_cache && get_options()->DirPort)
  1491. router_append_to_journal(&router->cache_info);
  1492. routerlist_insert_old(routerlist, router);
  1493. *msg = "Router descriptor was not new.";
  1494. return -1;
  1495. } else {
  1496. /* Same key, new. */
  1497. int unreachable = 0;
  1498. log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
  1499. router->nickname, old_router->nickname,
  1500. hex_str(id_digest,DIGEST_LEN));
  1501. if (router->addr == old_router->addr &&
  1502. router->or_port == old_router->or_port) {
  1503. /* these carry over when the address and orport are unchanged.*/
  1504. router->last_reachable = old_router->last_reachable;
  1505. router->testing_since = old_router->testing_since;
  1506. router->num_unreachable_notifications =
  1507. old_router->num_unreachable_notifications;
  1508. }
  1509. if (authdir && !from_cache && !from_fetch &&
  1510. router_have_minimum_dir_info() &&
  1511. dirserv_thinks_router_is_blatantly_unreachable(router,
  1512. time(NULL))) {
  1513. if (router->num_unreachable_notifications >= 3) {
  1514. unreachable = 1;
  1515. log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
  1516. "(ContactInfo '%s', platform '%s').",
  1517. router->nickname,
  1518. router->contact_info ? router->contact_info : "",
  1519. router->platform ? router->platform : "");
  1520. } else {
  1521. log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
  1522. "descriptors were thought to be unreachable.",
  1523. router->nickname, router->num_unreachable_notifications);
  1524. router->num_unreachable_notifications++;
  1525. }
  1526. }
  1527. routerlist_replace(routerlist, old_router, router, i, 1);
  1528. if (!from_cache) {
  1529. router_append_to_journal(&router->cache_info);
  1530. }
  1531. directory_set_dirty();
  1532. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1533. authdir_believes_valid ? "Valid server updated" :
  1534. ("Invalid server updated. (This dirserver is marking your "
  1535. "server as unapproved.)");
  1536. return unreachable ? 1 : 0;
  1537. }
  1538. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1539. /* nicknames match, keys don't. */
  1540. if (router->is_named) {
  1541. /* The new named router replaces the old one; remove the
  1542. * old one. And carry on to the end of the list, in case
  1543. * there are more old unnamed routers with this nickname.
  1544. */
  1545. /* mark-for-close connections using the old key, so we can
  1546. * make new ones with the new key.
  1547. */
  1548. connection_t *conn;
  1549. while ((conn = connection_or_get_by_identity_digest(
  1550. old_router->cache_info.identity_digest))) {
  1551. log_info(LD_DIR,"Closing conn to router '%s'; there is now a named "
  1552. "router with that name.",
  1553. old_router->nickname);
  1554. connection_mark_for_close(conn);
  1555. }
  1556. routerlist_remove(routerlist, old_router, i--, 0);
  1557. } else if (old_router->is_named) {
  1558. /* Can't replace a named router with an unnamed one. */
  1559. log_debug(LD_DIR, "Skipping unnamed entry for named router '%s'",
  1560. router->nickname);
  1561. routerinfo_free(router);
  1562. *msg =
  1563. "Already have named router with same nickname and different key.";
  1564. return -2;
  1565. }
  1566. }
  1567. }
  1568. /* We haven't seen a router with this name before. Add it to the end of
  1569. * the list. */
  1570. routerlist_insert(routerlist, router);
  1571. if (!from_cache)
  1572. router_append_to_journal(&router->cache_info);
  1573. directory_set_dirty();
  1574. return 0;
  1575. }
  1576. static int
  1577. _compare_old_routers_by_identity(const void **_a, const void **_b)
  1578. {
  1579. int i;
  1580. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  1581. if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  1582. return i;
  1583. return r1->published_on - r2->published_on;
  1584. }
  1585. struct duration_idx_t {
  1586. int duration;
  1587. int idx;
  1588. int old;
  1589. };
  1590. static int
  1591. _compare_duration_idx(const void *_d1, const void *_d2)
  1592. {
  1593. const struct duration_idx_t *d1 = _d1;
  1594. const struct duration_idx_t *d2 = _d2;
  1595. return d1->duration - d2->duration;
  1596. }
  1597. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  1598. * must contain routerinfo_t with the same identity and with publication time
  1599. * in ascending order. Remove members from this range until there are no more
  1600. * than max_descriptors_per_router() remaining. Start by removing the oldest
  1601. * members from before <b>cutoff</b>, then remove members which were current
  1602. * for the lowest amount of time. The order of members of old_routers at
  1603. * indices <b>lo</b> or higher may be changed.
  1604. */
  1605. static void
  1606. routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
  1607. digestmap_t *retain)
  1608. {
  1609. int i, n = hi-lo+1, n_extra;
  1610. int n_rmv = 0;
  1611. struct duration_idx_t *lifespans;
  1612. uint8_t *rmv, *must_keep;
  1613. smartlist_t *lst = routerlist->old_routers;
  1614. #if 1
  1615. const char *ident;
  1616. tor_assert(hi < smartlist_len(lst));
  1617. tor_assert(lo <= hi);
  1618. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  1619. for (i = lo+1; i <= hi; ++i) {
  1620. signed_descriptor_t *r = smartlist_get(lst, i);
  1621. tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
  1622. }
  1623. #endif
  1624. /* Check whether we need to do anything at all. */
  1625. n_extra = n - max_descriptors_per_router();
  1626. if (n_extra <= 0)
  1627. return;
  1628. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  1629. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  1630. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  1631. /* Set lifespans to contain the lifespan and index of each server. */
  1632. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  1633. for (i = lo; i <= hi; ++i) {
  1634. signed_descriptor_t *r = smartlist_get(lst, i);
  1635. signed_descriptor_t *r_next;
  1636. lifespans[i-lo].idx = i;
  1637. if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
  1638. must_keep[i-lo] = 1;
  1639. }
  1640. if (i < hi) {
  1641. r_next = smartlist_get(lst, i+1);
  1642. tor_assert(r->published_on <= r_next->published_on);
  1643. lifespans[i-lo].duration = (r_next->published_on - r->published_on);
  1644. } else {
  1645. r_next = NULL;
  1646. lifespans[i-lo].duration = INT_MAX;
  1647. }
  1648. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  1649. ++n_rmv;
  1650. lifespans[i-lo].old = 1;
  1651. rmv[i-lo] = 1;
  1652. }
  1653. }
  1654. if (n_rmv < n_extra) {
  1655. /**
  1656. * We aren't removing enough servers for being old. Sort lifespans by
  1657. * the duration of liveness, and remove the ones we're not already going to
  1658. * remove based on how long they were alive.
  1659. **/
  1660. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  1661. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  1662. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  1663. rmv[lifespans[i].idx-lo] = 1;
  1664. ++n_rmv;
  1665. }
  1666. }
  1667. }
  1668. for (i = hi; i >= lo; --i) {
  1669. if (rmv[i-lo])
  1670. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  1671. }
  1672. tor_free(must_keep);
  1673. tor_free(rmv);
  1674. tor_free(lifespans);
  1675. }
  1676. /** Deactivate any routers from the routerlist that are more than
  1677. * ROUTER_MAX_AGE seconds old; remove old routers from the list of
  1678. * cached routers if we have too many.
  1679. */
  1680. void
  1681. routerlist_remove_old_routers(void)
  1682. {
  1683. int i, hi=-1;
  1684. const char *cur_id = NULL;
  1685. time_t now = time(NULL);
  1686. time_t cutoff;
  1687. routerinfo_t *router;
  1688. signed_descriptor_t *sd;
  1689. digestmap_t *retain;
  1690. or_options_t *options = get_options();
  1691. if (!routerlist || !networkstatus_list)
  1692. return;
  1693. retain = digestmap_new();
  1694. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1695. if (options->DirPort) {
  1696. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1697. {
  1698. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1699. if (rs->published_on >= cutoff)
  1700. digestmap_set(retain, rs->descriptor_digest, (void*)1));
  1701. });
  1702. }
  1703. cutoff = now - ROUTER_MAX_AGE;
  1704. /* Remove too-old members of routerlist->routers. */
  1705. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1706. router = smartlist_get(routerlist->routers, i);
  1707. if (router->cache_info.published_on <= cutoff &&
  1708. !digestmap_get(retain, router->cache_info.signed_descriptor_digest)) {
  1709. /* Too old. Remove it. */
  1710. log_info(LD_DIR,
  1711. "Forgetting obsolete (too old) routerinfo for router '%s'",
  1712. router->nickname);
  1713. routerlist_remove(routerlist, router, i--, 1);
  1714. }
  1715. }
  1716. /* Remove far-too-old members of routerlist->old_routers. */
  1717. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1718. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  1719. sd = smartlist_get(routerlist->old_routers, i);
  1720. if (sd->published_on <= cutoff &&
  1721. !digestmap_get(retain, sd->signed_descriptor_digest)) {
  1722. /* Too old. Remove it. */
  1723. routerlist_remove_old(routerlist, sd, i--);
  1724. }
  1725. }
  1726. /* Now we're looking at routerlist->old_routers for extraneous
  1727. * members. (We'd keep all the members if we could, but we'd like to save
  1728. * space.) First, check whether we have too many router descriptors, total.
  1729. * We're okay with having too many for some given router, so long as the
  1730. * total number doesn't approach max_descriptors_per_router()*len(router).
  1731. */
  1732. if (smartlist_len(routerlist->old_routers) <
  1733. smartlist_len(routerlist->routers) * (max_descriptors_per_router() - 1))
  1734. goto done;
  1735. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  1736. /* Iterate through the list from back to front, so when we remove descriptors
  1737. * we don't mess up groups we haven't gotten to. */
  1738. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  1739. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  1740. if (!cur_id) {
  1741. cur_id = r->identity_digest;
  1742. hi = i;
  1743. }
  1744. if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
  1745. routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
  1746. cur_id = r->identity_digest;
  1747. hi = i;
  1748. }
  1749. }
  1750. if (hi>=0)
  1751. routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
  1752. routerlist_assert_ok(routerlist);
  1753. done:
  1754. digestmap_free(retain, NULL);
  1755. }
  1756. /**
  1757. * Code to parse a single router descriptor and insert it into the
  1758. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1759. * descriptor was well-formed but could not be added; and 1 if the
  1760. * descriptor was added.
  1761. *
  1762. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1763. * *<b>msg</b> a static string describing the reason for refusing the
  1764. * descriptor.
  1765. *
  1766. * This is used only by the controller.
  1767. */
  1768. int
  1769. router_load_single_router(const char *s, uint8_t purpose, const char **msg)
  1770. {
  1771. routerinfo_t *ri;
  1772. int r;
  1773. smartlist_t *lst;
  1774. tor_assert(msg);
  1775. *msg = NULL;
  1776. if (!(ri = router_parse_entry_from_string(s, NULL, 1))) {
  1777. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  1778. *msg = "Couldn't parse router descriptor.";
  1779. return -1;
  1780. }
  1781. ri->purpose = purpose;
  1782. if (router_is_me(ri)) {
  1783. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  1784. *msg = "Router's identity key matches mine.";
  1785. routerinfo_free(ri);
  1786. return 0;
  1787. }
  1788. lst = smartlist_create();
  1789. smartlist_add(lst, ri);
  1790. routers_update_status_from_networkstatus(lst, 0);
  1791. if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
  1792. /* we've already assigned to *msg now, and ri is already freed */
  1793. tor_assert(*msg);
  1794. if (r < -1)
  1795. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  1796. smartlist_free(lst);
  1797. return 0;
  1798. } else {
  1799. control_event_descriptors_changed(lst);
  1800. smartlist_free(lst);
  1801. log_debug(LD_DIR, "Added router to list");
  1802. return 1;
  1803. }
  1804. }
  1805. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1806. * routers into our directory. If <b>from_cache</b> is false, the routers
  1807. * are in response to a query to the network: cache them.
  1808. *
  1809. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1810. * uppercased identity fingerprints. Do not update any router whose
  1811. * fingerprint is not on the list; after updating a router, remove its
  1812. * fingerprint from the list.
  1813. * DOCDOC saved_location
  1814. */
  1815. void
  1816. router_load_routers_from_string(const char *s, saved_location_t saved_location,
  1817. smartlist_t *requested_fingerprints)
  1818. {
  1819. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1820. char fp[HEX_DIGEST_LEN+1];
  1821. const char *msg;
  1822. int from_cache = (saved_location != SAVED_NOWHERE);
  1823. router_parse_list_from_string(&s, routers, saved_location);
  1824. routers_update_status_from_networkstatus(routers, !from_cache);
  1825. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  1826. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1827. {
  1828. base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
  1829. DIGEST_LEN);
  1830. if (requested_fingerprints) {
  1831. if (smartlist_string_isin(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. if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
  1846. smartlist_add(changed, ri);
  1847. });
  1848. if (smartlist_len(changed))
  1849. control_event_descriptors_changed(changed);
  1850. routerlist_assert_ok(routerlist);
  1851. router_rebuild_store(0);
  1852. smartlist_free(routers);
  1853. smartlist_free(changed);
  1854. }
  1855. /** Helper: return a newly allocated string containing the name of the filename
  1856. * where we plan to cache <b>ns</b>. */
  1857. static char *
  1858. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1859. {
  1860. const char *datadir = get_options()->DataDirectory;
  1861. size_t len = strlen(datadir)+64;
  1862. char fp[HEX_DIGEST_LEN+1];
  1863. char *fn = tor_malloc(len+1);
  1864. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1865. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1866. return fn;
  1867. }
  1868. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1869. * publication date. */
  1870. static int
  1871. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1872. {
  1873. const networkstatus_t *a = *_a, *b = *_b;
  1874. if (a->published_on < b->published_on)
  1875. return -1;
  1876. else if (a->published_on > b->published_on)
  1877. return 1;
  1878. else
  1879. return 0;
  1880. }
  1881. /** Add the parsed neworkstatus in <b>ns</b> (with original document in
  1882. * <b>s</b> to the disk cache (and the in-memory directory server cache) as
  1883. * appropriate. */
  1884. static int
  1885. add_networkstatus_to_cache(const char *s,
  1886. networkstatus_source_t source,
  1887. networkstatus_t *ns)
  1888. {
  1889. if (source != NS_FROM_CACHE) {
  1890. char *fn = networkstatus_get_cache_filename(ns);
  1891. if (write_str_to_file(fn, s, 0)<0) {
  1892. log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
  1893. }
  1894. tor_free(fn);
  1895. }
  1896. if (get_options()->DirPort)
  1897. dirserv_set_cached_networkstatus_v2(s,
  1898. ns->identity_digest,
  1899. ns->published_on);
  1900. return 0;
  1901. }
  1902. /** How far in the future do we allow a network-status to get before removing
  1903. * it? (seconds) */
  1904. #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
  1905. /** Given a string <b>s</b> containing a network status that we received at
  1906. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1907. * store it, and put it into our cache as necessary.
  1908. *
  1909. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1910. * own networkstatus_t (if we're a directory server).
  1911. *
  1912. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1913. * cache.
  1914. *
  1915. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1916. * uppercased identity fingerprints. Do not update any networkstatus whose
  1917. * fingerprint is not on the list; after updating a networkstatus, remove its
  1918. * fingerprint from the list.
  1919. *
  1920. * Return 0 on success, -1 on failure.
  1921. *
  1922. * Callers should make sure that routers_update_all_from_networkstatus() is
  1923. * invoked after this function succeeds.
  1924. */
  1925. int
  1926. router_set_networkstatus(const char *s, time_t arrived_at,
  1927. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1928. {
  1929. networkstatus_t *ns;
  1930. int i, found;
  1931. time_t now;
  1932. int skewed = 0;
  1933. trusted_dir_server_t *trusted_dir = NULL;
  1934. const char *source_desc = NULL;
  1935. char fp[HEX_DIGEST_LEN+1];
  1936. char published[ISO_TIME_LEN+1];
  1937. ns = networkstatus_parse_from_string(s);
  1938. if (!ns) {
  1939. log_warn(LD_DIR, "Couldn't parse network status.");
  1940. return -1;
  1941. }
  1942. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1943. if (!(trusted_dir =
  1944. router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  1945. log_info(LD_DIR, "Network status was signed, but not by an authoritative "
  1946. "directory we recognize.");
  1947. if (!get_options()->DirPort) {
  1948. networkstatus_free(ns);
  1949. return 0;
  1950. }
  1951. source_desc = fp;
  1952. } else {
  1953. source_desc = trusted_dir->description;
  1954. }
  1955. now = time(NULL);
  1956. if (arrived_at > now)
  1957. arrived_at = now;
  1958. ns->received_on = arrived_at;
  1959. format_iso_time(published, ns->published_on);
  1960. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1961. log_warn(LD_GENERAL, "Network status from %s was published in the future "
  1962. "(%s GMT). Somebody is skewed here: check your clock. "
  1963. "Not caching.",
  1964. source_desc, published);
  1965. skewed = 1;
  1966. }
  1967. if (!networkstatus_list)
  1968. networkstatus_list = smartlist_create();
  1969. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1970. /* Don't replace our own networkstatus when we get it from somebody else.*/
  1971. networkstatus_free(ns);
  1972. return 0;
  1973. }
  1974. if (requested_fingerprints) {
  1975. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1976. smartlist_string_remove(requested_fingerprints, fp);
  1977. } else {
  1978. char *requested =
  1979. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1980. log_warn(LD_DIR,
  1981. "We received a network status with a fingerprint (%s) that we "
  1982. "never requested. (We asked for: %s.) Dropping.",
  1983. fp, requested);
  1984. tor_free(requested);
  1985. return 0;
  1986. }
  1987. }
  1988. if (!trusted_dir) {
  1989. if (!skewed && get_options()->DirPort) {
  1990. /* We got a non-trusted networkstatus, and we're a directory cache.
  1991. * This means that we asked an authority, and it told us about another
  1992. * authority we didn't recognize. */
  1993. add_networkstatus_to_cache(s, source, ns);
  1994. networkstatus_free(ns);
  1995. }
  1996. return 0;
  1997. }
  1998. if (source != NS_FROM_CACHE && trusted_dir)
  1999. trusted_dir->n_networkstatus_failures = 0;
  2000. found = 0;
  2001. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  2002. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  2003. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  2004. if (!memcmp(old_ns->networkstatus_digest,
  2005. ns->networkstatus_digest, DIGEST_LEN)) {
  2006. /* Same one we had before. */
  2007. networkstatus_free(ns);
  2008. log_info(LD_DIR,
  2009. "Not replacing network-status from %s (published %s); "
  2010. "we already have it.",
  2011. trusted_dir->description, published);
  2012. if (old_ns->received_on < arrived_at) {
  2013. if (source != NS_FROM_CACHE) {
  2014. char *fn = networkstatus_get_cache_filename(old_ns);
  2015. /* We use mtime to tell when it arrived, so update that. */
  2016. touch_file(fn);
  2017. tor_free(fn);
  2018. }
  2019. old_ns->received_on = arrived_at;
  2020. }
  2021. return 0;
  2022. } else if (old_ns->published_on >= ns->published_on) {
  2023. char old_published[ISO_TIME_LEN+1];
  2024. format_iso_time(old_published, old_ns->published_on);
  2025. log_info(LD_DIR,
  2026. "Not replacing network-status from %s (published %s);"
  2027. " we have a newer one (published %s) for this authority.",
  2028. trusted_dir->description, published,
  2029. old_published);
  2030. networkstatus_free(ns);
  2031. return 0;
  2032. } else {
  2033. networkstatus_free(old_ns);
  2034. smartlist_set(networkstatus_list, i, ns);
  2035. found = 1;
  2036. break;
  2037. }
  2038. }
  2039. }
  2040. if (!found)
  2041. smartlist_add(networkstatus_list, ns);
  2042. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  2043. {
  2044. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  2045. rs->need_to_mirror = 1;
  2046. });
  2047. log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
  2048. source == NS_FROM_CACHE?"cached from":
  2049. (source==NS_FROM_DIR?"downloaded from":"generated for"),
  2050. trusted_dir->description, published);
  2051. networkstatus_list_has_changed = 1;
  2052. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  2053. if (!skewed)
  2054. add_networkstatus_to_cache(s, source, ns);
  2055. networkstatus_list_update_recent(now);
  2056. return 0;
  2057. }
  2058. /** How old do we allow a network-status to get before removing it
  2059. * completely? */
  2060. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  2061. /** Remove all very-old network_status_t objects from memory and from the
  2062. * disk cache. */
  2063. void
  2064. networkstatus_list_clean(time_t now)
  2065. {
  2066. int i;
  2067. if (!networkstatus_list)
  2068. return;
  2069. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  2070. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2071. char *fname = NULL;;
  2072. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  2073. continue;
  2074. /* Okay, this one is too old. Remove it from the list, and delete it
  2075. * from the cache. */
  2076. smartlist_del(networkstatus_list, i--);
  2077. fname = networkstatus_get_cache_filename(ns);
  2078. if (file_status(fname) == FN_FILE) {
  2079. log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
  2080. unlink(fname);
  2081. }
  2082. tor_free(fname);
  2083. if (get_options()->DirPort) {
  2084. dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
  2085. }
  2086. networkstatus_free(ns);
  2087. }
  2088. }
  2089. /** Helper for bsearching a list of routerstatus_t pointers.*/
  2090. static int
  2091. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  2092. {
  2093. const char *key = _key;
  2094. const routerstatus_t *rs = *_member;
  2095. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  2096. }
  2097. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  2098. * NULL if none was found. */
  2099. static routerstatus_t *
  2100. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  2101. {
  2102. return smartlist_bsearch(ns->entries, digest,
  2103. _compare_digest_to_routerstatus_entry);
  2104. }
  2105. /** Return the consensus view of the status of the router whose digest is
  2106. * <b>digest</b>, or NULL if we don't know about any such router. */
  2107. local_routerstatus_t *
  2108. router_get_combined_status_by_digest(const char *digest)
  2109. {
  2110. if (!routerstatus_list)
  2111. return NULL;
  2112. return smartlist_bsearch(routerstatus_list, digest,
  2113. _compare_digest_to_routerstatus_entry);
  2114. }
  2115. static local_routerstatus_t *
  2116. router_get_combined_status_by_nickname(const char *nickname,
  2117. int warn_if_unnamed)
  2118. {
  2119. char digest[DIGEST_LEN];
  2120. local_routerstatus_t *best=NULL;
  2121. smartlist_t *matches=NULL;
  2122. if (!routerstatus_list || !nickname)
  2123. return NULL;
  2124. if (nickname[0] == '$') {
  2125. if (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))<0)
  2126. return NULL;
  2127. return router_get_combined_status_by_digest(digest);
  2128. } else if (strlen(nickname) == HEX_DIGEST_LEN &&
  2129. (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))==0)) {
  2130. return router_get_combined_status_by_digest(digest);
  2131. }
  2132. matches = smartlist_create();
  2133. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
  2134. {
  2135. if (!strcasecmp(lrs->status.nickname, nickname)) {
  2136. if (lrs->status.is_named) {
  2137. smartlist_free(matches);
  2138. return lrs;
  2139. } else {
  2140. smartlist_add(matches, lrs);
  2141. best = lrs;
  2142. }
  2143. }
  2144. });
  2145. if (smartlist_len(matches)>1 && warn_if_unnamed) {
  2146. int any_unwarned=0;
  2147. SMARTLIST_FOREACH(matches, local_routerstatus_t *, lrs,
  2148. {
  2149. if (! lrs->name_lookup_warned) {
  2150. lrs->name_lookup_warned=1;
  2151. any_unwarned=1;
  2152. }
  2153. });
  2154. if (any_unwarned) {
  2155. log_warn(LD_CONFIG,"There are multiple matches for the nickname \"%s\",",
  2156. " but none is listed as named by the directory authorites. "
  2157. "Choosing one arbitrarily.");
  2158. }
  2159. } else if (warn_if_unnamed && best && !best->name_lookup_warned) {
  2160. char fp[HEX_DIGEST_LEN+1];
  2161. base16_encode(fp, sizeof(fp),
  2162. best->status.identity_digest, DIGEST_LEN);
  2163. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
  2164. "directory authorities do not have a binding for this nickname. "
  2165. "To make sure you get the same server in the future, refer to "
  2166. "it by key, as \"$%s\".", nickname, fp);
  2167. best->name_lookup_warned = 1;
  2168. }
  2169. smartlist_free(matches);
  2170. return best;
  2171. }
  2172. /** Return true iff any networkstatus includes a descriptor whose digest
  2173. * is that of <b>desc</b>. */
  2174. static int
  2175. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  2176. {
  2177. routerstatus_t *rs;
  2178. if (!networkstatus_list)
  2179. return 0;
  2180. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2181. {
  2182. if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
  2183. continue;
  2184. if (!memcmp(rs->descriptor_digest,
  2185. desc->signed_descriptor_digest, DIGEST_LEN))
  2186. return 1;
  2187. });
  2188. return 0;
  2189. }
  2190. /** How frequently do directory authorities re-download fresh networkstatus
  2191. * documents? */
  2192. #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
  2193. /** How frequently do non-authority directory caches re-download fresh
  2194. * networkstatus documents? */
  2195. #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
  2196. /** We are a directory server, and so cache network_status documents.
  2197. * Initiate downloads as needed to update them. For authorities, this means
  2198. * asking each trusted directory for its network-status. For caches, this
  2199. * means asking a random authority for all network-statuses.
  2200. */
  2201. static void
  2202. update_networkstatus_cache_downloads(time_t now)
  2203. {
  2204. int authority = authdir_mode(get_options());
  2205. int interval =
  2206. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  2207. if (last_networkstatus_download_attempted + interval >= now)
  2208. return;
  2209. if (!trusted_dir_servers)
  2210. return;
  2211. last_networkstatus_download_attempted = now;
  2212. if (authority) {
  2213. /* An authority launches a separate connection for everybody. */
  2214. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2215. {
  2216. char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
  2217. if (router_digest_is_me(ds->digest))
  2218. continue;
  2219. if (connection_get_by_type_addr_port_purpose(
  2220. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  2221. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  2222. /* We are already fetching this one. */
  2223. continue;
  2224. }
  2225. strlcpy(resource, "fp/", sizeof(resource));
  2226. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  2227. strlcat(resource, ".z", sizeof(resource));
  2228. directory_initiate_command_routerstatus(
  2229. &ds->fake_status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
  2230. 0, /* Not private */
  2231. resource,
  2232. NULL, 0 /* No payload. */);
  2233. });
  2234. } else {
  2235. /* A non-authority cache launches one connection to a random authority. */
  2236. /* (Check whether we're currently fetching network-status objects.) */
  2237. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  2238. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2239. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  2240. }
  2241. }
  2242. /** How long (in seconds) does a client wait after getting a network status
  2243. * before downloading the next in sequence? */
  2244. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  2245. /* How many times do we allow a networkstatus download to fail before we
  2246. * assume that the authority isn't publishing? */
  2247. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  2248. /** We are not a directory cache or authority. Update our network-status list
  2249. * by launching a new directory fetch for enough network-status documents "as
  2250. * necessary". See function comments for implementation details.
  2251. */
  2252. static void
  2253. update_networkstatus_client_downloads(time_t now)
  2254. {
  2255. int n_live = 0, n_dirservers, n_running_dirservers, needed = 0;
  2256. int fetch_latest = 0;
  2257. int most_recent_idx = -1;
  2258. trusted_dir_server_t *most_recent = NULL;
  2259. time_t most_recent_received = 0;
  2260. char *resource, *cp;
  2261. size_t resource_len;
  2262. smartlist_t *missing;
  2263. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  2264. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2265. return;
  2266. /* This is a little tricky. We want to download enough network-status
  2267. * objects so that we have all of them under
  2268. * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
  2269. * *one* if the most recent one's publication time is under
  2270. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  2271. */
  2272. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  2273. return;
  2274. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  2275. missing = smartlist_create();
  2276. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2277. {
  2278. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  2279. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2280. --n_running_dirservers;
  2281. continue;
  2282. }
  2283. if (ns && ns->published_on > now-NETWORKSTATUS_MAX_AGE)
  2284. ++n_live;
  2285. else
  2286. smartlist_add(missing, ds->digest);
  2287. if (ns && (!most_recent || ns->received_on > most_recent_received)) {
  2288. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  2289. most_recent = ds;
  2290. most_recent_received = ns->received_on;
  2291. }
  2292. });
  2293. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  2294. if (!smartlist_len(missing) &&
  2295. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL) {
  2296. log_info(LD_DIR, "Our most recent network-status document (from %s) "
  2297. "is %d seconds old; downloading another.",
  2298. most_recent?most_recent->description:"nobody",
  2299. (int)(now-most_recent_received));
  2300. fetch_latest = 1;
  2301. needed = 1;
  2302. } else if (smartlist_len(missing)) {
  2303. log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
  2304. " network-status documents. Downloading %d.",
  2305. n_running_dirservers, n_dirservers, n_live,
  2306. smartlist_len(missing));
  2307. needed = smartlist_len(missing);
  2308. } else {
  2309. smartlist_free(missing);
  2310. return;
  2311. }
  2312. /* If no networkstatus was found, choose a dirserver at random as "most
  2313. * recent". */
  2314. if (most_recent_idx<0)
  2315. most_recent_idx = crypto_rand_int(n_dirservers);
  2316. if (fetch_latest) {
  2317. int i;
  2318. int n_failed = 0;
  2319. for (i = most_recent_idx + 1; 1; ++i) {
  2320. trusted_dir_server_t *ds;
  2321. if (i >= n_dirservers)
  2322. i = 0;
  2323. ds = smartlist_get(trusted_dir_servers, i);
  2324. if (n_failed < n_dirservers &&
  2325. ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2326. ++n_failed;
  2327. continue;
  2328. }
  2329. smartlist_add(missing, ds->digest);
  2330. break;
  2331. }
  2332. }
  2333. /* Build a request string for all the resources we want. */
  2334. resource_len = smartlist_len(missing) * (HEX_DIGEST_LEN+1) + 6;
  2335. resource = tor_malloc(resource_len);
  2336. memcpy(resource, "fp/", 3);
  2337. cp = resource+3;
  2338. smartlist_sort_digests(missing);
  2339. needed = smartlist_len(missing);
  2340. SMARTLIST_FOREACH(missing, const char *, d,
  2341. {
  2342. base16_encode(cp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  2343. cp += HEX_DIGEST_LEN;
  2344. --needed;
  2345. if (needed)
  2346. *cp++ = '+';
  2347. });
  2348. memcpy(cp, ".z", 3);
  2349. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  2350. tor_free(resource);
  2351. smartlist_free(missing);
  2352. }
  2353. /** Launch requests for networkstatus documents as appropriate. */
  2354. void
  2355. update_networkstatus_downloads(time_t now)
  2356. {
  2357. or_options_t *options = get_options();
  2358. if (options->DirPort)
  2359. update_networkstatus_cache_downloads(now);
  2360. else
  2361. update_networkstatus_client_downloads(now);
  2362. }
  2363. /** Return 1 if all running sufficiently-stable routers will reject
  2364. * addr:port, return 0 if any might accept it. */
  2365. int
  2366. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  2367. int need_uptime)
  2368. {
  2369. addr_policy_result_t r;
  2370. if (!routerlist) return 1;
  2371. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  2372. {
  2373. if (router->is_running &&
  2374. !router_is_unreliable(router, need_uptime, 0, 0)) {
  2375. r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
  2376. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2377. return 0; /* this one could be ok. good enough. */
  2378. }
  2379. });
  2380. return 1; /* all will reject. */
  2381. }
  2382. /** Return true iff <b>router</b> does not permit exit streams.
  2383. */
  2384. int
  2385. router_exit_policy_rejects_all(routerinfo_t *router)
  2386. {
  2387. return compare_addr_to_addr_policy(0, 0, router->exit_policy)
  2388. == ADDR_POLICY_REJECTED;
  2389. }
  2390. /** Add to the list of authorized directory servers one at
  2391. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  2392. * <b>address</b> is NULL, add ourself. */
  2393. void
  2394. add_trusted_dir_server(const char *nickname, const char *address,
  2395. uint16_t port, const char *digest, int is_v1_authority)
  2396. {
  2397. trusted_dir_server_t *ent;
  2398. uint32_t a;
  2399. char *hostname = NULL;
  2400. size_t dlen;
  2401. if (!trusted_dir_servers)
  2402. trusted_dir_servers = smartlist_create();
  2403. if (!address) { /* The address is us; we should guess. */
  2404. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  2405. log_warn(LD_CONFIG,
  2406. "Couldn't find a suitable address when adding ourself as a "
  2407. "trusted directory server.");
  2408. return;
  2409. }
  2410. } else {
  2411. if (tor_lookup_hostname(address, &a)) {
  2412. log_warn(LD_CONFIG,
  2413. "Unable to lookup address for directory server at '%s'",
  2414. address);
  2415. return;
  2416. }
  2417. hostname = tor_strdup(address);
  2418. a = ntohl(a);
  2419. }
  2420. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  2421. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  2422. ent->address = hostname;
  2423. ent->addr = a;
  2424. ent->dir_port = port;
  2425. ent->is_running = 1;
  2426. ent->is_v1_authority = is_v1_authority;
  2427. memcpy(ent->digest, digest, DIGEST_LEN);
  2428. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  2429. ent->description = tor_malloc(dlen);
  2430. if (nickname)
  2431. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  2432. nickname, hostname, (int)port);
  2433. else
  2434. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  2435. hostname, (int)port);
  2436. ent->fake_status.addr = ent->addr;
  2437. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  2438. if (nickname)
  2439. strlcpy(ent->fake_status.nickname, nickname,
  2440. sizeof(ent->fake_status.nickname));
  2441. else
  2442. ent->fake_status.nickname[0] = '\0';
  2443. ent->fake_status.dir_port = ent->dir_port;
  2444. smartlist_add(trusted_dir_servers, ent);
  2445. }
  2446. /** Free storage held in <b>ds</b> */
  2447. void
  2448. trusted_dir_server_free(trusted_dir_server_t *ds)
  2449. {
  2450. tor_free(ds->nickname);
  2451. tor_free(ds->description);
  2452. tor_free(ds->address);
  2453. tor_free(ds);
  2454. }
  2455. /** Remove all members from the list of trusted dir servers. */
  2456. void
  2457. clear_trusted_dir_servers(void)
  2458. {
  2459. if (trusted_dir_servers) {
  2460. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2461. trusted_dir_server_free(ent));
  2462. smartlist_clear(trusted_dir_servers);
  2463. } else {
  2464. trusted_dir_servers = smartlist_create();
  2465. }
  2466. }
  2467. /** Return 1 if any trusted dir server supports v1 directories,
  2468. * else return 0. */
  2469. int
  2470. any_trusted_dir_is_v1_authority(void)
  2471. {
  2472. if (trusted_dir_servers)
  2473. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2474. if (ent->is_v1_authority) return 1);
  2475. return 0;
  2476. }
  2477. /** Return the network status with a given identity digest. */
  2478. networkstatus_t *
  2479. networkstatus_get_by_digest(const char *digest)
  2480. {
  2481. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2482. {
  2483. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  2484. return ns;
  2485. });
  2486. return NULL;
  2487. }
  2488. /** We believe networkstatuses more recent than this when they tell us that
  2489. * our server is broken, invalid, obsolete, etc. */
  2490. #define SELF_OPINION_INTERVAL (90*60)
  2491. /** Return a string naming the versions of Tor recommended by
  2492. * more than half the versioning networkstatuses. */
  2493. static char *
  2494. compute_recommended_versions(time_t now, int client)
  2495. {
  2496. int n_seen;
  2497. char *current;
  2498. smartlist_t *combined, *recommended;
  2499. int n_versioning;
  2500. char *result;
  2501. (void) now; /* right now, we consider *all* ors. */
  2502. if (!networkstatus_list)
  2503. return tor_strdup("<none>");
  2504. combined = smartlist_create();
  2505. n_versioning = 0;
  2506. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2507. {
  2508. const char *vers;
  2509. smartlist_t *versions;
  2510. if (! ns->recommends_versions)
  2511. continue;
  2512. n_versioning++;
  2513. vers = client ? ns->client_versions : ns->server_versions;
  2514. if (!vers)
  2515. continue;
  2516. versions = smartlist_create();
  2517. smartlist_split_string(versions, vers, ",",
  2518. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2519. sort_version_list(versions, 1);
  2520. smartlist_add_all(combined, versions);
  2521. smartlist_free(versions);
  2522. });
  2523. sort_version_list(combined, 0);
  2524. current = NULL;
  2525. n_seen = 0;
  2526. recommended = smartlist_create();
  2527. SMARTLIST_FOREACH(combined, char *, cp,
  2528. {
  2529. if (current && !strcmp(cp, current)) {
  2530. ++n_seen;
  2531. } else {
  2532. if (n_seen >= n_versioning/2 && current)
  2533. smartlist_add(recommended, current);
  2534. n_seen = 0;
  2535. current = cp;
  2536. }
  2537. });
  2538. if (n_seen >= n_versioning/2 && current)
  2539. smartlist_add(recommended, current);
  2540. result = smartlist_join_strings(recommended, ", ", 0, NULL);
  2541. SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
  2542. smartlist_free(combined);
  2543. smartlist_free(recommended);
  2544. return result;
  2545. }
  2546. /** If the network-status list has changed since the last time we called this
  2547. * function, update the status of every routerinfo from the network-status
  2548. * list.
  2549. */
  2550. void
  2551. routers_update_all_from_networkstatus(void)
  2552. {
  2553. routerinfo_t *me;
  2554. time_t now;
  2555. if (!routerlist || !networkstatus_list ||
  2556. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  2557. return;
  2558. now = time(NULL);
  2559. if (networkstatus_list_has_changed)
  2560. routerstatus_list_update_from_networkstatus(now);
  2561. routers_update_status_from_networkstatus(routerlist->routers, 0);
  2562. me = router_get_my_routerinfo();
  2563. if (me && !have_warned_about_invalid_status &&
  2564. have_tried_downloading_all_statuses(4)) {
  2565. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0, n_naming = 0;
  2566. routerstatus_t *rs;
  2567. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2568. {
  2569. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  2570. continue;
  2571. ++n_recent;
  2572. if (ns->binds_names)
  2573. ++n_naming;
  2574. if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
  2575. continue;
  2576. ++n_listing;
  2577. if (rs->is_valid)
  2578. ++n_valid;
  2579. if (rs->is_named)
  2580. ++n_named;
  2581. });
  2582. if (n_listing) {
  2583. if (n_valid <= n_listing/2) {
  2584. log_info(LD_GENERAL,
  2585. "%d/%d recent statements from directory authorities list us "
  2586. "as unapproved. Are you misconfigured?",
  2587. n_listing-n_valid, n_listing);
  2588. have_warned_about_invalid_status = 1;
  2589. } else if (n_naming && !n_named) {
  2590. log_info(LD_GENERAL, "0/%d name-binding directory authorities "
  2591. "recognize your nickname. Please consider sending your "
  2592. "nickname and identity fingerprint to the tor-ops.",
  2593. n_naming);
  2594. have_warned_about_invalid_status = 1;
  2595. }
  2596. }
  2597. }
  2598. entry_guards_set_status_from_directory();
  2599. if (!have_warned_about_old_version &&
  2600. have_tried_downloading_all_statuses(4)) {
  2601. int n_versioning = 0;
  2602. int n_recommended = 0;
  2603. int is_server = server_mode(get_options());
  2604. version_status_t consensus = VS_RECOMMENDED;
  2605. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2606. {
  2607. version_status_t vs;
  2608. if (!ns->recommends_versions)
  2609. continue;
  2610. vs = tor_version_is_obsolete(
  2611. VERSION, is_server ? ns->server_versions : ns->client_versions);
  2612. if (vs == VS_RECOMMENDED)
  2613. ++n_recommended;
  2614. if (n_versioning++ == 0) {
  2615. consensus = vs;
  2616. } else if (consensus != vs) {
  2617. consensus = version_status_join(consensus, vs);
  2618. }
  2619. });
  2620. if (n_versioning && n_recommended <= n_versioning/2) {
  2621. if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
  2622. if (!have_warned_about_new_version) {
  2623. char *rec = compute_recommended_versions(now, !is_server);
  2624. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  2625. "recommended version%s, according to %d/%d network "
  2626. "statuses. Versions recommended by more than %d "
  2627. "authorit%s are: %s",
  2628. VERSION,
  2629. consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  2630. n_versioning-n_recommended, n_versioning, n_versioning/2,
  2631. n_versioning/2 > 1 ? "ies" : "y", rec);
  2632. have_warned_about_new_version = 1;
  2633. tor_free(rec);
  2634. }
  2635. } else {
  2636. char *rec = compute_recommended_versions(now, !is_server);
  2637. log_warn(LD_GENERAL, "Please upgrade! "
  2638. "This version of Tor (%s) is %s, according to "
  2639. "%d/%d network statuses. Versions recommended by "
  2640. "at least %d authorit%s are: %s",
  2641. VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
  2642. n_versioning-n_recommended, n_versioning, n_versioning/2,
  2643. n_versioning/2 > 1 ? "ies" : "y", rec);
  2644. have_warned_about_old_version = 1;
  2645. tor_free(rec);
  2646. }
  2647. } else {
  2648. log_info(LD_GENERAL, "%d/%d statements from "
  2649. "directory authorities say my version is ok.",
  2650. n_recommended, n_versioning);
  2651. }
  2652. }
  2653. routerstatus_list_has_changed = 0;
  2654. }
  2655. /** Allow any network-status newer than this to influence our view of who's
  2656. * running. */
  2657. #define DEFAULT_RUNNING_INTERVAL (60*60)
  2658. /** If possible, always allow at least this many network-statuses to influence
  2659. * our view of who's running. */
  2660. #define MIN_TO_INFLUENCE_RUNNING 3
  2661. /** Change the is_recent field of each member of networkstatus_list so that
  2662. * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
  2663. * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
  2664. * others are recent. Set networkstatus_list_has_changed if anything happened.
  2665. */
  2666. void
  2667. networkstatus_list_update_recent(time_t now)
  2668. {
  2669. int n_statuses, n_recent, changed, i;
  2670. char published[ISO_TIME_LEN+1];
  2671. if (!networkstatus_list)
  2672. return;
  2673. n_statuses = smartlist_len(networkstatus_list);
  2674. n_recent = 0;
  2675. changed = 0;
  2676. for (i=n_statuses-1; i >= 0; --i) {
  2677. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2678. trusted_dir_server_t *ds =
  2679. router_get_trusteddirserver_by_digest(ns->identity_digest);
  2680. const char *src = ds?ds->description:ns->source_address;
  2681. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  2682. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  2683. if (!ns->is_recent) {
  2684. format_iso_time(published, ns->published_on);
  2685. log_info(LD_DIR,
  2686. "Networkstatus from %s (published %s) is now \"recent\"",
  2687. src, published);
  2688. changed = 1;
  2689. }
  2690. ns->is_recent = 1;
  2691. ++n_recent;
  2692. } else {
  2693. if (ns->is_recent) {
  2694. format_iso_time(published, ns->published_on);
  2695. log_info(LD_DIR,
  2696. "Networkstatus from %s (published %s) is "
  2697. "no longer \"recent\"",
  2698. src, published);
  2699. changed = 1;
  2700. ns->is_recent = 0;
  2701. }
  2702. }
  2703. }
  2704. if (changed)
  2705. networkstatus_list_has_changed = 1;
  2706. }
  2707. /** Helper for routerstatus_list_update_from_networkstatus: remember how many
  2708. * authorities recommend a given descriptor digest. */
  2709. typedef struct {
  2710. routerstatus_t *rs;
  2711. int count;
  2712. } desc_digest_count_t;
  2713. /** Update our view of router status (as stored in routerstatus_list) from the
  2714. * current set of network status documents (as stored in networkstatus_list).
  2715. * Do nothing unless the network status list has changed since the last time
  2716. * this function was called.
  2717. */
  2718. static void
  2719. routerstatus_list_update_from_networkstatus(time_t now)
  2720. {
  2721. or_options_t *options = get_options();
  2722. int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
  2723. int i, j, warned;
  2724. int *index, *size;
  2725. networkstatus_t **networkstatus;
  2726. smartlist_t *result;
  2727. strmap_t *name_map;
  2728. char conflict[DIGEST_LEN]; /* Sentinel value */
  2729. desc_digest_count_t *digest_counts = NULL;
  2730. /* compute which network statuses will have a vote now */
  2731. networkstatus_list_update_recent(now);
  2732. if (!networkstatus_list_has_changed)
  2733. return;
  2734. if (!networkstatus_list)
  2735. networkstatus_list = smartlist_create();
  2736. if (!routerstatus_list)
  2737. routerstatus_list = smartlist_create();
  2738. if (!trusted_dir_servers)
  2739. trusted_dir_servers = smartlist_create();
  2740. if (!warned_conflicts)
  2741. warned_conflicts = smartlist_create();
  2742. n_trusted = smartlist_len(trusted_dir_servers);
  2743. n_statuses = smartlist_len(networkstatus_list);
  2744. if (n_statuses <= n_trusted/2) {
  2745. /* Not enough statuses to adjust status. */
  2746. log_info(LD_DIR,
  2747. "Not enough statuses to update router status list. (%d/%d)",
  2748. n_statuses, n_trusted);
  2749. return;
  2750. }
  2751. log_info(LD_DIR, "Rebuilding router status list.");
  2752. index = tor_malloc(sizeof(int)*n_statuses);
  2753. size = tor_malloc(sizeof(int)*n_statuses);
  2754. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  2755. for (i = 0; i < n_statuses; ++i) {
  2756. index[i] = 0;
  2757. networkstatus[i] = smartlist_get(networkstatus_list, i);
  2758. size[i] = smartlist_len(networkstatus[i]->entries);
  2759. if (networkstatus[i]->binds_names)
  2760. ++n_naming;
  2761. if (networkstatus[i]->is_recent)
  2762. ++n_recent;
  2763. }
  2764. /** Iterate over all entries in all networkstatuses, and build
  2765. * name_map as a map from lc nickname to identity digest. If there
  2766. * is a conflict on that nickname, map the lc nickname to conflict.
  2767. */
  2768. name_map = strmap_new();
  2769. memset(conflict, 0xff, sizeof(conflict));
  2770. for (i = 0; i < n_statuses; ++i) {
  2771. if (!networkstatus[i]->binds_names)
  2772. continue;
  2773. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  2774. {
  2775. const char *other_digest;
  2776. if (!rs->is_named)
  2777. continue;
  2778. other_digest = strmap_get_lc(name_map, rs->nickname);
  2779. warned = smartlist_string_isin(warned_conflicts, rs->nickname);
  2780. if (!other_digest) {
  2781. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  2782. if (warned)
  2783. smartlist_string_remove(warned_conflicts, rs->nickname);
  2784. } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  2785. other_digest != conflict) {
  2786. if (!warned) {
  2787. int should_warn = options->DirPort && options->AuthoritativeDir;
  2788. char fp1[HEX_DIGEST_LEN+1];
  2789. char fp2[HEX_DIGEST_LEN+1];
  2790. base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
  2791. base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
  2792. log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
  2793. "Naming authorities disagree about which key goes with %s. "
  2794. "($%s vs $%s)",
  2795. rs->nickname, fp1, fp2);
  2796. strmap_set_lc(name_map, rs->nickname, conflict);
  2797. smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
  2798. }
  2799. } else {
  2800. if (warned)
  2801. smartlist_string_remove(warned_conflicts, rs->nickname);
  2802. }
  2803. });
  2804. }
  2805. result = smartlist_create();
  2806. digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
  2807. /* Iterate through all of the sorted routerstatus lists in lockstep.
  2808. * Invariants:
  2809. * - For 0 <= i < n_statuses: index[i] is an index into
  2810. * networkstatus[i]->entries, which has size[i] elements.
  2811. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  2812. * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
  2813. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  2814. *
  2815. * (That is, the indices are always advanced past lower digest before
  2816. * higher.)
  2817. */
  2818. while (1) {
  2819. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  2820. int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0;
  2821. int n_desc_digests=0, highest_count=0;
  2822. const char *the_name = NULL;
  2823. local_routerstatus_t *rs_out, *rs_old;
  2824. routerstatus_t *rs, *most_recent;
  2825. networkstatus_t *ns;
  2826. const char *lowest = NULL;
  2827. /* Find out which of the digests appears first. */
  2828. for (i = 0; i < n_statuses; ++i) {
  2829. if (index[i] < size[i]) {
  2830. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  2831. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  2832. lowest = rs->identity_digest;
  2833. }
  2834. }
  2835. if (!lowest) {
  2836. /* We're out of routers. Great! */
  2837. break;
  2838. }
  2839. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  2840. * match "lowest" are next in order. Iterate over them, incrementing those
  2841. * index[i] as we go. */
  2842. for (i = 0; i < n_statuses; ++i) {
  2843. if (index[i] >= size[i])
  2844. continue;
  2845. ns = networkstatus[i];
  2846. rs = smartlist_get(ns->entries, index[i]);
  2847. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  2848. continue;
  2849. /* At this point, we know that we're looking at a routersatus with
  2850. * identity "lowest".
  2851. */
  2852. ++index[i];
  2853. ++n_listing;
  2854. /* Should we name this router? Only if all the names from naming
  2855. * authorities match. */
  2856. if (rs->is_named && ns->binds_names) {
  2857. if (!the_name)
  2858. the_name = rs->nickname;
  2859. if (!strcasecmp(rs->nickname, the_name)) {
  2860. ++n_named;
  2861. } else if (strcmp(the_name,"**mismatch**")) {
  2862. char hd[HEX_DIGEST_LEN+1];
  2863. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  2864. if (! smartlist_string_isin(warned_conflicts, hd)) {
  2865. log_warn(LD_DIR,
  2866. "Naming authorities disagree about nicknames for $%s "
  2867. "(\"%s\" vs \"%s\")",
  2868. hd, the_name, rs->nickname);
  2869. smartlist_add(warned_conflicts, tor_strdup(hd));
  2870. }
  2871. the_name = "**mismatch**";
  2872. }
  2873. }
  2874. /* Keep a running count of how often which descriptor digests
  2875. * appear. */
  2876. for (j = 0; j < n_desc_digests; ++j) {
  2877. if (!memcmp(rs->descriptor_digest,
  2878. digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
  2879. if (++digest_counts[j].count > highest_count)
  2880. highest_count = digest_counts[j].count;
  2881. goto found;
  2882. }
  2883. }
  2884. digest_counts[n_desc_digests].rs = rs;
  2885. digest_counts[n_desc_digests].count = 1;
  2886. if (!highest_count)
  2887. highest_count = 1;
  2888. ++n_desc_digests;
  2889. found:
  2890. /* Now tally up the easily-tallied flags. */
  2891. if (rs->is_valid)
  2892. ++n_valid;
  2893. if (rs->is_running && ns->is_recent)
  2894. ++n_running;
  2895. if (rs->is_exit)
  2896. ++n_exit;
  2897. if (rs->is_fast)
  2898. ++n_fast;
  2899. if (rs->is_possible_guard)
  2900. ++n_guard;
  2901. if (rs->is_stable)
  2902. ++n_stable;
  2903. if (rs->is_v2_dir)
  2904. ++n_v2_dir;
  2905. }
  2906. /* Go over the descriptor digests and figure out which descriptor we
  2907. * want. */
  2908. most_recent = NULL;
  2909. for (i = 0; i < n_desc_digests; ++i) {
  2910. /* If any digest appears twice or more, ignore those that don't.*/
  2911. if (highest_count >= 2 && digest_counts[i].count < 2)
  2912. continue;
  2913. if (!most_recent ||
  2914. digest_counts[i].rs->published_on > most_recent->published_on)
  2915. most_recent = digest_counts[i].rs;
  2916. }
  2917. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  2918. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  2919. /* Copy status info about this router, if we had any before. */
  2920. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  2921. if (!memcmp(rs_out->status.descriptor_digest,
  2922. most_recent->descriptor_digest, DIGEST_LEN)) {
  2923. rs_out->n_download_failures = rs_old->n_download_failures;
  2924. rs_out->next_attempt_at = rs_old->next_attempt_at;
  2925. }
  2926. rs_out->name_lookup_warned = rs_old->name_lookup_warned;
  2927. }
  2928. smartlist_add(result, rs_out);
  2929. log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
  2930. "named by %d/%d, validated by %d/%d, and %d/%d recent "
  2931. "directories think it's running.",
  2932. rs_out->status.nickname,
  2933. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  2934. n_running, n_recent);
  2935. rs_out->status.is_named = 0;
  2936. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  2937. const char *d = strmap_get_lc(name_map, the_name);
  2938. if (d && d != conflict)
  2939. rs_out->status.is_named = 1;
  2940. if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
  2941. smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
  2942. }
  2943. if (rs_out->status.is_named)
  2944. strlcpy(rs_out->status.nickname, the_name,
  2945. sizeof(rs_out->status.nickname));
  2946. rs_out->status.is_valid = n_valid > n_statuses/2;
  2947. rs_out->status.is_running = n_running > n_recent/2;
  2948. rs_out->status.is_exit = n_exit > n_statuses/2;
  2949. rs_out->status.is_fast = n_fast > n_statuses/2;
  2950. rs_out->status.is_possible_guard = n_guard > n_statuses/2;
  2951. rs_out->status.is_stable = n_stable > n_statuses/2;
  2952. rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
  2953. }
  2954. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2955. local_routerstatus_free(rs));
  2956. smartlist_free(routerstatus_list);
  2957. routerstatus_list = result;
  2958. tor_free(networkstatus);
  2959. tor_free(index);
  2960. tor_free(size);
  2961. tor_free(digest_counts);
  2962. strmap_free(name_map, NULL);
  2963. networkstatus_list_has_changed = 0;
  2964. routerstatus_list_has_changed = 1;
  2965. }
  2966. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  2967. * is_named, is_valid, and is_running fields according to our current
  2968. * networkstatus_t documents. */
  2969. void
  2970. routers_update_status_from_networkstatus(smartlist_t *routers,
  2971. int reset_failures)
  2972. {
  2973. trusted_dir_server_t *ds;
  2974. local_routerstatus_t *rs;
  2975. or_options_t *options = get_options();
  2976. int authdir = options->AuthoritativeDir;
  2977. int namingdir = options->AuthoritativeDir &&
  2978. options->NamingAuthoritativeDir;
  2979. if (!routerstatus_list)
  2980. return;
  2981. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  2982. {
  2983. const char *digest = router->cache_info.identity_digest;
  2984. rs = router_get_combined_status_by_digest(digest);
  2985. ds = router_get_trusteddirserver_by_digest(digest);
  2986. if (!rs)
  2987. continue;
  2988. if (!namingdir)
  2989. router->is_named = rs->status.is_named;
  2990. if (!authdir) {
  2991. /* If we're not an authdir, believe others. */
  2992. router->is_valid = rs->status.is_valid;
  2993. router->is_running = rs->status.is_running;
  2994. router->is_fast = rs->status.is_fast;
  2995. router->is_stable = rs->status.is_stable;
  2996. router->is_possible_guard = rs->status.is_possible_guard;
  2997. }
  2998. if (router->is_running && ds) {
  2999. ds->n_networkstatus_failures = 0;
  3000. }
  3001. if (reset_failures) {
  3002. rs->n_download_failures = 0;
  3003. rs->next_attempt_at = 0;
  3004. }
  3005. });
  3006. }
  3007. /** For every router descriptor we are currently downloading by descriptor
  3008. * digest, set result[d] to 1. */
  3009. static void
  3010. list_pending_descriptor_downloads(digestmap_t *result)
  3011. {
  3012. const char *prefix = "d/";
  3013. size_t p_len = strlen(prefix);
  3014. int i, n_conns;
  3015. connection_t **carray;
  3016. smartlist_t *tmp = smartlist_create();
  3017. tor_assert(result);
  3018. get_connection_array(&carray, &n_conns);
  3019. for (i = 0; i < n_conns; ++i) {
  3020. connection_t *conn = carray[i];
  3021. if (conn->type == CONN_TYPE_DIR &&
  3022. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  3023. !conn->marked_for_close) {
  3024. if (!strcmpstart(conn->requested_resource, prefix))
  3025. dir_split_resource_into_fingerprints(conn->requested_resource+p_len,
  3026. tmp, NULL, 1, 0);
  3027. }
  3028. }
  3029. SMARTLIST_FOREACH(tmp, char *, d,
  3030. {
  3031. digestmap_set(result, d, (void*)1);
  3032. tor_free(d);
  3033. });
  3034. smartlist_free(tmp);
  3035. }
  3036. /** Launch downloads for all the descriptors whose digests are listed
  3037. * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
  3038. * If <b>source</b> is given, download from <b>source</b>; otherwise,
  3039. * download from an appropriate random directory server.
  3040. */
  3041. static void
  3042. initiate_descriptor_downloads(routerstatus_t *source,
  3043. smartlist_t *digests,
  3044. int lo, int hi)
  3045. {
  3046. int i, n = hi-lo;
  3047. char *resource, *cp;
  3048. size_t r_len;
  3049. if (n <= 0)
  3050. return;
  3051. if (lo < 0)
  3052. lo = 0;
  3053. if (hi > smartlist_len(digests))
  3054. hi = smartlist_len(digests);
  3055. r_len = 8 + (HEX_DIGEST_LEN+1)*n;
  3056. cp = resource = tor_malloc(r_len);
  3057. memcpy(cp, "d/", 2);
  3058. cp += 2;
  3059. for (i = lo; i < hi; ++i) {
  3060. base16_encode(cp, r_len-(cp-resource),
  3061. smartlist_get(digests,i), DIGEST_LEN);
  3062. cp += HEX_DIGEST_LEN;
  3063. *cp++ = '+';
  3064. }
  3065. memcpy(cp-1, ".z", 3);
  3066. if (source) {
  3067. /* We know which authority we want. */
  3068. directory_initiate_command_routerstatus(source,
  3069. DIR_PURPOSE_FETCH_SERVERDESC,
  3070. 0, /* not private */
  3071. resource, NULL, 0);
  3072. } else {
  3073. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  3074. resource,
  3075. 1);
  3076. }
  3077. tor_free(resource);
  3078. }
  3079. /** Clients don't download any descriptor this recent, since it will probably
  3080. * not have propageted to enough caches. */
  3081. #define ESTIMATED_PROPAGATION_TIME (10*60)
  3082. /** Return 0 if this routerstatus is obsolete, too new, isn't
  3083. * running, or otherwise not a descriptor that we would make any
  3084. * use of even if we had it. Else return 1. */
  3085. static int
  3086. client_would_use_router(routerstatus_t *rs, time_t now)
  3087. {
  3088. if (rs->published_on + ROUTER_MAX_AGE < now) {
  3089. /* This one is too old to consider. */
  3090. return 0;
  3091. }
  3092. if (!rs->is_running && !get_options()->FetchUselessDescriptors) {
  3093. /* If we had this router descriptor, we wouldn't even bother using it.
  3094. * But, if we want to have a complete list, fetch it anyway. */
  3095. return 0;
  3096. }
  3097. if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
  3098. /* Most caches probably don't have this descriptor yet. */
  3099. return 0;
  3100. }
  3101. return 1;
  3102. }
  3103. /** Return new list of ID fingerprints for routers that we (as a client) would
  3104. * like to download.
  3105. */
  3106. static smartlist_t *
  3107. router_list_client_downloadable(void)
  3108. {
  3109. int n_downloadable = 0;
  3110. smartlist_t *downloadable = smartlist_create();
  3111. digestmap_t *downloading;
  3112. time_t now = time(NULL);
  3113. /* these are just used for logging */
  3114. int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_wouldnt_use = 0;
  3115. if (!routerstatus_list)
  3116. return downloadable;
  3117. downloading = digestmap_new();
  3118. list_pending_descriptor_downloads(downloading);
  3119. routerstatus_list_update_from_networkstatus(now);
  3120. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3121. {
  3122. routerinfo_t *ri;
  3123. if (!client_would_use_router(&rs->status, now)) {
  3124. /* We wouldn't want this descriptor even if we got it. */
  3125. ++n_wouldnt_use;
  3126. } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
  3127. /* We're downloading this one now. */
  3128. ++n_in_progress;
  3129. } else if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
  3130. /* We have the 'best' descriptor for this router. */
  3131. ++n_uptodate;
  3132. } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
  3133. ri->cache_info.published_on > rs->status.published_on) {
  3134. /* Oddly, we have a descriptor more recent than the 'best' one, but it
  3135. was once best. So that's okay. */
  3136. ++n_uptodate;
  3137. } else if (rs->next_attempt_at > now) {
  3138. /* We failed too recently to try again. */
  3139. ++n_not_ready;
  3140. } else {
  3141. /* Okay, time to try it. */
  3142. smartlist_add(downloadable, rs->status.descriptor_digest);
  3143. ++n_downloadable;
  3144. }
  3145. });
  3146. #if 0
  3147. log_info(LD_DIR,
  3148. "%d router descriptors are downloadable. "
  3149. "%d are in progress. %d are up-to-date. "
  3150. "%d are non-useful. %d failed too recently to retry.",
  3151. n_downloadable, n_in_progress, n_uptodate,
  3152. n_wouldnt_use, n_not_ready);
  3153. #endif
  3154. digestmap_free(downloading, NULL);
  3155. return downloadable;
  3156. }
  3157. /** Initiate new router downloads as needed, using the strategy for
  3158. * non-directory-servers.
  3159. *
  3160. * We only allow one router descriptor download at a time.
  3161. * If we have less than two network-status documents, we ask
  3162. * a directory for "all descriptors."
  3163. * Otherwise, we ask for all descriptors that we think are different
  3164. * from what we have.
  3165. */
  3166. static void
  3167. update_router_descriptor_client_downloads(time_t now)
  3168. {
  3169. /* Max amount of hashes to download per request.
  3170. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3171. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3172. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3173. * So use 96 because it's a nice number.
  3174. */
  3175. #define MAX_DL_PER_REQUEST 96
  3176. /** Don't split our requests so finely that we are requesting fewer than
  3177. * this number per server. */
  3178. #define MIN_DL_PER_REQUEST 4
  3179. /** To prevent a single screwy cache from confusing us by selective reply,
  3180. * try to split our requests into at least this this many requests. */
  3181. #define MIN_REQUESTS 3
  3182. /** If we want fewer than this many descriptors, wait until we
  3183. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3184. * passed. */
  3185. #define MAX_DL_TO_DELAY 16
  3186. /** When directory clients have only a few servers to request, they batch
  3187. * them until they have more, or until this amount of time has passed. */
  3188. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3189. smartlist_t *downloadable = NULL;
  3190. int should_delay, n_downloadable;
  3191. or_options_t *options = get_options();
  3192. if (options->DirPort) {
  3193. log_warn(LD_BUG,
  3194. "Called router_descriptor_client_downloads() on a dir mirror?");
  3195. }
  3196. if (rep_hist_circbuilding_dormant(now)) {
  3197. log_info(LD_CIRC, "Skipping descriptor downloads: we haven't needed "
  3198. "any circuits lately.");
  3199. return;
  3200. }
  3201. if (networkstatus_list && smartlist_len(networkstatus_list) <=
  3202. smartlist_len(trusted_dir_servers)/2) {
  3203. log_info(LD_DIR,
  3204. "Not enough networkstatus documents to launch requests.");
  3205. }
  3206. downloadable = router_list_client_downloadable();
  3207. n_downloadable = smartlist_len(downloadable);
  3208. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3209. log_debug(LD_DIR,
  3210. "There are enough downloadable routerdescs to launch requests.");
  3211. should_delay = 0;
  3212. } else if (n_downloadable == 0) {
  3213. // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
  3214. should_delay = 1;
  3215. } else {
  3216. should_delay = (last_routerdesc_download_attempted +
  3217. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3218. if (!should_delay) {
  3219. if (last_routerdesc_download_attempted) {
  3220. log_info(LD_DIR,
  3221. "There are not many downloadable routerdescs, but we've "
  3222. "been waiting long enough (%d seconds). Downloading.",
  3223. (int)(now-last_routerdesc_download_attempted));
  3224. } else {
  3225. log_info(LD_DIR,
  3226. "There are not many downloadable routerdescs, but we haven't "
  3227. "tried downloading descriptors recently. Downloading.");
  3228. }
  3229. }
  3230. }
  3231. if (! should_delay) {
  3232. int i, n_per_request;
  3233. n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
  3234. if (n_per_request > MAX_DL_PER_REQUEST)
  3235. n_per_request = MAX_DL_PER_REQUEST;
  3236. if (n_per_request < MIN_DL_PER_REQUEST)
  3237. n_per_request = MIN_DL_PER_REQUEST;
  3238. log_info(LD_DIR,
  3239. "Launching %d request%s for %d router%s, %d at a time",
  3240. (n_downloadable+n_per_request-1)/n_per_request,
  3241. n_downloadable>n_per_request?"s":"",
  3242. n_downloadable, n_downloadable>1?"s":"", n_per_request);
  3243. smartlist_sort_digests(downloadable);
  3244. for (i=0; i < n_downloadable; i += n_per_request) {
  3245. initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
  3246. }
  3247. last_routerdesc_download_attempted = now;
  3248. }
  3249. smartlist_free(downloadable);
  3250. }
  3251. /** Launch downloads for router status as needed, using the strategy used by
  3252. * authorities and caches: download every descriptor we don't have but would
  3253. * serve from a random authoritiy that lists it. */
  3254. static void
  3255. update_router_descriptor_cache_downloads(time_t now)
  3256. {
  3257. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3258. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3259. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3260. int i, j, n;
  3261. int n_download;
  3262. or_options_t *options = get_options();
  3263. (void) now;
  3264. if (!options->DirPort) {
  3265. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
  3266. "on a non-dir-mirror?");
  3267. }
  3268. if (!networkstatus_list || !smartlist_len(networkstatus_list))
  3269. return;
  3270. map = digestmap_new();
  3271. n = smartlist_len(networkstatus_list);
  3272. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3273. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3274. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3275. * downloading. */
  3276. list_pending_descriptor_downloads(map);
  3277. /* For the digest of every descriptor that we don't have, and that we aren't
  3278. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3279. * about that descriptor, and we haven't already failed to get that
  3280. * descriptor from the corresponding authority.
  3281. */
  3282. n_download = 0;
  3283. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3284. {
  3285. smartlist_t *dl = smartlist_create();
  3286. downloadable[ns_sl_idx] = dl;
  3287. download_from[ns_sl_idx] = smartlist_create();
  3288. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  3289. {
  3290. if (!rs->need_to_mirror)
  3291. continue;
  3292. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3293. log_warn(LD_BUG,
  3294. "Bug: We have a router descriptor, but need_to_mirror=1.");
  3295. rs->need_to_mirror = 0;
  3296. continue;
  3297. }
  3298. if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
  3299. rs->need_to_mirror = 0;
  3300. continue;
  3301. }
  3302. if (digestmap_get(map, rs->descriptor_digest)) {
  3303. /* We're downloading it already. */
  3304. continue;
  3305. } else {
  3306. /* We could download it from this guy. */
  3307. smartlist_add(dl, rs->descriptor_digest);
  3308. ++n_download;
  3309. }
  3310. });
  3311. });
  3312. /* At random, assign descriptors to authorities such that:
  3313. * - if d is a member of some downloadable[x], d is a member of some
  3314. * download_from[y]. (Everything we want to download, we try to download
  3315. * from somebody.)
  3316. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3317. * (We only try to download descriptors from authorities who claim to have
  3318. * them.)
  3319. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3320. * (We don't try to download anything from two authorities concurrently.)
  3321. */
  3322. while (n_download) {
  3323. int which_ns = crypto_rand_int(n);
  3324. smartlist_t *dl = downloadable[which_ns];
  3325. int idx;
  3326. char *d;
  3327. tor_assert(dl);
  3328. if (!smartlist_len(dl))
  3329. continue;
  3330. idx = crypto_rand_int(smartlist_len(dl));
  3331. d = smartlist_get(dl, idx);
  3332. if (! digestmap_get(map, d)) {
  3333. smartlist_add(download_from[which_ns], d);
  3334. digestmap_set(map, d, (void*) 1);
  3335. }
  3336. smartlist_del(dl, idx);
  3337. --n_download;
  3338. }
  3339. /* Now, we can actually launch our requests. */
  3340. for (i=0; i<n; ++i) {
  3341. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  3342. trusted_dir_server_t *ds =
  3343. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3344. smartlist_t *dl = download_from[i];
  3345. if (!ds) {
  3346. log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
  3347. continue;
  3348. }
  3349. if (! smartlist_len(dl))
  3350. continue;
  3351. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3352. smartlist_len(dl), ds->nickname);
  3353. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3354. initiate_descriptor_downloads(&(ds->fake_status), dl, j,
  3355. j+MAX_DL_PER_REQUEST);
  3356. }
  3357. }
  3358. for (i=0; i<n; ++i) {
  3359. smartlist_free(download_from[i]);
  3360. smartlist_free(downloadable[i]);
  3361. }
  3362. tor_free(download_from);
  3363. tor_free(downloadable);
  3364. digestmap_free(map,NULL);
  3365. }
  3366. /** Launch downloads for router status as needed. */
  3367. void
  3368. update_router_descriptor_downloads(time_t now)
  3369. {
  3370. or_options_t *options = get_options();
  3371. if (options->DirPort) {
  3372. update_router_descriptor_cache_downloads(now);
  3373. } else {
  3374. update_router_descriptor_client_downloads(now);
  3375. }
  3376. }
  3377. static int
  3378. routerstatus_count_usable_entries(smartlist_t *entries)
  3379. {
  3380. int count = 0;
  3381. time_t now = time(NULL);
  3382. SMARTLIST_FOREACH(entries, routerstatus_t *, rs,
  3383. if (client_would_use_router(rs, now)) count++);
  3384. return count;
  3385. }
  3386. /** Return true iff we have enough networkstatus and router information to
  3387. * start building circuits. Right now, this means "more than half the
  3388. * networkstatus documents, and at least 1/4 of expected routers." */
  3389. //XXX should consider whether we have enough exiting nodes here.
  3390. int
  3391. router_have_minimum_dir_info(void)
  3392. {
  3393. int tot = 0, num_running = 0;
  3394. int n_ns, n_authorities, res, avg;
  3395. static int have_enough = 0;
  3396. if (!networkstatus_list || !routerlist) {
  3397. res = 0;
  3398. goto done;
  3399. }
  3400. n_authorities = smartlist_len(trusted_dir_servers);
  3401. n_ns = smartlist_len(networkstatus_list);
  3402. if (n_ns<=n_authorities/2) {
  3403. log_info(LD_DIR,
  3404. "We have %d of %d network statuses, and we want "
  3405. "more than %d.", n_ns, n_authorities, n_authorities/2);
  3406. res = 0;
  3407. goto done;
  3408. }
  3409. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3410. tot += routerstatus_count_usable_entries(ns->entries));
  3411. avg = tot / n_ns;
  3412. if (!routerstatus_list)
  3413. routerstatus_list = smartlist_create();
  3414. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3415. {
  3416. if (rs->status.is_running)
  3417. num_running++;
  3418. });
  3419. res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
  3420. done:
  3421. if (res && !have_enough) {
  3422. log(LOG_NOTICE, LD_DIR,
  3423. "We now have enough directory information to build circuits.");
  3424. }
  3425. if (!res && have_enough) {
  3426. log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
  3427. "enough to build circuits.%s",
  3428. num_running > 2 ? "" : " (Not enough servers seem reachable -- "
  3429. "is your network connection down?)");
  3430. }
  3431. have_enough = res;
  3432. return res;
  3433. }
  3434. /** Return true iff we have downloaded, or attempted to download at least
  3435. * n_failures times, a network status for each authority. */
  3436. static int
  3437. have_tried_downloading_all_statuses(int n_failures)
  3438. {
  3439. if (!trusted_dir_servers)
  3440. return 0;
  3441. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  3442. {
  3443. /* If we don't have the status, and we haven't failed to get the status,
  3444. * we haven't tried to get the status. */
  3445. if (!networkstatus_get_by_digest(ds->digest) &&
  3446. ds->n_networkstatus_failures <= n_failures)
  3447. return 0;
  3448. });
  3449. return 1;
  3450. }
  3451. /** Reset the descriptor download failure count on all routers, so that we
  3452. * can retry any long-failed routers immediately.
  3453. */
  3454. void
  3455. router_reset_descriptor_download_failures(void)
  3456. {
  3457. if (!routerstatus_list)
  3458. return;
  3459. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3460. {
  3461. rs->n_download_failures = 0;
  3462. rs->next_attempt_at = 0;
  3463. });
  3464. tor_assert(networkstatus_list);
  3465. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3466. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  3467. {
  3468. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  3469. rs->need_to_mirror = 1;
  3470. }));
  3471. last_routerdesc_download_attempted = 0;
  3472. }
  3473. /** Any changes in a router descriptor's publication time larger than this are
  3474. * automatically non-cosmetic. */
  3475. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  3476. /** We allow uptime to vary from how much it ought to be by this much. */
  3477. #define ROUTER_ALLOW_UPTIME_DRIFT (30*60)
  3478. /** Return true iff the only differences between r1 and r2 are such that
  3479. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  3480. */
  3481. int
  3482. router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
  3483. {
  3484. time_t r1pub, r2pub;
  3485. tor_assert(r1 && r2);
  3486. /* r1 should be the one that was published first. */
  3487. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  3488. routerinfo_t *ri_tmp = r2;
  3489. r2 = r1;
  3490. r1 = ri_tmp;
  3491. }
  3492. /* If any key fields differ, they're different. */
  3493. if (strcasecmp(r1->address, r2->address) ||
  3494. strcasecmp(r1->nickname, r2->nickname) ||
  3495. r1->or_port != r2->or_port ||
  3496. r1->dir_port != r2->dir_port ||
  3497. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  3498. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  3499. strcasecmp(r1->platform, r2->platform) ||
  3500. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  3501. (!r1->contact_info && r2->contact_info) ||
  3502. (r1->contact_info && r2->contact_info &&
  3503. strcasecmp(r1->contact_info, r2->contact_info)) ||
  3504. r1->is_hibernating != r2->is_hibernating ||
  3505. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  3506. return 0;
  3507. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  3508. return 0;
  3509. if (r1->declared_family && r2->declared_family) {
  3510. int i, n;
  3511. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  3512. return 0;
  3513. n = smartlist_len(r1->declared_family);
  3514. for (i=0; i < n; ++i) {
  3515. if (strcasecmp(smartlist_get(r1->declared_family, i),
  3516. smartlist_get(r2->declared_family, i)))
  3517. return 0;
  3518. }
  3519. }
  3520. /* Did bandwidth change a lot? */
  3521. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  3522. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  3523. return 0;
  3524. /* Did more than 12 hours pass? */
  3525. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  3526. < r2->cache_info.published_on)
  3527. return 0;
  3528. /* Did uptime fail to increase by approximately the amount we would think,
  3529. * give or take 30 minutes? */
  3530. r1pub = r1->cache_info.published_on;
  3531. r2pub = r2->cache_info.published_on;
  3532. if (abs(r2->uptime - (r1->uptime + (r2pub - r1pub)))
  3533. > ROUTER_ALLOW_UPTIME_DRIFT)
  3534. return 0;
  3535. /* Otherwise, the difference is cosmetic. */
  3536. return 1;
  3537. }
  3538. static void
  3539. routerlist_assert_ok(routerlist_t *rl)
  3540. {
  3541. digestmap_iter_t *iter;
  3542. routerinfo_t *r2;
  3543. signed_descriptor_t *sd2;
  3544. if (!routerlist)
  3545. return;
  3546. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  3547. {
  3548. r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
  3549. tor_assert(r == r2);
  3550. sd2 = digestmap_get(rl->desc_digest_map,
  3551. r->cache_info.signed_descriptor_digest);
  3552. tor_assert(&(r->cache_info) == sd2);
  3553. });
  3554. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  3555. {
  3556. r2 = digestmap_get(rl->identity_map, sd->identity_digest);
  3557. tor_assert(sd != &(r2->cache_info));
  3558. sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  3559. tor_assert(sd == sd2);
  3560. });
  3561. iter = digestmap_iter_init(rl->identity_map);
  3562. while (!digestmap_iter_done(iter)) {
  3563. const char *d;
  3564. void *_r;
  3565. routerinfo_t *r;
  3566. digestmap_iter_get(iter, &d, &_r);
  3567. r = _r;
  3568. tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
  3569. iter = digestmap_iter_next(rl->identity_map, iter);
  3570. }
  3571. iter = digestmap_iter_init(rl->desc_digest_map);
  3572. while (!digestmap_iter_done(iter)) {
  3573. const char *d;
  3574. void *_sd;
  3575. signed_descriptor_t *sd;
  3576. digestmap_iter_get(iter, &d, &_sd);
  3577. sd = _sd;
  3578. tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
  3579. iter = digestmap_iter_next(rl->desc_digest_map, iter);
  3580. }
  3581. }
  3582. /** Allocate and return a new string representing the contact info
  3583. * and platform string for <b>router</b>,
  3584. * surrounded by quotes and using standard C escapes.
  3585. *
  3586. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  3587. * thread. Also, each call invalidates the last-returned value, so don't
  3588. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  3589. */
  3590. const char *
  3591. esc_router_info(routerinfo_t *router)
  3592. {
  3593. static char *info;
  3594. char *esc_contact, *esc_platform;
  3595. size_t len;
  3596. if (info)
  3597. tor_free(info);
  3598. esc_contact = esc_for_log(router->contact_info);
  3599. esc_platform = esc_for_log(router->platform);
  3600. len = strlen(esc_contact)+strlen(esc_platform)+32;
  3601. info = tor_malloc(len);
  3602. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  3603. esc_platform);
  3604. tor_free(esc_contact);
  3605. tor_free(esc_platform);
  3606. return info;
  3607. }