routerlist.c 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534
  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. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  1441. * a copy of router <b>ri</b> yet, add it to the list of old (not
  1442. * recommended but still served) descriptors. Else free it. */
  1443. static void
  1444. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  1445. {
  1446. if (get_options()->DirPort &&
  1447. !digestmap_get(rl->desc_digest_map,
  1448. ri->cache_info.signed_descriptor_digest)) {
  1449. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  1450. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1451. smartlist_add(rl->old_routers, sd);
  1452. } else {
  1453. routerinfo_free(ri);
  1454. }
  1455. // routerlist_assert_ok(rl);
  1456. }
  1457. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  1458. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  1459. * idx) == ri, we don't need to do a linear search over the list to decide
  1460. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  1461. * the list, if any exists. <b>ri</b> is freed. */
  1462. void
  1463. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
  1464. {
  1465. routerinfo_t *ri_tmp;
  1466. idx = _routerlist_find_elt(rl->routers, ri, idx);
  1467. if (idx < 0)
  1468. return;
  1469. ri->routerlist_index = -1;
  1470. smartlist_del(rl->routers, idx);
  1471. if (idx < smartlist_len(rl->routers)) {
  1472. routerinfo_t *r = smartlist_get(rl->routers, idx);
  1473. r->routerlist_index = idx;
  1474. }
  1475. ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
  1476. router_dir_info_changed();
  1477. tor_assert(ri_tmp == ri);
  1478. if (make_old && get_options()->DirPort) {
  1479. signed_descriptor_t *sd;
  1480. sd = signed_descriptor_from_routerinfo(ri);
  1481. smartlist_add(rl->old_routers, sd);
  1482. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1483. } else {
  1484. ri_tmp = digestmap_remove(rl->desc_digest_map,
  1485. ri->cache_info.signed_descriptor_digest);
  1486. tor_assert(ri_tmp == ri);
  1487. router_bytes_dropped += ri->cache_info.signed_descriptor_len;
  1488. routerinfo_free(ri);
  1489. }
  1490. // routerlist_assert_ok(rl);
  1491. }
  1492. static void
  1493. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  1494. {
  1495. signed_descriptor_t *sd_tmp;
  1496. idx = _routerlist_find_elt(rl->old_routers, sd, idx);
  1497. if (idx < 0)
  1498. return;
  1499. smartlist_del(rl->old_routers, idx);
  1500. sd_tmp = digestmap_remove(rl->desc_digest_map,
  1501. sd->signed_descriptor_digest);
  1502. tor_assert(sd_tmp == sd);
  1503. router_bytes_dropped += sd->signed_descriptor_len;
  1504. signed_descriptor_free(sd);
  1505. // routerlist_assert_ok(rl);
  1506. }
  1507. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  1508. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  1509. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  1510. * search over the list to decide which to remove. We put ri_new in the same
  1511. * index as ri_old, if possible. ri is freed as appropriate. */
  1512. static void
  1513. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  1514. routerinfo_t *ri_new, int idx, int make_old)
  1515. {
  1516. tor_assert(ri_old != ri_new);
  1517. idx = _routerlist_find_elt(rl->routers, ri_old, idx);
  1518. router_dir_info_changed();
  1519. if (idx >= 0) {
  1520. smartlist_set(rl->routers, idx, ri_new);
  1521. ri_old->routerlist_index = -1;
  1522. ri_new->routerlist_index = idx;
  1523. } else {
  1524. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  1525. routerlist_insert(rl, ri_new);
  1526. return;
  1527. }
  1528. if (memcmp(ri_old->cache_info.identity_digest,
  1529. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  1530. /* digests don't match; digestmap_set won't replace */
  1531. digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  1532. }
  1533. digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
  1534. digestmap_set(rl->desc_digest_map,
  1535. ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
  1536. if (make_old && get_options()->DirPort) {
  1537. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  1538. smartlist_add(rl->old_routers, sd);
  1539. digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  1540. } else {
  1541. if (memcmp(ri_old->cache_info.signed_descriptor_digest,
  1542. ri_new->cache_info.signed_descriptor_digest,
  1543. DIGEST_LEN)) {
  1544. /* digests don't match; digestmap_set didn't replace */
  1545. digestmap_remove(rl->desc_digest_map,
  1546. ri_old->cache_info.signed_descriptor_digest);
  1547. }
  1548. routerinfo_free(ri_old);
  1549. }
  1550. // routerlist_assert_ok(rl);
  1551. }
  1552. /** Free all memory held by the routerlist module. */
  1553. void
  1554. routerlist_free_all(void)
  1555. {
  1556. if (routerlist)
  1557. routerlist_free(routerlist);
  1558. routerlist = NULL;
  1559. if (warned_nicknames) {
  1560. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1561. smartlist_free(warned_nicknames);
  1562. warned_nicknames = NULL;
  1563. }
  1564. if (warned_conflicts) {
  1565. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1566. smartlist_free(warned_conflicts);
  1567. warned_conflicts = NULL;
  1568. }
  1569. if (trusted_dir_servers) {
  1570. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1571. trusted_dir_server_free(ds));
  1572. smartlist_free(trusted_dir_servers);
  1573. trusted_dir_servers = NULL;
  1574. }
  1575. if (networkstatus_list) {
  1576. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1577. networkstatus_free(ns));
  1578. smartlist_free(networkstatus_list);
  1579. networkstatus_list = NULL;
  1580. }
  1581. if (routerstatus_list) {
  1582. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1583. local_routerstatus_free(rs));
  1584. smartlist_free(routerstatus_list);
  1585. routerstatus_list = NULL;
  1586. }
  1587. if (named_server_map) {
  1588. strmap_free(named_server_map, _tor_free);
  1589. }
  1590. }
  1591. /** Free all storage held by the routerstatus object <b>rs</b>. */
  1592. void
  1593. routerstatus_free(routerstatus_t *rs)
  1594. {
  1595. tor_free(rs);
  1596. }
  1597. /** Free all storage held by the local_routerstatus object <b>rs</b>. */
  1598. static void
  1599. local_routerstatus_free(local_routerstatus_t *rs)
  1600. {
  1601. tor_free(rs);
  1602. }
  1603. /** Free all storage held by the networkstatus object <b>ns</b>. */
  1604. void
  1605. networkstatus_free(networkstatus_t *ns)
  1606. {
  1607. tor_free(ns->source_address);
  1608. tor_free(ns->contact);
  1609. if (ns->signing_key)
  1610. crypto_free_pk_env(ns->signing_key);
  1611. tor_free(ns->client_versions);
  1612. tor_free(ns->server_versions);
  1613. if (ns->entries) {
  1614. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1615. routerstatus_free(rs));
  1616. smartlist_free(ns->entries);
  1617. }
  1618. tor_free(ns);
  1619. }
  1620. /** Forget that we have issued any router-related warnings, so that we'll
  1621. * warn again if we see the same errors. */
  1622. void
  1623. routerlist_reset_warnings(void)
  1624. {
  1625. if (!warned_nicknames)
  1626. warned_nicknames = smartlist_create();
  1627. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1628. smartlist_clear(warned_nicknames); /* now the list is empty. */
  1629. if (!warned_conflicts)
  1630. warned_conflicts = smartlist_create();
  1631. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1632. smartlist_clear(warned_conflicts); /* now the list is empty. */
  1633. if (!routerstatus_list)
  1634. routerstatus_list = smartlist_create();
  1635. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1636. rs->name_lookup_warned = 0);
  1637. have_warned_about_invalid_status = 0;
  1638. have_warned_about_old_version = 0;
  1639. have_warned_about_new_version = 0;
  1640. }
  1641. /** Mark the router with ID <b>digest</b> as running or non-running
  1642. * in our routerlist. */
  1643. void
  1644. router_set_status(const char *digest, int up)
  1645. {
  1646. routerinfo_t *router;
  1647. local_routerstatus_t *status;
  1648. tor_assert(digest);
  1649. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  1650. if (!memcmp(d->digest, digest, DIGEST_LEN))
  1651. d->is_running = up);
  1652. router = router_get_by_digest(digest);
  1653. if (router) {
  1654. log_debug(LD_DIR,"Marking router '%s' as %s.",
  1655. router->nickname, up ? "up" : "down");
  1656. if (!up && router_is_me(router) && !we_are_hibernating())
  1657. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  1658. "addresses reachable?");
  1659. router->is_running = up;
  1660. }
  1661. status = router_get_combined_status_by_digest(digest);
  1662. if (status && status->status.is_running != up) {
  1663. status->status.is_running = up;
  1664. control_event_networkstatus_changed_single(status);
  1665. }
  1666. router_dir_info_changed();
  1667. }
  1668. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  1669. * older entries (if any) with the same key. Note: Callers should not hold
  1670. * their pointers to <b>router</b> if this function fails; <b>router</b>
  1671. * will either be inserted into the routerlist or freed.
  1672. *
  1673. * Returns >= 0 if the router was added; less than 0 if it was not.
  1674. *
  1675. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  1676. * describing the reason for not liking the routerinfo.
  1677. *
  1678. * If the return value is less than -1, there was a problem with the
  1679. * routerinfo. If the return value is equal to -1, then the routerinfo was
  1680. * fine, but out-of-date. If the return value is equal to 1, the
  1681. * routerinfo was accepted, but we should notify the generator of the
  1682. * descriptor using the message *<b>msg</b>.
  1683. *
  1684. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  1685. * <b>from_fetch</b>, we received it in response to a request we made.
  1686. * (If both are false, that means it was uploaded to us as an auth dir
  1687. * server or via the controller.)
  1688. *
  1689. * This function should be called *after*
  1690. * routers_update_status_from_networkstatus; subsequently, you should call
  1691. * router_rebuild_store and control_event_descriptors_changed.
  1692. */
  1693. int
  1694. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  1695. int from_cache, int from_fetch)
  1696. {
  1697. const char *id_digest;
  1698. int authdir = get_options()->AuthoritativeDir;
  1699. int authdir_believes_valid = 0;
  1700. routerinfo_t *old_router;
  1701. tor_assert(msg);
  1702. if (!routerlist)
  1703. router_get_routerlist();
  1704. if (!networkstatus_list)
  1705. networkstatus_list = smartlist_create();
  1706. id_digest = router->cache_info.identity_digest;
  1707. /* Make sure that we haven't already got this exact descriptor. */
  1708. if (digestmap_get(routerlist->desc_digest_map,
  1709. router->cache_info.signed_descriptor_digest)) {
  1710. log_info(LD_DIR,
  1711. "Dropping descriptor that we already have for router '%s'",
  1712. router->nickname);
  1713. *msg = "Router descriptor was not new.";
  1714. routerinfo_free(router);
  1715. return -1;
  1716. }
  1717. if (routerlist_is_overfull(routerlist))
  1718. routerlist_remove_old_routers();
  1719. if (authdir) {
  1720. if (authdir_wants_to_reject_router(router, msg,
  1721. !from_cache && !from_fetch)) {
  1722. tor_assert(*msg);
  1723. routerinfo_free(router);
  1724. return -2;
  1725. }
  1726. authdir_believes_valid = router->is_valid;
  1727. } else if (from_fetch) {
  1728. /* Only check the descriptor digest against the network statuses when
  1729. * we are receiving in response to a fetch. */
  1730. if (!signed_desc_digest_is_recognized(&router->cache_info)) {
  1731. /* We asked for it, so some networkstatus must have listed it when we
  1732. * did. Save it if we're a cache in case somebody else asks for it. */
  1733. log_info(LD_DIR,
  1734. "Received a no-longer-recognized descriptor for router '%s'",
  1735. router->nickname);
  1736. *msg = "Router descriptor is not referenced by any network-status.";
  1737. /* Only journal this desc if we'll be serving it. */
  1738. if (!from_cache && get_options()->DirPort)
  1739. router_append_to_journal(&router->cache_info);
  1740. routerlist_insert_old(routerlist, router);
  1741. return -1;
  1742. }
  1743. }
  1744. /* We no longer need a router with this descriptor digest. */
  1745. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1746. {
  1747. routerstatus_t *rs =
  1748. networkstatus_find_entry(ns, router->cache_info.identity_digest);
  1749. if (rs && !memcmp(rs->descriptor_digest,
  1750. router->cache_info.signed_descriptor_digest,
  1751. DIGEST_LEN))
  1752. rs->need_to_mirror = 0;
  1753. });
  1754. /* If we have a router with the same identity key, choose the newer one. */
  1755. old_router = digestmap_get(routerlist->identity_map,
  1756. router->cache_info.identity_digest);
  1757. if (old_router) {
  1758. int pos = old_router->routerlist_index;
  1759. tor_assert(smartlist_get(routerlist->routers, pos) == old_router);
  1760. if (router->cache_info.published_on <=
  1761. old_router->cache_info.published_on) {
  1762. /* Same key, but old */
  1763. log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
  1764. router->nickname);
  1765. /* Only journal this desc if we'll be serving it. */
  1766. if (!from_cache && get_options()->DirPort)
  1767. router_append_to_journal(&router->cache_info);
  1768. routerlist_insert_old(routerlist, router);
  1769. *msg = "Router descriptor was not new.";
  1770. return -1;
  1771. } else {
  1772. /* Same key, new. */
  1773. int unreachable = 0;
  1774. log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
  1775. router->nickname, old_router->nickname,
  1776. hex_str(id_digest,DIGEST_LEN));
  1777. if (router->addr == old_router->addr &&
  1778. router->or_port == old_router->or_port) {
  1779. /* these carry over when the address and orport are unchanged.*/
  1780. router->last_reachable = old_router->last_reachable;
  1781. router->testing_since = old_router->testing_since;
  1782. router->num_unreachable_notifications =
  1783. old_router->num_unreachable_notifications;
  1784. }
  1785. if (authdir && !from_cache && !from_fetch &&
  1786. router_have_minimum_dir_info() &&
  1787. dirserv_thinks_router_is_blatantly_unreachable(router,
  1788. time(NULL))) {
  1789. if (router->num_unreachable_notifications >= 3) {
  1790. unreachable = 1;
  1791. log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
  1792. "(ContactInfo '%s', platform '%s').",
  1793. router->nickname,
  1794. router->contact_info ? router->contact_info : "",
  1795. router->platform ? router->platform : "");
  1796. } else {
  1797. log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
  1798. "descriptors were thought to be unreachable.",
  1799. router->nickname, router->num_unreachable_notifications);
  1800. router->num_unreachable_notifications++;
  1801. }
  1802. }
  1803. routerlist_replace(routerlist, old_router, router, pos, 1);
  1804. if (!from_cache) {
  1805. router_append_to_journal(&router->cache_info);
  1806. }
  1807. directory_set_dirty();
  1808. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1809. authdir_believes_valid ? "Valid server updated" :
  1810. ("Invalid server updated. (This dirserver is marking your "
  1811. "server as unapproved.)");
  1812. return unreachable ? 1 : 0;
  1813. }
  1814. }
  1815. /* We haven't seen a router with this identity before. Add it to the end of
  1816. * the list. */
  1817. routerlist_insert(routerlist, router);
  1818. if (!from_cache)
  1819. router_append_to_journal(&router->cache_info);
  1820. directory_set_dirty();
  1821. return 0;
  1822. }
  1823. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  1824. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  1825. * to, or later than that of *<b>b</b>. */
  1826. static int
  1827. _compare_old_routers_by_identity(const void **_a, const void **_b)
  1828. {
  1829. int i;
  1830. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  1831. if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  1832. return i;
  1833. return r1->published_on - r2->published_on;
  1834. }
  1835. /** Internal type used to represent how long an old descriptor was valid,
  1836. * where it appeared in the list of old descriptors, and whether it's extra
  1837. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  1838. struct duration_idx_t {
  1839. int duration;
  1840. int idx;
  1841. int old;
  1842. };
  1843. /** Sorting helper: compare two duration_idx_t by their duration. */
  1844. static int
  1845. _compare_duration_idx(const void *_d1, const void *_d2)
  1846. {
  1847. const struct duration_idx_t *d1 = _d1;
  1848. const struct duration_idx_t *d2 = _d2;
  1849. return d1->duration - d2->duration;
  1850. }
  1851. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  1852. * must contain routerinfo_t with the same identity and with publication time
  1853. * in ascending order. Remove members from this range until there are no more
  1854. * than max_descriptors_per_router() remaining. Start by removing the oldest
  1855. * members from before <b>cutoff</b>, then remove members which were current
  1856. * for the lowest amount of time. The order of members of old_routers at
  1857. * indices <b>lo</b> or higher may be changed.
  1858. */
  1859. static void
  1860. routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
  1861. digestmap_t *retain)
  1862. {
  1863. int i, n = hi-lo+1, n_extra;
  1864. int n_rmv = 0;
  1865. struct duration_idx_t *lifespans;
  1866. uint8_t *rmv, *must_keep;
  1867. smartlist_t *lst = routerlist->old_routers;
  1868. #if 1
  1869. const char *ident;
  1870. tor_assert(hi < smartlist_len(lst));
  1871. tor_assert(lo <= hi);
  1872. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  1873. for (i = lo+1; i <= hi; ++i) {
  1874. signed_descriptor_t *r = smartlist_get(lst, i);
  1875. tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
  1876. }
  1877. #endif
  1878. /* Check whether we need to do anything at all. */
  1879. n_extra = n - max_descriptors_per_router();
  1880. if (n_extra <= 0)
  1881. return;
  1882. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  1883. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  1884. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  1885. /* Set lifespans to contain the lifespan and index of each server. */
  1886. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  1887. for (i = lo; i <= hi; ++i) {
  1888. signed_descriptor_t *r = smartlist_get(lst, i);
  1889. signed_descriptor_t *r_next;
  1890. lifespans[i-lo].idx = i;
  1891. if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
  1892. must_keep[i-lo] = 1;
  1893. }
  1894. if (i < hi) {
  1895. r_next = smartlist_get(lst, i+1);
  1896. tor_assert(r->published_on <= r_next->published_on);
  1897. lifespans[i-lo].duration = (r_next->published_on - r->published_on);
  1898. } else {
  1899. r_next = NULL;
  1900. lifespans[i-lo].duration = INT_MAX;
  1901. }
  1902. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  1903. ++n_rmv;
  1904. lifespans[i-lo].old = 1;
  1905. rmv[i-lo] = 1;
  1906. }
  1907. }
  1908. if (n_rmv < n_extra) {
  1909. /**
  1910. * We aren't removing enough servers for being old. Sort lifespans by
  1911. * the duration of liveness, and remove the ones we're not already going to
  1912. * remove based on how long they were alive.
  1913. **/
  1914. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  1915. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  1916. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  1917. rmv[lifespans[i].idx-lo] = 1;
  1918. ++n_rmv;
  1919. }
  1920. }
  1921. }
  1922. for (i = hi; i >= lo; --i) {
  1923. if (rmv[i-lo])
  1924. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  1925. }
  1926. tor_free(must_keep);
  1927. tor_free(rmv);
  1928. tor_free(lifespans);
  1929. }
  1930. /** Deactivate any routers from the routerlist that are more than
  1931. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  1932. * remove old routers from the list of cached routers if we have too many.
  1933. */
  1934. void
  1935. routerlist_remove_old_routers(void)
  1936. {
  1937. int i, hi=-1;
  1938. const char *cur_id = NULL;
  1939. time_t now = time(NULL);
  1940. time_t cutoff;
  1941. routerinfo_t *router;
  1942. signed_descriptor_t *sd;
  1943. digestmap_t *retain;
  1944. if (!routerlist || !networkstatus_list)
  1945. return;
  1946. retain = digestmap_new();
  1947. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1948. /* Build a list of all the descriptors that _anybody_ recommends. */
  1949. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1950. {
  1951. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  1952. if (rs->published_on >= cutoff)
  1953. digestmap_set(retain, rs->descriptor_digest, (void*)1));
  1954. });
  1955. /* If we have a bunch of networkstatuses, we should consider pruning current
  1956. * routers that are too old and that nobody recommends. (If we don't have
  1957. * enough networkstatuses, then we should get more before we decide to kill
  1958. * routers.) */
  1959. if (smartlist_len(networkstatus_list) > get_n_v2_authorities() / 2) {
  1960. cutoff = now - ROUTER_MAX_AGE;
  1961. /* Remove too-old unrecommended members of routerlist->routers. */
  1962. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1963. router = smartlist_get(routerlist->routers, i);
  1964. if (router->cache_info.published_on <= cutoff &&
  1965. !digestmap_get(retain,router->cache_info.signed_descriptor_digest)) {
  1966. /* Too old: remove it. (If we're a cache, just move it into
  1967. * old_routers.) */
  1968. log_info(LD_DIR,
  1969. "Forgetting obsolete (too old) routerinfo for router '%s'",
  1970. router->nickname);
  1971. routerlist_remove(routerlist, router, i--, 1);
  1972. }
  1973. }
  1974. }
  1975. /* Remove far-too-old members of routerlist->old_routers. */
  1976. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  1977. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  1978. sd = smartlist_get(routerlist->old_routers, i);
  1979. if (sd->published_on <= cutoff &&
  1980. !digestmap_get(retain, sd->signed_descriptor_digest)) {
  1981. /* Too old. Remove it. */
  1982. routerlist_remove_old(routerlist, sd, i--);
  1983. }
  1984. }
  1985. /* Now we might have to look at routerlist->old_routers for extraneous
  1986. * members. (We'd keep all the members if we could, but we need to save
  1987. * space.) First, check whether we have too many router descriptors, total.
  1988. * We're okay with having too many for some given router, so long as the
  1989. * total number doesn't approach max_descriptors_per_router()*len(router).
  1990. */
  1991. if (smartlist_len(routerlist->old_routers) <
  1992. smartlist_len(routerlist->routers) * (max_descriptors_per_router() - 1))
  1993. goto done;
  1994. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  1995. /* Iterate through the list from back to front, so when we remove descriptors
  1996. * we don't mess up groups we haven't gotten to. */
  1997. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  1998. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  1999. if (!cur_id) {
  2000. cur_id = r->identity_digest;
  2001. hi = i;
  2002. }
  2003. if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
  2004. routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
  2005. cur_id = r->identity_digest;
  2006. hi = i;
  2007. }
  2008. }
  2009. if (hi>=0)
  2010. routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
  2011. routerlist_assert_ok(routerlist);
  2012. done:
  2013. digestmap_free(retain, NULL);
  2014. }
  2015. /**
  2016. * Code to parse a single router descriptor and insert it into the
  2017. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  2018. * descriptor was well-formed but could not be added; and 1 if the
  2019. * descriptor was added.
  2020. *
  2021. * If we don't add it and <b>msg</b> is not NULL, then assign to
  2022. * *<b>msg</b> a static string describing the reason for refusing the
  2023. * descriptor.
  2024. *
  2025. * This is used only by the controller.
  2026. */
  2027. int
  2028. router_load_single_router(const char *s, uint8_t purpose, const char **msg)
  2029. {
  2030. routerinfo_t *ri;
  2031. int r;
  2032. smartlist_t *lst;
  2033. tor_assert(msg);
  2034. *msg = NULL;
  2035. if (!(ri = router_parse_entry_from_string(s, NULL, 1))) {
  2036. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  2037. *msg = "Couldn't parse router descriptor.";
  2038. return -1;
  2039. }
  2040. ri->purpose = purpose;
  2041. if (router_is_me(ri)) {
  2042. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  2043. *msg = "Router's identity key matches mine.";
  2044. routerinfo_free(ri);
  2045. return 0;
  2046. }
  2047. lst = smartlist_create();
  2048. smartlist_add(lst, ri);
  2049. routers_update_status_from_networkstatus(lst, 0);
  2050. if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
  2051. /* we've already assigned to *msg now, and ri is already freed */
  2052. tor_assert(*msg);
  2053. if (r < -1)
  2054. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  2055. smartlist_free(lst);
  2056. return 0;
  2057. } else {
  2058. control_event_descriptors_changed(lst);
  2059. smartlist_free(lst);
  2060. log_debug(LD_DIR, "Added router to list");
  2061. return 1;
  2062. }
  2063. }
  2064. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  2065. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  2066. * are in response to a query to the network: cache them by adding them to
  2067. * the journal.
  2068. *
  2069. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  2070. * uppercased identity fingerprints. Do not update any router whose
  2071. * fingerprint is not on the list; after updating a router, remove its
  2072. * fingerprint from the list.
  2073. */
  2074. void
  2075. router_load_routers_from_string(const char *s, saved_location_t saved_location,
  2076. smartlist_t *requested_fingerprints)
  2077. {
  2078. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  2079. char fp[HEX_DIGEST_LEN+1];
  2080. const char *msg;
  2081. int from_cache = (saved_location != SAVED_NOWHERE);
  2082. router_parse_list_from_string(&s, routers, saved_location);
  2083. routers_update_status_from_networkstatus(routers, !from_cache);
  2084. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  2085. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  2086. {
  2087. base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
  2088. DIGEST_LEN);
  2089. if (requested_fingerprints) {
  2090. if (smartlist_string_isin(requested_fingerprints, fp)) {
  2091. smartlist_string_remove(requested_fingerprints, fp);
  2092. } else {
  2093. char *requested =
  2094. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  2095. log_warn(LD_DIR,
  2096. "We received a router descriptor with a fingerprint (%s) "
  2097. "that we never requested. (We asked for: %s.) Dropping.",
  2098. fp, requested);
  2099. tor_free(requested);
  2100. routerinfo_free(ri);
  2101. continue;
  2102. }
  2103. }
  2104. if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
  2105. smartlist_add(changed, ri);
  2106. });
  2107. if (smartlist_len(changed))
  2108. control_event_descriptors_changed(changed);
  2109. routerlist_assert_ok(routerlist);
  2110. router_rebuild_store(0);
  2111. smartlist_free(routers);
  2112. smartlist_free(changed);
  2113. }
  2114. /** Helper: return a newly allocated string containing the name of the filename
  2115. * where we plan to cache the network status with the given identity digest. */
  2116. char *
  2117. networkstatus_get_cache_filename(const char *identity_digest)
  2118. {
  2119. const char *datadir = get_options()->DataDirectory;
  2120. size_t len = strlen(datadir)+64;
  2121. char fp[HEX_DIGEST_LEN+1];
  2122. char *fn = tor_malloc(len+1);
  2123. base16_encode(fp, HEX_DIGEST_LEN+1, identity_digest, DIGEST_LEN);
  2124. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  2125. return fn;
  2126. }
  2127. /** Helper for smartlist_sort: Compare two networkstatus objects by
  2128. * publication date. */
  2129. static int
  2130. _compare_networkstatus_published_on(const void **_a, const void **_b)
  2131. {
  2132. const networkstatus_t *a = *_a, *b = *_b;
  2133. if (a->published_on < b->published_on)
  2134. return -1;
  2135. else if (a->published_on > b->published_on)
  2136. return 1;
  2137. else
  2138. return 0;
  2139. }
  2140. /** Add the parsed neworkstatus in <b>ns</b> (with original document in
  2141. * <b>s</b> to the disk cache (and the in-memory directory server cache) as
  2142. * appropriate. */
  2143. static int
  2144. add_networkstatus_to_cache(const char *s,
  2145. networkstatus_source_t source,
  2146. networkstatus_t *ns)
  2147. {
  2148. if (source != NS_FROM_CACHE) {
  2149. char *fn = networkstatus_get_cache_filename(ns->identity_digest);
  2150. if (write_str_to_file(fn, s, 0)<0) {
  2151. log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
  2152. }
  2153. tor_free(fn);
  2154. }
  2155. if (get_options()->DirPort)
  2156. dirserv_set_cached_networkstatus_v2(s,
  2157. ns->identity_digest,
  2158. ns->published_on);
  2159. return 0;
  2160. }
  2161. /** How far in the future do we allow a network-status to get before removing
  2162. * it? (seconds) */
  2163. #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
  2164. /** Given a string <b>s</b> containing a network status that we received at
  2165. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  2166. * store it, and put it into our cache as necessary.
  2167. *
  2168. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  2169. * own networkstatus_t (if we're an authoritative directory server).
  2170. *
  2171. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  2172. * cache.
  2173. *
  2174. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  2175. * uppercased identity fingerprints. Do not update any networkstatus whose
  2176. * fingerprint is not on the list; after updating a networkstatus, remove its
  2177. * fingerprint from the list.
  2178. *
  2179. * Return 0 on success, -1 on failure.
  2180. *
  2181. * Callers should make sure that routers_update_all_from_networkstatus() is
  2182. * invoked after this function succeeds.
  2183. */
  2184. int
  2185. router_set_networkstatus(const char *s, time_t arrived_at,
  2186. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  2187. {
  2188. networkstatus_t *ns;
  2189. int i, found;
  2190. time_t now;
  2191. int skewed = 0;
  2192. trusted_dir_server_t *trusted_dir = NULL;
  2193. const char *source_desc = NULL;
  2194. char fp[HEX_DIGEST_LEN+1];
  2195. char published[ISO_TIME_LEN+1];
  2196. ns = networkstatus_parse_from_string(s);
  2197. if (!ns) {
  2198. log_warn(LD_DIR, "Couldn't parse network status.");
  2199. return -1;
  2200. }
  2201. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  2202. if (!(trusted_dir =
  2203. router_get_trusteddirserver_by_digest(ns->identity_digest)) ||
  2204. !trusted_dir->is_v2_authority) {
  2205. log_info(LD_DIR, "Network status was signed, but not by an authoritative "
  2206. "directory we recognize.");
  2207. if (!get_options()->DirPort) {
  2208. networkstatus_free(ns);
  2209. return 0;
  2210. }
  2211. source_desc = fp;
  2212. } else {
  2213. source_desc = trusted_dir->description;
  2214. }
  2215. now = time(NULL);
  2216. if (arrived_at > now)
  2217. arrived_at = now;
  2218. ns->received_on = arrived_at;
  2219. format_iso_time(published, ns->published_on);
  2220. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  2221. log_warn(LD_GENERAL, "Network status from %s was published in the future "
  2222. "(%s GMT). Somebody is skewed here: check your clock. "
  2223. "Not caching.",
  2224. source_desc, published);
  2225. control_event_general_status(LOG_WARN,
  2226. "CLOCK_SKEW SOURCE=NETWORKSTATUS:%s:%d",
  2227. ns->source_address, ns->source_dirport);
  2228. skewed = 1;
  2229. }
  2230. if (!networkstatus_list)
  2231. networkstatus_list = smartlist_create();
  2232. if ( (source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) &&
  2233. router_digest_is_me(ns->identity_digest)) {
  2234. /* Don't replace our own networkstatus when we get it from somebody else.*/
  2235. networkstatus_free(ns);
  2236. return 0;
  2237. }
  2238. if (requested_fingerprints) {
  2239. if (smartlist_string_isin(requested_fingerprints, fp)) {
  2240. smartlist_string_remove(requested_fingerprints, fp);
  2241. } else {
  2242. char *requested =
  2243. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  2244. if (source != NS_FROM_DIR_ALL) {
  2245. log_warn(LD_DIR,
  2246. "We received a network status with a fingerprint (%s) that we "
  2247. "never requested. (We asked for: %s.) Dropping.",
  2248. fp, requested);
  2249. tor_free(requested);
  2250. return 0;
  2251. }
  2252. }
  2253. }
  2254. if (!trusted_dir) {
  2255. if (!skewed && get_options()->DirPort) {
  2256. /* We got a non-trusted networkstatus, and we're a directory cache.
  2257. * This means that we asked an authority, and it told us about another
  2258. * authority we didn't recognize. */
  2259. log_info(LD_DIR,
  2260. "We do not recognize authority (%s) but we are willing "
  2261. "to cache it", fp);
  2262. add_networkstatus_to_cache(s, source, ns);
  2263. networkstatus_free(ns);
  2264. }
  2265. return 0;
  2266. }
  2267. if (source != NS_FROM_CACHE && trusted_dir)
  2268. trusted_dir->n_networkstatus_failures = 0;
  2269. found = 0;
  2270. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  2271. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  2272. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  2273. if (!memcmp(old_ns->networkstatus_digest,
  2274. ns->networkstatus_digest, DIGEST_LEN)) {
  2275. /* Same one we had before. */
  2276. networkstatus_free(ns);
  2277. log_info(LD_DIR,
  2278. "Not replacing network-status from %s (published %s); "
  2279. "we already have it.",
  2280. trusted_dir->description, published);
  2281. if (old_ns->received_on < arrived_at) {
  2282. if (source != NS_FROM_CACHE) {
  2283. char *fn;
  2284. fn = networkstatus_get_cache_filename(old_ns->identity_digest);
  2285. /* We use mtime to tell when it arrived, so update that. */
  2286. touch_file(fn);
  2287. tor_free(fn);
  2288. }
  2289. old_ns->received_on = arrived_at;
  2290. }
  2291. return 0;
  2292. } else if (old_ns->published_on >= ns->published_on) {
  2293. char old_published[ISO_TIME_LEN+1];
  2294. format_iso_time(old_published, old_ns->published_on);
  2295. log_info(LD_DIR,
  2296. "Not replacing network-status from %s (published %s);"
  2297. " we have a newer one (published %s) for this authority.",
  2298. trusted_dir->description, published,
  2299. old_published);
  2300. networkstatus_free(ns);
  2301. return 0;
  2302. } else {
  2303. networkstatus_free(old_ns);
  2304. smartlist_set(networkstatus_list, i, ns);
  2305. found = 1;
  2306. break;
  2307. }
  2308. }
  2309. }
  2310. if (!found)
  2311. smartlist_add(networkstatus_list, ns);
  2312. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  2313. {
  2314. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  2315. rs->need_to_mirror = 1;
  2316. });
  2317. log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
  2318. source == NS_FROM_CACHE?"cached from":
  2319. ((source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) ?
  2320. "downloaded from":"generated for"),
  2321. trusted_dir->description, published);
  2322. networkstatus_list_has_changed = 1;
  2323. router_dir_info_changed();
  2324. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  2325. if (!skewed)
  2326. add_networkstatus_to_cache(s, source, ns);
  2327. networkstatus_list_update_recent(now);
  2328. return 0;
  2329. }
  2330. /** How old do we allow a network-status to get before removing it
  2331. * completely? */
  2332. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  2333. /** Remove all very-old network_status_t objects from memory and from the
  2334. * disk cache. */
  2335. void
  2336. networkstatus_list_clean(time_t now)
  2337. {
  2338. int i;
  2339. if (!networkstatus_list)
  2340. return;
  2341. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  2342. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2343. char *fname = NULL;
  2344. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  2345. continue;
  2346. /* Okay, this one is too old. Remove it from the list, and delete it
  2347. * from the cache. */
  2348. smartlist_del(networkstatus_list, i--);
  2349. fname = networkstatus_get_cache_filename(ns->identity_digest);
  2350. if (file_status(fname) == FN_FILE) {
  2351. log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
  2352. unlink(fname);
  2353. }
  2354. tor_free(fname);
  2355. if (get_options()->DirPort) {
  2356. dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
  2357. }
  2358. networkstatus_free(ns);
  2359. router_dir_info_changed();
  2360. }
  2361. /* And now go through the directory cache for any cached untrusted
  2362. * networkstatuses and other network info. */
  2363. dirserv_clear_old_networkstatuses(now - MAX_NETWORKSTATUS_AGE);
  2364. dirserv_clear_old_v1_info(now);
  2365. }
  2366. /** Helper for bsearching a list of routerstatus_t pointers.*/
  2367. static int
  2368. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  2369. {
  2370. const char *key = _key;
  2371. const routerstatus_t *rs = *_member;
  2372. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  2373. }
  2374. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  2375. * NULL if none was found. */
  2376. static routerstatus_t *
  2377. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  2378. {
  2379. return smartlist_bsearch(ns->entries, digest,
  2380. _compare_digest_to_routerstatus_entry);
  2381. }
  2382. /** Return the consensus view of the status of the router whose digest is
  2383. * <b>digest</b>, or NULL if we don't know about any such router. */
  2384. local_routerstatus_t *
  2385. router_get_combined_status_by_digest(const char *digest)
  2386. {
  2387. if (!routerstatus_list)
  2388. return NULL;
  2389. return smartlist_bsearch(routerstatus_list, digest,
  2390. _compare_digest_to_routerstatus_entry);
  2391. }
  2392. /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
  2393. * the corresponding local_routerstatus_t, or NULL if none exists. Warn the
  2394. * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
  2395. * nickname, but the Named flag isn't set for that router. */
  2396. static local_routerstatus_t *
  2397. router_get_combined_status_by_nickname(const char *nickname,
  2398. int warn_if_unnamed)
  2399. {
  2400. char digest[DIGEST_LEN];
  2401. local_routerstatus_t *best=NULL;
  2402. smartlist_t *matches=NULL;
  2403. if (!routerstatus_list || !nickname)
  2404. return NULL;
  2405. if (nickname[0] == '$') {
  2406. if (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))<0)
  2407. return NULL;
  2408. return router_get_combined_status_by_digest(digest);
  2409. } else if (strlen(nickname) == HEX_DIGEST_LEN &&
  2410. (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))==0)) {
  2411. return router_get_combined_status_by_digest(digest);
  2412. }
  2413. matches = smartlist_create();
  2414. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
  2415. {
  2416. if (!strcasecmp(lrs->status.nickname, nickname)) {
  2417. if (lrs->status.is_named) {
  2418. smartlist_free(matches);
  2419. return lrs;
  2420. } else {
  2421. smartlist_add(matches, lrs);
  2422. best = lrs;
  2423. }
  2424. }
  2425. });
  2426. if (smartlist_len(matches)>1 && warn_if_unnamed) {
  2427. int any_unwarned=0;
  2428. SMARTLIST_FOREACH(matches, local_routerstatus_t *, lrs,
  2429. {
  2430. if (! lrs->name_lookup_warned) {
  2431. lrs->name_lookup_warned=1;
  2432. any_unwarned=1;
  2433. }
  2434. });
  2435. if (any_unwarned) {
  2436. log_warn(LD_CONFIG,"There are multiple matches for the nickname \"%s\","
  2437. " but none is listed as named by the directory authorites. "
  2438. "Choosing one arbitrarily.", nickname);
  2439. }
  2440. } else if (warn_if_unnamed && best && !best->name_lookup_warned) {
  2441. char fp[HEX_DIGEST_LEN+1];
  2442. base16_encode(fp, sizeof(fp),
  2443. best->status.identity_digest, DIGEST_LEN);
  2444. log_warn(LD_CONFIG,
  2445. "To look up a status, you specified a server \"%s\" by name, but the "
  2446. "directory authorities do not have a binding for this nickname. "
  2447. "To make sure you get the same server in the future, refer to "
  2448. "it by key, as \"$%s\".", nickname, fp);
  2449. best->name_lookup_warned = 1;
  2450. }
  2451. smartlist_free(matches);
  2452. return best;
  2453. }
  2454. /** Find a routerstatus_t that corresponds to <b>hexdigest</b>, if
  2455. * any. Prefer ones that belong to authorities. */
  2456. routerstatus_t *
  2457. routerstatus_get_by_hexdigest(const char *hexdigest)
  2458. {
  2459. char digest[DIGEST_LEN];
  2460. local_routerstatus_t *rs;
  2461. trusted_dir_server_t *ds;
  2462. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  2463. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  2464. return NULL;
  2465. if ((ds = router_get_trusteddirserver_by_digest(digest)))
  2466. return &(ds->fake_status.status);
  2467. if ((rs = router_get_combined_status_by_digest(digest)))
  2468. return &(rs->status);
  2469. return NULL;
  2470. }
  2471. /** Return true iff any networkstatus includes a descriptor whose digest
  2472. * is that of <b>desc</b>. */
  2473. static int
  2474. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  2475. {
  2476. routerstatus_t *rs;
  2477. if (!networkstatus_list)
  2478. return 0;
  2479. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2480. {
  2481. if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
  2482. continue;
  2483. if (!memcmp(rs->descriptor_digest,
  2484. desc->signed_descriptor_digest, DIGEST_LEN))
  2485. return 1;
  2486. });
  2487. return 0;
  2488. }
  2489. /** How frequently do directory authorities re-download fresh networkstatus
  2490. * documents? */
  2491. #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
  2492. /** How frequently do non-authority directory caches re-download fresh
  2493. * networkstatus documents? */
  2494. #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
  2495. /** We are a directory server, and so cache network_status documents.
  2496. * Initiate downloads as needed to update them. For authorities, this means
  2497. * asking each trusted directory for its network-status. For caches, this
  2498. * means asking a random authority for all network-statuses.
  2499. */
  2500. static void
  2501. update_networkstatus_cache_downloads(time_t now)
  2502. {
  2503. int authority = authdir_mode(get_options());
  2504. int interval =
  2505. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  2506. if (last_networkstatus_download_attempted + interval >= now)
  2507. return;
  2508. if (!trusted_dir_servers)
  2509. return;
  2510. last_networkstatus_download_attempted = now;
  2511. if (authority) {
  2512. /* An authority launches a separate connection for everybody. */
  2513. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2514. {
  2515. char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
  2516. if (!ds->is_v2_authority)
  2517. continue;
  2518. if (router_digest_is_me(ds->digest))
  2519. continue;
  2520. if (connection_get_by_type_addr_port_purpose(
  2521. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  2522. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  2523. /* We are already fetching this one. */
  2524. continue;
  2525. }
  2526. strlcpy(resource, "fp/", sizeof(resource));
  2527. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  2528. strlcat(resource, ".z", sizeof(resource));
  2529. directory_initiate_command_routerstatus(
  2530. &ds->fake_status.status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
  2531. 0, /* Not private */
  2532. resource,
  2533. NULL, 0 /* No payload. */);
  2534. });
  2535. } else {
  2536. /* A non-authority cache launches one connection to a random authority. */
  2537. /* (Check whether we're currently fetching network-status objects.) */
  2538. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  2539. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2540. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  2541. }
  2542. }
  2543. /** How long (in seconds) does a client wait after getting a network status
  2544. * before downloading the next in sequence? */
  2545. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  2546. /** How many times do we allow a networkstatus download to fail before we
  2547. * assume that the authority isn't publishing? */
  2548. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  2549. /** We are not a directory cache or authority. Update our network-status list
  2550. * by launching a new directory fetch for enough network-status documents "as
  2551. * necessary". See function comments for implementation details.
  2552. */
  2553. static void
  2554. update_networkstatus_client_downloads(time_t now)
  2555. {
  2556. int n_live = 0, n_dirservers, n_running_dirservers, needed = 0;
  2557. int fetch_latest = 0;
  2558. int most_recent_idx = -1;
  2559. trusted_dir_server_t *most_recent = NULL;
  2560. time_t most_recent_received = 0;
  2561. char *resource, *cp;
  2562. size_t resource_len;
  2563. smartlist_t *missing;
  2564. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  2565. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  2566. return;
  2567. /* This is a little tricky. We want to download enough network-status
  2568. * objects so that we have all of them under
  2569. * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
  2570. * *one* if the most recent one's publication time is under
  2571. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  2572. */
  2573. if (!get_n_v2_authorities())
  2574. return;
  2575. n_dirservers = n_running_dirservers = 0;
  2576. missing = smartlist_create();
  2577. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2578. {
  2579. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  2580. if (!ds->is_v2_authority)
  2581. continue;
  2582. ++n_dirservers;
  2583. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
  2584. continue;
  2585. ++n_running_dirservers;
  2586. if (ns && ns->published_on > now-NETWORKSTATUS_MAX_AGE)
  2587. ++n_live;
  2588. else
  2589. smartlist_add(missing, ds->digest);
  2590. if (ns && (!most_recent || ns->received_on > most_recent_received)) {
  2591. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  2592. most_recent = ds;
  2593. most_recent_received = ns->received_on;
  2594. }
  2595. });
  2596. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  2597. if (!smartlist_len(missing) &&
  2598. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL) {
  2599. log_info(LD_DIR, "Our most recent network-status document (from %s) "
  2600. "is %d seconds old; downloading another.",
  2601. most_recent?most_recent->description:"nobody",
  2602. (int)(now-most_recent_received));
  2603. fetch_latest = 1;
  2604. needed = 1;
  2605. } else if (smartlist_len(missing)) {
  2606. log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
  2607. " network-status documents. Downloading %d.",
  2608. n_running_dirservers, n_dirservers, n_live,
  2609. smartlist_len(missing));
  2610. needed = smartlist_len(missing);
  2611. } else {
  2612. smartlist_free(missing);
  2613. return;
  2614. }
  2615. /* If no networkstatus was found, choose a dirserver at random as "most
  2616. * recent". */
  2617. if (most_recent_idx<0)
  2618. most_recent_idx = crypto_rand_int(n_dirservers);
  2619. if (fetch_latest) {
  2620. int i;
  2621. int n_failed = 0;
  2622. for (i = most_recent_idx + 1; 1; ++i) {
  2623. trusted_dir_server_t *ds;
  2624. if (i >= n_dirservers)
  2625. i = 0;
  2626. ds = smartlist_get(trusted_dir_servers, i);
  2627. if (! ds->is_v2_authority)
  2628. continue;
  2629. if (n_failed < n_dirservers &&
  2630. ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  2631. ++n_failed;
  2632. continue;
  2633. }
  2634. smartlist_add(missing, ds->digest);
  2635. break;
  2636. }
  2637. }
  2638. /* Build a request string for all the resources we want. */
  2639. resource_len = smartlist_len(missing) * (HEX_DIGEST_LEN+1) + 6;
  2640. resource = tor_malloc(resource_len);
  2641. memcpy(resource, "fp/", 3);
  2642. cp = resource+3;
  2643. smartlist_sort_digests(missing);
  2644. needed = smartlist_len(missing);
  2645. SMARTLIST_FOREACH(missing, const char *, d,
  2646. {
  2647. base16_encode(cp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  2648. cp += HEX_DIGEST_LEN;
  2649. --needed;
  2650. if (needed)
  2651. *cp++ = '+';
  2652. });
  2653. memcpy(cp, ".z", 3);
  2654. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  2655. tor_free(resource);
  2656. smartlist_free(missing);
  2657. }
  2658. /** Launch requests for networkstatus documents as appropriate. */
  2659. void
  2660. update_networkstatus_downloads(time_t now)
  2661. {
  2662. or_options_t *options = get_options();
  2663. if (options->DirPort)
  2664. update_networkstatus_cache_downloads(now);
  2665. else
  2666. update_networkstatus_client_downloads(now);
  2667. }
  2668. /** Return 1 if all running sufficiently-stable routers will reject
  2669. * addr:port, return 0 if any might accept it. */
  2670. int
  2671. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  2672. int need_uptime)
  2673. {
  2674. addr_policy_result_t r;
  2675. if (!routerlist) return 1;
  2676. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  2677. {
  2678. if (router->is_running &&
  2679. !router_is_unreliable(router, need_uptime, 0, 0)) {
  2680. r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
  2681. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2682. return 0; /* this one could be ok. good enough. */
  2683. }
  2684. });
  2685. return 1; /* all will reject. */
  2686. }
  2687. /** Return true iff <b>router</b> does not permit exit streams.
  2688. */
  2689. int
  2690. router_exit_policy_rejects_all(routerinfo_t *router)
  2691. {
  2692. return compare_addr_to_addr_policy(0, 0, router->exit_policy)
  2693. == ADDR_POLICY_REJECTED;
  2694. }
  2695. /** Add to the list of authorized directory servers one at
  2696. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  2697. * <b>address</b> is NULL, add ourself. */
  2698. void
  2699. add_trusted_dir_server(const char *nickname, const char *address,
  2700. uint16_t dir_port, uint16_t or_port,
  2701. const char *digest, int is_v1_authority,
  2702. int is_v2_authority, int is_hidserv_authority)
  2703. {
  2704. trusted_dir_server_t *ent;
  2705. uint32_t a;
  2706. char *hostname = NULL;
  2707. size_t dlen;
  2708. if (!trusted_dir_servers)
  2709. trusted_dir_servers = smartlist_create();
  2710. if (!address) { /* The address is us; we should guess. */
  2711. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  2712. log_warn(LD_CONFIG,
  2713. "Couldn't find a suitable address when adding ourself as a "
  2714. "trusted directory server.");
  2715. return;
  2716. }
  2717. } else {
  2718. if (tor_lookup_hostname(address, &a)) {
  2719. log_warn(LD_CONFIG,
  2720. "Unable to lookup address for directory server at '%s'",
  2721. address);
  2722. return;
  2723. }
  2724. hostname = tor_strdup(address);
  2725. a = ntohl(a);
  2726. }
  2727. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  2728. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  2729. ent->address = hostname;
  2730. ent->addr = a;
  2731. ent->dir_port = dir_port;
  2732. ent->or_port = or_port;
  2733. ent->is_running = 1;
  2734. ent->is_v1_authority = is_v1_authority;
  2735. ent->is_v2_authority = is_v2_authority;
  2736. ent->is_hidserv_authority = is_hidserv_authority;
  2737. memcpy(ent->digest, digest, DIGEST_LEN);
  2738. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  2739. ent->description = tor_malloc(dlen);
  2740. if (nickname)
  2741. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  2742. nickname, hostname, (int)dir_port);
  2743. else
  2744. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  2745. hostname, (int)dir_port);
  2746. ent->fake_status.status.addr = ent->addr;
  2747. memcpy(ent->fake_status.status.identity_digest, digest, DIGEST_LEN);
  2748. if (nickname)
  2749. strlcpy(ent->fake_status.status.nickname, nickname,
  2750. sizeof(ent->fake_status.status.nickname));
  2751. else
  2752. ent->fake_status.status.nickname[0] = '\0';
  2753. ent->fake_status.status.dir_port = ent->dir_port;
  2754. ent->fake_status.status.or_port = ent->or_port;
  2755. smartlist_add(trusted_dir_servers, ent);
  2756. router_dir_info_changed();
  2757. }
  2758. /** Free storage held in <b>ds</b> */
  2759. void
  2760. trusted_dir_server_free(trusted_dir_server_t *ds)
  2761. {
  2762. tor_free(ds->nickname);
  2763. tor_free(ds->description);
  2764. tor_free(ds->address);
  2765. tor_free(ds);
  2766. }
  2767. /** Remove all members from the list of trusted dir servers. */
  2768. void
  2769. clear_trusted_dir_servers(void)
  2770. {
  2771. if (trusted_dir_servers) {
  2772. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2773. trusted_dir_server_free(ent));
  2774. smartlist_clear(trusted_dir_servers);
  2775. } else {
  2776. trusted_dir_servers = smartlist_create();
  2777. }
  2778. router_dir_info_changed();
  2779. }
  2780. /** Return 1 if any trusted dir server supports v1 directories,
  2781. * else return 0. */
  2782. int
  2783. any_trusted_dir_is_v1_authority(void)
  2784. {
  2785. if (trusted_dir_servers)
  2786. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2787. if (ent->is_v1_authority) return 1);
  2788. return 0;
  2789. }
  2790. /** Return the network status with a given identity digest. */
  2791. networkstatus_t *
  2792. networkstatus_get_by_digest(const char *digest)
  2793. {
  2794. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2795. {
  2796. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  2797. return ns;
  2798. });
  2799. return NULL;
  2800. }
  2801. /** We believe networkstatuses more recent than this when they tell us that
  2802. * our server is broken, invalid, obsolete, etc. */
  2803. #define SELF_OPINION_INTERVAL (90*60)
  2804. /** Result of checking whether a version is recommended. */
  2805. typedef struct combined_version_status_t {
  2806. /** How many networkstatuses claim to know about versions? */
  2807. int n_versioning;
  2808. /** What do the majority of networkstatuses believe about this version? */
  2809. version_status_t consensus;
  2810. /** How many networkstatuses constitute the majority? */
  2811. int n_concurring;
  2812. } combined_version_status_t;
  2813. /** Return a string naming the versions of Tor recommended by
  2814. * more than half the versioning networkstatuses. */
  2815. static char *
  2816. compute_recommended_versions(time_t now, int client,
  2817. const char *my_version,
  2818. combined_version_status_t *status_out)
  2819. {
  2820. int n_seen;
  2821. char *current;
  2822. smartlist_t *combined, *recommended;
  2823. int n_versioning, n_recommending;
  2824. char *result;
  2825. /** holds the compromise status taken among all non-recommending
  2826. * authorities */
  2827. version_status_t consensus = VS_RECOMMENDED;
  2828. (void) now; /* right now, we consider *all* statuses, regardless of age. */
  2829. tor_assert(my_version);
  2830. tor_assert(status_out);
  2831. memset(status_out, 0, sizeof(combined_version_status_t));
  2832. if (!networkstatus_list)
  2833. return tor_strdup("<none>");
  2834. combined = smartlist_create();
  2835. n_versioning = n_recommending = 0;
  2836. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2837. {
  2838. const char *vers;
  2839. smartlist_t *versions;
  2840. version_status_t status;
  2841. if (! ns->recommends_versions)
  2842. continue;
  2843. n_versioning++;
  2844. vers = client ? ns->client_versions : ns->server_versions;
  2845. if (!vers)
  2846. continue;
  2847. versions = smartlist_create();
  2848. smartlist_split_string(versions, vers, ",",
  2849. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2850. sort_version_list(versions, 1);
  2851. smartlist_add_all(combined, versions);
  2852. smartlist_free(versions);
  2853. /* now, check _our_ version */
  2854. status = tor_version_is_obsolete(my_version, vers);
  2855. if (status == VS_RECOMMENDED)
  2856. n_recommending++;
  2857. consensus = version_status_join(status, consensus);
  2858. });
  2859. sort_version_list(combined, 0);
  2860. current = NULL;
  2861. n_seen = 0;
  2862. recommended = smartlist_create();
  2863. SMARTLIST_FOREACH(combined, char *, cp,
  2864. {
  2865. if (current && !strcmp(cp, current)) {
  2866. ++n_seen;
  2867. } else {
  2868. if (n_seen > n_versioning/2 && current)
  2869. smartlist_add(recommended, current);
  2870. n_seen = 0;
  2871. current = cp;
  2872. }
  2873. });
  2874. if (n_seen > n_versioning/2 && current)
  2875. smartlist_add(recommended, current);
  2876. result = smartlist_join_strings(recommended, ", ", 0, NULL);
  2877. SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
  2878. smartlist_free(combined);
  2879. smartlist_free(recommended);
  2880. status_out->n_versioning = n_versioning;
  2881. if (n_recommending > n_versioning/2) {
  2882. status_out->consensus = VS_RECOMMENDED;
  2883. status_out->n_concurring = n_recommending;
  2884. } else {
  2885. status_out->consensus = consensus;
  2886. status_out->n_concurring = n_versioning - n_recommending;
  2887. }
  2888. return result;
  2889. }
  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 set up router statuses? */
  2892. #define N_NS_ATTEMPTS_TO_SET_ROUTERS 4
  2893. /** How many times do we have to fail at getting a networkstatus we can't find
  2894. * before we're willing to believe it's okay to check our version? */
  2895. #define N_NS_ATTEMPTS_TO_CHECK_VERSION 4
  2896. /** If the network-status list has changed since the last time we called this
  2897. * function, update the status of every routerinfo from the network-status
  2898. * list.
  2899. */
  2900. void
  2901. routers_update_all_from_networkstatus(void)
  2902. {
  2903. routerinfo_t *me;
  2904. time_t now;
  2905. if (!routerlist || !networkstatus_list ||
  2906. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  2907. return;
  2908. router_dir_info_changed();
  2909. now = time(NULL);
  2910. if (networkstatus_list_has_changed)
  2911. routerstatus_list_update_from_networkstatus(now);
  2912. routers_update_status_from_networkstatus(routerlist->routers, 0);
  2913. me = router_get_my_routerinfo();
  2914. if (me && !have_warned_about_invalid_status &&
  2915. have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_SET_ROUTERS)) {
  2916. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0, n_naming = 0;
  2917. routerstatus_t *rs;
  2918. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2919. {
  2920. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  2921. continue;
  2922. ++n_recent;
  2923. if (ns->binds_names)
  2924. ++n_naming;
  2925. if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
  2926. continue;
  2927. ++n_listing;
  2928. if (rs->is_valid)
  2929. ++n_valid;
  2930. if (rs->is_named)
  2931. ++n_named;
  2932. });
  2933. if (n_listing) {
  2934. if (n_valid <= n_listing/2) {
  2935. log_info(LD_GENERAL,
  2936. "%d/%d recent statements from directory authorities list us "
  2937. "as unapproved. Are you misconfigured?",
  2938. n_listing-n_valid, n_listing);
  2939. have_warned_about_invalid_status = 1;
  2940. } else if (n_naming && !n_named) {
  2941. log_info(LD_GENERAL, "0/%d name-binding directory authorities "
  2942. "recognize your nickname. Please consider sending your "
  2943. "nickname and identity fingerprint to the tor-ops.",
  2944. n_naming);
  2945. have_warned_about_invalid_status = 1;
  2946. }
  2947. }
  2948. }
  2949. entry_guards_compute_status();
  2950. if (!have_warned_about_old_version &&
  2951. have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_CHECK_VERSION)) {
  2952. combined_version_status_t st;
  2953. int is_server = server_mode(get_options());
  2954. char *recommended;
  2955. recommended = compute_recommended_versions(now, !is_server, VERSION, &st);
  2956. if (st.n_versioning) {
  2957. if (st.consensus == VS_RECOMMENDED) {
  2958. log_info(LD_GENERAL, "%d/%d statements from version-listing "
  2959. "directory authorities say my version is ok.",
  2960. st.n_concurring, st.n_versioning);
  2961. } else if (st.consensus == VS_NEW || st.consensus == VS_NEW_IN_SERIES) {
  2962. if (!have_warned_about_new_version) {
  2963. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  2964. "recommended version%s, according to %d/%d version-listing "
  2965. "network statuses. Versions recommended by more than %d "
  2966. "authorit%s are: %s",
  2967. VERSION,
  2968. st.consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  2969. st.n_concurring, st.n_versioning, st.n_versioning/2,
  2970. st.n_versioning/2 > 1 ? "ies" : "y", recommended);
  2971. have_warned_about_new_version = 1;
  2972. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  2973. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  2974. VERSION, "NEW", recommended);
  2975. }
  2976. } else {
  2977. log_warn(LD_GENERAL, "Please upgrade! "
  2978. "This version of Tor (%s) is %s, according to %d/%d version-"
  2979. "listing network statuses. Versions recommended by "
  2980. "at least %d authorit%s are: %s",
  2981. VERSION,
  2982. st.consensus == VS_OLD ? "obsolete" : "not recommended",
  2983. st.n_concurring, st.n_versioning, st.n_versioning/2,
  2984. st.n_versioning/2 > 1 ? "ies" : "y", recommended);
  2985. have_warned_about_old_version = 1;
  2986. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  2987. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  2988. VERSION, st.consensus == VS_OLD ? "OLD" : "UNRECOMMENDED",
  2989. recommended);
  2990. }
  2991. }
  2992. tor_free(recommended);
  2993. }
  2994. routerstatus_list_has_changed = 0;
  2995. }
  2996. /** Allow any network-status newer than this to influence our view of who's
  2997. * running. */
  2998. #define DEFAULT_RUNNING_INTERVAL (60*60)
  2999. /** If possible, always allow at least this many network-statuses to influence
  3000. * our view of who's running. */
  3001. #define MIN_TO_INFLUENCE_RUNNING 3
  3002. /** Change the is_recent field of each member of networkstatus_list so that
  3003. * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
  3004. * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
  3005. * others are recent. Set networkstatus_list_has_changed if anything happened.
  3006. */
  3007. void
  3008. networkstatus_list_update_recent(time_t now)
  3009. {
  3010. int n_statuses, n_recent, changed, i;
  3011. char published[ISO_TIME_LEN+1];
  3012. if (!networkstatus_list)
  3013. return;
  3014. n_statuses = smartlist_len(networkstatus_list);
  3015. n_recent = 0;
  3016. changed = 0;
  3017. for (i=n_statuses-1; i >= 0; --i) {
  3018. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  3019. trusted_dir_server_t *ds =
  3020. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3021. const char *src = ds?ds->description:ns->source_address;
  3022. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  3023. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  3024. if (!ns->is_recent) {
  3025. format_iso_time(published, ns->published_on);
  3026. log_info(LD_DIR,
  3027. "Networkstatus from %s (published %s) is now \"recent\"",
  3028. src, published);
  3029. changed = 1;
  3030. }
  3031. ns->is_recent = 1;
  3032. ++n_recent;
  3033. } else {
  3034. if (ns->is_recent) {
  3035. format_iso_time(published, ns->published_on);
  3036. log_info(LD_DIR,
  3037. "Networkstatus from %s (published %s) is "
  3038. "no longer \"recent\"",
  3039. src, published);
  3040. changed = 1;
  3041. ns->is_recent = 0;
  3042. }
  3043. }
  3044. }
  3045. if (changed) {
  3046. networkstatus_list_has_changed = 1;
  3047. router_dir_info_changed();
  3048. }
  3049. }
  3050. /** Helper for routerstatus_list_update_from_networkstatus: remember how many
  3051. * authorities recommend a given descriptor digest. */
  3052. typedef struct {
  3053. routerstatus_t *rs;
  3054. int count;
  3055. } desc_digest_count_t;
  3056. /** Update our view of router status (as stored in routerstatus_list) from the
  3057. * current set of network status documents (as stored in networkstatus_list).
  3058. * Do nothing unless the network status list has changed since the last time
  3059. * this function was called.
  3060. */
  3061. static void
  3062. routerstatus_list_update_from_networkstatus(time_t now)
  3063. {
  3064. or_options_t *options = get_options();
  3065. int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
  3066. int n_listing_bad_exits = 0, n_listing_bad_directories = 0;
  3067. int i, j, warned;
  3068. int *index, *size;
  3069. networkstatus_t **networkstatus;
  3070. smartlist_t *result, *changed_list;
  3071. strmap_t *name_map;
  3072. char conflict[DIGEST_LEN]; /* Sentinel value */
  3073. desc_digest_count_t *digest_counts = NULL;
  3074. /* compute which network statuses will have a vote now */
  3075. networkstatus_list_update_recent(now);
  3076. router_dir_info_changed();
  3077. if (!networkstatus_list_has_changed)
  3078. return;
  3079. if (!networkstatus_list)
  3080. networkstatus_list = smartlist_create();
  3081. if (!routerstatus_list)
  3082. routerstatus_list = smartlist_create();
  3083. if (!trusted_dir_servers)
  3084. trusted_dir_servers = smartlist_create();
  3085. if (!warned_conflicts)
  3086. warned_conflicts = smartlist_create();
  3087. n_statuses = smartlist_len(networkstatus_list);
  3088. n_trusted = get_n_v2_authorities();
  3089. if (n_statuses <= n_trusted/2) {
  3090. /* Not enough statuses to adjust status. */
  3091. log_info(LD_DIR,
  3092. "Not enough statuses to update router status list. (%d/%d)",
  3093. n_statuses, n_trusted);
  3094. return;
  3095. }
  3096. log_info(LD_DIR, "Rebuilding router status list.");
  3097. index = tor_malloc(sizeof(int)*n_statuses);
  3098. size = tor_malloc(sizeof(int)*n_statuses);
  3099. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  3100. for (i = 0; i < n_statuses; ++i) {
  3101. index[i] = 0;
  3102. networkstatus[i] = smartlist_get(networkstatus_list, i);
  3103. size[i] = smartlist_len(networkstatus[i]->entries);
  3104. if (networkstatus[i]->binds_names)
  3105. ++n_naming;
  3106. if (networkstatus[i]->is_recent)
  3107. ++n_recent;
  3108. if (networkstatus[i]->lists_bad_exits)
  3109. ++n_listing_bad_exits;
  3110. if (networkstatus[i]->lists_bad_directories)
  3111. ++n_listing_bad_directories;
  3112. }
  3113. /** Iterate over all entries in all networkstatuses, and build
  3114. * name_map as a map from lc nickname to identity digest. If there
  3115. * is a conflict on that nickname, map the lc nickname to conflict.
  3116. */
  3117. name_map = strmap_new();
  3118. /* Clear the global map... */
  3119. if (named_server_map)
  3120. strmap_free(named_server_map, _tor_free);
  3121. named_server_map = strmap_new();
  3122. memset(conflict, 0xff, sizeof(conflict));
  3123. for (i = 0; i < n_statuses; ++i) {
  3124. if (!networkstatus[i]->binds_names)
  3125. continue;
  3126. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  3127. {
  3128. const char *other_digest;
  3129. if (!rs->is_named)
  3130. continue;
  3131. other_digest = strmap_get_lc(name_map, rs->nickname);
  3132. warned = smartlist_string_isin(warned_conflicts, rs->nickname);
  3133. if (!other_digest) {
  3134. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  3135. strmap_set_lc(named_server_map, rs->nickname,
  3136. tor_memdup(rs->identity_digest, DIGEST_LEN));
  3137. if (warned)
  3138. smartlist_string_remove(warned_conflicts, rs->nickname);
  3139. } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  3140. other_digest != conflict) {
  3141. if (!warned) {
  3142. char *d;
  3143. int should_warn = options->DirPort && options->AuthoritativeDir;
  3144. char fp1[HEX_DIGEST_LEN+1];
  3145. char fp2[HEX_DIGEST_LEN+1];
  3146. base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
  3147. base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
  3148. log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
  3149. "Naming authorities disagree about which key goes with %s. "
  3150. "($%s vs $%s)",
  3151. rs->nickname, fp1, fp2);
  3152. strmap_set_lc(name_map, rs->nickname, conflict);
  3153. d = strmap_remove_lc(named_server_map, rs->nickname);
  3154. tor_free(d);
  3155. smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
  3156. }
  3157. } else {
  3158. if (warned)
  3159. smartlist_string_remove(warned_conflicts, rs->nickname);
  3160. }
  3161. });
  3162. }
  3163. result = smartlist_create();
  3164. changed_list = smartlist_create();
  3165. digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
  3166. /* Iterate through all of the sorted routerstatus lists in lockstep.
  3167. * Invariants:
  3168. * - For 0 <= i < n_statuses: index[i] is an index into
  3169. * networkstatus[i]->entries, which has size[i] elements.
  3170. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  3171. * j < index[i1]: networkstatus[i1]->entries[j]->identity_digest <
  3172. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  3173. *
  3174. * (That is, the indices are always advanced past lower digest before
  3175. * higher.)
  3176. */
  3177. while (1) {
  3178. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  3179. int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0, n_bad_exit=0;
  3180. int n_bad_directory=0;
  3181. int n_version_known=0, n_supports_begindir=0;
  3182. int n_desc_digests=0, highest_count=0;
  3183. const char *the_name = NULL;
  3184. local_routerstatus_t *rs_out, *rs_old;
  3185. routerstatus_t *rs, *most_recent;
  3186. networkstatus_t *ns;
  3187. const char *lowest = NULL;
  3188. /* Find out which of the digests appears first. */
  3189. for (i = 0; i < n_statuses; ++i) {
  3190. if (index[i] < size[i]) {
  3191. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  3192. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  3193. lowest = rs->identity_digest;
  3194. }
  3195. }
  3196. if (!lowest) {
  3197. /* We're out of routers. Great! */
  3198. break;
  3199. }
  3200. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  3201. * match "lowest" are next in order. Iterate over them, incrementing those
  3202. * index[i] as we go. */
  3203. for (i = 0; i < n_statuses; ++i) {
  3204. if (index[i] >= size[i])
  3205. continue;
  3206. ns = networkstatus[i];
  3207. rs = smartlist_get(ns->entries, index[i]);
  3208. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  3209. continue;
  3210. /* At this point, we know that we're looking at a routersatus with
  3211. * identity "lowest".
  3212. */
  3213. ++index[i];
  3214. ++n_listing;
  3215. /* Should we name this router? Only if all the names from naming
  3216. * authorities match. */
  3217. if (rs->is_named && ns->binds_names) {
  3218. if (!the_name)
  3219. the_name = rs->nickname;
  3220. if (!strcasecmp(rs->nickname, the_name)) {
  3221. ++n_named;
  3222. } else if (strcmp(the_name,"**mismatch**")) {
  3223. char hd[HEX_DIGEST_LEN+1];
  3224. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  3225. if (! smartlist_string_isin(warned_conflicts, hd)) {
  3226. log_warn(LD_DIR,
  3227. "Naming authorities disagree about nicknames for $%s "
  3228. "(\"%s\" vs \"%s\")",
  3229. hd, the_name, rs->nickname);
  3230. smartlist_add(warned_conflicts, tor_strdup(hd));
  3231. }
  3232. the_name = "**mismatch**";
  3233. }
  3234. }
  3235. /* Keep a running count of how often which descriptor digests
  3236. * appear. */
  3237. for (j = 0; j < n_desc_digests; ++j) {
  3238. if (!memcmp(rs->descriptor_digest,
  3239. digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
  3240. if (++digest_counts[j].count > highest_count)
  3241. highest_count = digest_counts[j].count;
  3242. goto found;
  3243. }
  3244. }
  3245. digest_counts[n_desc_digests].rs = rs;
  3246. digest_counts[n_desc_digests].count = 1;
  3247. if (!highest_count)
  3248. highest_count = 1;
  3249. ++n_desc_digests;
  3250. found:
  3251. /* Now tally up the easily-tallied flags. */
  3252. if (rs->is_valid)
  3253. ++n_valid;
  3254. if (rs->is_running && ns->is_recent)
  3255. ++n_running;
  3256. if (rs->is_exit)
  3257. ++n_exit;
  3258. if (rs->is_fast)
  3259. ++n_fast;
  3260. if (rs->is_possible_guard)
  3261. ++n_guard;
  3262. if (rs->is_stable)
  3263. ++n_stable;
  3264. if (rs->is_v2_dir)
  3265. ++n_v2_dir;
  3266. if (rs->is_bad_exit)
  3267. ++n_bad_exit;
  3268. if (rs->is_bad_directory)
  3269. ++n_bad_directory;
  3270. if (rs->version_known)
  3271. ++n_version_known;
  3272. if (rs->version_supports_begindir)
  3273. ++n_supports_begindir;
  3274. }
  3275. /* Go over the descriptor digests and figure out which descriptor we
  3276. * want. */
  3277. most_recent = NULL;
  3278. for (i = 0; i < n_desc_digests; ++i) {
  3279. /* If any digest appears twice or more, ignore those that don't.*/
  3280. if (highest_count >= 2 && digest_counts[i].count < 2)
  3281. continue;
  3282. if (!most_recent ||
  3283. digest_counts[i].rs->published_on > most_recent->published_on)
  3284. most_recent = digest_counts[i].rs;
  3285. }
  3286. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  3287. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  3288. /* Copy status info about this router, if we had any before. */
  3289. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  3290. if (!memcmp(rs_out->status.descriptor_digest,
  3291. most_recent->descriptor_digest, DIGEST_LEN)) {
  3292. rs_out->n_download_failures = rs_old->n_download_failures;
  3293. rs_out->next_attempt_at = rs_old->next_attempt_at;
  3294. }
  3295. rs_out->name_lookup_warned = rs_old->name_lookup_warned;
  3296. rs_out->last_dir_503_at = rs_old->last_dir_503_at;
  3297. }
  3298. smartlist_add(result, rs_out);
  3299. log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
  3300. "named by %d/%d, validated by %d/%d, and %d/%d recent "
  3301. "directories think it's running.",
  3302. rs_out->status.nickname,
  3303. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  3304. n_running, n_recent);
  3305. rs_out->status.is_named = 0;
  3306. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  3307. const char *d = strmap_get_lc(name_map, the_name);
  3308. if (d && d != conflict)
  3309. rs_out->status.is_named = 1;
  3310. if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
  3311. smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
  3312. }
  3313. if (rs_out->status.is_named)
  3314. strlcpy(rs_out->status.nickname, the_name,
  3315. sizeof(rs_out->status.nickname));
  3316. rs_out->status.is_valid = n_valid > n_statuses/2;
  3317. rs_out->status.is_running = n_running > n_recent/2;
  3318. rs_out->status.is_exit = n_exit > n_statuses/2;
  3319. rs_out->status.is_fast = n_fast > n_statuses/2;
  3320. rs_out->status.is_possible_guard = n_guard > n_statuses/2;
  3321. rs_out->status.is_stable = n_stable > n_statuses/2;
  3322. rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
  3323. rs_out->status.is_bad_exit = n_bad_exit > n_listing_bad_exits/2;
  3324. rs_out->status.is_bad_directory =
  3325. n_bad_directory > n_listing_bad_directories/2;
  3326. rs_out->status.version_known = n_version_known > 0;
  3327. rs_out->status.version_supports_begindir =
  3328. n_supports_begindir > n_version_known/2;
  3329. if (!rs_old || memcmp(rs_old, rs_out, sizeof(local_routerstatus_t)))
  3330. smartlist_add(changed_list, rs_out);
  3331. }
  3332. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3333. local_routerstatus_free(rs));
  3334. smartlist_free(routerstatus_list);
  3335. routerstatus_list = result;
  3336. tor_free(networkstatus);
  3337. tor_free(index);
  3338. tor_free(size);
  3339. tor_free(digest_counts);
  3340. strmap_free(name_map, NULL);
  3341. networkstatus_list_has_changed = 0;
  3342. routerstatus_list_has_changed = 1;
  3343. control_event_networkstatus_changed(changed_list);
  3344. smartlist_free(changed_list);
  3345. }
  3346. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  3347. * is_named, is_valid, and is_running fields according to our current
  3348. * networkstatus_t documents. */
  3349. void
  3350. routers_update_status_from_networkstatus(smartlist_t *routers,
  3351. int reset_failures)
  3352. {
  3353. trusted_dir_server_t *ds;
  3354. local_routerstatus_t *rs;
  3355. or_options_t *options = get_options();
  3356. int authdir = options->AuthoritativeDir;
  3357. int namingdir = options->AuthoritativeDir &&
  3358. options->NamingAuthoritativeDir;
  3359. if (!routerstatus_list)
  3360. return;
  3361. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  3362. {
  3363. const char *digest = router->cache_info.identity_digest;
  3364. rs = router_get_combined_status_by_digest(digest);
  3365. ds = router_get_trusteddirserver_by_digest(digest);
  3366. if (!rs)
  3367. continue;
  3368. if (!namingdir)
  3369. router->is_named = rs->status.is_named;
  3370. if (!authdir) {
  3371. /* If we're not an authdir, believe others. */
  3372. router->is_valid = rs->status.is_valid;
  3373. router->is_running = rs->status.is_running;
  3374. router->is_fast = rs->status.is_fast;
  3375. router->is_stable = rs->status.is_stable;
  3376. router->is_possible_guard = rs->status.is_possible_guard;
  3377. router->is_exit = rs->status.is_exit;
  3378. router->is_bad_exit = rs->status.is_bad_exit;
  3379. }
  3380. if (router->is_running && ds) {
  3381. ds->n_networkstatus_failures = 0;
  3382. }
  3383. if (reset_failures) {
  3384. rs->n_download_failures = 0;
  3385. rs->next_attempt_at = 0;
  3386. }
  3387. });
  3388. router_dir_info_changed();
  3389. }
  3390. /** For every router descriptor we are currently downloading by descriptor
  3391. * digest, set result[d] to 1. */
  3392. static void
  3393. list_pending_descriptor_downloads(digestmap_t *result)
  3394. {
  3395. const char *prefix = "d/";
  3396. size_t p_len = strlen(prefix);
  3397. int i, n_conns;
  3398. connection_t **carray;
  3399. smartlist_t *tmp = smartlist_create();
  3400. tor_assert(result);
  3401. get_connection_array(&carray, &n_conns);
  3402. for (i = 0; i < n_conns; ++i) {
  3403. connection_t *conn = carray[i];
  3404. if (conn->type == CONN_TYPE_DIR &&
  3405. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  3406. !conn->marked_for_close) {
  3407. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3408. if (!strcmpstart(resource, prefix))
  3409. dir_split_resource_into_fingerprints(resource + p_len,
  3410. tmp, NULL, 1, 0);
  3411. }
  3412. }
  3413. SMARTLIST_FOREACH(tmp, char *, d,
  3414. {
  3415. digestmap_set(result, d, (void*)1);
  3416. tor_free(d);
  3417. });
  3418. smartlist_free(tmp);
  3419. }
  3420. /** Launch downloads for all the descriptors whose digests are listed
  3421. * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
  3422. * If <b>source</b> is given, download from <b>source</b>; otherwise,
  3423. * download from an appropriate random directory server.
  3424. */
  3425. static void
  3426. initiate_descriptor_downloads(routerstatus_t *source,
  3427. smartlist_t *digests,
  3428. int lo, int hi)
  3429. {
  3430. int i, n = hi-lo;
  3431. char *resource, *cp;
  3432. size_t r_len;
  3433. if (n <= 0)
  3434. return;
  3435. if (lo < 0)
  3436. lo = 0;
  3437. if (hi > smartlist_len(digests))
  3438. hi = smartlist_len(digests);
  3439. r_len = 8 + (HEX_DIGEST_LEN+1)*n;
  3440. cp = resource = tor_malloc(r_len);
  3441. memcpy(cp, "d/", 2);
  3442. cp += 2;
  3443. for (i = lo; i < hi; ++i) {
  3444. base16_encode(cp, r_len-(cp-resource),
  3445. smartlist_get(digests,i), DIGEST_LEN);
  3446. cp += HEX_DIGEST_LEN;
  3447. *cp++ = '+';
  3448. }
  3449. memcpy(cp-1, ".z", 3);
  3450. if (source) {
  3451. /* We know which authority we want. */
  3452. directory_initiate_command_routerstatus(source,
  3453. DIR_PURPOSE_FETCH_SERVERDESC,
  3454. 0, /* not private */
  3455. resource, NULL, 0);
  3456. } else {
  3457. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  3458. resource,
  3459. 1);
  3460. }
  3461. tor_free(resource);
  3462. }
  3463. /** Clients don't download any descriptor this recent, since it will probably
  3464. * not have propageted to enough caches. */
  3465. #define ESTIMATED_PROPAGATION_TIME (10*60)
  3466. /** Return 0 if this routerstatus is obsolete, too new, isn't
  3467. * running, or otherwise not a descriptor that we would make any
  3468. * use of even if we had it. Else return 1. */
  3469. static INLINE int
  3470. client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
  3471. {
  3472. if (!rs->is_running && !options->FetchUselessDescriptors) {
  3473. /* If we had this router descriptor, we wouldn't even bother using it.
  3474. * But, if we want to have a complete list, fetch it anyway. */
  3475. return 0;
  3476. }
  3477. if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
  3478. /* Most caches probably don't have this descriptor yet. */
  3479. return 0;
  3480. }
  3481. return 1;
  3482. }
  3483. /** Return new list of ID fingerprints for routers that we (as a client) would
  3484. * like to download.
  3485. */
  3486. static smartlist_t *
  3487. router_list_client_downloadable(void)
  3488. {
  3489. int n_downloadable = 0;
  3490. smartlist_t *downloadable = smartlist_create();
  3491. digestmap_t *downloading;
  3492. time_t now = time(NULL);
  3493. /* these are just used for logging */
  3494. int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_wouldnt_use = 0;
  3495. or_options_t *options = get_options();
  3496. if (!routerstatus_list)
  3497. return downloadable;
  3498. downloading = digestmap_new();
  3499. list_pending_descriptor_downloads(downloading);
  3500. routerstatus_list_update_from_networkstatus(now);
  3501. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3502. {
  3503. routerinfo_t *ri;
  3504. if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
  3505. /* We have the 'best' descriptor for this router. */
  3506. ++n_uptodate;
  3507. } else if (!client_would_use_router(&rs->status, now, options)) {
  3508. /* We wouldn't want this descriptor even if we got it. */
  3509. ++n_wouldnt_use;
  3510. } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
  3511. /* We're downloading this one now. */
  3512. ++n_in_progress;
  3513. } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
  3514. ri->cache_info.published_on > rs->status.published_on) {
  3515. /* Oddly, we have a descriptor more recent than the 'best' one, but it
  3516. was once best. So that's okay. */
  3517. ++n_uptodate;
  3518. } else if (rs->next_attempt_at > now) {
  3519. /* We failed too recently to try again. */
  3520. ++n_not_ready;
  3521. } else {
  3522. /* Okay, time to try it. */
  3523. smartlist_add(downloadable, rs->status.descriptor_digest);
  3524. ++n_downloadable;
  3525. }
  3526. });
  3527. #if 0
  3528. log_info(LD_DIR,
  3529. "%d router descriptors are downloadable. "
  3530. "%d are in progress. %d are up-to-date. "
  3531. "%d are non-useful. %d failed too recently to retry.",
  3532. n_downloadable, n_in_progress, n_uptodate,
  3533. n_wouldnt_use, n_not_ready);
  3534. #endif
  3535. digestmap_free(downloading, NULL);
  3536. return downloadable;
  3537. }
  3538. /** Initiate new router downloads as needed, using the strategy for
  3539. * non-directory-servers.
  3540. *
  3541. * We don't launch any downloads if there are fewer than MAX_DL_TO_DELAY
  3542. * descriptors to get and less than MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
  3543. * seconds have passed.
  3544. *
  3545. * Otherwise, we ask for all descriptors that we think are different from what
  3546. * we have, and that we don't currently have an in-progress download attempt
  3547. * for. */
  3548. static void
  3549. update_router_descriptor_client_downloads(time_t now)
  3550. {
  3551. /** Max amount of hashes to download per request.
  3552. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3553. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3554. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3555. * So use 96 because it's a nice number.
  3556. */
  3557. #define MAX_DL_PER_REQUEST 96
  3558. /** Don't split our requests so finely that we are requesting fewer than
  3559. * this number per server. */
  3560. #define MIN_DL_PER_REQUEST 4
  3561. /** To prevent a single screwy cache from confusing us by selective reply,
  3562. * try to split our requests into at least this this many requests. */
  3563. #define MIN_REQUESTS 3
  3564. /** If we want fewer than this many descriptors, wait until we
  3565. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3566. * passed. */
  3567. #define MAX_DL_TO_DELAY 16
  3568. /** When directory clients have only a few servers to request, they batch
  3569. * them until they have more, or until this amount of time has passed. */
  3570. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3571. smartlist_t *downloadable = NULL;
  3572. int should_delay, n_downloadable;
  3573. or_options_t *options = get_options();
  3574. if (options->DirPort) {
  3575. log_warn(LD_BUG,
  3576. "Called router_descriptor_client_downloads() on a dir mirror?");
  3577. }
  3578. if (rep_hist_circbuilding_dormant(now)) {
  3579. log_info(LD_CIRC, "Skipping descriptor downloads: we haven't needed "
  3580. "any circuits lately.");
  3581. return;
  3582. }
  3583. if (networkstatus_list &&
  3584. smartlist_len(networkstatus_list) <= get_n_v2_authorities()/2) {
  3585. log_info(LD_DIR,
  3586. "Not enough networkstatus documents to launch requests.");
  3587. return;
  3588. }
  3589. downloadable = router_list_client_downloadable();
  3590. n_downloadable = smartlist_len(downloadable);
  3591. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3592. log_debug(LD_DIR,
  3593. "There are enough downloadable routerdescs to launch requests.");
  3594. should_delay = 0;
  3595. } else if (n_downloadable == 0) {
  3596. // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
  3597. should_delay = 1;
  3598. } else {
  3599. should_delay = (last_routerdesc_download_attempted +
  3600. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3601. if (!should_delay) {
  3602. if (last_routerdesc_download_attempted) {
  3603. log_info(LD_DIR,
  3604. "There are not many downloadable routerdescs, but we've "
  3605. "been waiting long enough (%d seconds). Downloading.",
  3606. (int)(now-last_routerdesc_download_attempted));
  3607. } else {
  3608. log_info(LD_DIR,
  3609. "There are not many downloadable routerdescs, but we haven't "
  3610. "tried downloading descriptors recently. Downloading.");
  3611. }
  3612. }
  3613. }
  3614. if (! should_delay) {
  3615. int i, n_per_request;
  3616. n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
  3617. if (n_per_request > MAX_DL_PER_REQUEST)
  3618. n_per_request = MAX_DL_PER_REQUEST;
  3619. if (n_per_request < MIN_DL_PER_REQUEST)
  3620. n_per_request = MIN_DL_PER_REQUEST;
  3621. log_info(LD_DIR,
  3622. "Launching %d request%s for %d router%s, %d at a time",
  3623. (n_downloadable+n_per_request-1)/n_per_request,
  3624. n_downloadable>n_per_request?"s":"",
  3625. n_downloadable, n_downloadable>1?"s":"", n_per_request);
  3626. smartlist_sort_digests(downloadable);
  3627. for (i=0; i < n_downloadable; i += n_per_request) {
  3628. initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
  3629. }
  3630. last_routerdesc_download_attempted = now;
  3631. }
  3632. smartlist_free(downloadable);
  3633. }
  3634. /** Launch downloads for router status as needed, using the strategy used by
  3635. * authorities and caches: download every descriptor we don't have but would
  3636. * serve, from a random authority that lists it. */
  3637. static void
  3638. update_router_descriptor_cache_downloads(time_t now)
  3639. {
  3640. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3641. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3642. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3643. int i, j, n;
  3644. int n_download;
  3645. or_options_t *options = get_options();
  3646. (void) now;
  3647. if (!options->DirPort) {
  3648. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
  3649. "on a non-dir-mirror?");
  3650. }
  3651. if (!networkstatus_list || !smartlist_len(networkstatus_list))
  3652. return;
  3653. map = digestmap_new();
  3654. n = smartlist_len(networkstatus_list);
  3655. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3656. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3657. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3658. * downloading. */
  3659. list_pending_descriptor_downloads(map);
  3660. /* For the digest of every descriptor that we don't have, and that we aren't
  3661. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3662. * about that descriptor, and we haven't already failed to get that
  3663. * descriptor from the corresponding authority.
  3664. */
  3665. n_download = 0;
  3666. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3667. {
  3668. smartlist_t *dl;
  3669. dl = downloadable[ns_sl_idx] = smartlist_create();
  3670. download_from[ns_sl_idx] = smartlist_create();
  3671. if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
  3672. /* Don't download if the networkstatus is almost ancient. */
  3673. /* Actually, I suspect what's happening here is that we ask
  3674. * for the descriptor when we have a given networkstatus,
  3675. * and then we get a newer networkstatus, and then we receive
  3676. * the descriptor. Having a networkstatus actually expire is
  3677. * probably a rare event, and we'll probably be happiest if
  3678. * we take this clause out. -RD */
  3679. continue;
  3680. }
  3681. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  3682. {
  3683. if (!rs->need_to_mirror)
  3684. continue;
  3685. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3686. log_warn(LD_BUG,
  3687. "Bug: We have a router descriptor, but need_to_mirror=1.");
  3688. rs->need_to_mirror = 0;
  3689. continue;
  3690. }
  3691. if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
  3692. rs->need_to_mirror = 0;
  3693. continue;
  3694. }
  3695. if (digestmap_get(map, rs->descriptor_digest)) {
  3696. /* We're downloading it already. */
  3697. continue;
  3698. } else {
  3699. /* We could download it from this guy. */
  3700. smartlist_add(dl, rs->descriptor_digest);
  3701. ++n_download;
  3702. }
  3703. });
  3704. });
  3705. /* At random, assign descriptors to authorities such that:
  3706. * - if d is a member of some downloadable[x], d is a member of some
  3707. * download_from[y]. (Everything we want to download, we try to download
  3708. * from somebody.)
  3709. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3710. * (We only try to download descriptors from authorities who claim to have
  3711. * them.)
  3712. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3713. * (We don't try to download anything from two authorities concurrently.)
  3714. */
  3715. while (n_download) {
  3716. int which_ns = crypto_rand_int(n);
  3717. smartlist_t *dl = downloadable[which_ns];
  3718. int idx;
  3719. char *d;
  3720. if (!smartlist_len(dl))
  3721. continue;
  3722. idx = crypto_rand_int(smartlist_len(dl));
  3723. d = smartlist_get(dl, idx);
  3724. if (! digestmap_get(map, d)) {
  3725. smartlist_add(download_from[which_ns], d);
  3726. digestmap_set(map, d, (void*) 1);
  3727. }
  3728. smartlist_del(dl, idx);
  3729. --n_download;
  3730. }
  3731. /* Now, we can actually launch our requests. */
  3732. for (i=0; i<n; ++i) {
  3733. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  3734. trusted_dir_server_t *ds =
  3735. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3736. smartlist_t *dl = download_from[i];
  3737. if (!ds) {
  3738. log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
  3739. continue;
  3740. }
  3741. if (! smartlist_len(dl))
  3742. continue;
  3743. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3744. smartlist_len(dl), ds->nickname);
  3745. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3746. initiate_descriptor_downloads(&(ds->fake_status.status), dl, j,
  3747. j+MAX_DL_PER_REQUEST);
  3748. }
  3749. }
  3750. for (i=0; i<n; ++i) {
  3751. smartlist_free(download_from[i]);
  3752. smartlist_free(downloadable[i]);
  3753. }
  3754. tor_free(download_from);
  3755. tor_free(downloadable);
  3756. digestmap_free(map,NULL);
  3757. }
  3758. /** Launch downloads for router status as needed. */
  3759. void
  3760. update_router_descriptor_downloads(time_t now)
  3761. {
  3762. or_options_t *options = get_options();
  3763. if (options->DirPort) {
  3764. update_router_descriptor_cache_downloads(now);
  3765. } else {
  3766. update_router_descriptor_client_downloads(now);
  3767. }
  3768. }
  3769. /** Return the number of routerstatus_t in <b>entries</b> that we'd actually
  3770. * use. */
  3771. static int
  3772. routerstatus_count_usable_entries(smartlist_t *entries)
  3773. {
  3774. int count = 0;
  3775. time_t now = time(NULL);
  3776. or_options_t *options = get_options();
  3777. SMARTLIST_FOREACH(entries, routerstatus_t *, rs,
  3778. if (client_would_use_router(rs, now, options)) count++);
  3779. return count;
  3780. }
  3781. /** True iff, the last time we checked whether we had enough directory info
  3782. * to build circuits, the answer was "yes". */
  3783. static int have_min_dir_info = 0;
  3784. /** True iff enough has changed since the last time we checked whether we had
  3785. * enough directory info to build circuits that our old answer can no longer
  3786. * be trusted. */
  3787. static int need_to_update_have_min_dir_info = 1;
  3788. /** Return true iff we have enough networkstatus and router information to
  3789. * start building circuits. Right now, this means "more than half the
  3790. * networkstatus documents, and at least 1/4 of expected routers." */
  3791. //XXX should consider whether we have enough exiting nodes here.
  3792. int
  3793. router_have_minimum_dir_info(void)
  3794. {
  3795. if (PREDICT(need_to_update_have_min_dir_info, 0)) {
  3796. update_router_have_minimum_dir_info();
  3797. need_to_update_have_min_dir_info = 0;
  3798. }
  3799. return have_min_dir_info;
  3800. }
  3801. /** Called when our internal view of the directory has changed. This can be
  3802. * when the authorities change, networkstatuses change, the list of routerdescs
  3803. * changes, or number of running routers changes.
  3804. */
  3805. static void
  3806. router_dir_info_changed(void)
  3807. {
  3808. need_to_update_have_min_dir_info = 1;
  3809. }
  3810. /** Change the value of have_min_dir_info, setting it true iff we have enough
  3811. * network and router information to build circuits. Clear the value of
  3812. * need_to_update_have_min_dir_info. */
  3813. static void
  3814. update_router_have_minimum_dir_info(void)
  3815. {
  3816. int tot = 0, num_running = 0;
  3817. int n_ns, n_authorities, res, avg;
  3818. time_t now = time(NULL);
  3819. if (!networkstatus_list || !routerlist) {
  3820. res = 0;
  3821. goto done;
  3822. }
  3823. routerlist_remove_old_routers();
  3824. networkstatus_list_clean(now);
  3825. n_authorities = get_n_v2_authorities();
  3826. n_ns = smartlist_len(networkstatus_list);
  3827. if (n_ns<=n_authorities/2) {
  3828. log_info(LD_DIR,
  3829. "We have %d of %d network statuses, and we want "
  3830. "more than %d.", n_ns, n_authorities, n_authorities/2);
  3831. res = 0;
  3832. goto done;
  3833. }
  3834. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3835. tot += routerstatus_count_usable_entries(ns->entries));
  3836. avg = tot / n_ns;
  3837. if (!routerstatus_list)
  3838. routerstatus_list = smartlist_create();
  3839. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3840. {
  3841. if (rs->status.is_running)
  3842. num_running++;
  3843. });
  3844. res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
  3845. done:
  3846. if (res && !have_min_dir_info) {
  3847. log(LOG_NOTICE, LD_DIR,
  3848. "We now have enough directory information to build circuits.");
  3849. control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
  3850. }
  3851. if (!res && have_min_dir_info) {
  3852. log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
  3853. "enough to build circuits.%s",
  3854. num_running > 2 ? "" : " (Not enough servers seem reachable -- "
  3855. "is your network connection down?)");
  3856. control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
  3857. }
  3858. have_min_dir_info = res;
  3859. }
  3860. /** Return true iff we have downloaded, or attempted to download at least
  3861. * n_failures times, a network status for each authority. */
  3862. static int
  3863. have_tried_downloading_all_statuses(int n_failures)
  3864. {
  3865. if (!trusted_dir_servers)
  3866. return 0;
  3867. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  3868. {
  3869. if (!ds->is_v2_authority)
  3870. continue;
  3871. /* If we don't have the status, and we haven't failed to get the status,
  3872. * we haven't tried to get the status. */
  3873. if (!networkstatus_get_by_digest(ds->digest) &&
  3874. ds->n_networkstatus_failures <= n_failures)
  3875. return 0;
  3876. });
  3877. return 1;
  3878. }
  3879. /** Reset the descriptor download failure count on all routers, so that we
  3880. * can retry any long-failed routers immediately.
  3881. */
  3882. void
  3883. router_reset_descriptor_download_failures(void)
  3884. {
  3885. if (!routerstatus_list)
  3886. return;
  3887. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  3888. {
  3889. rs->n_download_failures = 0;
  3890. rs->next_attempt_at = 0;
  3891. });
  3892. tor_assert(networkstatus_list);
  3893. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  3894. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  3895. {
  3896. if (!router_get_by_descriptor_digest(rs->descriptor_digest))
  3897. rs->need_to_mirror = 1;
  3898. }));
  3899. last_routerdesc_download_attempted = 0;
  3900. }
  3901. /** Any changes in a router descriptor's publication time larger than this are
  3902. * automatically non-cosmetic. */
  3903. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  3904. /** We allow uptime to vary from how much it ought to be by this much. */
  3905. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  3906. /** Return true iff the only differences between r1 and r2 are such that
  3907. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  3908. */
  3909. int
  3910. router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
  3911. {
  3912. time_t r1pub, r2pub;
  3913. int time_difference;
  3914. tor_assert(r1 && r2);
  3915. /* r1 should be the one that was published first. */
  3916. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  3917. routerinfo_t *ri_tmp = r2;
  3918. r2 = r1;
  3919. r1 = ri_tmp;
  3920. }
  3921. /* If any key fields differ, they're different. */
  3922. if (strcasecmp(r1->address, r2->address) ||
  3923. strcasecmp(r1->nickname, r2->nickname) ||
  3924. r1->or_port != r2->or_port ||
  3925. r1->dir_port != r2->dir_port ||
  3926. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  3927. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  3928. strcasecmp(r1->platform, r2->platform) ||
  3929. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  3930. (!r1->contact_info && r2->contact_info) ||
  3931. (r1->contact_info && r2->contact_info &&
  3932. strcasecmp(r1->contact_info, r2->contact_info)) ||
  3933. r1->is_hibernating != r2->is_hibernating ||
  3934. r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
  3935. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  3936. return 0;
  3937. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  3938. return 0;
  3939. if (r1->declared_family && r2->declared_family) {
  3940. int i, n;
  3941. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  3942. return 0;
  3943. n = smartlist_len(r1->declared_family);
  3944. for (i=0; i < n; ++i) {
  3945. if (strcasecmp(smartlist_get(r1->declared_family, i),
  3946. smartlist_get(r2->declared_family, i)))
  3947. return 0;
  3948. }
  3949. }
  3950. /* Did bandwidth change a lot? */
  3951. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  3952. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  3953. return 0;
  3954. /* Did more than 12 hours pass? */
  3955. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  3956. < r2->cache_info.published_on)
  3957. return 0;
  3958. /* Did uptime fail to increase by approximately the amount we would think,
  3959. * give or take some slop? */
  3960. r1pub = r1->cache_info.published_on;
  3961. r2pub = r2->cache_info.published_on;
  3962. time_difference = abs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  3963. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  3964. time_difference > r1->uptime * .05 &&
  3965. time_difference > r2->uptime * .05)
  3966. return 0;
  3967. /* Otherwise, the difference is cosmetic. */
  3968. return 1;
  3969. }
  3970. /** Generate networkstatus lines for a single routerstatus_t object, and
  3971. * return the result in a newly allocated string. Used only by controller
  3972. * interface (for now.) */
  3973. /* XXXX This should eventually merge into generate_v2_networkstatus() */
  3974. char *
  3975. networkstatus_getinfo_helper_single(routerstatus_t *rs)
  3976. {
  3977. char buf[192];
  3978. int r;
  3979. struct in_addr in;
  3980. int f_authority;
  3981. char published[ISO_TIME_LEN+1];
  3982. char ipaddr[INET_NTOA_BUF_LEN];
  3983. char identity64[BASE64_DIGEST_LEN+1];
  3984. char digest64[BASE64_DIGEST_LEN+1];
  3985. format_iso_time(published, rs->published_on);
  3986. digest_to_base64(identity64, rs->identity_digest);
  3987. digest_to_base64(digest64, rs->descriptor_digest);
  3988. in.s_addr = htonl(rs->addr);
  3989. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  3990. f_authority = router_digest_is_trusted_dir(rs->identity_digest);
  3991. r = tor_snprintf(buf, sizeof(buf),
  3992. "r %s %s %s %s %s %d %d\n"
  3993. "s%s%s%s%s%s%s%s%s%s%s\n",
  3994. rs->nickname,
  3995. identity64,
  3996. digest64,
  3997. published,
  3998. ipaddr,
  3999. (int)rs->or_port,
  4000. (int)rs->dir_port,
  4001. f_authority?" Authority":"",
  4002. rs->is_bad_exit?" BadExit":"",
  4003. rs->is_exit?" Exit":"",
  4004. rs->is_fast?" Fast":"",
  4005. rs->is_possible_guard?" Guard":"",
  4006. rs->is_named?" Named":"",
  4007. rs->is_stable?" Stable":"",
  4008. rs->is_running?" Running":"",
  4009. rs->is_valid?" Valid":"",
  4010. rs->is_v2_dir?" V2Dir":"");
  4011. if (r<0)
  4012. log_warn(LD_BUG, "Not enough space in buffer.");
  4013. return tor_strdup(buf);
  4014. }
  4015. /** If <b>question</b> is a string beginning with "ns/" in a format the
  4016. * control interface expects for a GETINFO question, set *<b>answer</b> to a
  4017. * newly-allocated string containing networkstatus lines for the appropriate
  4018. * ORs. Return 0 on success, -1 on unrecognized question format. */
  4019. int
  4020. getinfo_helper_networkstatus(control_connection_t *conn,
  4021. const char *question, char **answer)
  4022. {
  4023. local_routerstatus_t *status;
  4024. (void) conn;
  4025. if (!routerstatus_list) {
  4026. *answer = tor_strdup("");
  4027. return 0;
  4028. }
  4029. if (!strcmp(question, "ns/all")) {
  4030. smartlist_t *statuses = smartlist_create();
  4031. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
  4032. {
  4033. routerstatus_t *rs = &(lrs->status);
  4034. smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
  4035. });
  4036. *answer = smartlist_join_strings(statuses, "", 0, NULL);
  4037. SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
  4038. smartlist_free(statuses);
  4039. return 0;
  4040. } else if (!strcmpstart(question, "ns/id/")) {
  4041. char d[DIGEST_LEN];
  4042. if (base16_decode(d, DIGEST_LEN, question+6, strlen(question+6)))
  4043. return -1;
  4044. status = router_get_combined_status_by_digest(d);
  4045. } else if (!strcmpstart(question, "ns/name/")) {
  4046. status = router_get_combined_status_by_nickname(question+8, 0);
  4047. } else {
  4048. return -1;
  4049. }
  4050. if (status) {
  4051. *answer = networkstatus_getinfo_helper_single(&status->status);
  4052. }
  4053. return 0;
  4054. }
  4055. /** Assert that the internal representation of <b>rl</b> is
  4056. * self-consistent. */
  4057. static void
  4058. routerlist_assert_ok(routerlist_t *rl)
  4059. {
  4060. digestmap_iter_t *iter;
  4061. routerinfo_t *r2;
  4062. signed_descriptor_t *sd2;
  4063. if (!routerlist)
  4064. return;
  4065. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  4066. {
  4067. r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
  4068. tor_assert(r == r2);
  4069. sd2 = digestmap_get(rl->desc_digest_map,
  4070. r->cache_info.signed_descriptor_digest);
  4071. tor_assert(&(r->cache_info) == sd2);
  4072. tor_assert(r->routerlist_index == r_sl_idx);
  4073. });
  4074. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  4075. {
  4076. r2 = digestmap_get(rl->identity_map, sd->identity_digest);
  4077. tor_assert(sd != &(r2->cache_info));
  4078. sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  4079. tor_assert(sd == sd2);
  4080. });
  4081. iter = digestmap_iter_init(rl->identity_map);
  4082. while (!digestmap_iter_done(iter)) {
  4083. const char *d;
  4084. void *_r;
  4085. routerinfo_t *r;
  4086. digestmap_iter_get(iter, &d, &_r);
  4087. r = _r;
  4088. tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
  4089. iter = digestmap_iter_next(rl->identity_map, iter);
  4090. }
  4091. iter = digestmap_iter_init(rl->desc_digest_map);
  4092. while (!digestmap_iter_done(iter)) {
  4093. const char *d;
  4094. void *_sd;
  4095. signed_descriptor_t *sd;
  4096. digestmap_iter_get(iter, &d, &_sd);
  4097. sd = _sd;
  4098. tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
  4099. iter = digestmap_iter_next(rl->desc_digest_map, iter);
  4100. }
  4101. }
  4102. /** Allocate and return a new string representing the contact info
  4103. * and platform string for <b>router</b>,
  4104. * surrounded by quotes and using standard C escapes.
  4105. *
  4106. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  4107. * thread. Also, each call invalidates the last-returned value, so don't
  4108. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  4109. */
  4110. const char *
  4111. esc_router_info(routerinfo_t *router)
  4112. {
  4113. static char *info;
  4114. char *esc_contact, *esc_platform;
  4115. size_t len;
  4116. if (info)
  4117. tor_free(info);
  4118. esc_contact = esc_for_log(router->contact_info);
  4119. esc_platform = esc_for_log(router->platform);
  4120. len = strlen(esc_contact)+strlen(esc_platform)+32;
  4121. info = tor_malloc(len);
  4122. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  4123. esc_platform);
  4124. tor_free(esc_contact);
  4125. tor_free(esc_platform);
  4126. return info;
  4127. }