routerlist.c 145 KB

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