routerlist.c 181 KB

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