routerlist.c 172 KB

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