routerlist.c 157 KB

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