routerlist.c 198 KB

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