routerlist.c 172 KB

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