routerlist.c 200 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906
  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_create();
  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_create();
  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_create();
  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_create();
  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_create();
  624. /* We sort the routers by age to enhance locality on disk. */
  625. signed_descriptors = smartlist_create();
  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_create();
  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_create();
  978. tunnel = smartlist_create();
  979. trusted_direct = smartlist_create();
  980. trusted_tunnel = smartlist_create();
  981. overloaded_direct = smartlist_create();
  982. overloaded_tunnel = smartlist_create();
  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_create();
  1091. tunnel = smartlist_create();
  1092. overloaded_direct = smartlist_create();
  1093. overloaded_tunnel = smartlist_create();
  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_create();
  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_create(),
  1944. *excludednodes=smartlist_create();
  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_create();
  2157. int any_unwarned = 0;
  2158. SMARTLIST_FOREACH_BEGIN(routerlist->routers, routerinfo_t *, router) {
  2159. routerstatus_t *rs;
  2160. char *desc;
  2161. size_t dlen;
  2162. char fp[HEX_DIGEST_LEN+1];
  2163. if (strcasecmp(router->nickname, nickname))
  2164. continue;
  2165. rs = router_get_mutable_consensus_status_by_id(
  2166. router->cache_info.identity_digest);
  2167. if (rs && !rs->name_lookup_warned) {
  2168. rs->name_lookup_warned = 1;
  2169. any_unwarned = 1;
  2170. }
  2171. base16_encode(fp, sizeof(fp),
  2172. router->cache_info.identity_digest, DIGEST_LEN);
  2173. dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
  2174. desc = tor_malloc(dlen);
  2175. tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
  2176. fp, router->address, router->or_port);
  2177. smartlist_add(fps, desc);
  2178. } SMARTLIST_FOREACH_END(router);
  2179. if (any_unwarned) {
  2180. char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
  2181. log_warn(LD_CONFIG,
  2182. "There are multiple matches for the nickname \"%s\","
  2183. " but none is listed as named by the directory authorities. "
  2184. "Choosing one arbitrarily. If you meant one in particular, "
  2185. "you should say %s.", nickname, alternatives);
  2186. tor_free(alternatives);
  2187. }
  2188. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  2189. smartlist_free(fps);
  2190. } else if (warn_if_unnamed) {
  2191. routerstatus_t *rs = router_get_mutable_consensus_status_by_id(
  2192. best_match->cache_info.identity_digest);
  2193. if (rs && !rs->name_lookup_warned) {
  2194. char fp[HEX_DIGEST_LEN+1];
  2195. base16_encode(fp, sizeof(fp),
  2196. best_match->cache_info.identity_digest, DIGEST_LEN);
  2197. log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
  2198. "name is not registered, so it could be used by any server, "
  2199. "not just the one you meant. "
  2200. "To make sure you get the same server in the future, refer to "
  2201. "it by key, as \"$%s\".", nickname, fp);
  2202. rs->name_lookup_warned = 1;
  2203. }
  2204. }
  2205. return best_match;
  2206. }
  2207. return NULL;
  2208. #endif
  2209. }
  2210. /** Return true iff <b>digest</b> is the digest of the identity key of a
  2211. * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
  2212. * is zero, any authority is okay. */
  2213. int
  2214. router_digest_is_trusted_dir_type(const char *digest, dirinfo_type_t type)
  2215. {
  2216. if (!trusted_dir_servers)
  2217. return 0;
  2218. if (authdir_mode(get_options()) && router_digest_is_me(digest))
  2219. return 1;
  2220. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2221. if (tor_memeq(digest, ent->digest, DIGEST_LEN)) {
  2222. return (!type) || ((type & ent->type) != 0);
  2223. });
  2224. return 0;
  2225. }
  2226. /** Return true iff <b>addr</b> is the address of one of our trusted
  2227. * directory authorities. */
  2228. int
  2229. router_addr_is_trusted_dir(uint32_t addr)
  2230. {
  2231. if (!trusted_dir_servers)
  2232. return 0;
  2233. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  2234. if (ent->addr == addr)
  2235. return 1;
  2236. );
  2237. return 0;
  2238. }
  2239. /** If hexdigest is correctly formed, base16_decode it into
  2240. * digest, which must have DIGEST_LEN space in it.
  2241. * Return 0 on success, -1 on failure.
  2242. */
  2243. int
  2244. hexdigest_to_digest(const char *hexdigest, char *digest)
  2245. {
  2246. if (hexdigest[0]=='$')
  2247. ++hexdigest;
  2248. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  2249. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  2250. return -1;
  2251. return 0;
  2252. }
  2253. /** Return the router in our routerlist whose hexadecimal key digest
  2254. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  2255. const routerinfo_t *
  2256. router_get_by_hexdigest(const char *hexdigest)
  2257. {
  2258. if (is_legal_nickname(hexdigest))
  2259. return NULL;
  2260. /* It's not a legal nickname, so it must be a hexdigest or nothing. */
  2261. return router_get_by_nickname(hexdigest, 1);
  2262. }
  2263. /** As router_get_by_id_digest,but return a pointer that you're allowed to
  2264. * modify */
  2265. routerinfo_t *
  2266. router_get_mutable_by_digest(const char *digest)
  2267. {
  2268. tor_assert(digest);
  2269. if (!routerlist) return NULL;
  2270. // routerlist_assert_ok(routerlist);
  2271. return rimap_get(routerlist->identity_map, digest);
  2272. }
  2273. /** Return the router in our routerlist whose 20-byte key digest
  2274. * is <b>digest</b>. Return NULL if no such router is known. */
  2275. const routerinfo_t *
  2276. router_get_by_id_digest(const char *digest)
  2277. {
  2278. return router_get_mutable_by_digest(digest);
  2279. }
  2280. /** Return the router in our routerlist whose 20-byte descriptor
  2281. * is <b>digest</b>. Return NULL if no such router is known. */
  2282. signed_descriptor_t *
  2283. router_get_by_descriptor_digest(const char *digest)
  2284. {
  2285. tor_assert(digest);
  2286. if (!routerlist) return NULL;
  2287. return sdmap_get(routerlist->desc_digest_map, digest);
  2288. }
  2289. /** Return the signed descriptor for the router in our routerlist whose
  2290. * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
  2291. * is known. */
  2292. signed_descriptor_t *
  2293. router_get_by_extrainfo_digest(const char *digest)
  2294. {
  2295. tor_assert(digest);
  2296. if (!routerlist) return NULL;
  2297. return sdmap_get(routerlist->desc_by_eid_map, digest);
  2298. }
  2299. /** Return the signed descriptor for the extrainfo_t in our routerlist whose
  2300. * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
  2301. * document is known. */
  2302. signed_descriptor_t *
  2303. extrainfo_get_by_descriptor_digest(const char *digest)
  2304. {
  2305. extrainfo_t *ei;
  2306. tor_assert(digest);
  2307. if (!routerlist) return NULL;
  2308. ei = eimap_get(routerlist->extra_info_map, digest);
  2309. return ei ? &ei->cache_info : NULL;
  2310. }
  2311. /** Return a pointer to the signed textual representation of a descriptor.
  2312. * The returned string is not guaranteed to be NUL-terminated: the string's
  2313. * length will be in desc-\>signed_descriptor_len.
  2314. *
  2315. * If <b>with_annotations</b> is set, the returned string will include
  2316. * the annotations
  2317. * (if any) preceding the descriptor. This will increase the length of the
  2318. * string by desc-\>annotations_len.
  2319. *
  2320. * The caller must not free the string returned.
  2321. */
  2322. static const char *
  2323. signed_descriptor_get_body_impl(const signed_descriptor_t *desc,
  2324. int with_annotations)
  2325. {
  2326. const char *r = NULL;
  2327. size_t len = desc->signed_descriptor_len;
  2328. off_t offset = desc->saved_offset;
  2329. if (with_annotations)
  2330. len += desc->annotations_len;
  2331. else
  2332. offset += desc->annotations_len;
  2333. tor_assert(len > 32);
  2334. if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
  2335. desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
  2336. if (store && store->mmap) {
  2337. tor_assert(desc->saved_offset + len <= store->mmap->size);
  2338. r = store->mmap->data + offset;
  2339. } else if (store) {
  2340. log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
  2341. "mmaped in our cache. Is another process running in our data "
  2342. "directory? Exiting.");
  2343. exit(1);
  2344. }
  2345. }
  2346. if (!r) /* no mmap, or not in cache. */
  2347. r = desc->signed_descriptor_body +
  2348. (with_annotations ? 0 : desc->annotations_len);
  2349. tor_assert(r);
  2350. if (!with_annotations) {
  2351. if (fast_memcmp("router ", r, 7) && fast_memcmp("extra-info ", r, 11)) {
  2352. char *cp = tor_strndup(r, 64);
  2353. log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
  2354. "Is another process running in our data directory? Exiting.",
  2355. desc, escaped(cp));
  2356. exit(1);
  2357. }
  2358. }
  2359. return r;
  2360. }
  2361. /** Return a pointer to the signed textual representation of a descriptor.
  2362. * The returned string is not guaranteed to be NUL-terminated: the string's
  2363. * length will be in desc-\>signed_descriptor_len.
  2364. *
  2365. * The caller must not free the string returned.
  2366. */
  2367. const char *
  2368. signed_descriptor_get_body(const signed_descriptor_t *desc)
  2369. {
  2370. return signed_descriptor_get_body_impl(desc, 0);
  2371. }
  2372. /** As signed_descriptor_get_body(), but points to the beginning of the
  2373. * annotations section rather than the beginning of the descriptor. */
  2374. const char *
  2375. signed_descriptor_get_annotations(const signed_descriptor_t *desc)
  2376. {
  2377. return signed_descriptor_get_body_impl(desc, 1);
  2378. }
  2379. /** Return the current list of all known routers. */
  2380. routerlist_t *
  2381. router_get_routerlist(void)
  2382. {
  2383. if (PREDICT_UNLIKELY(!routerlist)) {
  2384. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  2385. routerlist->routers = smartlist_create();
  2386. routerlist->old_routers = smartlist_create();
  2387. routerlist->identity_map = rimap_new();
  2388. routerlist->desc_digest_map = sdmap_new();
  2389. routerlist->desc_by_eid_map = sdmap_new();
  2390. routerlist->extra_info_map = eimap_new();
  2391. routerlist->desc_store.fname_base = "cached-descriptors";
  2392. routerlist->desc_store.fname_alt_base = "cached-routers";
  2393. routerlist->extrainfo_store.fname_base = "cached-extrainfo";
  2394. routerlist->desc_store.type = ROUTER_STORE;
  2395. routerlist->extrainfo_store.type = EXTRAINFO_STORE;
  2396. routerlist->desc_store.description = "router descriptors";
  2397. routerlist->extrainfo_store.description = "extra-info documents";
  2398. }
  2399. return routerlist;
  2400. }
  2401. /** Free all storage held by <b>router</b>. */
  2402. void
  2403. routerinfo_free(routerinfo_t *router)
  2404. {
  2405. if (!router)
  2406. return;
  2407. tor_free(router->cache_info.signed_descriptor_body);
  2408. tor_free(router->address);
  2409. tor_free(router->nickname);
  2410. tor_free(router->platform);
  2411. tor_free(router->contact_info);
  2412. if (router->onion_pkey)
  2413. crypto_free_pk_env(router->onion_pkey);
  2414. if (router->identity_pkey)
  2415. crypto_free_pk_env(router->identity_pkey);
  2416. if (router->declared_family) {
  2417. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  2418. smartlist_free(router->declared_family);
  2419. }
  2420. addr_policy_list_free(router->exit_policy);
  2421. memset(router, 77, sizeof(routerinfo_t));
  2422. tor_free(router);
  2423. }
  2424. /** Release all storage held by <b>extrainfo</b> */
  2425. void
  2426. extrainfo_free(extrainfo_t *extrainfo)
  2427. {
  2428. if (!extrainfo)
  2429. return;
  2430. tor_free(extrainfo->cache_info.signed_descriptor_body);
  2431. tor_free(extrainfo->pending_sig);
  2432. memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  2433. tor_free(extrainfo);
  2434. }
  2435. /** Release storage held by <b>sd</b>. */
  2436. static void
  2437. signed_descriptor_free(signed_descriptor_t *sd)
  2438. {
  2439. if (!sd)
  2440. return;
  2441. tor_free(sd->signed_descriptor_body);
  2442. memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
  2443. tor_free(sd);
  2444. }
  2445. /** Extract a signed_descriptor_t from a general routerinfo, and free the
  2446. * routerinfo.
  2447. */
  2448. static signed_descriptor_t *
  2449. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  2450. {
  2451. signed_descriptor_t *sd;
  2452. tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
  2453. sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  2454. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  2455. sd->routerlist_index = -1;
  2456. ri->cache_info.signed_descriptor_body = NULL;
  2457. routerinfo_free(ri);
  2458. return sd;
  2459. }
  2460. /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
  2461. static void
  2462. _extrainfo_free(void *e)
  2463. {
  2464. extrainfo_free(e);
  2465. }
  2466. /** Free all storage held by a routerlist <b>rl</b>. */
  2467. void
  2468. routerlist_free(routerlist_t *rl)
  2469. {
  2470. if (!rl)
  2471. return;
  2472. rimap_free(rl->identity_map, NULL);
  2473. sdmap_free(rl->desc_digest_map, NULL);
  2474. sdmap_free(rl->desc_by_eid_map, NULL);
  2475. eimap_free(rl->extra_info_map, _extrainfo_free);
  2476. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2477. routerinfo_free(r));
  2478. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  2479. signed_descriptor_free(sd));
  2480. smartlist_free(rl->routers);
  2481. smartlist_free(rl->old_routers);
  2482. if (routerlist->desc_store.mmap)
  2483. tor_munmap_file(routerlist->desc_store.mmap);
  2484. if (routerlist->extrainfo_store.mmap)
  2485. tor_munmap_file(routerlist->extrainfo_store.mmap);
  2486. tor_free(rl);
  2487. router_dir_info_changed();
  2488. }
  2489. /** Log information about how much memory is being used for routerlist,
  2490. * at log level <b>severity</b>. */
  2491. void
  2492. dump_routerlist_mem_usage(int severity)
  2493. {
  2494. uint64_t livedescs = 0;
  2495. uint64_t olddescs = 0;
  2496. if (!routerlist)
  2497. return;
  2498. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  2499. livedescs += r->cache_info.signed_descriptor_len);
  2500. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  2501. olddescs += sd->signed_descriptor_len);
  2502. log(severity, LD_DIR,
  2503. "In %d live descriptors: "U64_FORMAT" bytes. "
  2504. "In %d old descriptors: "U64_FORMAT" bytes.",
  2505. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  2506. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  2507. }
  2508. /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
  2509. * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
  2510. * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
  2511. * is not in <b>sl</b>. */
  2512. static INLINE int
  2513. _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
  2514. {
  2515. if (idx < 0) {
  2516. idx = -1;
  2517. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  2518. if (r == ri) {
  2519. idx = r_sl_idx;
  2520. break;
  2521. });
  2522. } else {
  2523. tor_assert(idx < smartlist_len(sl));
  2524. tor_assert(smartlist_get(sl, idx) == ri);
  2525. };
  2526. return idx;
  2527. }
  2528. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  2529. * as needed. There must be no previous member of <b>rl</b> with the same
  2530. * identity digest as <b>ri</b>: If there is, call routerlist_replace
  2531. * instead.
  2532. */
  2533. static void
  2534. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  2535. {
  2536. routerinfo_t *ri_old;
  2537. signed_descriptor_t *sd_old;
  2538. {
  2539. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2540. tor_assert(ri_generated != ri);
  2541. }
  2542. tor_assert(ri->cache_info.routerlist_index == -1);
  2543. ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  2544. tor_assert(!ri_old);
  2545. sd_old = sdmap_set(rl->desc_digest_map,
  2546. ri->cache_info.signed_descriptor_digest,
  2547. &(ri->cache_info));
  2548. if (sd_old) {
  2549. rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
  2550. sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
  2551. signed_descriptor_free(sd_old);
  2552. }
  2553. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2554. sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
  2555. &ri->cache_info);
  2556. smartlist_add(rl->routers, ri);
  2557. ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
  2558. nodelist_add_routerinfo(ri);
  2559. router_dir_info_changed();
  2560. #ifdef DEBUG_ROUTERLIST
  2561. routerlist_assert_ok(rl);
  2562. #endif
  2563. }
  2564. /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
  2565. * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
  2566. * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
  2567. static int
  2568. extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
  2569. {
  2570. int r = 0;
  2571. routerinfo_t *ri = rimap_get(rl->identity_map,
  2572. ei->cache_info.identity_digest);
  2573. signed_descriptor_t *sd =
  2574. sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
  2575. extrainfo_t *ei_tmp;
  2576. {
  2577. extrainfo_t *ei_generated = router_get_my_extrainfo();
  2578. tor_assert(ei_generated != ei);
  2579. }
  2580. if (!ri) {
  2581. /* This router is unknown; we can't even verify the signature. Give up.*/
  2582. goto done;
  2583. }
  2584. if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
  2585. goto done;
  2586. }
  2587. /* Okay, if we make it here, we definitely have a router corresponding to
  2588. * this extrainfo. */
  2589. ei_tmp = eimap_set(rl->extra_info_map,
  2590. ei->cache_info.signed_descriptor_digest,
  2591. ei);
  2592. r = 1;
  2593. if (ei_tmp) {
  2594. rl->extrainfo_store.bytes_dropped +=
  2595. ei_tmp->cache_info.signed_descriptor_len;
  2596. extrainfo_free(ei_tmp);
  2597. }
  2598. done:
  2599. if (r == 0)
  2600. extrainfo_free(ei);
  2601. #ifdef DEBUG_ROUTERLIST
  2602. routerlist_assert_ok(rl);
  2603. #endif
  2604. return r;
  2605. }
  2606. #define should_cache_old_descriptors() \
  2607. directory_caches_dir_info(get_options())
  2608. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  2609. * a copy of router <b>ri</b> yet, add it to the list of old (not
  2610. * recommended but still served) descriptors. Else free it. */
  2611. static void
  2612. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  2613. {
  2614. {
  2615. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2616. tor_assert(ri_generated != ri);
  2617. }
  2618. tor_assert(ri->cache_info.routerlist_index == -1);
  2619. if (should_cache_old_descriptors() &&
  2620. ri->purpose == ROUTER_PURPOSE_GENERAL &&
  2621. !sdmap_get(rl->desc_digest_map,
  2622. ri->cache_info.signed_descriptor_digest)) {
  2623. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  2624. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2625. smartlist_add(rl->old_routers, sd);
  2626. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2627. if (!tor_digest_is_zero(sd->extra_info_digest))
  2628. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2629. } else {
  2630. routerinfo_free(ri);
  2631. }
  2632. #ifdef DEBUG_ROUTERLIST
  2633. routerlist_assert_ok(rl);
  2634. #endif
  2635. }
  2636. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  2637. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  2638. * idx) == ri, we don't need to do a linear search over the list to decide
  2639. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  2640. * the list, if any exists. <b>ri</b> is freed.
  2641. *
  2642. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  2643. * it to rl-&gt;old_routers. */
  2644. void
  2645. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
  2646. {
  2647. routerinfo_t *ri_tmp;
  2648. extrainfo_t *ei_tmp;
  2649. int idx = ri->cache_info.routerlist_index;
  2650. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2651. tor_assert(smartlist_get(rl->routers, idx) == ri);
  2652. nodelist_remove_routerinfo(ri);
  2653. /* make sure the rephist module knows that it's not running */
  2654. rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
  2655. ri->cache_info.routerlist_index = -1;
  2656. smartlist_del(rl->routers, idx);
  2657. if (idx < smartlist_len(rl->routers)) {
  2658. routerinfo_t *r = smartlist_get(rl->routers, idx);
  2659. r->cache_info.routerlist_index = idx;
  2660. }
  2661. ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  2662. router_dir_info_changed();
  2663. tor_assert(ri_tmp == ri);
  2664. if (make_old && should_cache_old_descriptors() &&
  2665. ri->purpose == ROUTER_PURPOSE_GENERAL) {
  2666. signed_descriptor_t *sd;
  2667. sd = signed_descriptor_from_routerinfo(ri);
  2668. smartlist_add(rl->old_routers, sd);
  2669. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2670. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2671. if (!tor_digest_is_zero(sd->extra_info_digest))
  2672. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2673. } else {
  2674. signed_descriptor_t *sd_tmp;
  2675. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2676. ri->cache_info.signed_descriptor_digest);
  2677. tor_assert(sd_tmp == &(ri->cache_info));
  2678. rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
  2679. ei_tmp = eimap_remove(rl->extra_info_map,
  2680. ri->cache_info.extra_info_digest);
  2681. if (ei_tmp) {
  2682. rl->extrainfo_store.bytes_dropped +=
  2683. ei_tmp->cache_info.signed_descriptor_len;
  2684. extrainfo_free(ei_tmp);
  2685. }
  2686. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2687. sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
  2688. routerinfo_free(ri);
  2689. }
  2690. #ifdef DEBUG_ROUTERLIST
  2691. routerlist_assert_ok(rl);
  2692. #endif
  2693. }
  2694. /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
  2695. * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
  2696. * <b>sd</b>. */
  2697. static void
  2698. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  2699. {
  2700. signed_descriptor_t *sd_tmp;
  2701. extrainfo_t *ei_tmp;
  2702. desc_store_t *store;
  2703. if (idx == -1) {
  2704. idx = sd->routerlist_index;
  2705. }
  2706. tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
  2707. /* XXXX edmanm's bridge relay triggered the following assert while
  2708. * running 0.2.0.12-alpha. If anybody triggers this again, see if we
  2709. * can get a backtrace. */
  2710. tor_assert(smartlist_get(rl->old_routers, idx) == sd);
  2711. tor_assert(idx == sd->routerlist_index);
  2712. sd->routerlist_index = -1;
  2713. smartlist_del(rl->old_routers, idx);
  2714. if (idx < smartlist_len(rl->old_routers)) {
  2715. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2716. d->routerlist_index = idx;
  2717. }
  2718. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2719. sd->signed_descriptor_digest);
  2720. tor_assert(sd_tmp == sd);
  2721. store = desc_get_store(rl, sd);
  2722. if (store)
  2723. store->bytes_dropped += sd->signed_descriptor_len;
  2724. ei_tmp = eimap_remove(rl->extra_info_map,
  2725. sd->extra_info_digest);
  2726. if (ei_tmp) {
  2727. rl->extrainfo_store.bytes_dropped +=
  2728. ei_tmp->cache_info.signed_descriptor_len;
  2729. extrainfo_free(ei_tmp);
  2730. }
  2731. if (!tor_digest_is_zero(sd->extra_info_digest))
  2732. sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
  2733. signed_descriptor_free(sd);
  2734. #ifdef DEBUG_ROUTERLIST
  2735. routerlist_assert_ok(rl);
  2736. #endif
  2737. }
  2738. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  2739. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  2740. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  2741. * search over the list to decide which to remove. We put ri_new in the same
  2742. * index as ri_old, if possible. ri is freed as appropriate.
  2743. *
  2744. * If should_cache_descriptors() is true, instead of deleting the router,
  2745. * we add it to rl-&gt;old_routers. */
  2746. static void
  2747. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  2748. routerinfo_t *ri_new)
  2749. {
  2750. int idx;
  2751. int same_descriptors;
  2752. routerinfo_t *ri_tmp;
  2753. extrainfo_t *ei_tmp;
  2754. {
  2755. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2756. tor_assert(ri_generated != ri_new);
  2757. }
  2758. tor_assert(ri_old != ri_new);
  2759. tor_assert(ri_new->cache_info.routerlist_index == -1);
  2760. idx = ri_old->cache_info.routerlist_index;
  2761. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2762. tor_assert(smartlist_get(rl->routers, idx) == ri_old);
  2763. nodelist_remove_routerinfo(ri_old);
  2764. nodelist_add_routerinfo(ri_new);
  2765. router_dir_info_changed();
  2766. if (idx >= 0) {
  2767. smartlist_set(rl->routers, idx, ri_new);
  2768. ri_old->cache_info.routerlist_index = -1;
  2769. ri_new->cache_info.routerlist_index = idx;
  2770. /* Check that ri_old is not in rl->routers anymore: */
  2771. tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
  2772. } else {
  2773. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  2774. routerlist_insert(rl, ri_new);
  2775. return;
  2776. }
  2777. if (tor_memneq(ri_old->cache_info.identity_digest,
  2778. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  2779. /* digests don't match; digestmap_set won't replace */
  2780. rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  2781. }
  2782. ri_tmp = rimap_set(rl->identity_map,
  2783. ri_new->cache_info.identity_digest, ri_new);
  2784. tor_assert(!ri_tmp || ri_tmp == ri_old);
  2785. sdmap_set(rl->desc_digest_map,
  2786. ri_new->cache_info.signed_descriptor_digest,
  2787. &(ri_new->cache_info));
  2788. if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
  2789. sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
  2790. &ri_new->cache_info);
  2791. }
  2792. same_descriptors = tor_memeq(ri_old->cache_info.signed_descriptor_digest,
  2793. ri_new->cache_info.signed_descriptor_digest,
  2794. DIGEST_LEN);
  2795. if (should_cache_old_descriptors() &&
  2796. ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
  2797. !same_descriptors) {
  2798. /* ri_old is going to become a signed_descriptor_t and go into
  2799. * old_routers */
  2800. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  2801. smartlist_add(rl->old_routers, sd);
  2802. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2803. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2804. if (!tor_digest_is_zero(sd->extra_info_digest))
  2805. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2806. } else {
  2807. /* We're dropping ri_old. */
  2808. if (!same_descriptors) {
  2809. /* digests don't match; The sdmap_set above didn't replace */
  2810. sdmap_remove(rl->desc_digest_map,
  2811. ri_old->cache_info.signed_descriptor_digest);
  2812. if (tor_memneq(ri_old->cache_info.extra_info_digest,
  2813. ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
  2814. ei_tmp = eimap_remove(rl->extra_info_map,
  2815. ri_old->cache_info.extra_info_digest);
  2816. if (ei_tmp) {
  2817. rl->extrainfo_store.bytes_dropped +=
  2818. ei_tmp->cache_info.signed_descriptor_len;
  2819. extrainfo_free(ei_tmp);
  2820. }
  2821. }
  2822. if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
  2823. sdmap_remove(rl->desc_by_eid_map,
  2824. ri_old->cache_info.extra_info_digest);
  2825. }
  2826. }
  2827. rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
  2828. routerinfo_free(ri_old);
  2829. }
  2830. #ifdef DEBUG_ROUTERLIST
  2831. routerlist_assert_ok(rl);
  2832. #endif
  2833. }
  2834. /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
  2835. * it as a fresh routerinfo_t. */
  2836. static routerinfo_t *
  2837. routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
  2838. {
  2839. routerinfo_t *ri;
  2840. const char *body;
  2841. body = signed_descriptor_get_annotations(sd);
  2842. ri = router_parse_entry_from_string(body,
  2843. body+sd->signed_descriptor_len+sd->annotations_len,
  2844. 0, 1, NULL);
  2845. if (!ri)
  2846. return NULL;
  2847. memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
  2848. sd->signed_descriptor_body = NULL; /* Steal reference. */
  2849. ri->cache_info.routerlist_index = -1;
  2850. routerlist_remove_old(rl, sd, -1);
  2851. return ri;
  2852. }
  2853. /** Free all memory held by the routerlist module. */
  2854. void
  2855. routerlist_free_all(void)
  2856. {
  2857. routerlist_free(routerlist);
  2858. routerlist = NULL;
  2859. if (warned_nicknames) {
  2860. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2861. smartlist_free(warned_nicknames);
  2862. warned_nicknames = NULL;
  2863. }
  2864. if (trusted_dir_servers) {
  2865. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2866. trusted_dir_server_free(ds));
  2867. smartlist_free(trusted_dir_servers);
  2868. trusted_dir_servers = NULL;
  2869. }
  2870. if (trusted_dir_certs) {
  2871. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  2872. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  2873. authority_cert_free(cert));
  2874. smartlist_free(cl->certs);
  2875. tor_free(cl);
  2876. } DIGESTMAP_FOREACH_END;
  2877. digestmap_free(trusted_dir_certs, NULL);
  2878. trusted_dir_certs = NULL;
  2879. }
  2880. }
  2881. /** Forget that we have issued any router-related warnings, so that we'll
  2882. * warn again if we see the same errors. */
  2883. void
  2884. routerlist_reset_warnings(void)
  2885. {
  2886. if (!warned_nicknames)
  2887. warned_nicknames = smartlist_create();
  2888. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2889. smartlist_clear(warned_nicknames); /* now the list is empty. */
  2890. networkstatus_reset_warnings();
  2891. }
  2892. /** Mark the router with ID <b>digest</b> as running or non-running
  2893. * in our routerlist. */
  2894. void
  2895. router_set_status(const char *digest, int up)
  2896. {
  2897. node_t *node;
  2898. tor_assert(digest);
  2899. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  2900. if (tor_memeq(d->digest, digest, DIGEST_LEN))
  2901. d->is_running = up);
  2902. node = node_get_mutable_by_id(digest);
  2903. if (node) {
  2904. #if 0
  2905. log_debug(LD_DIR,"Marking router %s as %s.",
  2906. node_describe(node), up ? "up" : "down");
  2907. #endif
  2908. if (!up && node_is_me(node) && !net_is_disabled())
  2909. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  2910. "addresses reachable?");
  2911. node->is_running = up;
  2912. }
  2913. router_dir_info_changed();
  2914. }
  2915. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  2916. * older entries (if any) with the same key. Note: Callers should not hold
  2917. * their pointers to <b>router</b> if this function fails; <b>router</b>
  2918. * will either be inserted into the routerlist or freed. Similarly, even
  2919. * if this call succeeds, they should not hold their pointers to
  2920. * <b>router</b> after subsequent calls with other routerinfo's -- they
  2921. * might cause the original routerinfo to get freed.
  2922. *
  2923. * Returns the status for the operation. Might set *<b>msg</b> if it wants
  2924. * the poster of the router to know something.
  2925. *
  2926. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  2927. * <b>from_fetch</b>, we received it in response to a request we made.
  2928. * (If both are false, that means it was uploaded to us as an auth dir
  2929. * server or via the controller.)
  2930. *
  2931. * This function should be called *after*
  2932. * routers_update_status_from_consensus_networkstatus; subsequently, you
  2933. * should call router_rebuild_store and routerlist_descriptors_added.
  2934. */
  2935. was_router_added_t
  2936. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  2937. int from_cache, int from_fetch)
  2938. {
  2939. const char *id_digest;
  2940. const or_options_t *options = get_options();
  2941. int authdir = authdir_mode_handles_descs(options, router->purpose);
  2942. int authdir_believes_valid = 0;
  2943. routerinfo_t *old_router;
  2944. networkstatus_t *consensus =
  2945. networkstatus_get_latest_consensus_by_flavor(FLAV_NS);
  2946. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2947. int in_consensus = 0;
  2948. tor_assert(msg);
  2949. if (!routerlist)
  2950. router_get_routerlist();
  2951. id_digest = router->cache_info.identity_digest;
  2952. old_router = router_get_mutable_by_digest(id_digest);
  2953. /* Make sure that we haven't already got this exact descriptor. */
  2954. if (sdmap_get(routerlist->desc_digest_map,
  2955. router->cache_info.signed_descriptor_digest)) {
  2956. /* If we have this descriptor already and the new descriptor is a bridge
  2957. * descriptor, replace it. If we had a bridge descriptor before and the
  2958. * new one is not a bridge descriptor, don't replace it. */
  2959. /* Only members of routerlist->identity_map can be bridges; we don't
  2960. * put bridges in old_routers. */
  2961. const int was_bridge = old_router &&
  2962. old_router->purpose == ROUTER_PURPOSE_BRIDGE;
  2963. if (routerinfo_is_a_configured_bridge(router) &&
  2964. router->purpose == ROUTER_PURPOSE_BRIDGE &&
  2965. !was_bridge) {
  2966. log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
  2967. "descriptor for router %s",
  2968. router_describe(router));
  2969. } else {
  2970. log_info(LD_DIR,
  2971. "Dropping descriptor that we already have for router %s",
  2972. router_describe(router));
  2973. *msg = "Router descriptor was not new.";
  2974. routerinfo_free(router);
  2975. return ROUTER_WAS_NOT_NEW;
  2976. }
  2977. }
  2978. if (authdir) {
  2979. if (authdir_wants_to_reject_router(router, msg,
  2980. !from_cache && !from_fetch,
  2981. &authdir_believes_valid)) {
  2982. tor_assert(*msg);
  2983. routerinfo_free(router);
  2984. return ROUTER_AUTHDIR_REJECTS;
  2985. }
  2986. } else if (from_fetch) {
  2987. /* Only check the descriptor digest against the network statuses when
  2988. * we are receiving in response to a fetch. */
  2989. if (!signed_desc_digest_is_recognized(&router->cache_info) &&
  2990. !routerinfo_is_a_configured_bridge(router)) {
  2991. /* We asked for it, so some networkstatus must have listed it when we
  2992. * did. Save it if we're a cache in case somebody else asks for it. */
  2993. log_info(LD_DIR,
  2994. "Received a no-longer-recognized descriptor for router %s",
  2995. router_describe(router));
  2996. *msg = "Router descriptor is not referenced by any network-status.";
  2997. /* Only journal this desc if we'll be serving it. */
  2998. if (!from_cache && should_cache_old_descriptors())
  2999. signed_desc_append_to_journal(&router->cache_info,
  3000. &routerlist->desc_store);
  3001. routerlist_insert_old(routerlist, router);
  3002. return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
  3003. }
  3004. }
  3005. /* We no longer need a router with this descriptor digest. */
  3006. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3007. {
  3008. routerstatus_t *rs =
  3009. networkstatus_v2_find_mutable_entry(ns, id_digest);
  3010. if (rs && tor_memeq(rs->descriptor_digest,
  3011. router->cache_info.signed_descriptor_digest,
  3012. DIGEST_LEN))
  3013. rs->need_to_mirror = 0;
  3014. });
  3015. if (consensus) {
  3016. routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
  3017. consensus, id_digest);
  3018. if (rs && tor_memeq(rs->descriptor_digest,
  3019. router->cache_info.signed_descriptor_digest,
  3020. DIGEST_LEN)) {
  3021. in_consensus = 1;
  3022. rs->need_to_mirror = 0;
  3023. }
  3024. }
  3025. if (router->purpose == ROUTER_PURPOSE_GENERAL &&
  3026. consensus && !in_consensus && !authdir) {
  3027. /* If it's a general router not listed in the consensus, then don't
  3028. * consider replacing the latest router with it. */
  3029. if (!from_cache && should_cache_old_descriptors())
  3030. signed_desc_append_to_journal(&router->cache_info,
  3031. &routerlist->desc_store);
  3032. routerlist_insert_old(routerlist, router);
  3033. *msg = "Skipping router descriptor: not in consensus.";
  3034. return ROUTER_NOT_IN_CONSENSUS;
  3035. }
  3036. /* If we're reading a bridge descriptor from our cache, and we don't
  3037. * recognize it as one of our currently configured bridges, drop the
  3038. * descriptor. Otherwise we could end up using it as one of our entry
  3039. * guards even if it isn't in our Bridge config lines. */
  3040. if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
  3041. !authdir_mode_bridge(options) &&
  3042. !routerinfo_is_a_configured_bridge(router)) {
  3043. log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
  3044. "no bridge configured at that address.",
  3045. safe_str_client(router_describe(router)));
  3046. *msg = "Router descriptor was not a configured bridge.";
  3047. routerinfo_free(router);
  3048. return ROUTER_WAS_NOT_WANTED;
  3049. }
  3050. /* If we have a router with the same identity key, choose the newer one. */
  3051. if (old_router) {
  3052. if (!in_consensus && (router->cache_info.published_on <=
  3053. old_router->cache_info.published_on)) {
  3054. /* Same key, but old. This one is not listed in the consensus. */
  3055. log_debug(LD_DIR, "Not-new descriptor for router %s",
  3056. router_describe(router));
  3057. /* Only journal this desc if we'll be serving it. */
  3058. if (!from_cache && should_cache_old_descriptors())
  3059. signed_desc_append_to_journal(&router->cache_info,
  3060. &routerlist->desc_store);
  3061. routerlist_insert_old(routerlist, router);
  3062. *msg = "Router descriptor was not new.";
  3063. return ROUTER_WAS_NOT_NEW;
  3064. } else {
  3065. /* Same key, and either new, or listed in the consensus. */
  3066. log_debug(LD_DIR, "Replacing entry for router %s",
  3067. router_describe(router));
  3068. if (routers_have_same_or_addr(router, old_router)) {
  3069. /* these carry over when the address and orport are unchanged. */
  3070. router->last_reachable = old_router->last_reachable;
  3071. router->testing_since = old_router->testing_since;
  3072. }
  3073. routerlist_replace(routerlist, old_router, router);
  3074. if (!from_cache) {
  3075. signed_desc_append_to_journal(&router->cache_info,
  3076. &routerlist->desc_store);
  3077. }
  3078. directory_set_dirty();
  3079. *msg = authdir_believes_valid ? "Valid server updated" :
  3080. ("Invalid server updated. (This dirserver is marking your "
  3081. "server as unapproved.)");
  3082. return ROUTER_ADDED_SUCCESSFULLY;
  3083. }
  3084. }
  3085. if (!in_consensus && from_cache &&
  3086. router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
  3087. *msg = "Router descriptor was really old.";
  3088. routerinfo_free(router);
  3089. return ROUTER_WAS_NOT_NEW;
  3090. }
  3091. /* We haven't seen a router with this identity before. Add it to the end of
  3092. * the list. */
  3093. routerlist_insert(routerlist, router);
  3094. if (!from_cache) {
  3095. signed_desc_append_to_journal(&router->cache_info,
  3096. &routerlist->desc_store);
  3097. }
  3098. directory_set_dirty();
  3099. return ROUTER_ADDED_SUCCESSFULLY;
  3100. }
  3101. /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
  3102. * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
  3103. * we actually inserted it, ROUTER_BAD_EI otherwise.
  3104. */
  3105. was_router_added_t
  3106. router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
  3107. int from_cache, int from_fetch)
  3108. {
  3109. int inserted;
  3110. (void)from_fetch;
  3111. if (msg) *msg = NULL;
  3112. /*XXXX023 Do something with msg */
  3113. inserted = extrainfo_insert(router_get_routerlist(), ei);
  3114. if (inserted && !from_cache)
  3115. signed_desc_append_to_journal(&ei->cache_info,
  3116. &routerlist->extrainfo_store);
  3117. if (inserted)
  3118. return ROUTER_ADDED_SUCCESSFULLY;
  3119. else
  3120. return ROUTER_BAD_EI;
  3121. }
  3122. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  3123. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  3124. * to, or later than that of *<b>b</b>. */
  3125. static int
  3126. _compare_old_routers_by_identity(const void **_a, const void **_b)
  3127. {
  3128. int i;
  3129. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  3130. if ((i = fast_memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  3131. return i;
  3132. return (int)(r1->published_on - r2->published_on);
  3133. }
  3134. /** Internal type used to represent how long an old descriptor was valid,
  3135. * where it appeared in the list of old descriptors, and whether it's extra
  3136. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  3137. struct duration_idx_t {
  3138. int duration;
  3139. int idx;
  3140. int old;
  3141. };
  3142. /** Sorting helper: compare two duration_idx_t by their duration. */
  3143. static int
  3144. _compare_duration_idx(const void *_d1, const void *_d2)
  3145. {
  3146. const struct duration_idx_t *d1 = _d1;
  3147. const struct duration_idx_t *d2 = _d2;
  3148. return d1->duration - d2->duration;
  3149. }
  3150. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  3151. * must contain routerinfo_t with the same identity and with publication time
  3152. * in ascending order. Remove members from this range until there are no more
  3153. * than max_descriptors_per_router() remaining. Start by removing the oldest
  3154. * members from before <b>cutoff</b>, then remove members which were current
  3155. * for the lowest amount of time. The order of members of old_routers at
  3156. * indices <b>lo</b> or higher may be changed.
  3157. */
  3158. static void
  3159. routerlist_remove_old_cached_routers_with_id(time_t now,
  3160. time_t cutoff, int lo, int hi,
  3161. digestset_t *retain)
  3162. {
  3163. int i, n = hi-lo+1;
  3164. unsigned n_extra, n_rmv = 0;
  3165. struct duration_idx_t *lifespans;
  3166. uint8_t *rmv, *must_keep;
  3167. smartlist_t *lst = routerlist->old_routers;
  3168. #if 1
  3169. const char *ident;
  3170. tor_assert(hi < smartlist_len(lst));
  3171. tor_assert(lo <= hi);
  3172. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  3173. for (i = lo+1; i <= hi; ++i) {
  3174. signed_descriptor_t *r = smartlist_get(lst, i);
  3175. tor_assert(tor_memeq(ident, r->identity_digest, DIGEST_LEN));
  3176. }
  3177. #endif
  3178. /* Check whether we need to do anything at all. */
  3179. {
  3180. int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
  3181. if (n <= mdpr)
  3182. return;
  3183. n_extra = n - mdpr;
  3184. }
  3185. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  3186. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  3187. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  3188. /* Set lifespans to contain the lifespan and index of each server. */
  3189. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  3190. for (i = lo; i <= hi; ++i) {
  3191. signed_descriptor_t *r = smartlist_get(lst, i);
  3192. signed_descriptor_t *r_next;
  3193. lifespans[i-lo].idx = i;
  3194. if (r->last_listed_as_valid_until >= now ||
  3195. (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
  3196. must_keep[i-lo] = 1;
  3197. }
  3198. if (i < hi) {
  3199. r_next = smartlist_get(lst, i+1);
  3200. tor_assert(r->published_on <= r_next->published_on);
  3201. lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
  3202. } else {
  3203. r_next = NULL;
  3204. lifespans[i-lo].duration = INT_MAX;
  3205. }
  3206. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  3207. ++n_rmv;
  3208. lifespans[i-lo].old = 1;
  3209. rmv[i-lo] = 1;
  3210. }
  3211. }
  3212. if (n_rmv < n_extra) {
  3213. /**
  3214. * We aren't removing enough servers for being old. Sort lifespans by
  3215. * the duration of liveness, and remove the ones we're not already going to
  3216. * remove based on how long they were alive.
  3217. **/
  3218. qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
  3219. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  3220. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  3221. rmv[lifespans[i].idx-lo] = 1;
  3222. ++n_rmv;
  3223. }
  3224. }
  3225. }
  3226. i = hi;
  3227. do {
  3228. if (rmv[i-lo])
  3229. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  3230. } while (--i >= lo);
  3231. tor_free(must_keep);
  3232. tor_free(rmv);
  3233. tor_free(lifespans);
  3234. }
  3235. /** Deactivate any routers from the routerlist that are more than
  3236. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  3237. * remove old routers from the list of cached routers if we have too many.
  3238. */
  3239. void
  3240. routerlist_remove_old_routers(void)
  3241. {
  3242. int i, hi=-1;
  3243. const char *cur_id = NULL;
  3244. time_t now = time(NULL);
  3245. time_t cutoff;
  3246. routerinfo_t *router;
  3247. signed_descriptor_t *sd;
  3248. digestset_t *retain;
  3249. int caches = directory_caches_dir_info(get_options());
  3250. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3251. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3252. int have_enough_v2;
  3253. trusted_dirs_remove_old_certs();
  3254. if (!routerlist || !consensus)
  3255. return;
  3256. // routerlist_assert_ok(routerlist);
  3257. /* We need to guess how many router descriptors we will wind up wanting to
  3258. retain, so that we can be sure to allocate a large enough Bloom filter
  3259. to hold the digest set. Overestimating is fine; underestimating is bad.
  3260. */
  3261. {
  3262. /* We'll probably retain everything in the consensus. */
  3263. int n_max_retain = smartlist_len(consensus->routerstatus_list);
  3264. if (caches && networkstatus_v2_list) {
  3265. /* If we care about v2 statuses, we'll retain at most as many as are
  3266. listed any of the v2 statues. This will be at least the length of
  3267. the largest v2 networkstatus, and in the worst case, this set will be
  3268. equal to the sum of the lengths of all v2 consensuses. Take the
  3269. worst case.
  3270. */
  3271. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3272. n_max_retain += smartlist_len(ns->entries));
  3273. }
  3274. retain = digestset_new(n_max_retain);
  3275. }
  3276. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3277. /* Build a list of all the descriptors that _anybody_ lists. */
  3278. if (caches && networkstatus_v2_list) {
  3279. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3280. {
  3281. /* XXXX The inner loop here gets pretty expensive, and actually shows up
  3282. * on some profiles. It may be the reason digestmap_set shows up in
  3283. * profiles too. If instead we kept a per-descriptor digest count of
  3284. * how many networkstatuses recommended each descriptor, and changed
  3285. * that only when the networkstatuses changed, that would be a speed
  3286. * improvement, possibly 1-4% if it also removes digestmap_set from the
  3287. * profile. Not worth it for 0.1.2.x, though. The new directory
  3288. * system will obsolete this whole thing in 0.2.0.x. */
  3289. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
  3290. if (rs->published_on >= cutoff)
  3291. digestset_add(retain, rs->descriptor_digest));
  3292. });
  3293. }
  3294. /* Retain anything listed in the consensus. */
  3295. if (consensus) {
  3296. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  3297. if (rs->published_on >= cutoff)
  3298. digestset_add(retain, rs->descriptor_digest));
  3299. }
  3300. /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
  3301. * we should consider pruning current routers that are too old and that
  3302. * nobody recommends. (If we don't have a consensus or enough v2
  3303. * networkstatuses, then we should get more before we decide to kill
  3304. * routers.) */
  3305. /* we set this to true iff we don't care about v2 info, or we have enough. */
  3306. have_enough_v2 = !caches ||
  3307. (networkstatus_v2_list &&
  3308. smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
  3309. if (have_enough_v2 && consensus) {
  3310. cutoff = now - ROUTER_MAX_AGE;
  3311. /* Remove too-old unrecommended members of routerlist->routers. */
  3312. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  3313. router = smartlist_get(routerlist->routers, i);
  3314. if (router->cache_info.published_on <= cutoff &&
  3315. router->cache_info.last_listed_as_valid_until < now &&
  3316. !digestset_isin(retain,
  3317. router->cache_info.signed_descriptor_digest)) {
  3318. /* Too old: remove it. (If we're a cache, just move it into
  3319. * old_routers.) */
  3320. log_info(LD_DIR,
  3321. "Forgetting obsolete (too old) routerinfo for router %s",
  3322. router_describe(router));
  3323. routerlist_remove(routerlist, router, 1, now);
  3324. i--;
  3325. }
  3326. }
  3327. }
  3328. //routerlist_assert_ok(routerlist);
  3329. /* Remove far-too-old members of routerlist->old_routers. */
  3330. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3331. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3332. sd = smartlist_get(routerlist->old_routers, i);
  3333. if (sd->published_on <= cutoff &&
  3334. sd->last_listed_as_valid_until < now &&
  3335. !digestset_isin(retain, sd->signed_descriptor_digest)) {
  3336. /* Too old. Remove it. */
  3337. routerlist_remove_old(routerlist, sd, i--);
  3338. }
  3339. }
  3340. //routerlist_assert_ok(routerlist);
  3341. log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
  3342. smartlist_len(routerlist->routers),
  3343. smartlist_len(routerlist->old_routers));
  3344. /* Now we might have to look at routerlist->old_routers for extraneous
  3345. * members. (We'd keep all the members if we could, but we need to save
  3346. * space.) First, check whether we have too many router descriptors, total.
  3347. * We're okay with having too many for some given router, so long as the
  3348. * total number doesn't approach max_descriptors_per_router()*len(router).
  3349. */
  3350. if (smartlist_len(routerlist->old_routers) <
  3351. smartlist_len(routerlist->routers))
  3352. goto done;
  3353. /* Sort by identity, then fix indices. */
  3354. smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  3355. /* Fix indices. */
  3356. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3357. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3358. r->routerlist_index = i;
  3359. }
  3360. /* Iterate through the list from back to front, so when we remove descriptors
  3361. * we don't mess up groups we haven't gotten to. */
  3362. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  3363. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3364. if (!cur_id) {
  3365. cur_id = r->identity_digest;
  3366. hi = i;
  3367. }
  3368. if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
  3369. routerlist_remove_old_cached_routers_with_id(now,
  3370. cutoff, i+1, hi, retain);
  3371. cur_id = r->identity_digest;
  3372. hi = i;
  3373. }
  3374. }
  3375. if (hi>=0)
  3376. routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
  3377. //routerlist_assert_ok(routerlist);
  3378. done:
  3379. digestset_free(retain);
  3380. router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
  3381. router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
  3382. }
  3383. /** We just added a new set of descriptors. Take whatever extra steps
  3384. * we need. */
  3385. void
  3386. routerlist_descriptors_added(smartlist_t *sl, int from_cache)
  3387. {
  3388. tor_assert(sl);
  3389. control_event_descriptors_changed(sl);
  3390. SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
  3391. if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
  3392. learned_bridge_descriptor(ri, from_cache);
  3393. if (ri->needs_retest_if_added) {
  3394. ri->needs_retest_if_added = 0;
  3395. dirserv_single_reachability_test(approx_time(), ri);
  3396. }
  3397. } SMARTLIST_FOREACH_END(ri);
  3398. }
  3399. /**
  3400. * Code to parse a single router descriptor and insert it into the
  3401. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  3402. * descriptor was well-formed but could not be added; and 1 if the
  3403. * descriptor was added.
  3404. *
  3405. * If we don't add it and <b>msg</b> is not NULL, then assign to
  3406. * *<b>msg</b> a static string describing the reason for refusing the
  3407. * descriptor.
  3408. *
  3409. * This is used only by the controller.
  3410. */
  3411. int
  3412. router_load_single_router(const char *s, uint8_t purpose, int cache,
  3413. const char **msg)
  3414. {
  3415. routerinfo_t *ri;
  3416. was_router_added_t r;
  3417. smartlist_t *lst;
  3418. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  3419. tor_assert(msg);
  3420. *msg = NULL;
  3421. tor_snprintf(annotation_buf, sizeof(annotation_buf),
  3422. "@source controller\n"
  3423. "@purpose %s\n", router_purpose_to_string(purpose));
  3424. if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
  3425. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  3426. *msg = "Couldn't parse router descriptor.";
  3427. return -1;
  3428. }
  3429. tor_assert(ri->purpose == purpose);
  3430. if (router_is_me(ri)) {
  3431. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  3432. *msg = "Router's identity key matches mine.";
  3433. routerinfo_free(ri);
  3434. return 0;
  3435. }
  3436. if (!cache) /* obey the preference of the controller */
  3437. ri->cache_info.do_not_cache = 1;
  3438. lst = smartlist_create();
  3439. smartlist_add(lst, ri);
  3440. routers_update_status_from_consensus_networkstatus(lst, 0);
  3441. r = router_add_to_routerlist(ri, msg, 0, 0);
  3442. if (!WRA_WAS_ADDED(r)) {
  3443. /* we've already assigned to *msg now, and ri is already freed */
  3444. tor_assert(*msg);
  3445. if (r == ROUTER_AUTHDIR_REJECTS)
  3446. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  3447. smartlist_free(lst);
  3448. return 0;
  3449. } else {
  3450. routerlist_descriptors_added(lst, 0);
  3451. smartlist_free(lst);
  3452. log_debug(LD_DIR, "Added router to list");
  3453. return 1;
  3454. }
  3455. }
  3456. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  3457. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  3458. * are in response to a query to the network: cache them by adding them to
  3459. * the journal.
  3460. *
  3461. * Return the number of routers actually added.
  3462. *
  3463. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  3464. * uppercased fingerprints. Do not update any router whose
  3465. * fingerprint is not on the list; after updating a router, remove its
  3466. * fingerprint from the list.
  3467. *
  3468. * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
  3469. * are descriptor digests. Otherwise they are identity digests.
  3470. */
  3471. int
  3472. router_load_routers_from_string(const char *s, const char *eos,
  3473. saved_location_t saved_location,
  3474. smartlist_t *requested_fingerprints,
  3475. int descriptor_digests,
  3476. const char *prepend_annotations)
  3477. {
  3478. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  3479. char fp[HEX_DIGEST_LEN+1];
  3480. const char *msg;
  3481. int from_cache = (saved_location != SAVED_NOWHERE);
  3482. int allow_annotations = (saved_location != SAVED_NOWHERE);
  3483. int any_changed = 0;
  3484. router_parse_list_from_string(&s, eos, routers, saved_location, 0,
  3485. allow_annotations, prepend_annotations);
  3486. routers_update_status_from_consensus_networkstatus(routers, !from_cache);
  3487. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  3488. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  3489. was_router_added_t r;
  3490. char d[DIGEST_LEN];
  3491. if (requested_fingerprints) {
  3492. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3493. ri->cache_info.signed_descriptor_digest :
  3494. ri->cache_info.identity_digest,
  3495. DIGEST_LEN);
  3496. if (smartlist_string_isin(requested_fingerprints, fp)) {
  3497. smartlist_string_remove(requested_fingerprints, fp);
  3498. } else {
  3499. char *requested =
  3500. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  3501. log_warn(LD_DIR,
  3502. "We received a router descriptor with a fingerprint (%s) "
  3503. "that we never requested. (We asked for: %s.) Dropping.",
  3504. fp, requested);
  3505. tor_free(requested);
  3506. routerinfo_free(ri);
  3507. continue;
  3508. }
  3509. }
  3510. memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
  3511. r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
  3512. if (WRA_WAS_ADDED(r)) {
  3513. any_changed++;
  3514. smartlist_add(changed, ri);
  3515. routerlist_descriptors_added(changed, from_cache);
  3516. smartlist_clear(changed);
  3517. } else if (WRA_WAS_REJECTED(r)) {
  3518. download_status_t *dl_status;
  3519. dl_status = router_get_dl_status_by_descriptor_digest(d);
  3520. if (dl_status) {
  3521. log_info(LD_GENERAL, "Marking router %s as never downloadable",
  3522. hex_str(d, DIGEST_LEN));
  3523. download_status_mark_impossible(dl_status);
  3524. }
  3525. }
  3526. } SMARTLIST_FOREACH_END(ri);
  3527. routerlist_assert_ok(routerlist);
  3528. if (any_changed)
  3529. router_rebuild_store(0, &routerlist->desc_store);
  3530. smartlist_free(routers);
  3531. smartlist_free(changed);
  3532. return any_changed;
  3533. }
  3534. /** Parse one or more extrainfos from <b>s</b> (ending immediately before
  3535. * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
  3536. * router_load_routers_from_string(). */
  3537. void
  3538. router_load_extrainfo_from_string(const char *s, const char *eos,
  3539. saved_location_t saved_location,
  3540. smartlist_t *requested_fingerprints,
  3541. int descriptor_digests)
  3542. {
  3543. smartlist_t *extrainfo_list = smartlist_create();
  3544. const char *msg;
  3545. int from_cache = (saved_location != SAVED_NOWHERE);
  3546. router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
  3547. NULL);
  3548. log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
  3549. SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
  3550. was_router_added_t added =
  3551. router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
  3552. if (WRA_WAS_ADDED(added) && requested_fingerprints) {
  3553. char fp[HEX_DIGEST_LEN+1];
  3554. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3555. ei->cache_info.signed_descriptor_digest :
  3556. ei->cache_info.identity_digest,
  3557. DIGEST_LEN);
  3558. smartlist_string_remove(requested_fingerprints, fp);
  3559. /* We silently let people stuff us with extrainfos we didn't ask for,
  3560. * so long as we would have wanted them anyway. Since we always fetch
  3561. * all the extrainfos we want, and we never actually act on them
  3562. * inside Tor, this should be harmless. */
  3563. }
  3564. });
  3565. routerlist_assert_ok(routerlist);
  3566. router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
  3567. smartlist_free(extrainfo_list);
  3568. }
  3569. /** Return true iff any networkstatus includes a descriptor whose digest
  3570. * is that of <b>desc</b>. */
  3571. static int
  3572. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  3573. {
  3574. const routerstatus_t *rs;
  3575. networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3576. int caches = directory_caches_dir_info(get_options());
  3577. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3578. if (consensus) {
  3579. rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
  3580. if (rs && tor_memeq(rs->descriptor_digest,
  3581. desc->signed_descriptor_digest, DIGEST_LEN))
  3582. return 1;
  3583. }
  3584. if (caches && networkstatus_v2_list) {
  3585. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3586. {
  3587. if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
  3588. continue;
  3589. if (tor_memeq(rs->descriptor_digest,
  3590. desc->signed_descriptor_digest, DIGEST_LEN))
  3591. return 1;
  3592. });
  3593. }
  3594. return 0;
  3595. }
  3596. /** Update downloads for router descriptors and/or microdescriptors as
  3597. * appropriate. */
  3598. void
  3599. update_all_descriptor_downloads(time_t now)
  3600. {
  3601. if (get_options()->DisableNetwork)
  3602. return;
  3603. update_router_descriptor_downloads(now);
  3604. update_microdesc_downloads(now);
  3605. launch_dummy_descriptor_download_as_needed(now, get_options());
  3606. }
  3607. /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
  3608. * give it all a try again. */
  3609. void
  3610. routerlist_retry_directory_downloads(time_t now)
  3611. {
  3612. router_reset_status_download_failures();
  3613. router_reset_descriptor_download_failures();
  3614. if (get_options()->DisableNetwork)
  3615. return;
  3616. update_networkstatus_downloads(now);
  3617. update_all_descriptor_downloads(now);
  3618. }
  3619. /** Return 1 if all running sufficiently-stable routers we can use will reject
  3620. * addr:port, return 0 if any might accept it. */
  3621. int
  3622. router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port,
  3623. int need_uptime)
  3624. { /* XXXX MOVE */
  3625. addr_policy_result_t r;
  3626. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  3627. if (node->is_running &&
  3628. !node_is_unreliable(node, need_uptime, 0, 0)) {
  3629. r = compare_tor_addr_to_node_policy(addr, port, node);
  3630. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  3631. return 0; /* this one could be ok. good enough. */
  3632. }
  3633. } SMARTLIST_FOREACH_END(node);
  3634. return 1; /* all will reject. */
  3635. }
  3636. /** Return true iff <b>router</b> does not permit exit streams.
  3637. */
  3638. int
  3639. router_exit_policy_rejects_all(const routerinfo_t *router)
  3640. {
  3641. return router->policy_is_reject_star;
  3642. }
  3643. /** Add to the list of authoritative directory servers one at
  3644. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  3645. * <b>address</b> is NULL, add ourself. Return the new trusted directory
  3646. * server entry on success or NULL if we couldn't add it. */
  3647. trusted_dir_server_t *
  3648. add_trusted_dir_server(const char *nickname, const char *address,
  3649. uint16_t dir_port, uint16_t or_port,
  3650. const char *digest, const char *v3_auth_digest,
  3651. dirinfo_type_t type)
  3652. {
  3653. trusted_dir_server_t *ent;
  3654. uint32_t a;
  3655. char *hostname = NULL;
  3656. size_t dlen;
  3657. if (!trusted_dir_servers)
  3658. trusted_dir_servers = smartlist_create();
  3659. if (!address) { /* The address is us; we should guess. */
  3660. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  3661. log_warn(LD_CONFIG,
  3662. "Couldn't find a suitable address when adding ourself as a "
  3663. "trusted directory server.");
  3664. return NULL;
  3665. }
  3666. } else {
  3667. if (tor_lookup_hostname(address, &a)) {
  3668. log_warn(LD_CONFIG,
  3669. "Unable to lookup address for directory server at '%s'",
  3670. address);
  3671. return NULL;
  3672. }
  3673. hostname = tor_strdup(address);
  3674. }
  3675. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  3676. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  3677. ent->address = hostname;
  3678. ent->addr = a;
  3679. ent->dir_port = dir_port;
  3680. ent->or_port = or_port;
  3681. ent->is_running = 1;
  3682. ent->type = type;
  3683. memcpy(ent->digest, digest, DIGEST_LEN);
  3684. if (v3_auth_digest && (type & V3_DIRINFO))
  3685. memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
  3686. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  3687. ent->description = tor_malloc(dlen);
  3688. if (nickname)
  3689. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  3690. nickname, hostname, (int)dir_port);
  3691. else
  3692. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  3693. hostname, (int)dir_port);
  3694. ent->fake_status.addr = ent->addr;
  3695. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  3696. if (nickname)
  3697. strlcpy(ent->fake_status.nickname, nickname,
  3698. sizeof(ent->fake_status.nickname));
  3699. else
  3700. ent->fake_status.nickname[0] = '\0';
  3701. ent->fake_status.dir_port = ent->dir_port;
  3702. ent->fake_status.or_port = ent->or_port;
  3703. if (ent->or_port)
  3704. ent->fake_status.version_supports_begindir = 1;
  3705. ent->fake_status.version_supports_conditional_consensus = 1;
  3706. smartlist_add(trusted_dir_servers, ent);
  3707. router_dir_info_changed();
  3708. return ent;
  3709. }
  3710. /** Free storage held in <b>cert</b>. */
  3711. void
  3712. authority_cert_free(authority_cert_t *cert)
  3713. {
  3714. if (!cert)
  3715. return;
  3716. tor_free(cert->cache_info.signed_descriptor_body);
  3717. crypto_free_pk_env(cert->signing_key);
  3718. crypto_free_pk_env(cert->identity_key);
  3719. tor_free(cert);
  3720. }
  3721. /** Free storage held in <b>ds</b>. */
  3722. static void
  3723. trusted_dir_server_free(trusted_dir_server_t *ds)
  3724. {
  3725. if (!ds)
  3726. return;
  3727. tor_free(ds->nickname);
  3728. tor_free(ds->description);
  3729. tor_free(ds->address);
  3730. tor_free(ds);
  3731. }
  3732. /** Remove all members from the list of trusted dir servers. */
  3733. void
  3734. clear_trusted_dir_servers(void)
  3735. {
  3736. if (trusted_dir_servers) {
  3737. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  3738. trusted_dir_server_free(ent));
  3739. smartlist_clear(trusted_dir_servers);
  3740. } else {
  3741. trusted_dir_servers = smartlist_create();
  3742. }
  3743. router_dir_info_changed();
  3744. }
  3745. /** Return 1 if any trusted dir server supports v1 directories,
  3746. * else return 0. */
  3747. int
  3748. any_trusted_dir_is_v1_authority(void)
  3749. {
  3750. if (trusted_dir_servers)
  3751. return get_n_authorities(V1_DIRINFO) > 0;
  3752. return 0;
  3753. }
  3754. /** For every current directory connection whose purpose is <b>purpose</b>,
  3755. * and where the resource being downloaded begins with <b>prefix</b>, split
  3756. * rest of the resource into base16 fingerprints, decode them, and set the
  3757. * corresponding elements of <b>result</b> to a nonzero value.
  3758. * DOCDOC purpose==microdesc
  3759. */
  3760. static void
  3761. list_pending_downloads(digestmap_t *result,
  3762. int purpose, const char *prefix)
  3763. {
  3764. const size_t p_len = strlen(prefix);
  3765. smartlist_t *tmp = smartlist_create();
  3766. smartlist_t *conns = get_connection_array();
  3767. int flags = DSR_HEX;
  3768. if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
  3769. flags = DSR_DIGEST256|DSR_BASE64;
  3770. tor_assert(result);
  3771. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3772. if (conn->type == CONN_TYPE_DIR &&
  3773. conn->purpose == purpose &&
  3774. !conn->marked_for_close) {
  3775. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3776. if (!strcmpstart(resource, prefix))
  3777. dir_split_resource_into_fingerprints(resource + p_len,
  3778. tmp, NULL, flags);
  3779. }
  3780. } SMARTLIST_FOREACH_END(conn);
  3781. SMARTLIST_FOREACH(tmp, char *, d,
  3782. {
  3783. digestmap_set(result, d, (void*)1);
  3784. tor_free(d);
  3785. });
  3786. smartlist_free(tmp);
  3787. }
  3788. /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
  3789. * true) we are currently downloading by descriptor digest, set result[d] to
  3790. * (void*)1. */
  3791. static void
  3792. list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
  3793. {
  3794. int purpose =
  3795. extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
  3796. list_pending_downloads(result, purpose, "d/");
  3797. }
  3798. /** DOCDOC */
  3799. /*XXXX NM should use digest256, if one comes into being. */
  3800. void
  3801. list_pending_microdesc_downloads(digestmap_t *result)
  3802. {
  3803. list_pending_downloads(result, DIR_PURPOSE_FETCH_MICRODESC, "d/");
  3804. }
  3805. /** Launch downloads for all the descriptors whose digests or digests256
  3806. * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
  3807. * range.) If <b>source</b> is given, download from <b>source</b>;
  3808. * otherwise, download from an appropriate random directory server.
  3809. */
  3810. static void
  3811. initiate_descriptor_downloads(const routerstatus_t *source,
  3812. int purpose,
  3813. smartlist_t *digests,
  3814. int lo, int hi, int pds_flags)
  3815. {
  3816. int i, n = hi-lo;
  3817. char *resource, *cp;
  3818. size_t r_len;
  3819. int digest_len = DIGEST_LEN, enc_digest_len = HEX_DIGEST_LEN;
  3820. char sep = '+';
  3821. int b64_256 = 0;
  3822. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3823. /* Microdescriptors are downloaded by "-"-separated base64-encoded
  3824. * 256-bit digests. */
  3825. digest_len = DIGEST256_LEN;
  3826. enc_digest_len = BASE64_DIGEST256_LEN;
  3827. sep = '-';
  3828. b64_256 = 1;
  3829. }
  3830. if (n <= 0)
  3831. return;
  3832. if (lo < 0)
  3833. lo = 0;
  3834. if (hi > smartlist_len(digests))
  3835. hi = smartlist_len(digests);
  3836. r_len = 8 + (enc_digest_len+1)*n;
  3837. cp = resource = tor_malloc(r_len);
  3838. memcpy(cp, "d/", 2);
  3839. cp += 2;
  3840. for (i = lo; i < hi; ++i) {
  3841. if (b64_256) {
  3842. digest256_to_base64(cp, smartlist_get(digests, i));
  3843. } else {
  3844. base16_encode(cp, r_len-(cp-resource),
  3845. smartlist_get(digests,i), digest_len);
  3846. }
  3847. cp += enc_digest_len;
  3848. *cp++ = sep;
  3849. }
  3850. memcpy(cp-1, ".z", 3);
  3851. if (source) {
  3852. /* We know which authority we want. */
  3853. directory_initiate_command_routerstatus(source, purpose,
  3854. ROUTER_PURPOSE_GENERAL,
  3855. 0, /* not private */
  3856. resource, NULL, 0, 0);
  3857. } else {
  3858. directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
  3859. pds_flags);
  3860. }
  3861. tor_free(resource);
  3862. }
  3863. /** Return 0 if this routerstatus is obsolete, too new, isn't
  3864. * running, or otherwise not a descriptor that we would make any
  3865. * use of even if we had it. Else return 1. */
  3866. static INLINE int
  3867. client_would_use_router(const routerstatus_t *rs, time_t now,
  3868. const or_options_t *options)
  3869. {
  3870. if (!rs->is_flagged_running && !options->FetchUselessDescriptors) {
  3871. /* If we had this router descriptor, we wouldn't even bother using it.
  3872. * But, if we want to have a complete list, fetch it anyway. */
  3873. return 0;
  3874. }
  3875. if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
  3876. > now) {
  3877. /* Most caches probably don't have this descriptor yet. */
  3878. return 0;
  3879. }
  3880. if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
  3881. /* We'd drop it immediately for being too old. */
  3882. return 0;
  3883. }
  3884. return 1;
  3885. }
  3886. /** Max amount of hashes to download per request.
  3887. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3888. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3889. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3890. * So use 96 because it's a nice number.
  3891. */
  3892. #define MAX_DL_PER_REQUEST 96
  3893. #define MAX_MICRODESC_DL_PER_REQUEST 92
  3894. /** Don't split our requests so finely that we are requesting fewer than
  3895. * this number per server. */
  3896. #define MIN_DL_PER_REQUEST 4
  3897. /** To prevent a single screwy cache from confusing us by selective reply,
  3898. * try to split our requests into at least this many requests. */
  3899. #define MIN_REQUESTS 3
  3900. /** If we want fewer than this many descriptors, wait until we
  3901. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3902. * passed. */
  3903. #define MAX_DL_TO_DELAY 16
  3904. /** When directory clients have only a few servers to request, they batch
  3905. * them until they have more, or until this amount of time has passed. */
  3906. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3907. /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
  3908. * router descriptor digests or microdescriptor digest256s in
  3909. * <b>downloadable</b>, decide whether to delay fetching until we have more.
  3910. * If we don't want to delay, launch one or more requests to the appropriate
  3911. * directory authorities.
  3912. */
  3913. void
  3914. launch_descriptor_downloads(int purpose,
  3915. smartlist_t *downloadable,
  3916. const routerstatus_t *source, time_t now)
  3917. {
  3918. int should_delay = 0, n_downloadable;
  3919. const or_options_t *options = get_options();
  3920. const char *descname;
  3921. tor_assert(purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  3922. purpose == DIR_PURPOSE_FETCH_MICRODESC);
  3923. descname = (purpose == DIR_PURPOSE_FETCH_SERVERDESC) ?
  3924. "routerdesc" : "microdesc";
  3925. n_downloadable = smartlist_len(downloadable);
  3926. if (!directory_fetches_dir_info_early(options)) {
  3927. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3928. log_debug(LD_DIR,
  3929. "There are enough downloadable %ss to launch requests.",
  3930. descname);
  3931. should_delay = 0;
  3932. } else {
  3933. should_delay = (last_descriptor_download_attempted +
  3934. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3935. if (!should_delay && n_downloadable) {
  3936. if (last_descriptor_download_attempted) {
  3937. log_info(LD_DIR,
  3938. "There are not many downloadable %ss, but we've "
  3939. "been waiting long enough (%d seconds). Downloading.",
  3940. descname,
  3941. (int)(now-last_descriptor_download_attempted));
  3942. } else {
  3943. log_info(LD_DIR,
  3944. "There are not many downloadable %ss, but we haven't "
  3945. "tried downloading descriptors recently. Downloading.",
  3946. descname);
  3947. }
  3948. }
  3949. }
  3950. }
  3951. /* XXX should we consider having even the dir mirrors delay
  3952. * a little bit, so we don't load the authorities as much? -RD
  3953. * I don't think so. If we do, clients that want those descriptors may
  3954. * not actually find them if the caches haven't got them yet. -NM
  3955. */
  3956. if (! should_delay && n_downloadable) {
  3957. int i, n_per_request;
  3958. const char *req_plural = "", *rtr_plural = "";
  3959. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3960. if (! authdir_mode_any_nonhidserv(options)) {
  3961. /* If we wind up going to the authorities, we want to only open one
  3962. * connection to each authority at a time, so that we don't overload
  3963. * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
  3964. * regardless of whether we're a cache or not; it gets ignored if we're
  3965. * not calling router_pick_trusteddirserver.
  3966. *
  3967. * Setting this flag can make initiate_descriptor_downloads() ignore
  3968. * requests. We need to make sure that we do in fact call
  3969. * update_router_descriptor_downloads() later on, once the connections
  3970. * have succeeded or failed.
  3971. */
  3972. pds_flags |= (purpose == DIR_PURPOSE_FETCH_MICRODESC) ?
  3973. PDS_NO_EXISTING_MICRODESC_FETCH :
  3974. PDS_NO_EXISTING_SERVERDESC_FETCH;
  3975. }
  3976. n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
  3977. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3978. if (n_per_request > MAX_MICRODESC_DL_PER_REQUEST)
  3979. n_per_request = MAX_MICRODESC_DL_PER_REQUEST;
  3980. } else {
  3981. if (n_per_request > MAX_DL_PER_REQUEST)
  3982. n_per_request = MAX_DL_PER_REQUEST;
  3983. }
  3984. if (n_per_request < MIN_DL_PER_REQUEST)
  3985. n_per_request = MIN_DL_PER_REQUEST;
  3986. if (n_downloadable > n_per_request)
  3987. req_plural = rtr_plural = "s";
  3988. else if (n_downloadable > 1)
  3989. rtr_plural = "s";
  3990. log_info(LD_DIR,
  3991. "Launching %d request%s for %d router%s, %d at a time",
  3992. CEIL_DIV(n_downloadable, n_per_request),
  3993. req_plural, n_downloadable, rtr_plural, n_per_request);
  3994. smartlist_sort_digests(downloadable);
  3995. for (i=0; i < n_downloadable; i += n_per_request) {
  3996. initiate_descriptor_downloads(source, purpose,
  3997. downloadable, i, i+n_per_request,
  3998. pds_flags);
  3999. }
  4000. last_descriptor_download_attempted = now;
  4001. }
  4002. }
  4003. /** Launch downloads for router status as needed, using the strategy used by
  4004. * authorities and caches: based on the v2 networkstatuses we have, download
  4005. * every descriptor we don't have but would serve, from a random authority
  4006. * that lists it. */
  4007. static void
  4008. update_router_descriptor_cache_downloads_v2(time_t now)
  4009. {
  4010. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  4011. smartlist_t **download_from; /* ... and, what will we dl from it? */
  4012. digestmap_t *map; /* Which descs are in progress, or assigned? */
  4013. int i, j, n;
  4014. int n_download;
  4015. const or_options_t *options = get_options();
  4016. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  4017. if (! directory_fetches_dir_info_early(options)) {
  4018. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
  4019. "on a non-dir-mirror?");
  4020. }
  4021. if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
  4022. return;
  4023. map = digestmap_new();
  4024. n = smartlist_len(networkstatus_v2_list);
  4025. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  4026. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  4027. /* Set map[d]=1 for the digest of every descriptor that we are currently
  4028. * downloading. */
  4029. list_pending_descriptor_downloads(map, 0);
  4030. /* For the digest of every descriptor that we don't have, and that we aren't
  4031. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  4032. * about that descriptor, and we haven't already failed to get that
  4033. * descriptor from the corresponding authority.
  4034. */
  4035. n_download = 0;
  4036. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  4037. {
  4038. trusted_dir_server_t *ds;
  4039. smartlist_t *dl;
  4040. dl = downloadable[ns_sl_idx] = smartlist_create();
  4041. download_from[ns_sl_idx] = smartlist_create();
  4042. if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
  4043. /* Don't download if the networkstatus is almost ancient. */
  4044. /* Actually, I suspect what's happening here is that we ask
  4045. * for the descriptor when we have a given networkstatus,
  4046. * and then we get a newer networkstatus, and then we receive
  4047. * the descriptor. Having a networkstatus actually expire is
  4048. * probably a rare event, and we'll probably be happiest if
  4049. * we take this clause out. -RD */
  4050. continue;
  4051. }
  4052. /* Don't try dirservers that we think are down -- we might have
  4053. * just tried them and just marked them as down. */
  4054. ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
  4055. if (ds && !ds->is_running)
  4056. continue;
  4057. SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
  4058. {
  4059. if (!rs->need_to_mirror)
  4060. continue;
  4061. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  4062. log_warn(LD_BUG,
  4063. "We have a router descriptor, but need_to_mirror=1.");
  4064. rs->need_to_mirror = 0;
  4065. continue;
  4066. }
  4067. if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
  4068. rs->need_to_mirror = 0;
  4069. continue;
  4070. }
  4071. if (digestmap_get(map, rs->descriptor_digest)) {
  4072. /* We're downloading it already. */
  4073. continue;
  4074. } else {
  4075. /* We could download it from this guy. */
  4076. smartlist_add(dl, rs->descriptor_digest);
  4077. ++n_download;
  4078. }
  4079. });
  4080. });
  4081. /* At random, assign descriptors to authorities such that:
  4082. * - if d is a member of some downloadable[x], d is a member of some
  4083. * download_from[y]. (Everything we want to download, we try to download
  4084. * from somebody.)
  4085. * - If d is a member of download_from[y], d is a member of downloadable[y].
  4086. * (We only try to download descriptors from authorities who claim to have
  4087. * them.)
  4088. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  4089. * (We don't try to download anything from two authorities concurrently.)
  4090. */
  4091. while (n_download) {
  4092. int which_ns = crypto_rand_int(n);
  4093. smartlist_t *dl = downloadable[which_ns];
  4094. int idx;
  4095. char *d;
  4096. if (!smartlist_len(dl))
  4097. continue;
  4098. idx = crypto_rand_int(smartlist_len(dl));
  4099. d = smartlist_get(dl, idx);
  4100. if (! digestmap_get(map, d)) {
  4101. smartlist_add(download_from[which_ns], d);
  4102. digestmap_set(map, d, (void*) 1);
  4103. }
  4104. smartlist_del(dl, idx);
  4105. --n_download;
  4106. }
  4107. /* Now, we can actually launch our requests. */
  4108. for (i=0; i<n; ++i) {
  4109. networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
  4110. trusted_dir_server_t *ds =
  4111. router_get_trusteddirserver_by_digest(ns->identity_digest);
  4112. smartlist_t *dl = download_from[i];
  4113. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  4114. if (! authdir_mode_any_nonhidserv(options))
  4115. pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
  4116. if (!ds) {
  4117. log_info(LD_DIR, "Networkstatus with no corresponding authority!");
  4118. continue;
  4119. }
  4120. if (! smartlist_len(dl))
  4121. continue;
  4122. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  4123. smartlist_len(dl), ds->nickname);
  4124. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  4125. initiate_descriptor_downloads(&(ds->fake_status),
  4126. DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
  4127. j+MAX_DL_PER_REQUEST, pds_flags);
  4128. }
  4129. }
  4130. for (i=0; i<n; ++i) {
  4131. smartlist_free(download_from[i]);
  4132. smartlist_free(downloadable[i]);
  4133. }
  4134. tor_free(download_from);
  4135. tor_free(downloadable);
  4136. digestmap_free(map,NULL);
  4137. }
  4138. /** For any descriptor that we want that's currently listed in
  4139. * <b>consensus</b>, download it as appropriate. */
  4140. void
  4141. update_consensus_router_descriptor_downloads(time_t now, int is_vote,
  4142. networkstatus_t *consensus)
  4143. {
  4144. const or_options_t *options = get_options();
  4145. digestmap_t *map = NULL;
  4146. smartlist_t *no_longer_old = smartlist_create();
  4147. smartlist_t *downloadable = smartlist_create();
  4148. routerstatus_t *source = NULL;
  4149. int authdir = authdir_mode(options);
  4150. int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
  4151. n_inprogress=0, n_in_oldrouters=0;
  4152. if (directory_too_idle_to_fetch_descriptors(options, now))
  4153. goto done;
  4154. if (!consensus)
  4155. goto done;
  4156. if (is_vote) {
  4157. /* where's it from, so we know whom to ask for descriptors */
  4158. trusted_dir_server_t *ds;
  4159. networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
  4160. tor_assert(voter);
  4161. ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
  4162. if (ds)
  4163. source = &(ds->fake_status);
  4164. else
  4165. log_warn(LD_DIR, "couldn't lookup source from vote?");
  4166. }
  4167. map = digestmap_new();
  4168. list_pending_descriptor_downloads(map, 0);
  4169. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
  4170. routerstatus_t *rs =
  4171. is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
  4172. signed_descriptor_t *sd;
  4173. if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
  4174. const routerinfo_t *ri;
  4175. ++n_have;
  4176. if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
  4177. tor_memneq(ri->cache_info.signed_descriptor_digest,
  4178. sd->signed_descriptor_digest, DIGEST_LEN)) {
  4179. /* We have a descriptor with this digest, but either there is no
  4180. * entry in routerlist with the same ID (!ri), or there is one,
  4181. * but the identity digest differs (memcmp).
  4182. */
  4183. smartlist_add(no_longer_old, sd);
  4184. ++n_in_oldrouters; /* We have it in old_routers. */
  4185. }
  4186. continue; /* We have it already. */
  4187. }
  4188. if (digestmap_get(map, rs->descriptor_digest)) {
  4189. ++n_inprogress;
  4190. continue; /* We have an in-progress download. */
  4191. }
  4192. if (!download_status_is_ready(&rs->dl_status, now,
  4193. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  4194. ++n_delayed; /* Not ready for retry. */
  4195. continue;
  4196. }
  4197. if (authdir && dirserv_would_reject_router(rs)) {
  4198. ++n_would_reject;
  4199. continue; /* We would throw it out immediately. */
  4200. }
  4201. if (!directory_caches_dir_info(options) &&
  4202. !client_would_use_router(rs, now, options)) {
  4203. ++n_wouldnt_use;
  4204. continue; /* We would never use it ourself. */
  4205. }
  4206. if (is_vote && source) {
  4207. char time_bufnew[ISO_TIME_LEN+1];
  4208. char time_bufold[ISO_TIME_LEN+1];
  4209. const routerinfo_t *oldrouter;
  4210. oldrouter = router_get_by_id_digest(rs->identity_digest);
  4211. format_iso_time(time_bufnew, rs->published_on);
  4212. if (oldrouter)
  4213. format_iso_time(time_bufold, oldrouter->cache_info.published_on);
  4214. log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
  4215. routerstatus_describe(rs),
  4216. time_bufnew,
  4217. oldrouter ? time_bufold : "none",
  4218. source->nickname, oldrouter ? "known" : "unknown");
  4219. }
  4220. smartlist_add(downloadable, rs->descriptor_digest);
  4221. } SMARTLIST_FOREACH_END(rsp);
  4222. if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
  4223. && smartlist_len(no_longer_old)) {
  4224. routerlist_t *rl = router_get_routerlist();
  4225. log_info(LD_DIR, "%d router descriptors listed in consensus are "
  4226. "currently in old_routers; making them current.",
  4227. smartlist_len(no_longer_old));
  4228. SMARTLIST_FOREACH(no_longer_old, signed_descriptor_t *, sd, {
  4229. const char *msg;
  4230. was_router_added_t r;
  4231. routerinfo_t *ri = routerlist_reparse_old(rl, sd);
  4232. if (!ri) {
  4233. log_warn(LD_BUG, "Failed to re-parse a router.");
  4234. continue;
  4235. }
  4236. r = router_add_to_routerlist(ri, &msg, 1, 0);
  4237. if (WRA_WAS_OUTDATED(r)) {
  4238. log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
  4239. msg?msg:"???");
  4240. }
  4241. });
  4242. routerlist_assert_ok(rl);
  4243. }
  4244. log_info(LD_DIR,
  4245. "%d router descriptors downloadable. %d delayed; %d present "
  4246. "(%d of those were in old_routers); %d would_reject; "
  4247. "%d wouldnt_use; %d in progress.",
  4248. smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
  4249. n_would_reject, n_wouldnt_use, n_inprogress);
  4250. launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC,
  4251. downloadable, source, now);
  4252. digestmap_free(map, NULL);
  4253. done:
  4254. smartlist_free(downloadable);
  4255. smartlist_free(no_longer_old);
  4256. }
  4257. /** How often should we launch a server/authority request to be sure of getting
  4258. * a guess for our IP? */
  4259. /*XXXX023 this info should come from netinfo cells or something, or we should
  4260. * do this only when we aren't seeing incoming data. see bug 652. */
  4261. #define DUMMY_DOWNLOAD_INTERVAL (20*60)
  4262. /** As needed, launch a dummy router descriptor fetch to see if our
  4263. * address has changed. */
  4264. static void
  4265. launch_dummy_descriptor_download_as_needed(time_t now,
  4266. const or_options_t *options)
  4267. {
  4268. static time_t last_dummy_download = 0;
  4269. /* XXXX023 we could be smarter here; see notes on bug 652. */
  4270. /* If we're a server that doesn't have a configured address, we rely on
  4271. * directory fetches to learn when our address changes. So if we haven't
  4272. * tried to get any routerdescs in a long time, try a dummy fetch now. */
  4273. if (!options->Address &&
  4274. server_mode(options) &&
  4275. last_descriptor_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
  4276. last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
  4277. last_dummy_download = now;
  4278. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  4279. ROUTER_PURPOSE_GENERAL, "authority.z",
  4280. PDS_RETRY_IF_NO_SERVERS);
  4281. }
  4282. }
  4283. /** Launch downloads for router status as needed. */
  4284. void
  4285. update_router_descriptor_downloads(time_t now)
  4286. {
  4287. const or_options_t *options = get_options();
  4288. if (should_delay_dir_fetches(options))
  4289. return;
  4290. if (!we_fetch_router_descriptors(options))
  4291. return;
  4292. if (directory_fetches_dir_info_early(options)) {
  4293. update_router_descriptor_cache_downloads_v2(now);
  4294. }
  4295. update_consensus_router_descriptor_downloads(now, 0,
  4296. networkstatus_get_reasonably_live_consensus(now, FLAV_NS));
  4297. }
  4298. /** Launch extrainfo downloads as needed. */
  4299. void
  4300. update_extrainfo_downloads(time_t now)
  4301. {
  4302. const or_options_t *options = get_options();
  4303. routerlist_t *rl;
  4304. smartlist_t *wanted;
  4305. digestmap_t *pending;
  4306. int old_routers, i;
  4307. int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
  4308. if (! options->DownloadExtraInfo)
  4309. return;
  4310. if (should_delay_dir_fetches(options))
  4311. return;
  4312. if (!router_have_minimum_dir_info())
  4313. return;
  4314. pending = digestmap_new();
  4315. list_pending_descriptor_downloads(pending, 1);
  4316. rl = router_get_routerlist();
  4317. wanted = smartlist_create();
  4318. for (old_routers = 0; old_routers < 2; ++old_routers) {
  4319. smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
  4320. for (i = 0; i < smartlist_len(lst); ++i) {
  4321. signed_descriptor_t *sd;
  4322. char *d;
  4323. if (old_routers)
  4324. sd = smartlist_get(lst, i);
  4325. else
  4326. sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
  4327. if (sd->is_extrainfo)
  4328. continue; /* This should never happen. */
  4329. if (old_routers && !router_get_by_id_digest(sd->identity_digest))
  4330. continue; /* Couldn't check the signature if we got it. */
  4331. if (sd->extrainfo_is_bogus)
  4332. continue;
  4333. d = sd->extra_info_digest;
  4334. if (tor_digest_is_zero(d)) {
  4335. ++n_no_ei;
  4336. continue;
  4337. }
  4338. if (eimap_get(rl->extra_info_map, d)) {
  4339. ++n_have;
  4340. continue;
  4341. }
  4342. if (!download_status_is_ready(&sd->ei_dl_status, now,
  4343. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  4344. ++n_delay;
  4345. continue;
  4346. }
  4347. if (digestmap_get(pending, d)) {
  4348. ++n_pending;
  4349. continue;
  4350. }
  4351. smartlist_add(wanted, d);
  4352. }
  4353. }
  4354. digestmap_free(pending, NULL);
  4355. log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
  4356. "with present ei, %d delaying, %d pending, %d downloadable.",
  4357. n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
  4358. smartlist_shuffle(wanted);
  4359. for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
  4360. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
  4361. wanted, i, i + MAX_DL_PER_REQUEST,
  4362. PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
  4363. }
  4364. smartlist_free(wanted);
  4365. }
  4366. /** True iff, the last time we checked whether we had enough directory info
  4367. * to build circuits, the answer was "yes". */
  4368. static int have_min_dir_info = 0;
  4369. /** True iff enough has changed since the last time we checked whether we had
  4370. * enough directory info to build circuits that our old answer can no longer
  4371. * be trusted. */
  4372. static int need_to_update_have_min_dir_info = 1;
  4373. /** String describing what we're missing before we have enough directory
  4374. * info. */
  4375. static char dir_info_status[128] = "";
  4376. /** Return true iff we have enough networkstatus and router information to
  4377. * start building circuits. Right now, this means "more than half the
  4378. * networkstatus documents, and at least 1/4 of expected routers." */
  4379. //XXX should consider whether we have enough exiting nodes here.
  4380. int
  4381. router_have_minimum_dir_info(void)
  4382. {
  4383. if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
  4384. update_router_have_minimum_dir_info();
  4385. need_to_update_have_min_dir_info = 0;
  4386. }
  4387. return have_min_dir_info;
  4388. }
  4389. /** Called when our internal view of the directory has changed. This can be
  4390. * when the authorities change, networkstatuses change, the list of routerdescs
  4391. * changes, or number of running routers changes.
  4392. */
  4393. void
  4394. router_dir_info_changed(void)
  4395. {
  4396. need_to_update_have_min_dir_info = 1;
  4397. rend_hsdir_routers_changed();
  4398. }
  4399. /** Return a string describing what we're missing before we have enough
  4400. * directory info. */
  4401. const char *
  4402. get_dir_info_status_string(void)
  4403. {
  4404. return dir_info_status;
  4405. }
  4406. /** Iterate over the servers listed in <b>consensus</b>, and count how many of
  4407. * them seem like ones we'd use, and how many of <em>those</em> we have
  4408. * descriptors for. Store the former in *<b>num_usable</b> and the latter in
  4409. * *<b>num_present</b>. If <b>in_set</b> is non-NULL, only consider those
  4410. * routers in <b>in_set</b>.
  4411. */
  4412. static void
  4413. count_usable_descriptors(int *num_present, int *num_usable,
  4414. const networkstatus_t *consensus,
  4415. const or_options_t *options, time_t now,
  4416. routerset_t *in_set)
  4417. {
  4418. const int md = (consensus->flavor == FLAV_MICRODESC);
  4419. *num_present = 0, *num_usable=0;
  4420. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *, rs)
  4421. {
  4422. if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1))
  4423. continue;
  4424. if (client_would_use_router(rs, now, options)) {
  4425. const char * const digest = rs->descriptor_digest;
  4426. int present;
  4427. ++*num_usable; /* the consensus says we want it. */
  4428. if (md)
  4429. present = NULL != microdesc_cache_lookup_by_digest256(NULL, digest);
  4430. else
  4431. present = NULL != router_get_by_descriptor_digest(digest);
  4432. if (present) {
  4433. /* we have the descriptor listed in the consensus. */
  4434. ++*num_present;
  4435. }
  4436. }
  4437. }
  4438. SMARTLIST_FOREACH_END(rs);
  4439. log_debug(LD_DIR, "%d usable, %d present.", *num_usable, *num_present);
  4440. }
  4441. /** We just fetched a new set of descriptors. Compute how far through
  4442. * the "loading descriptors" bootstrapping phase we are, so we can inform
  4443. * the controller of our progress. */
  4444. int
  4445. count_loading_descriptors_progress(void)
  4446. {
  4447. int num_present = 0, num_usable=0;
  4448. time_t now = time(NULL);
  4449. const networkstatus_t *consensus =
  4450. networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
  4451. double fraction;
  4452. if (!consensus)
  4453. return 0; /* can't count descriptors if we have no list of them */
  4454. count_usable_descriptors(&num_present, &num_usable,
  4455. consensus, get_options(), now, NULL);
  4456. if (num_usable == 0)
  4457. return 0; /* don't div by 0 */
  4458. fraction = num_present / (num_usable/4.);
  4459. if (fraction > 1.0)
  4460. return 0; /* it's not the number of descriptors holding us back */
  4461. return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
  4462. (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
  4463. BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
  4464. }
  4465. /** Change the value of have_min_dir_info, setting it true iff we have enough
  4466. * network and router information to build circuits. Clear the value of
  4467. * need_to_update_have_min_dir_info. */
  4468. static void
  4469. update_router_have_minimum_dir_info(void)
  4470. {
  4471. int num_present = 0, num_usable=0;
  4472. time_t now = time(NULL);
  4473. int res;
  4474. const or_options_t *options = get_options();
  4475. const networkstatus_t *consensus =
  4476. networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
  4477. int using_md;
  4478. if (!consensus) {
  4479. if (!networkstatus_get_latest_consensus())
  4480. strlcpy(dir_info_status, "We have no usable consensus.",
  4481. sizeof(dir_info_status));
  4482. else
  4483. strlcpy(dir_info_status, "We have no recent usable consensus.",
  4484. sizeof(dir_info_status));
  4485. res = 0;
  4486. goto done;
  4487. }
  4488. if (should_delay_dir_fetches(get_options())) {
  4489. log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
  4490. strlcpy(dir_info_status, "No live bridge descriptors.",
  4491. sizeof(dir_info_status));
  4492. res = 0;
  4493. goto done;
  4494. }
  4495. using_md = consensus->flavor == FLAV_MICRODESC;
  4496. count_usable_descriptors(&num_present, &num_usable, consensus, options, now,
  4497. NULL);
  4498. if (num_present < num_usable/4) {
  4499. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  4500. "We have only %d/%d usable %sdescriptors.",
  4501. num_present, num_usable, using_md ? "micro" : "");
  4502. res = 0;
  4503. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
  4504. goto done;
  4505. } else if (num_present < 2) {
  4506. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  4507. "Only %d %sdescriptor%s here and believed reachable!",
  4508. num_present, using_md ? "micro" : "", num_present ? "" : "s");
  4509. res = 0;
  4510. goto done;
  4511. }
  4512. /* Check for entry nodes. */
  4513. if (options->EntryNodes) {
  4514. count_usable_descriptors(&num_present, &num_usable, consensus, options,
  4515. now, options->EntryNodes);
  4516. if (!num_usable || !num_present) {
  4517. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  4518. "We have only %d/%d usable entry node %sdescriptors.",
  4519. num_present, num_usable, using_md?"micro":"");
  4520. res = 0;
  4521. goto done;
  4522. }
  4523. }
  4524. res = 1;
  4525. done:
  4526. if (res && !have_min_dir_info) {
  4527. log(LOG_NOTICE, LD_DIR,
  4528. "We now have enough directory information to build circuits.");
  4529. control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
  4530. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0);
  4531. }
  4532. if (!res && have_min_dir_info) {
  4533. int quiet = directory_too_idle_to_fetch_descriptors(options, now);
  4534. log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
  4535. "Our directory information is no longer up-to-date "
  4536. "enough to build circuits: %s", dir_info_status);
  4537. /* a) make us log when we next complete a circuit, so we know when Tor
  4538. * is back up and usable, and b) disable some activities that Tor
  4539. * should only do while circuits are working, like reachability tests
  4540. * and fetching bridge descriptors only over circuits. */
  4541. can_complete_circuit = 0;
  4542. control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
  4543. }
  4544. have_min_dir_info = res;
  4545. need_to_update_have_min_dir_info = 0;
  4546. }
  4547. /** Reset the descriptor download failure count on all routers, so that we
  4548. * can retry any long-failed routers immediately.
  4549. */
  4550. void
  4551. router_reset_descriptor_download_failures(void)
  4552. {
  4553. networkstatus_reset_download_failures();
  4554. last_descriptor_download_attempted = 0;
  4555. if (!routerlist)
  4556. return;
  4557. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  4558. {
  4559. download_status_reset(&ri->cache_info.ei_dl_status);
  4560. });
  4561. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  4562. {
  4563. download_status_reset(&sd->ei_dl_status);
  4564. });
  4565. }
  4566. /** Any changes in a router descriptor's publication time larger than this are
  4567. * automatically non-cosmetic. */
  4568. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
  4569. /** We allow uptime to vary from how much it ought to be by this much. */
  4570. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  4571. /** Return true iff the only differences between r1 and r2 are such that
  4572. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  4573. */
  4574. int
  4575. router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
  4576. {
  4577. time_t r1pub, r2pub;
  4578. long time_difference;
  4579. tor_assert(r1 && r2);
  4580. /* r1 should be the one that was published first. */
  4581. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  4582. const routerinfo_t *ri_tmp = r2;
  4583. r2 = r1;
  4584. r1 = ri_tmp;
  4585. }
  4586. /* If any key fields differ, they're different. */
  4587. if (strcasecmp(r1->address, r2->address) ||
  4588. strcasecmp(r1->nickname, r2->nickname) ||
  4589. r1->or_port != r2->or_port ||
  4590. r1->dir_port != r2->dir_port ||
  4591. r1->purpose != r2->purpose ||
  4592. crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
  4593. crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
  4594. strcasecmp(r1->platform, r2->platform) ||
  4595. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  4596. (!r1->contact_info && r2->contact_info) ||
  4597. (r1->contact_info && r2->contact_info &&
  4598. strcasecmp(r1->contact_info, r2->contact_info)) ||
  4599. r1->is_hibernating != r2->is_hibernating ||
  4600. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  4601. return 0;
  4602. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  4603. return 0;
  4604. if (r1->declared_family && r2->declared_family) {
  4605. int i, n;
  4606. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  4607. return 0;
  4608. n = smartlist_len(r1->declared_family);
  4609. for (i=0; i < n; ++i) {
  4610. if (strcasecmp(smartlist_get(r1->declared_family, i),
  4611. smartlist_get(r2->declared_family, i)))
  4612. return 0;
  4613. }
  4614. }
  4615. /* Did bandwidth change a lot? */
  4616. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  4617. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  4618. return 0;
  4619. /* Did the bandwidthrate or bandwidthburst change? */
  4620. if ((r1->bandwidthrate != r2->bandwidthrate) ||
  4621. (r1->bandwidthburst != r2->bandwidthburst))
  4622. return 0;
  4623. /* Did more than 12 hours pass? */
  4624. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  4625. < r2->cache_info.published_on)
  4626. return 0;
  4627. /* Did uptime fail to increase by approximately the amount we would think,
  4628. * give or take some slop? */
  4629. r1pub = r1->cache_info.published_on;
  4630. r2pub = r2->cache_info.published_on;
  4631. time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  4632. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  4633. time_difference > r1->uptime * .05 &&
  4634. time_difference > r2->uptime * .05)
  4635. return 0;
  4636. /* Otherwise, the difference is cosmetic. */
  4637. return 1;
  4638. }
  4639. /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
  4640. * extrainfo document
  4641. * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
  4642. * dropped. Return 0 for "compatible", return 1 for "reject, and inform
  4643. * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
  4644. * <b>msg</b> is present, set *<b>msg</b> to a description of the
  4645. * incompatibility (if any).
  4646. **/
  4647. int
  4648. routerinfo_incompatible_with_extrainfo(const routerinfo_t *ri,
  4649. extrainfo_t *ei,
  4650. signed_descriptor_t *sd,
  4651. const char **msg)
  4652. {
  4653. int digest_matches, r=1;
  4654. tor_assert(ri);
  4655. tor_assert(ei);
  4656. if (!sd)
  4657. sd = (signed_descriptor_t*)&ri->cache_info;
  4658. if (ei->bad_sig) {
  4659. if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
  4660. return 1;
  4661. }
  4662. digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
  4663. sd->extra_info_digest, DIGEST_LEN);
  4664. /* The identity must match exactly to have been generated at the same time
  4665. * by the same router. */
  4666. if (tor_memneq(ri->cache_info.identity_digest,
  4667. ei->cache_info.identity_digest,
  4668. DIGEST_LEN)) {
  4669. if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
  4670. goto err; /* different servers */
  4671. }
  4672. if (ei->pending_sig) {
  4673. char signed_digest[128];
  4674. if (crypto_pk_public_checksig(ri->identity_pkey,
  4675. signed_digest, sizeof(signed_digest),
  4676. ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
  4677. tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
  4678. DIGEST_LEN)) {
  4679. ei->bad_sig = 1;
  4680. tor_free(ei->pending_sig);
  4681. if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
  4682. goto err; /* Bad signature, or no match. */
  4683. }
  4684. ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
  4685. tor_free(ei->pending_sig);
  4686. }
  4687. if (ei->cache_info.published_on < sd->published_on) {
  4688. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4689. goto err;
  4690. } else if (ei->cache_info.published_on > sd->published_on) {
  4691. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4692. r = -1;
  4693. goto err;
  4694. }
  4695. if (!digest_matches) {
  4696. if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
  4697. goto err; /* Digest doesn't match declared value. */
  4698. }
  4699. return 0;
  4700. err:
  4701. if (digest_matches) {
  4702. /* This signature was okay, and the digest was right: This is indeed the
  4703. * corresponding extrainfo. But insanely, it doesn't match the routerinfo
  4704. * that lists it. Don't try to fetch this one again. */
  4705. sd->extrainfo_is_bogus = 1;
  4706. }
  4707. return r;
  4708. }
  4709. /** Assert that the internal representation of <b>rl</b> is
  4710. * self-consistent. */
  4711. void
  4712. routerlist_assert_ok(const routerlist_t *rl)
  4713. {
  4714. routerinfo_t *r2;
  4715. signed_descriptor_t *sd2;
  4716. if (!rl)
  4717. return;
  4718. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  4719. {
  4720. r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
  4721. tor_assert(r == r2);
  4722. sd2 = sdmap_get(rl->desc_digest_map,
  4723. r->cache_info.signed_descriptor_digest);
  4724. tor_assert(&(r->cache_info) == sd2);
  4725. tor_assert(r->cache_info.routerlist_index == r_sl_idx);
  4726. /* XXXX
  4727. *
  4728. * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
  4729. * commenting this out is just a band-aid.
  4730. *
  4731. * The problem is that, although well-behaved router descriptors
  4732. * should never have the same value for their extra_info_digest, it's
  4733. * possible for ill-behaved routers to claim whatever they like there.
  4734. *
  4735. * The real answer is to trash desc_by_eid_map and instead have
  4736. * something that indicates for a given extra-info digest we want,
  4737. * what its download status is. We'll do that as a part of routerlist
  4738. * refactoring once consensus directories are in. For now,
  4739. * this rep violation is probably harmless: an adversary can make us
  4740. * reset our retry count for an extrainfo, but that's not the end
  4741. * of the world. Changing the representation in 0.2.0.x would just
  4742. * destabilize the codebase.
  4743. if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
  4744. signed_descriptor_t *sd3 =
  4745. sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
  4746. tor_assert(sd3 == &(r->cache_info));
  4747. }
  4748. */
  4749. });
  4750. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  4751. {
  4752. r2 = rimap_get(rl->identity_map, sd->identity_digest);
  4753. tor_assert(sd != &(r2->cache_info));
  4754. sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  4755. tor_assert(sd == sd2);
  4756. tor_assert(sd->routerlist_index == sd_sl_idx);
  4757. /* XXXX see above.
  4758. if (!tor_digest_is_zero(sd->extra_info_digest)) {
  4759. signed_descriptor_t *sd3 =
  4760. sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
  4761. tor_assert(sd3 == sd);
  4762. }
  4763. */
  4764. });
  4765. RIMAP_FOREACH(rl->identity_map, d, r) {
  4766. tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
  4767. } DIGESTMAP_FOREACH_END;
  4768. SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
  4769. tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
  4770. } DIGESTMAP_FOREACH_END;
  4771. SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
  4772. tor_assert(!tor_digest_is_zero(d));
  4773. tor_assert(sd);
  4774. tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
  4775. } DIGESTMAP_FOREACH_END;
  4776. EIMAP_FOREACH(rl->extra_info_map, d, ei) {
  4777. signed_descriptor_t *sd;
  4778. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4779. d, DIGEST_LEN));
  4780. sd = sdmap_get(rl->desc_by_eid_map,
  4781. ei->cache_info.signed_descriptor_digest);
  4782. // tor_assert(sd); // XXXX see above
  4783. if (sd) {
  4784. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4785. sd->extra_info_digest, DIGEST_LEN));
  4786. }
  4787. } DIGESTMAP_FOREACH_END;
  4788. }
  4789. /** Allocate and return a new string representing the contact info
  4790. * and platform string for <b>router</b>,
  4791. * surrounded by quotes and using standard C escapes.
  4792. *
  4793. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  4794. * thread. Also, each call invalidates the last-returned value, so don't
  4795. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  4796. *
  4797. * If <b>router</b> is NULL, it just frees its internal memory and returns.
  4798. */
  4799. const char *
  4800. esc_router_info(const routerinfo_t *router)
  4801. {
  4802. static char *info=NULL;
  4803. char *esc_contact, *esc_platform;
  4804. size_t len;
  4805. tor_free(info);
  4806. if (!router)
  4807. return NULL; /* we're exiting; just free the memory we use */
  4808. esc_contact = esc_for_log(router->contact_info);
  4809. esc_platform = esc_for_log(router->platform);
  4810. len = strlen(esc_contact)+strlen(esc_platform)+32;
  4811. info = tor_malloc(len);
  4812. tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
  4813. esc_platform);
  4814. tor_free(esc_contact);
  4815. tor_free(esc_platform);
  4816. return info;
  4817. }
  4818. /** Helper for sorting: compare two routerinfos by their identity
  4819. * digest. */
  4820. static int
  4821. _compare_routerinfo_by_id_digest(const void **a, const void **b)
  4822. {
  4823. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  4824. return fast_memcmp(first->cache_info.identity_digest,
  4825. second->cache_info.identity_digest,
  4826. DIGEST_LEN);
  4827. }
  4828. /** Sort a list of routerinfo_t in ascending order of identity digest. */
  4829. void
  4830. routers_sort_by_identity(smartlist_t *routers)
  4831. {
  4832. smartlist_sort(routers, _compare_routerinfo_by_id_digest);
  4833. }
  4834. /** A routerset specifies constraints on a set of possible routerinfos, based
  4835. * on their names, identities, or addresses. It is optimized for determining
  4836. * whether a router is a member or not, in O(1+P) time, where P is the number
  4837. * of address policy constraints. */
  4838. struct routerset_t {
  4839. /** A list of strings for the elements of the policy. Each string is either
  4840. * a nickname, a hexadecimal identity fingerprint, or an address policy. A
  4841. * router belongs to the set if its nickname OR its identity OR its address
  4842. * matches an entry here. */
  4843. smartlist_t *list;
  4844. /** A map from lowercase nicknames of routers in the set to (void*)1 */
  4845. strmap_t *names;
  4846. /** A map from identity digests routers in the set to (void*)1 */
  4847. digestmap_t *digests;
  4848. /** An address policy for routers in the set. For implementation reasons,
  4849. * a router belongs to the set if it is _rejected_ by this policy. */
  4850. smartlist_t *policies;
  4851. /** A human-readable description of what this routerset is for. Used in
  4852. * log messages. */
  4853. char *description;
  4854. /** A list of the country codes in this set. */
  4855. smartlist_t *country_names;
  4856. /** Total number of countries we knew about when we built <b>countries</b>.*/
  4857. int n_countries;
  4858. /** Bit array mapping the return value of geoip_get_country() to 1 iff the
  4859. * country is a member of this routerset. Note that we MUST call
  4860. * routerset_refresh_countries() whenever the geoip country list is
  4861. * reloaded. */
  4862. bitarray_t *countries;
  4863. };
  4864. /** Return a new empty routerset. */
  4865. routerset_t *
  4866. routerset_new(void)
  4867. {
  4868. routerset_t *result = tor_malloc_zero(sizeof(routerset_t));
  4869. result->list = smartlist_create();
  4870. result->names = strmap_new();
  4871. result->digests = digestmap_new();
  4872. result->policies = smartlist_create();
  4873. result->country_names = smartlist_create();
  4874. return result;
  4875. }
  4876. /** If <b>c</b> is a country code in the form {cc}, return a newly allocated
  4877. * string holding the "cc" part. Else, return NULL. */
  4878. static char *
  4879. routerset_get_countryname(const char *c)
  4880. {
  4881. char *country;
  4882. if (strlen(c) < 4 || c[0] !='{' || c[3] !='}')
  4883. return NULL;
  4884. country = tor_strndup(c+1, 2);
  4885. tor_strlower(country);
  4886. return country;
  4887. }
  4888. /** Update the routerset's <b>countries</b> bitarray_t. Called whenever
  4889. * the GeoIP database is reloaded.
  4890. */
  4891. void
  4892. routerset_refresh_countries(routerset_t *target)
  4893. {
  4894. int cc;
  4895. bitarray_free(target->countries);
  4896. if (!geoip_is_loaded()) {
  4897. target->countries = NULL;
  4898. target->n_countries = 0;
  4899. return;
  4900. }
  4901. target->n_countries = geoip_get_n_countries();
  4902. target->countries = bitarray_init_zero(target->n_countries);
  4903. SMARTLIST_FOREACH_BEGIN(target->country_names, const char *, country) {
  4904. cc = geoip_get_country(country);
  4905. if (cc >= 0) {
  4906. tor_assert(cc < target->n_countries);
  4907. bitarray_set(target->countries, cc);
  4908. } else {
  4909. log(LOG_WARN, LD_CONFIG, "Country code '%s' is not recognized.",
  4910. country);
  4911. }
  4912. } SMARTLIST_FOREACH_END(country);
  4913. }
  4914. /** Parse the string <b>s</b> to create a set of routerset entries, and add
  4915. * them to <b>target</b>. In log messages, refer to the string as
  4916. * <b>description</b>. Return 0 on success, -1 on failure.
  4917. *
  4918. * Three kinds of elements are allowed in routersets: nicknames, IP address
  4919. * patterns, and fingerprints. They may be surrounded by optional space, and
  4920. * must be separated by commas.
  4921. */
  4922. int
  4923. routerset_parse(routerset_t *target, const char *s, const char *description)
  4924. {
  4925. int r = 0;
  4926. int added_countries = 0;
  4927. char *countryname;
  4928. smartlist_t *list = smartlist_create();
  4929. smartlist_split_string(list, s, ",",
  4930. SPLIT_SKIP_SPACE | SPLIT_IGNORE_BLANK, 0);
  4931. SMARTLIST_FOREACH_BEGIN(list, char *, nick) {
  4932. addr_policy_t *p;
  4933. if (is_legal_hexdigest(nick)) {
  4934. char d[DIGEST_LEN];
  4935. if (*nick == '$')
  4936. ++nick;
  4937. log_debug(LD_CONFIG, "Adding identity %s to %s", nick, description);
  4938. base16_decode(d, sizeof(d), nick, HEX_DIGEST_LEN);
  4939. digestmap_set(target->digests, d, (void*)1);
  4940. } else if (is_legal_nickname(nick)) {
  4941. log_debug(LD_CONFIG, "Adding nickname %s to %s", nick, description);
  4942. strmap_set_lc(target->names, nick, (void*)1);
  4943. } else if ((countryname = routerset_get_countryname(nick)) != NULL) {
  4944. log_debug(LD_CONFIG, "Adding country %s to %s", nick,
  4945. description);
  4946. smartlist_add(target->country_names, countryname);
  4947. added_countries = 1;
  4948. } else if ((strchr(nick,'.') || strchr(nick, '*')) &&
  4949. (p = router_parse_addr_policy_item_from_string(
  4950. nick, ADDR_POLICY_REJECT))) {
  4951. log_debug(LD_CONFIG, "Adding address %s to %s", nick, description);
  4952. smartlist_add(target->policies, p);
  4953. } else {
  4954. log_warn(LD_CONFIG, "Entry '%s' in %s is misformed.", nick,
  4955. description);
  4956. r = -1;
  4957. tor_free(nick);
  4958. SMARTLIST_DEL_CURRENT(list, nick);
  4959. }
  4960. } SMARTLIST_FOREACH_END(nick);
  4961. smartlist_add_all(target->list, list);
  4962. smartlist_free(list);
  4963. if (added_countries)
  4964. routerset_refresh_countries(target);
  4965. return r;
  4966. }
  4967. /** Called when we change a node set, or when we reload the geoip list:
  4968. * recompute all country info in all configuration node sets and in the
  4969. * routerlist. */
  4970. void
  4971. refresh_all_country_info(void)
  4972. {
  4973. const or_options_t *options = get_options();
  4974. if (options->EntryNodes)
  4975. routerset_refresh_countries(options->EntryNodes);
  4976. if (options->ExitNodes)
  4977. routerset_refresh_countries(options->ExitNodes);
  4978. if (options->ExcludeNodes)
  4979. routerset_refresh_countries(options->ExcludeNodes);
  4980. if (options->ExcludeExitNodes)
  4981. routerset_refresh_countries(options->ExcludeExitNodes);
  4982. if (options->_ExcludeExitNodesUnion)
  4983. routerset_refresh_countries(options->_ExcludeExitNodesUnion);
  4984. nodelist_refresh_countries();
  4985. }
  4986. /** Add all members of the set <b>source</b> to <b>target</b>. */
  4987. void
  4988. routerset_union(routerset_t *target, const routerset_t *source)
  4989. {
  4990. char *s;
  4991. tor_assert(target);
  4992. if (!source || !source->list)
  4993. return;
  4994. s = routerset_to_string(source);
  4995. routerset_parse(target, s, "other routerset");
  4996. tor_free(s);
  4997. }
  4998. /** Return true iff <b>set</b> lists only nicknames and digests, and includes
  4999. * no IP ranges or countries. */
  5000. int
  5001. routerset_is_list(const routerset_t *set)
  5002. {
  5003. return smartlist_len(set->country_names) == 0 &&
  5004. smartlist_len(set->policies) == 0;
  5005. }
  5006. /** Return true iff we need a GeoIP IP-to-country database to make sense of
  5007. * <b>set</b>. */
  5008. int
  5009. routerset_needs_geoip(const routerset_t *set)
  5010. {
  5011. return set && smartlist_len(set->country_names);
  5012. }
  5013. /** Return true iff there are no entries in <b>set</b>. */
  5014. int
  5015. routerset_is_empty(const routerset_t *set)
  5016. {
  5017. return !set || smartlist_len(set->list) == 0;
  5018. }
  5019. /** Helper. Return true iff <b>set</b> contains a router based on the other
  5020. * provided fields. Return higher values for more specific subentries: a
  5021. * single router is more specific than an address range of routers, which is
  5022. * more specific in turn than a country code.
  5023. *
  5024. * (If country is -1, then we take the country
  5025. * from addr.) */
  5026. static int
  5027. routerset_contains(const routerset_t *set, const tor_addr_t *addr,
  5028. uint16_t orport,
  5029. const char *nickname, const char *id_digest,
  5030. country_t country)
  5031. {
  5032. if (!set || !set->list)
  5033. return 0;
  5034. if (nickname && strmap_get_lc(set->names, nickname))
  5035. return 4;
  5036. if (id_digest && digestmap_get(set->digests, id_digest))
  5037. return 4;
  5038. if (addr && compare_tor_addr_to_addr_policy(addr, orport, set->policies)
  5039. == ADDR_POLICY_REJECTED)
  5040. return 3;
  5041. if (set->countries) {
  5042. if (country < 0 && addr)
  5043. country = geoip_get_country_by_ip(tor_addr_to_ipv4h(addr));
  5044. if (country >= 0 && country < set->n_countries &&
  5045. bitarray_is_set(set->countries, country))
  5046. return 2;
  5047. }
  5048. return 0;
  5049. }
  5050. /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
  5051. int
  5052. routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
  5053. {
  5054. return routerset_contains(set,
  5055. &ei->addr,
  5056. ei->port,
  5057. ei->nickname,
  5058. ei->identity_digest,
  5059. -1 /*country*/);
  5060. }
  5061. /** Return true iff <b>ri</b> is in <b>set</b>. If country is <b>-1</b>, we
  5062. * look up the country. */
  5063. int
  5064. routerset_contains_router(const routerset_t *set, const routerinfo_t *ri,
  5065. country_t country)
  5066. {
  5067. tor_addr_t addr;
  5068. tor_addr_from_ipv4h(&addr, ri->addr);
  5069. return routerset_contains(set,
  5070. &addr,
  5071. ri->or_port,
  5072. ri->nickname,
  5073. ri->cache_info.identity_digest,
  5074. country);
  5075. }
  5076. /** Return true iff <b>rs</b> is in <b>set</b>. If country is <b>-1</b>, we
  5077. * look up the country. */
  5078. int
  5079. routerset_contains_routerstatus(const routerset_t *set,
  5080. const routerstatus_t *rs,
  5081. country_t country)
  5082. {
  5083. tor_addr_t addr;
  5084. tor_addr_from_ipv4h(&addr, rs->addr);
  5085. return routerset_contains(set,
  5086. &addr,
  5087. rs->or_port,
  5088. rs->nickname,
  5089. rs->identity_digest,
  5090. country);
  5091. }
  5092. /** Return true iff <b>node</b> is in <b>set</b>. */
  5093. int
  5094. routerset_contains_node(const routerset_t *set, const node_t *node)
  5095. {
  5096. if (node->rs)
  5097. return routerset_contains_routerstatus(set, node->rs, node->country);
  5098. else if (node->ri)
  5099. return routerset_contains_router(set, node->ri, node->country);
  5100. else
  5101. return 0;
  5102. }
  5103. /** Add every known node_t that is a member of <b>routerset</b> to
  5104. * <b>out</b>, but never add any that are part of <b>excludeset</b>.
  5105. * If <b>running_only</b>, only add the running ones. */
  5106. void
  5107. routerset_get_all_nodes(smartlist_t *out, const routerset_t *routerset,
  5108. const routerset_t *excludeset, int running_only)
  5109. { /* XXXX MOVE */
  5110. tor_assert(out);
  5111. if (!routerset || !routerset->list)
  5112. return;
  5113. if (routerset_is_list(routerset)) {
  5114. /* No routers are specified by type; all are given by name or digest.
  5115. * we can do a lookup in O(len(routerset)). */
  5116. SMARTLIST_FOREACH(routerset->list, const char *, name, {
  5117. const node_t *node = node_get_by_nickname(name, 1);
  5118. if (node) {
  5119. if (!running_only || node->is_running)
  5120. if (!routerset_contains_node(excludeset, node))
  5121. smartlist_add(out, (void*)node);
  5122. }
  5123. });
  5124. } else {
  5125. /* We need to iterate over the routerlist to get all the ones of the
  5126. * right kind. */
  5127. smartlist_t *nodes = nodelist_get_list();
  5128. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  5129. if (running_only && !node->is_running)
  5130. continue;
  5131. if (routerset_contains_node(routerset, node) &&
  5132. !routerset_contains_node(excludeset, node))
  5133. smartlist_add(out, (void*)node);
  5134. });
  5135. }
  5136. }
  5137. #if 0
  5138. /** Add to <b>target</b> every node_t from <b>source</b> except:
  5139. *
  5140. * 1) Don't add it if <b>include</b> is non-empty and the relay isn't in
  5141. * <b>include</b>; and
  5142. * 2) Don't add it if <b>exclude</b> is non-empty and the relay is
  5143. * excluded in a more specific fashion by <b>exclude</b>.
  5144. * 3) If <b>running_only</b>, don't add non-running routers.
  5145. */
  5146. void
  5147. routersets_get_node_disjunction(smartlist_t *target,
  5148. const smartlist_t *source,
  5149. const routerset_t *include,
  5150. const routerset_t *exclude, int running_only)
  5151. {
  5152. SMARTLIST_FOREACH(source, const node_t *, node, {
  5153. int include_result;
  5154. if (running_only && !node->is_running)
  5155. continue;
  5156. if (!routerset_is_empty(include))
  5157. include_result = routerset_contains_node(include, node);
  5158. else
  5159. include_result = 1;
  5160. if (include_result) {
  5161. int exclude_result = routerset_contains_node(exclude, node);
  5162. if (include_result >= exclude_result)
  5163. smartlist_add(target, (void*)node);
  5164. }
  5165. });
  5166. }
  5167. #endif
  5168. /** Remove every node_t from <b>lst</b> that is in <b>routerset</b>. */
  5169. void
  5170. routerset_subtract_nodes(smartlist_t *lst, const routerset_t *routerset)
  5171. { /*XXXX MOVE ? */
  5172. tor_assert(lst);
  5173. if (!routerset)
  5174. return;
  5175. SMARTLIST_FOREACH(lst, const node_t *, node, {
  5176. if (routerset_contains_node(routerset, node)) {
  5177. //log_debug(LD_DIR, "Subtracting %s",r->nickname);
  5178. SMARTLIST_DEL_CURRENT(lst, node);
  5179. }
  5180. });
  5181. }
  5182. /** Return a new string that when parsed by routerset_parse_string() will
  5183. * yield <b>set</b>. */
  5184. char *
  5185. routerset_to_string(const routerset_t *set)
  5186. {
  5187. if (!set || !set->list)
  5188. return tor_strdup("");
  5189. return smartlist_join_strings(set->list, ",", 0, NULL);
  5190. }
  5191. /** Helper: return true iff old and new are both NULL, or both non-NULL
  5192. * equal routersets. */
  5193. int
  5194. routerset_equal(const routerset_t *old, const routerset_t *new)
  5195. {
  5196. if (routerset_is_empty(old) && routerset_is_empty(new)) {
  5197. /* Two empty sets are equal */
  5198. return 1;
  5199. } else if (routerset_is_empty(old) || routerset_is_empty(new)) {
  5200. /* An empty set is equal to nothing else. */
  5201. return 0;
  5202. }
  5203. tor_assert(old != NULL);
  5204. tor_assert(new != NULL);
  5205. if (smartlist_len(old->list) != smartlist_len(new->list))
  5206. return 0;
  5207. SMARTLIST_FOREACH(old->list, const char *, cp1, {
  5208. const char *cp2 = smartlist_get(new->list, cp1_sl_idx);
  5209. if (strcmp(cp1, cp2))
  5210. return 0;
  5211. });
  5212. return 1;
  5213. }
  5214. /** Free all storage held in <b>routerset</b>. */
  5215. void
  5216. routerset_free(routerset_t *routerset)
  5217. {
  5218. if (!routerset)
  5219. return;
  5220. SMARTLIST_FOREACH(routerset->list, char *, cp, tor_free(cp));
  5221. smartlist_free(routerset->list);
  5222. SMARTLIST_FOREACH(routerset->policies, addr_policy_t *, p,
  5223. addr_policy_free(p));
  5224. smartlist_free(routerset->policies);
  5225. SMARTLIST_FOREACH(routerset->country_names, char *, cp, tor_free(cp));
  5226. smartlist_free(routerset->country_names);
  5227. strmap_free(routerset->names, NULL);
  5228. digestmap_free(routerset->digests, NULL);
  5229. bitarray_free(routerset->countries);
  5230. tor_free(routerset);
  5231. }
  5232. /** Refresh the country code of <b>ri</b>. This function MUST be called on
  5233. * each router when the GeoIP database is reloaded, and on all new routers. */
  5234. void
  5235. node_set_country(node_t *node)
  5236. {
  5237. if (node->rs)
  5238. node->country = geoip_get_country_by_ip(node->rs->addr);
  5239. else if (node->ri)
  5240. node->country = geoip_get_country_by_ip(node->ri->addr);
  5241. else
  5242. node->country = -1;
  5243. }
  5244. /** Set the country code of all routers in the routerlist. */
  5245. void
  5246. nodelist_refresh_countries(void) /* MOVE */
  5247. {
  5248. smartlist_t *nodes = nodelist_get_list();
  5249. SMARTLIST_FOREACH(nodes, node_t *, node,
  5250. node_set_country(node));
  5251. }
  5252. /** Determine the routers that are responsible for <b>id</b> (binary) and
  5253. * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
  5254. * Return -1 if we're returning an empty smartlist, else return 0.
  5255. */
  5256. int
  5257. hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  5258. const char *id)
  5259. {
  5260. int start, found, n_added = 0, i;
  5261. networkstatus_t *c = networkstatus_get_latest_consensus();
  5262. if (!c || !smartlist_len(c->routerstatus_list)) {
  5263. log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
  5264. "rendezvous operations.");
  5265. return -1;
  5266. }
  5267. tor_assert(id);
  5268. start = networkstatus_vote_find_entry_idx(c, id, &found);
  5269. if (start == smartlist_len(c->routerstatus_list)) start = 0;
  5270. i = start;
  5271. do {
  5272. routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
  5273. if (r->is_hs_dir) {
  5274. smartlist_add(responsible_dirs, r);
  5275. if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
  5276. return 0;
  5277. }
  5278. if (++i == smartlist_len(c->routerstatus_list))
  5279. i = 0;
  5280. } while (i != start);
  5281. /* Even though we don't have the desired number of hidden service
  5282. * directories, be happy if we got any. */
  5283. return smartlist_len(responsible_dirs) ? 0 : -1;
  5284. }
  5285. /** Return true if this node is currently acting as hidden service
  5286. * directory, false otherwise. */
  5287. int
  5288. hid_serv_acting_as_directory(void)
  5289. {
  5290. const routerinfo_t *me = router_get_my_routerinfo();
  5291. if (!me)
  5292. return 0;
  5293. if (!get_options()->HidServDirectoryV2) {
  5294. log_info(LD_REND, "We are not acting as hidden service directory, "
  5295. "because we have not been configured as such.");
  5296. return 0;
  5297. }
  5298. return 1;
  5299. }
  5300. /** Return true if this node is responsible for storing the descriptor ID
  5301. * in <b>query</b> and false otherwise. */
  5302. int
  5303. hid_serv_responsible_for_desc_id(const char *query)
  5304. {
  5305. const routerinfo_t *me;
  5306. routerstatus_t *last_rs;
  5307. const char *my_id, *last_id;
  5308. int result;
  5309. smartlist_t *responsible;
  5310. if (!hid_serv_acting_as_directory())
  5311. return 0;
  5312. if (!(me = router_get_my_routerinfo()))
  5313. return 0; /* This is redundant, but let's be paranoid. */
  5314. my_id = me->cache_info.identity_digest;
  5315. responsible = smartlist_create();
  5316. if (hid_serv_get_responsible_directories(responsible, query) < 0) {
  5317. smartlist_free(responsible);
  5318. return 0;
  5319. }
  5320. last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
  5321. last_id = last_rs->identity_digest;
  5322. result = rend_id_is_in_interval(my_id, query, last_id);
  5323. smartlist_free(responsible);
  5324. return result;
  5325. }