routerlist.c 177 KB

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