routerlist.c 136 KB

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