routerlist.c 200 KB

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