routerlist.c 153 KB

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