routerlist.c 188 KB

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