routerlist.c 153 KB

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