routerlist.c 172 KB

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