routerlist.c 177 KB

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