routerlist.c 186 KB

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