routerlist.c 201 KB

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