circuitbuild.c 188 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613
  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-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitbuild.c
  8. * \brief The actual details of building circuits.
  9. **/
  10. #define CIRCUIT_PRIVATE
  11. #include "or.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_edge.h"
  18. #include "connection_or.h"
  19. #include "control.h"
  20. #include "directory.h"
  21. #include "main.h"
  22. #include "networkstatus.h"
  23. #include "nodelist.h"
  24. #include "onion.h"
  25. #include "policies.h"
  26. #include "transports.h"
  27. #include "relay.h"
  28. #include "rephist.h"
  29. #include "router.h"
  30. #include "routerlist.h"
  31. #include "routerparse.h"
  32. #include "crypto.h"
  33. #undef log
  34. #include <math.h>
  35. #ifndef MIN
  36. #define MIN(a,b) ((a)<(b)?(a):(b))
  37. #endif
  38. #define CBT_BIN_TO_MS(bin) ((bin)*CBT_BIN_WIDTH + (CBT_BIN_WIDTH/2))
  39. /********* START VARIABLES **********/
  40. /** Global list of circuit build times */
  41. // XXXX: Add this as a member for entry_guard_t instead of global?
  42. // Then we could do per-guard statistics, as guards are likely to
  43. // vary in their own latency. The downside of this is that guards
  44. // can change frequently, so we'd be building a lot more circuits
  45. // most likely.
  46. /* XXXX024 Make this static; add accessor functions. */
  47. circuit_build_times_t circ_times;
  48. /** A global list of all circuits at this hop. */
  49. extern circuit_t *global_circuitlist;
  50. /** An entry_guard_t represents our information about a chosen long-term
  51. * first hop, known as a "helper" node in the literature. We can't just
  52. * use a node_t, since we want to remember these even when we
  53. * don't have any directory info. */
  54. typedef struct {
  55. char nickname[MAX_NICKNAME_LEN+1];
  56. char identity[DIGEST_LEN];
  57. time_t chosen_on_date; /**< Approximately when was this guard added?
  58. * "0" if we don't know. */
  59. char *chosen_by_version; /**< What tor version added this guard? NULL
  60. * if we don't know. */
  61. unsigned int made_contact : 1; /**< 0 if we have never connected to this
  62. * router, 1 if we have. */
  63. unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
  64. * in spite of having it marked as unreachable?*/
  65. unsigned int path_bias_notice : 1; /**< Did we alert the user about path bias
  66. * for this node already? */
  67. unsigned int path_bias_disabled : 1; /**< Have we disabled this node because
  68. * of path bias issues? */
  69. time_t bad_since; /**< 0 if this guard is currently usable, or the time at
  70. * which it was observed to become (according to the
  71. * directory or the user configuration) unusable. */
  72. time_t unreachable_since; /**< 0 if we can connect to this guard, or the
  73. * time at which we first noticed we couldn't
  74. * connect to it. */
  75. time_t last_attempted; /**< 0 if we can connect to this guard, or the time
  76. * at which we last failed to connect to it. */
  77. unsigned first_hops; /**< Number of first hops this guard has completed */
  78. unsigned circuit_successes; /**< Number of successfully built circuits using
  79. * this guard as first hop. */
  80. } entry_guard_t;
  81. /** Information about a configured bridge. Currently this just matches the
  82. * ones in the torrc file, but one day we may be able to learn about new
  83. * bridges on our own, and remember them in the state file. */
  84. typedef struct {
  85. /** Address of the bridge. */
  86. tor_addr_t addr;
  87. /** TLS port for the bridge. */
  88. uint16_t port;
  89. /** Boolean: We are re-parsing our bridge list, and we are going to remove
  90. * this one if we don't find it in the list of configured bridges. */
  91. unsigned marked_for_removal : 1;
  92. /** Expected identity digest, or all zero bytes if we don't know what the
  93. * digest should be. */
  94. char identity[DIGEST_LEN];
  95. /** Name of pluggable transport protocol taken from its config line. */
  96. char *transport_name;
  97. /** When should we next try to fetch a descriptor for this bridge? */
  98. download_status_t fetch_status;
  99. } bridge_info_t;
  100. /** A list of our chosen entry guards. */
  101. static smartlist_t *entry_guards = NULL;
  102. /** A value of 1 means that the entry_guards list has changed
  103. * and those changes need to be flushed to disk. */
  104. static int entry_guards_dirty = 0;
  105. /** If set, we're running the unit tests: we should avoid clobbering
  106. * our state file or accessing get_options() or get_or_state() */
  107. static int unit_tests = 0;
  108. /********* END VARIABLES ************/
  109. static int circuit_deliver_create_cell(circuit_t *circ,
  110. uint8_t cell_type, const char *payload);
  111. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  112. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  113. static int onion_extend_cpath(origin_circuit_t *circ);
  114. static int count_acceptable_nodes(smartlist_t *routers);
  115. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  116. static void entry_guards_changed(void);
  117. static entry_guard_t *entry_guard_get_by_id_digest(const char *digest);
  118. static void bridge_free(bridge_info_t *bridge);
  119. /**
  120. * This function decides if CBT learning should be disabled. It returns
  121. * true if one or more of the following four conditions are met:
  122. *
  123. * 1. If the cbtdisabled consensus parameter is set.
  124. * 2. If the torrc option LearnCircuitBuildTimeout is false.
  125. * 3. If we are a directory authority
  126. * 4. If we fail to write circuit build time history to our state file.
  127. */
  128. static int
  129. circuit_build_times_disabled(void)
  130. {
  131. if (unit_tests) {
  132. return 0;
  133. } else {
  134. int consensus_disabled = networkstatus_get_param(NULL, "cbtdisabled",
  135. 0, 0, 1);
  136. int config_disabled = !get_options()->LearnCircuitBuildTimeout;
  137. int dirauth_disabled = get_options()->AuthoritativeDir;
  138. int state_disabled = did_last_state_file_write_fail() ? 1 : 0;
  139. if (consensus_disabled || config_disabled || dirauth_disabled ||
  140. state_disabled) {
  141. log_debug(LD_CIRC,
  142. "CircuitBuildTime learning is disabled. "
  143. "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
  144. consensus_disabled, config_disabled, dirauth_disabled,
  145. state_disabled);
  146. return 1;
  147. } else {
  148. log_debug(LD_CIRC,
  149. "CircuitBuildTime learning is not disabled. "
  150. "Consensus=%d, Config=%d, AuthDir=%d, StateFile=%d",
  151. consensus_disabled, config_disabled, dirauth_disabled,
  152. state_disabled);
  153. return 0;
  154. }
  155. }
  156. }
  157. /**
  158. * Retrieve and bounds-check the cbtmaxtimeouts consensus paramter.
  159. *
  160. * Effect: When this many timeouts happen in the last 'cbtrecentcount'
  161. * circuit attempts, the client should discard all of its history and
  162. * begin learning a fresh timeout value.
  163. */
  164. static int32_t
  165. circuit_build_times_max_timeouts(void)
  166. {
  167. int32_t cbt_maxtimeouts;
  168. cbt_maxtimeouts = networkstatus_get_param(NULL, "cbtmaxtimeouts",
  169. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT,
  170. CBT_MIN_MAX_RECENT_TIMEOUT_COUNT,
  171. CBT_MAX_MAX_RECENT_TIMEOUT_COUNT);
  172. if (!(get_options()->LearnCircuitBuildTimeout)) {
  173. log_debug(LD_BUG,
  174. "circuit_build_times_max_timeouts() called, cbtmaxtimeouts is"
  175. " %d",
  176. cbt_maxtimeouts);
  177. }
  178. return cbt_maxtimeouts;
  179. }
  180. /**
  181. * Retrieve and bounds-check the cbtnummodes consensus paramter.
  182. *
  183. * Effect: This value governs how many modes to use in the weighted
  184. * average calculation of Pareto parameter Xm. A value of 3 introduces
  185. * some bias (2-5% of CDF) under ideal conditions, but allows for better
  186. * performance in the event that a client chooses guard nodes of radically
  187. * different performance characteristics.
  188. */
  189. static int32_t
  190. circuit_build_times_default_num_xm_modes(void)
  191. {
  192. int32_t num = networkstatus_get_param(NULL, "cbtnummodes",
  193. CBT_DEFAULT_NUM_XM_MODES,
  194. CBT_MIN_NUM_XM_MODES,
  195. CBT_MAX_NUM_XM_MODES);
  196. if (!(get_options()->LearnCircuitBuildTimeout)) {
  197. log_debug(LD_BUG,
  198. "circuit_build_times_default_num_xm_modes() called, cbtnummodes"
  199. " is %d",
  200. num);
  201. }
  202. return num;
  203. }
  204. /**
  205. * Retrieve and bounds-check the cbtmincircs consensus paramter.
  206. *
  207. * Effect: This is the minimum number of circuits to build before
  208. * computing a timeout.
  209. */
  210. static int32_t
  211. circuit_build_times_min_circs_to_observe(void)
  212. {
  213. int32_t num = networkstatus_get_param(NULL, "cbtmincircs",
  214. CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE,
  215. CBT_MIN_MIN_CIRCUITS_TO_OBSERVE,
  216. CBT_MAX_MIN_CIRCUITS_TO_OBSERVE);
  217. if (!(get_options()->LearnCircuitBuildTimeout)) {
  218. log_debug(LD_BUG,
  219. "circuit_build_times_min_circs_to_observe() called, cbtmincircs"
  220. " is %d",
  221. num);
  222. }
  223. return num;
  224. }
  225. /** Return true iff <b>cbt</b> has recorded enough build times that we
  226. * want to start acting on the timeout it implies. */
  227. int
  228. circuit_build_times_enough_to_compute(circuit_build_times_t *cbt)
  229. {
  230. return cbt->total_build_times >= circuit_build_times_min_circs_to_observe();
  231. }
  232. /**
  233. * Retrieve and bounds-check the cbtquantile consensus paramter.
  234. *
  235. * Effect: This is the position on the quantile curve to use to set the
  236. * timeout value. It is a percent (10-99).
  237. */
  238. double
  239. circuit_build_times_quantile_cutoff(void)
  240. {
  241. int32_t num = networkstatus_get_param(NULL, "cbtquantile",
  242. CBT_DEFAULT_QUANTILE_CUTOFF,
  243. CBT_MIN_QUANTILE_CUTOFF,
  244. CBT_MAX_QUANTILE_CUTOFF);
  245. if (!(get_options()->LearnCircuitBuildTimeout)) {
  246. log_debug(LD_BUG,
  247. "circuit_build_times_quantile_cutoff() called, cbtquantile"
  248. " is %d",
  249. num);
  250. }
  251. return num/100.0;
  252. }
  253. /* DOCDOC circuit_build_times_get_bw_scale */
  254. int
  255. circuit_build_times_get_bw_scale(networkstatus_t *ns)
  256. {
  257. return networkstatus_get_param(ns, "bwweightscale",
  258. BW_WEIGHT_SCALE,
  259. BW_MIN_WEIGHT_SCALE,
  260. BW_MAX_WEIGHT_SCALE);
  261. }
  262. /**
  263. * Retrieve and bounds-check the cbtclosequantile consensus paramter.
  264. *
  265. * Effect: This is the position on the quantile curve to use to set the
  266. * timeout value to use to actually close circuits. It is a percent
  267. * (0-99).
  268. */
  269. static double
  270. circuit_build_times_close_quantile(void)
  271. {
  272. int32_t param;
  273. /* Cast is safe - circuit_build_times_quantile_cutoff() is capped */
  274. int32_t min = (int)tor_lround(100*circuit_build_times_quantile_cutoff());
  275. param = networkstatus_get_param(NULL, "cbtclosequantile",
  276. CBT_DEFAULT_CLOSE_QUANTILE,
  277. CBT_MIN_CLOSE_QUANTILE,
  278. CBT_MAX_CLOSE_QUANTILE);
  279. if (!(get_options()->LearnCircuitBuildTimeout)) {
  280. log_debug(LD_BUG,
  281. "circuit_build_times_close_quantile() called, cbtclosequantile"
  282. " is %d", param);
  283. }
  284. if (param < min) {
  285. log_warn(LD_DIR, "Consensus parameter cbtclosequantile is "
  286. "too small, raising to %d", min);
  287. param = min;
  288. }
  289. return param / 100.0;
  290. }
  291. /**
  292. * Retrieve and bounds-check the cbttestfreq consensus paramter.
  293. *
  294. * Effect: Describes how often in seconds to build a test circuit to
  295. * gather timeout values. Only applies if less than 'cbtmincircs'
  296. * have been recorded.
  297. */
  298. static int32_t
  299. circuit_build_times_test_frequency(void)
  300. {
  301. int32_t num = networkstatus_get_param(NULL, "cbttestfreq",
  302. CBT_DEFAULT_TEST_FREQUENCY,
  303. CBT_MIN_TEST_FREQUENCY,
  304. CBT_MAX_TEST_FREQUENCY);
  305. if (!(get_options()->LearnCircuitBuildTimeout)) {
  306. log_debug(LD_BUG,
  307. "circuit_build_times_test_frequency() called, cbttestfreq is %d",
  308. num);
  309. }
  310. return num;
  311. }
  312. /**
  313. * Retrieve and bounds-check the cbtmintimeout consensus parameter.
  314. *
  315. * Effect: This is the minimum allowed timeout value in milliseconds.
  316. * The minimum is to prevent rounding to 0 (we only check once
  317. * per second).
  318. */
  319. static int32_t
  320. circuit_build_times_min_timeout(void)
  321. {
  322. int32_t num = networkstatus_get_param(NULL, "cbtmintimeout",
  323. CBT_DEFAULT_TIMEOUT_MIN_VALUE,
  324. CBT_MIN_TIMEOUT_MIN_VALUE,
  325. CBT_MAX_TIMEOUT_MIN_VALUE);
  326. if (!(get_options()->LearnCircuitBuildTimeout)) {
  327. log_debug(LD_BUG,
  328. "circuit_build_times_min_timeout() called, cbtmintimeout is %d",
  329. num);
  330. }
  331. return num;
  332. }
  333. /**
  334. * Retrieve and bounds-check the cbtinitialtimeout consensus paramter.
  335. *
  336. * Effect: This is the timeout value to use before computing a timeout,
  337. * in milliseconds.
  338. */
  339. int32_t
  340. circuit_build_times_initial_timeout(void)
  341. {
  342. int32_t min = circuit_build_times_min_timeout();
  343. int32_t param = networkstatus_get_param(NULL, "cbtinitialtimeout",
  344. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE,
  345. CBT_MIN_TIMEOUT_INITIAL_VALUE,
  346. CBT_MAX_TIMEOUT_INITIAL_VALUE);
  347. if (!(get_options()->LearnCircuitBuildTimeout)) {
  348. log_debug(LD_BUG,
  349. "circuit_build_times_initial_timeout() called, "
  350. "cbtinitialtimeout is %d",
  351. param);
  352. }
  353. if (param < min) {
  354. log_warn(LD_DIR, "Consensus parameter cbtinitialtimeout is too small, "
  355. "raising to %d", min);
  356. param = min;
  357. }
  358. return param;
  359. }
  360. /**
  361. * Retrieve and bounds-check the cbtrecentcount consensus paramter.
  362. *
  363. * Effect: This is the number of circuit build times to keep track of
  364. * for deciding if we hit cbtmaxtimeouts and need to reset our state
  365. * and learn a new timeout.
  366. */
  367. static int32_t
  368. circuit_build_times_recent_circuit_count(networkstatus_t *ns)
  369. {
  370. int32_t num;
  371. num = networkstatus_get_param(ns, "cbtrecentcount",
  372. CBT_DEFAULT_RECENT_CIRCUITS,
  373. CBT_MIN_RECENT_CIRCUITS,
  374. CBT_MAX_RECENT_CIRCUITS);
  375. if (!(get_options()->LearnCircuitBuildTimeout)) {
  376. log_debug(LD_BUG,
  377. "circuit_build_times_recent_circuit_count() called, "
  378. "cbtrecentcount is %d",
  379. num);
  380. }
  381. return num;
  382. }
  383. /**
  384. * This function is called when we get a consensus update.
  385. *
  386. * It checks to see if we have changed any consensus parameters
  387. * that require reallocation or discard of previous stats.
  388. */
  389. void
  390. circuit_build_times_new_consensus_params(circuit_build_times_t *cbt,
  391. networkstatus_t *ns)
  392. {
  393. int32_t num;
  394. /*
  395. * First check if we're doing adaptive timeouts at all; nothing to
  396. * update if we aren't.
  397. */
  398. if (!circuit_build_times_disabled()) {
  399. num = circuit_build_times_recent_circuit_count(ns);
  400. if (num > 0) {
  401. if (num != cbt->liveness.num_recent_circs) {
  402. int8_t *recent_circs;
  403. log_notice(LD_CIRC, "The Tor Directory Consensus has changed how many "
  404. "circuits we must track to detect network failures from %d "
  405. "to %d.", cbt->liveness.num_recent_circs, num);
  406. tor_assert(cbt->liveness.timeouts_after_firsthop ||
  407. cbt->liveness.num_recent_circs == 0);
  408. /*
  409. * Technically this is a circular array that we are reallocating
  410. * and memcopying. However, since it only consists of either 1s
  411. * or 0s, and is only used in a statistical test to determine when
  412. * we should discard our history after a sufficient number of 1's
  413. * have been reached, it is fine if order is not preserved or
  414. * elements are lost.
  415. *
  416. * cbtrecentcount should only be changing in cases of severe network
  417. * distress anyway, so memory correctness here is paramount over
  418. * doing acrobatics to preserve the array.
  419. */
  420. recent_circs = tor_malloc_zero(sizeof(int8_t)*num);
  421. if (cbt->liveness.timeouts_after_firsthop &&
  422. cbt->liveness.num_recent_circs > 0) {
  423. memcpy(recent_circs, cbt->liveness.timeouts_after_firsthop,
  424. sizeof(int8_t)*MIN(num, cbt->liveness.num_recent_circs));
  425. }
  426. // Adjust the index if it needs it.
  427. if (num < cbt->liveness.num_recent_circs) {
  428. cbt->liveness.after_firsthop_idx = MIN(num-1,
  429. cbt->liveness.after_firsthop_idx);
  430. }
  431. tor_free(cbt->liveness.timeouts_after_firsthop);
  432. cbt->liveness.timeouts_after_firsthop = recent_circs;
  433. cbt->liveness.num_recent_circs = num;
  434. }
  435. /* else no change, nothing to do */
  436. } else { /* num == 0 */
  437. /*
  438. * Weird. This probably shouldn't happen, so log a warning, but try
  439. * to do something sensible anyway.
  440. */
  441. log_warn(LD_CIRC,
  442. "The cbtrecentcircs consensus parameter came back zero! "
  443. "This disables adaptive timeouts since we can't keep track of "
  444. "any recent circuits.");
  445. circuit_build_times_free_timeouts(cbt);
  446. }
  447. } else {
  448. /*
  449. * Adaptive timeouts are disabled; this might be because of the
  450. * LearnCircuitBuildTimes config parameter, and hence permanent, or
  451. * the cbtdisabled consensus parameter, so it may be a new condition.
  452. * Treat it like getting num == 0 above and free the circuit history
  453. * if we have any.
  454. */
  455. circuit_build_times_free_timeouts(cbt);
  456. }
  457. }
  458. /** Make a note that we're running unit tests (rather than running Tor
  459. * itself), so we avoid clobbering our state file. */
  460. void
  461. circuitbuild_running_unit_tests(void)
  462. {
  463. unit_tests = 1;
  464. }
  465. /**
  466. * Return the initial default or configured timeout in milliseconds
  467. */
  468. static double
  469. circuit_build_times_get_initial_timeout(void)
  470. {
  471. double timeout;
  472. /*
  473. * Check if we have LearnCircuitBuildTimeout, and if we don't,
  474. * always use CircuitBuildTimeout, no questions asked.
  475. */
  476. if (get_options()->LearnCircuitBuildTimeout) {
  477. if (!unit_tests && get_options()->CircuitBuildTimeout) {
  478. timeout = get_options()->CircuitBuildTimeout*1000;
  479. if (timeout < circuit_build_times_min_timeout()) {
  480. log_warn(LD_CIRC, "Config CircuitBuildTimeout too low. Setting to %ds",
  481. circuit_build_times_min_timeout()/1000);
  482. timeout = circuit_build_times_min_timeout();
  483. }
  484. } else {
  485. timeout = circuit_build_times_initial_timeout();
  486. }
  487. } else {
  488. timeout = get_options()->CircuitBuildTimeout*1000;
  489. }
  490. return timeout;
  491. }
  492. /**
  493. * Reset the build time state.
  494. *
  495. * Leave estimated parameters, timeout and network liveness intact
  496. * for future use.
  497. */
  498. void
  499. circuit_build_times_reset(circuit_build_times_t *cbt)
  500. {
  501. memset(cbt->circuit_build_times, 0, sizeof(cbt->circuit_build_times));
  502. cbt->total_build_times = 0;
  503. cbt->build_times_idx = 0;
  504. cbt->have_computed_timeout = 0;
  505. }
  506. /**
  507. * Initialize the buildtimes structure for first use.
  508. *
  509. * Sets the initial timeout values based on either the config setting,
  510. * the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).
  511. */
  512. void
  513. circuit_build_times_init(circuit_build_times_t *cbt)
  514. {
  515. memset(cbt, 0, sizeof(*cbt));
  516. /*
  517. * Check if we really are using adaptive timeouts, and don't keep
  518. * track of this stuff if not.
  519. */
  520. if (!circuit_build_times_disabled()) {
  521. cbt->liveness.num_recent_circs =
  522. circuit_build_times_recent_circuit_count(NULL);
  523. cbt->liveness.timeouts_after_firsthop =
  524. tor_malloc_zero(sizeof(int8_t)*cbt->liveness.num_recent_circs);
  525. } else {
  526. cbt->liveness.num_recent_circs = 0;
  527. cbt->liveness.timeouts_after_firsthop = NULL;
  528. }
  529. cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
  530. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  531. }
  532. /**
  533. * Free the saved timeouts, if the cbtdisabled consensus parameter got turned
  534. * on or something.
  535. */
  536. void
  537. circuit_build_times_free_timeouts(circuit_build_times_t *cbt)
  538. {
  539. if (!cbt) return;
  540. if (cbt->liveness.timeouts_after_firsthop) {
  541. tor_free(cbt->liveness.timeouts_after_firsthop);
  542. }
  543. cbt->liveness.num_recent_circs = 0;
  544. }
  545. #if 0
  546. /**
  547. * Rewind our build time history by n positions.
  548. */
  549. static void
  550. circuit_build_times_rewind_history(circuit_build_times_t *cbt, int n)
  551. {
  552. int i = 0;
  553. cbt->build_times_idx -= n;
  554. cbt->build_times_idx %= CBT_NCIRCUITS_TO_OBSERVE;
  555. for (i = 0; i < n; i++) {
  556. cbt->circuit_build_times[(i+cbt->build_times_idx)
  557. %CBT_NCIRCUITS_TO_OBSERVE]=0;
  558. }
  559. if (cbt->total_build_times > n) {
  560. cbt->total_build_times -= n;
  561. } else {
  562. cbt->total_build_times = 0;
  563. }
  564. log_info(LD_CIRC,
  565. "Rewound history by %d places. Current index: %d. "
  566. "Total: %d", n, cbt->build_times_idx, cbt->total_build_times);
  567. }
  568. #endif
  569. /**
  570. * Add a new build time value <b>time</b> to the set of build times. Time
  571. * units are milliseconds.
  572. *
  573. * circuit_build_times <b>cbt</b> is a circular array, so loop around when
  574. * array is full.
  575. */
  576. int
  577. circuit_build_times_add_time(circuit_build_times_t *cbt, build_time_t time)
  578. {
  579. if (time <= 0 || time > CBT_BUILD_TIME_MAX) {
  580. log_warn(LD_BUG, "Circuit build time is too large (%u)."
  581. "This is probably a bug.", time);
  582. tor_fragile_assert();
  583. return -1;
  584. }
  585. log_debug(LD_CIRC, "Adding circuit build time %u", time);
  586. cbt->circuit_build_times[cbt->build_times_idx] = time;
  587. cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
  588. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  589. cbt->total_build_times++;
  590. if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
  591. /* Save state every n circuit builds */
  592. if (!unit_tests && !get_options()->AvoidDiskWrites)
  593. or_state_mark_dirty(get_or_state(), 0);
  594. }
  595. return 0;
  596. }
  597. /**
  598. * Return maximum circuit build time
  599. */
  600. static build_time_t
  601. circuit_build_times_max(circuit_build_times_t *cbt)
  602. {
  603. int i = 0;
  604. build_time_t max_build_time = 0;
  605. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  606. if (cbt->circuit_build_times[i] > max_build_time
  607. && cbt->circuit_build_times[i] != CBT_BUILD_ABANDONED)
  608. max_build_time = cbt->circuit_build_times[i];
  609. }
  610. return max_build_time;
  611. }
  612. #if 0
  613. /** Return minimum circuit build time */
  614. build_time_t
  615. circuit_build_times_min(circuit_build_times_t *cbt)
  616. {
  617. int i = 0;
  618. build_time_t min_build_time = CBT_BUILD_TIME_MAX;
  619. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  620. if (cbt->circuit_build_times[i] && /* 0 <-> uninitialized */
  621. cbt->circuit_build_times[i] < min_build_time)
  622. min_build_time = cbt->circuit_build_times[i];
  623. }
  624. if (min_build_time == CBT_BUILD_TIME_MAX) {
  625. log_warn(LD_CIRC, "No build times less than CBT_BUILD_TIME_MAX!");
  626. }
  627. return min_build_time;
  628. }
  629. #endif
  630. /**
  631. * Calculate and return a histogram for the set of build times.
  632. *
  633. * Returns an allocated array of histrogram bins representing
  634. * the frequency of index*CBT_BIN_WIDTH millisecond
  635. * build times. Also outputs the number of bins in nbins.
  636. *
  637. * The return value must be freed by the caller.
  638. */
  639. static uint32_t *
  640. circuit_build_times_create_histogram(circuit_build_times_t *cbt,
  641. build_time_t *nbins)
  642. {
  643. uint32_t *histogram;
  644. build_time_t max_build_time = circuit_build_times_max(cbt);
  645. int i, c;
  646. *nbins = 1 + (max_build_time / CBT_BIN_WIDTH);
  647. histogram = tor_malloc_zero(*nbins * sizeof(build_time_t));
  648. // calculate histogram
  649. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  650. if (cbt->circuit_build_times[i] == 0
  651. || cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  652. continue; /* 0 <-> uninitialized */
  653. c = (cbt->circuit_build_times[i] / CBT_BIN_WIDTH);
  654. histogram[c]++;
  655. }
  656. return histogram;
  657. }
  658. /**
  659. * Return the Pareto start-of-curve parameter Xm.
  660. *
  661. * Because we are not a true Pareto curve, we compute this as the
  662. * weighted average of the N most frequent build time bins. N is either
  663. * 1 if we don't have enough circuit build time data collected, or
  664. * determined by the consensus parameter cbtnummodes (default 3).
  665. */
  666. static build_time_t
  667. circuit_build_times_get_xm(circuit_build_times_t *cbt)
  668. {
  669. build_time_t i, nbins;
  670. build_time_t *nth_max_bin;
  671. int32_t bin_counts=0;
  672. build_time_t ret = 0;
  673. uint32_t *histogram = circuit_build_times_create_histogram(cbt, &nbins);
  674. int n=0;
  675. int num_modes = circuit_build_times_default_num_xm_modes();
  676. tor_assert(nbins > 0);
  677. tor_assert(num_modes > 0);
  678. // Only use one mode if < 1000 buildtimes. Not enough data
  679. // for multiple.
  680. if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
  681. num_modes = 1;
  682. nth_max_bin = (build_time_t*)tor_malloc_zero(num_modes*sizeof(build_time_t));
  683. /* Determine the N most common build times */
  684. for (i = 0; i < nbins; i++) {
  685. if (histogram[i] >= histogram[nth_max_bin[0]]) {
  686. nth_max_bin[0] = i;
  687. }
  688. for (n = 1; n < num_modes; n++) {
  689. if (histogram[i] >= histogram[nth_max_bin[n]] &&
  690. (!histogram[nth_max_bin[n-1]]
  691. || histogram[i] < histogram[nth_max_bin[n-1]])) {
  692. nth_max_bin[n] = i;
  693. }
  694. }
  695. }
  696. for (n = 0; n < num_modes; n++) {
  697. bin_counts += histogram[nth_max_bin[n]];
  698. ret += CBT_BIN_TO_MS(nth_max_bin[n])*histogram[nth_max_bin[n]];
  699. log_info(LD_CIRC, "Xm mode #%d: %u %u", n, CBT_BIN_TO_MS(nth_max_bin[n]),
  700. histogram[nth_max_bin[n]]);
  701. }
  702. /* The following assert is safe, because we don't get called when we
  703. * haven't observed at least CBT_MIN_MIN_CIRCUITS_TO_OBSERVE circuits. */
  704. tor_assert(bin_counts > 0);
  705. ret /= bin_counts;
  706. tor_free(histogram);
  707. tor_free(nth_max_bin);
  708. return ret;
  709. }
  710. /**
  711. * Output a histogram of current circuit build times to
  712. * the or_state_t state structure.
  713. */
  714. void
  715. circuit_build_times_update_state(circuit_build_times_t *cbt,
  716. or_state_t *state)
  717. {
  718. uint32_t *histogram;
  719. build_time_t i = 0;
  720. build_time_t nbins = 0;
  721. config_line_t **next, *line;
  722. histogram = circuit_build_times_create_histogram(cbt, &nbins);
  723. // write to state
  724. config_free_lines(state->BuildtimeHistogram);
  725. next = &state->BuildtimeHistogram;
  726. *next = NULL;
  727. state->TotalBuildTimes = cbt->total_build_times;
  728. state->CircuitBuildAbandonedCount = 0;
  729. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  730. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
  731. state->CircuitBuildAbandonedCount++;
  732. }
  733. for (i = 0; i < nbins; i++) {
  734. // compress the histogram by skipping the blanks
  735. if (histogram[i] == 0) continue;
  736. *next = line = tor_malloc_zero(sizeof(config_line_t));
  737. line->key = tor_strdup("CircuitBuildTimeBin");
  738. tor_asprintf(&line->value, "%d %d",
  739. CBT_BIN_TO_MS(i), histogram[i]);
  740. next = &(line->next);
  741. }
  742. if (!unit_tests) {
  743. if (!get_options()->AvoidDiskWrites)
  744. or_state_mark_dirty(get_or_state(), 0);
  745. }
  746. tor_free(histogram);
  747. }
  748. /**
  749. * Shuffle the build times array.
  750. *
  751. * Adapted from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
  752. */
  753. static void
  754. circuit_build_times_shuffle_and_store_array(circuit_build_times_t *cbt,
  755. build_time_t *raw_times,
  756. uint32_t num_times)
  757. {
  758. uint32_t n = num_times;
  759. if (num_times > CBT_NCIRCUITS_TO_OBSERVE) {
  760. log_notice(LD_CIRC, "The number of circuit times that this Tor version "
  761. "uses to calculate build times is less than the number stored "
  762. "in your state file. Decreasing the circuit time history from "
  763. "%lu to %d.", (unsigned long)num_times,
  764. CBT_NCIRCUITS_TO_OBSERVE);
  765. }
  766. if (n > INT_MAX-1) {
  767. log_warn(LD_CIRC, "For some insane reasons, you had %lu circuit build "
  768. "observations in your state file. That's far too many; probably "
  769. "there's a bug here.", (unsigned long)n);
  770. n = INT_MAX-1;
  771. }
  772. /* This code can only be run on a compact array */
  773. while (n-- > 1) {
  774. int k = crypto_rand_int(n + 1); /* 0 <= k <= n. */
  775. build_time_t tmp = raw_times[k];
  776. raw_times[k] = raw_times[n];
  777. raw_times[n] = tmp;
  778. }
  779. /* Since the times are now shuffled, take a random CBT_NCIRCUITS_TO_OBSERVE
  780. * subset (ie the first CBT_NCIRCUITS_TO_OBSERVE values) */
  781. for (n = 0; n < MIN(num_times, CBT_NCIRCUITS_TO_OBSERVE); n++) {
  782. circuit_build_times_add_time(cbt, raw_times[n]);
  783. }
  784. }
  785. /**
  786. * Filter old synthetic timeouts that were created before the
  787. * new right-censored Pareto calculation was deployed.
  788. *
  789. * Once all clients before 0.2.1.13-alpha are gone, this code
  790. * will be unused.
  791. */
  792. static int
  793. circuit_build_times_filter_timeouts(circuit_build_times_t *cbt)
  794. {
  795. int num_filtered=0, i=0;
  796. double timeout_rate = 0;
  797. build_time_t max_timeout = 0;
  798. timeout_rate = circuit_build_times_timeout_rate(cbt);
  799. max_timeout = (build_time_t)cbt->close_ms;
  800. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  801. if (cbt->circuit_build_times[i] > max_timeout) {
  802. build_time_t replaced = cbt->circuit_build_times[i];
  803. num_filtered++;
  804. cbt->circuit_build_times[i] = CBT_BUILD_ABANDONED;
  805. log_debug(LD_CIRC, "Replaced timeout %d with %d", replaced,
  806. cbt->circuit_build_times[i]);
  807. }
  808. }
  809. log_info(LD_CIRC,
  810. "We had %d timeouts out of %d build times, "
  811. "and filtered %d above the max of %u",
  812. (int)(cbt->total_build_times*timeout_rate),
  813. cbt->total_build_times, num_filtered, max_timeout);
  814. return num_filtered;
  815. }
  816. /**
  817. * Load histogram from <b>state</b>, shuffling the resulting array
  818. * after we do so. Use this result to estimate parameters and
  819. * calculate the timeout.
  820. *
  821. * Return -1 on error.
  822. */
  823. int
  824. circuit_build_times_parse_state(circuit_build_times_t *cbt,
  825. or_state_t *state)
  826. {
  827. int tot_values = 0;
  828. uint32_t loaded_cnt = 0, N = 0;
  829. config_line_t *line;
  830. unsigned int i;
  831. build_time_t *loaded_times;
  832. int err = 0;
  833. circuit_build_times_init(cbt);
  834. if (circuit_build_times_disabled()) {
  835. return 0;
  836. }
  837. /* build_time_t 0 means uninitialized */
  838. loaded_times = tor_malloc_zero(sizeof(build_time_t)*state->TotalBuildTimes);
  839. for (line = state->BuildtimeHistogram; line; line = line->next) {
  840. smartlist_t *args = smartlist_new();
  841. smartlist_split_string(args, line->value, " ",
  842. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  843. if (smartlist_len(args) < 2) {
  844. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  845. "Too few arguments to CircuitBuildTime");
  846. err = 1;
  847. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  848. smartlist_free(args);
  849. break;
  850. } else {
  851. const char *ms_str = smartlist_get(args,0);
  852. const char *count_str = smartlist_get(args,1);
  853. uint32_t count, k;
  854. build_time_t ms;
  855. int ok;
  856. ms = (build_time_t)tor_parse_ulong(ms_str, 0, 0,
  857. CBT_BUILD_TIME_MAX, &ok, NULL);
  858. if (!ok) {
  859. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  860. "Unparsable bin number");
  861. err = 1;
  862. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  863. smartlist_free(args);
  864. break;
  865. }
  866. count = (uint32_t)tor_parse_ulong(count_str, 0, 0,
  867. UINT32_MAX, &ok, NULL);
  868. if (!ok) {
  869. log_warn(LD_GENERAL, "Unable to parse circuit build times: "
  870. "Unparsable bin count");
  871. err = 1;
  872. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  873. smartlist_free(args);
  874. break;
  875. }
  876. if (loaded_cnt+count+state->CircuitBuildAbandonedCount
  877. > state->TotalBuildTimes) {
  878. log_warn(LD_CIRC,
  879. "Too many build times in state file. "
  880. "Stopping short before %d",
  881. loaded_cnt+count);
  882. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  883. smartlist_free(args);
  884. break;
  885. }
  886. for (k = 0; k < count; k++) {
  887. loaded_times[loaded_cnt++] = ms;
  888. }
  889. N++;
  890. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  891. smartlist_free(args);
  892. }
  893. }
  894. log_info(LD_CIRC,
  895. "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  896. for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
  897. loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  898. }
  899. if (loaded_cnt != state->TotalBuildTimes) {
  900. log_warn(LD_CIRC,
  901. "Corrupt state file? Build times count mismatch. "
  902. "Read %d times, but file says %d", loaded_cnt,
  903. state->TotalBuildTimes);
  904. err = 1;
  905. circuit_build_times_reset(cbt);
  906. goto done;
  907. }
  908. circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);
  909. /* Verify that we didn't overwrite any indexes */
  910. for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  911. if (!cbt->circuit_build_times[i])
  912. break;
  913. tot_values++;
  914. }
  915. log_info(LD_CIRC,
  916. "Loaded %d/%d values from %d lines in circuit time histogram",
  917. tot_values, cbt->total_build_times, N);
  918. if (cbt->total_build_times != tot_values
  919. || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
  920. log_warn(LD_CIRC,
  921. "Corrupt state file? Shuffled build times mismatch. "
  922. "Read %d times, but file says %d", tot_values,
  923. state->TotalBuildTimes);
  924. err = 1;
  925. circuit_build_times_reset(cbt);
  926. goto done;
  927. }
  928. circuit_build_times_set_timeout(cbt);
  929. if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
  930. circuit_build_times_filter_timeouts(cbt);
  931. }
  932. done:
  933. tor_free(loaded_times);
  934. return err ? -1 : 0;
  935. }
  936. /**
  937. * Estimates the Xm and Alpha parameters using
  938. * http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
  939. *
  940. * The notable difference is that we use mode instead of min to estimate Xm.
  941. * This is because our distribution is frechet-like. We claim this is
  942. * an acceptable approximation because we are only concerned with the
  943. * accuracy of the CDF of the tail.
  944. */
  945. int
  946. circuit_build_times_update_alpha(circuit_build_times_t *cbt)
  947. {
  948. build_time_t *x=cbt->circuit_build_times;
  949. double a = 0;
  950. int n=0,i=0,abandoned_count=0;
  951. build_time_t max_time=0;
  952. /* http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation */
  953. /* We sort of cheat here and make our samples slightly more pareto-like
  954. * and less frechet-like. */
  955. cbt->Xm = circuit_build_times_get_xm(cbt);
  956. tor_assert(cbt->Xm > 0);
  957. for (i=0; i< CBT_NCIRCUITS_TO_OBSERVE; i++) {
  958. if (!x[i]) {
  959. continue;
  960. }
  961. if (x[i] < cbt->Xm) {
  962. a += tor_mathlog(cbt->Xm);
  963. } else if (x[i] == CBT_BUILD_ABANDONED) {
  964. abandoned_count++;
  965. } else {
  966. a += tor_mathlog(x[i]);
  967. if (x[i] > max_time)
  968. max_time = x[i];
  969. }
  970. n++;
  971. }
  972. /*
  973. * We are erring and asserting here because this can only happen
  974. * in codepaths other than startup. The startup state parsing code
  975. * performs this same check, and resets state if it hits it. If we
  976. * hit it at runtime, something serious has gone wrong.
  977. */
  978. if (n!=cbt->total_build_times) {
  979. log_err(LD_CIRC, "Discrepancy in build times count: %d vs %d", n,
  980. cbt->total_build_times);
  981. }
  982. tor_assert(n==cbt->total_build_times);
  983. if (max_time <= 0) {
  984. /* This can happen if Xm is actually the *maximum* value in the set.
  985. * It can also happen if we've abandoned every single circuit somehow.
  986. * In either case, tell the caller not to compute a new build timeout. */
  987. log_warn(LD_BUG,
  988. "Could not determine largest build time (%d). "
  989. "Xm is %dms and we've abandoned %d out of %d circuits.", max_time,
  990. cbt->Xm, abandoned_count, n);
  991. return 0;
  992. }
  993. a += abandoned_count*tor_mathlog(max_time);
  994. a -= n*tor_mathlog(cbt->Xm);
  995. // Estimator comes from Eq #4 in:
  996. // "Bayesian estimation based on trimmed samples from Pareto populations"
  997. // by Arturo J. Fernández. We are right-censored only.
  998. a = (n-abandoned_count)/a;
  999. cbt->alpha = a;
  1000. return 1;
  1001. }
  1002. /**
  1003. * This is the Pareto Quantile Function. It calculates the point x
  1004. * in the distribution such that F(x) = quantile (ie quantile*100%
  1005. * of the mass of the density function is below x on the curve).
  1006. *
  1007. * We use it to calculate the timeout and also to generate synthetic
  1008. * values of time for circuits that timeout before completion.
  1009. *
  1010. * See http://en.wikipedia.org/wiki/Quantile_function,
  1011. * http://en.wikipedia.org/wiki/Inverse_transform_sampling and
  1012. * http://en.wikipedia.org/wiki/Pareto_distribution#Generating_a_
  1013. * random_sample_from_Pareto_distribution
  1014. * That's right. I'll cite wikipedia all day long.
  1015. *
  1016. * Return value is in milliseconds.
  1017. */
  1018. double
  1019. circuit_build_times_calculate_timeout(circuit_build_times_t *cbt,
  1020. double quantile)
  1021. {
  1022. double ret;
  1023. tor_assert(quantile >= 0);
  1024. tor_assert(1.0-quantile > 0);
  1025. tor_assert(cbt->Xm > 0);
  1026. ret = cbt->Xm/pow(1.0-quantile,1.0/cbt->alpha);
  1027. if (ret > INT32_MAX) {
  1028. ret = INT32_MAX;
  1029. }
  1030. tor_assert(ret > 0);
  1031. return ret;
  1032. }
  1033. /** Pareto CDF */
  1034. double
  1035. circuit_build_times_cdf(circuit_build_times_t *cbt, double x)
  1036. {
  1037. double ret;
  1038. tor_assert(cbt->Xm > 0);
  1039. ret = 1.0-pow(cbt->Xm/x,cbt->alpha);
  1040. tor_assert(0 <= ret && ret <= 1.0);
  1041. return ret;
  1042. }
  1043. /**
  1044. * Generate a synthetic time using our distribution parameters.
  1045. *
  1046. * The return value will be within the [q_lo, q_hi) quantile points
  1047. * on the CDF.
  1048. */
  1049. build_time_t
  1050. circuit_build_times_generate_sample(circuit_build_times_t *cbt,
  1051. double q_lo, double q_hi)
  1052. {
  1053. double randval = crypto_rand_double();
  1054. build_time_t ret;
  1055. double u;
  1056. /* Generate between [q_lo, q_hi) */
  1057. /*XXXX This is what nextafter is supposed to be for; we should use it on the
  1058. * platforms that support it. */
  1059. q_hi -= 1.0/(INT32_MAX);
  1060. tor_assert(q_lo >= 0);
  1061. tor_assert(q_hi < 1);
  1062. tor_assert(q_lo < q_hi);
  1063. u = q_lo + (q_hi-q_lo)*randval;
  1064. tor_assert(0 <= u && u < 1.0);
  1065. /* circuit_build_times_calculate_timeout returns <= INT32_MAX */
  1066. ret = (build_time_t)
  1067. tor_lround(circuit_build_times_calculate_timeout(cbt, u));
  1068. tor_assert(ret > 0);
  1069. return ret;
  1070. }
  1071. /**
  1072. * Estimate an initial alpha parameter by solving the quantile
  1073. * function with a quantile point and a specific timeout value.
  1074. */
  1075. void
  1076. circuit_build_times_initial_alpha(circuit_build_times_t *cbt,
  1077. double quantile, double timeout_ms)
  1078. {
  1079. // Q(u) = Xm/((1-u)^(1/a))
  1080. // Q(0.8) = Xm/((1-0.8))^(1/a)) = CircBuildTimeout
  1081. // CircBuildTimeout = Xm/((1-0.8))^(1/a))
  1082. // CircBuildTimeout = Xm*((1-0.8))^(-1/a))
  1083. // ln(CircBuildTimeout) = ln(Xm)+ln(((1-0.8)))*(-1/a)
  1084. // -ln(1-0.8)/(ln(CircBuildTimeout)-ln(Xm))=a
  1085. tor_assert(quantile >= 0);
  1086. tor_assert(cbt->Xm > 0);
  1087. cbt->alpha = tor_mathlog(1.0-quantile)/
  1088. (tor_mathlog(cbt->Xm)-tor_mathlog(timeout_ms));
  1089. tor_assert(cbt->alpha > 0);
  1090. }
  1091. /**
  1092. * Returns true if we need circuits to be built
  1093. */
  1094. int
  1095. circuit_build_times_needs_circuits(circuit_build_times_t *cbt)
  1096. {
  1097. /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  1098. return !circuit_build_times_enough_to_compute(cbt);
  1099. }
  1100. /**
  1101. * Returns true if we should build a timeout test circuit
  1102. * right now.
  1103. */
  1104. int
  1105. circuit_build_times_needs_circuits_now(circuit_build_times_t *cbt)
  1106. {
  1107. return circuit_build_times_needs_circuits(cbt) &&
  1108. approx_time()-cbt->last_circ_at > circuit_build_times_test_frequency();
  1109. }
  1110. /**
  1111. * Called to indicate that the network showed some signs of liveness,
  1112. * i.e. we received a cell.
  1113. *
  1114. * This is used by circuit_build_times_network_check_live() to decide
  1115. * if we should record the circuit build timeout or not.
  1116. *
  1117. * This function is called every time we receive a cell. Avoid
  1118. * syscalls, events, and other high-intensity work.
  1119. */
  1120. void
  1121. circuit_build_times_network_is_live(circuit_build_times_t *cbt)
  1122. {
  1123. time_t now = approx_time();
  1124. if (cbt->liveness.nonlive_timeouts > 0) {
  1125. log_notice(LD_CIRC,
  1126. "Tor now sees network activity. Restoring circuit build "
  1127. "timeout recording. Network was down for %d seconds "
  1128. "during %d circuit attempts.",
  1129. (int)(now - cbt->liveness.network_last_live),
  1130. cbt->liveness.nonlive_timeouts);
  1131. }
  1132. cbt->liveness.network_last_live = now;
  1133. cbt->liveness.nonlive_timeouts = 0;
  1134. }
  1135. /**
  1136. * Called to indicate that we completed a circuit. Because this circuit
  1137. * succeeded, it doesn't count as a timeout-after-the-first-hop.
  1138. *
  1139. * This is used by circuit_build_times_network_check_changed() to determine
  1140. * if we had too many recent timeouts and need to reset our learned timeout
  1141. * to something higher.
  1142. */
  1143. void
  1144. circuit_build_times_network_circ_success(circuit_build_times_t *cbt)
  1145. {
  1146. /* Check for NULLness because we might not be using adaptive timeouts */
  1147. if (cbt->liveness.timeouts_after_firsthop &&
  1148. cbt->liveness.num_recent_circs > 0) {
  1149. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1150. = 0;
  1151. cbt->liveness.after_firsthop_idx++;
  1152. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1153. }
  1154. }
  1155. /**
  1156. * A circuit just timed out. If it failed after the first hop, record it
  1157. * in our history for later deciding if the network speed has changed.
  1158. *
  1159. * This is used by circuit_build_times_network_check_changed() to determine
  1160. * if we had too many recent timeouts and need to reset our learned timeout
  1161. * to something higher.
  1162. */
  1163. static void
  1164. circuit_build_times_network_timeout(circuit_build_times_t *cbt,
  1165. int did_onehop)
  1166. {
  1167. /* Check for NULLness because we might not be using adaptive timeouts */
  1168. if (cbt->liveness.timeouts_after_firsthop &&
  1169. cbt->liveness.num_recent_circs > 0) {
  1170. if (did_onehop) {
  1171. cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
  1172. = 1;
  1173. cbt->liveness.after_firsthop_idx++;
  1174. cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  1175. }
  1176. }
  1177. }
  1178. /**
  1179. * A circuit was just forcibly closed. If there has been no recent network
  1180. * activity at all, but this circuit was launched back when we thought the
  1181. * network was live, increment the number of "nonlive" circuit timeouts.
  1182. *
  1183. * This is used by circuit_build_times_network_check_live() to decide
  1184. * if we should record the circuit build timeout or not.
  1185. */
  1186. static void
  1187. circuit_build_times_network_close(circuit_build_times_t *cbt,
  1188. int did_onehop, time_t start_time)
  1189. {
  1190. time_t now = time(NULL);
  1191. /*
  1192. * Check if this is a timeout that was for a circuit that spent its
  1193. * entire existence during a time where we have had no network activity.
  1194. */
  1195. if (cbt->liveness.network_last_live < start_time) {
  1196. if (did_onehop) {
  1197. char last_live_buf[ISO_TIME_LEN+1];
  1198. char start_time_buf[ISO_TIME_LEN+1];
  1199. char now_buf[ISO_TIME_LEN+1];
  1200. format_local_iso_time(last_live_buf, cbt->liveness.network_last_live);
  1201. format_local_iso_time(start_time_buf, start_time);
  1202. format_local_iso_time(now_buf, now);
  1203. log_warn(LD_BUG,
  1204. "Circuit somehow completed a hop while the network was "
  1205. "not live. Network was last live at %s, but circuit launched "
  1206. "at %s. It's now %s.", last_live_buf, start_time_buf,
  1207. now_buf);
  1208. }
  1209. cbt->liveness.nonlive_timeouts++;
  1210. if (cbt->liveness.nonlive_timeouts == 1) {
  1211. log_notice(LD_CIRC,
  1212. "Tor has not observed any network activity for the past %d "
  1213. "seconds. Disabling circuit build timeout recording.",
  1214. (int)(now - cbt->liveness.network_last_live));
  1215. } else {
  1216. log_info(LD_CIRC,
  1217. "Got non-live timeout. Current count is: %d",
  1218. cbt->liveness.nonlive_timeouts);
  1219. }
  1220. }
  1221. }
  1222. /**
  1223. * When the network is not live, we do not record circuit build times.
  1224. *
  1225. * The network is considered not live if there has been at least one
  1226. * circuit build that began and ended (had its close_ms measurement
  1227. * period expire) since we last received a cell.
  1228. *
  1229. * Also has the side effect of rewinding the circuit time history
  1230. * in the case of recent liveness changes.
  1231. */
  1232. int
  1233. circuit_build_times_network_check_live(circuit_build_times_t *cbt)
  1234. {
  1235. if (cbt->liveness.nonlive_timeouts > 0) {
  1236. return 0;
  1237. }
  1238. return 1;
  1239. }
  1240. /**
  1241. * Returns true if we have seen more than MAX_RECENT_TIMEOUT_COUNT of
  1242. * the past RECENT_CIRCUITS time out after the first hop. Used to detect
  1243. * if the network connection has changed significantly, and if so,
  1244. * resets our circuit build timeout to the default.
  1245. *
  1246. * Also resets the entire timeout history in this case and causes us
  1247. * to restart the process of building test circuits and estimating a
  1248. * new timeout.
  1249. */
  1250. int
  1251. circuit_build_times_network_check_changed(circuit_build_times_t *cbt)
  1252. {
  1253. int total_build_times = cbt->total_build_times;
  1254. int timeout_count=0;
  1255. int i;
  1256. if (cbt->liveness.timeouts_after_firsthop &&
  1257. cbt->liveness.num_recent_circs > 0) {
  1258. /* how many of our recent circuits made it to the first hop but then
  1259. * timed out? */
  1260. for (i = 0; i < cbt->liveness.num_recent_circs; i++) {
  1261. timeout_count += cbt->liveness.timeouts_after_firsthop[i];
  1262. }
  1263. }
  1264. /* If 80% of our recent circuits are timing out after the first hop,
  1265. * we need to re-estimate a new initial alpha and timeout. */
  1266. if (timeout_count < circuit_build_times_max_timeouts()) {
  1267. return 0;
  1268. }
  1269. circuit_build_times_reset(cbt);
  1270. if (cbt->liveness.timeouts_after_firsthop &&
  1271. cbt->liveness.num_recent_circs > 0) {
  1272. memset(cbt->liveness.timeouts_after_firsthop, 0,
  1273. sizeof(*cbt->liveness.timeouts_after_firsthop)*
  1274. cbt->liveness.num_recent_circs);
  1275. }
  1276. cbt->liveness.after_firsthop_idx = 0;
  1277. /* Check to see if this has happened before. If so, double the timeout
  1278. * to give people on abysmally bad network connections a shot at access */
  1279. if (cbt->timeout_ms >= circuit_build_times_get_initial_timeout()) {
  1280. if (cbt->timeout_ms > INT32_MAX/2 || cbt->close_ms > INT32_MAX/2) {
  1281. log_warn(LD_CIRC, "Insanely large circuit build timeout value. "
  1282. "(timeout = %fmsec, close = %fmsec)",
  1283. cbt->timeout_ms, cbt->close_ms);
  1284. } else {
  1285. cbt->timeout_ms *= 2;
  1286. cbt->close_ms *= 2;
  1287. }
  1288. } else {
  1289. cbt->close_ms = cbt->timeout_ms
  1290. = circuit_build_times_get_initial_timeout();
  1291. }
  1292. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
  1293. log_notice(LD_CIRC,
  1294. "Your network connection speed appears to have changed. Resetting "
  1295. "timeout to %lds after %d timeouts and %d buildtimes.",
  1296. tor_lround(cbt->timeout_ms/1000), timeout_count,
  1297. total_build_times);
  1298. return 1;
  1299. }
  1300. /**
  1301. * Count the number of timeouts in a set of cbt data.
  1302. */
  1303. double
  1304. circuit_build_times_timeout_rate(const circuit_build_times_t *cbt)
  1305. {
  1306. int i=0,timeouts=0;
  1307. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1308. if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
  1309. timeouts++;
  1310. }
  1311. }
  1312. if (!cbt->total_build_times)
  1313. return 0;
  1314. return ((double)timeouts)/cbt->total_build_times;
  1315. }
  1316. /**
  1317. * Count the number of closed circuits in a set of cbt data.
  1318. */
  1319. double
  1320. circuit_build_times_close_rate(const circuit_build_times_t *cbt)
  1321. {
  1322. int i=0,closed=0;
  1323. for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
  1324. if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
  1325. closed++;
  1326. }
  1327. }
  1328. if (!cbt->total_build_times)
  1329. return 0;
  1330. return ((double)closed)/cbt->total_build_times;
  1331. }
  1332. /**
  1333. * Store a timeout as a synthetic value.
  1334. *
  1335. * Returns true if the store was successful and we should possibly
  1336. * update our timeout estimate.
  1337. */
  1338. int
  1339. circuit_build_times_count_close(circuit_build_times_t *cbt,
  1340. int did_onehop,
  1341. time_t start_time)
  1342. {
  1343. if (circuit_build_times_disabled()) {
  1344. cbt->close_ms = cbt->timeout_ms
  1345. = circuit_build_times_get_initial_timeout();
  1346. return 0;
  1347. }
  1348. /* Record this force-close to help determine if the network is dead */
  1349. circuit_build_times_network_close(cbt, did_onehop, start_time);
  1350. /* Only count timeouts if network is live.. */
  1351. if (!circuit_build_times_network_check_live(cbt)) {
  1352. return 0;
  1353. }
  1354. circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  1355. return 1;
  1356. }
  1357. /**
  1358. * Update timeout counts to determine if we need to expire
  1359. * our build time history due to excessive timeouts.
  1360. *
  1361. * We do not record any actual time values at this stage;
  1362. * we are only interested in recording the fact that a timeout
  1363. * happened. We record the time values via
  1364. * circuit_build_times_count_close() and circuit_build_times_add_time().
  1365. */
  1366. void
  1367. circuit_build_times_count_timeout(circuit_build_times_t *cbt,
  1368. int did_onehop)
  1369. {
  1370. if (circuit_build_times_disabled()) {
  1371. cbt->close_ms = cbt->timeout_ms
  1372. = circuit_build_times_get_initial_timeout();
  1373. return;
  1374. }
  1375. /* Register the fact that a timeout just occurred. */
  1376. circuit_build_times_network_timeout(cbt, did_onehop);
  1377. /* If there are a ton of timeouts, we should reset
  1378. * the circuit build timeout. */
  1379. circuit_build_times_network_check_changed(cbt);
  1380. }
  1381. /**
  1382. * Estimate a new timeout based on history and set our timeout
  1383. * variable accordingly.
  1384. */
  1385. static int
  1386. circuit_build_times_set_timeout_worker(circuit_build_times_t *cbt)
  1387. {
  1388. build_time_t max_time;
  1389. if (!circuit_build_times_enough_to_compute(cbt))
  1390. return 0;
  1391. if (!circuit_build_times_update_alpha(cbt))
  1392. return 0;
  1393. cbt->timeout_ms = circuit_build_times_calculate_timeout(cbt,
  1394. circuit_build_times_quantile_cutoff());
  1395. cbt->close_ms = circuit_build_times_calculate_timeout(cbt,
  1396. circuit_build_times_close_quantile());
  1397. max_time = circuit_build_times_max(cbt);
  1398. /* Sometimes really fast guard nodes give us such a steep curve
  1399. * that this ends up being not that much greater than timeout_ms.
  1400. * Make it be at least 1 min to handle this case. */
  1401. cbt->close_ms = MAX(cbt->close_ms, circuit_build_times_initial_timeout());
  1402. if (cbt->timeout_ms > max_time) {
  1403. log_info(LD_CIRC,
  1404. "Circuit build timeout of %dms is beyond the maximum build "
  1405. "time we have ever observed. Capping it to %dms.",
  1406. (int)cbt->timeout_ms, max_time);
  1407. cbt->timeout_ms = max_time;
  1408. }
  1409. if (max_time < INT32_MAX/2 && cbt->close_ms > 2*max_time) {
  1410. log_info(LD_CIRC,
  1411. "Circuit build measurement period of %dms is more than twice "
  1412. "the maximum build time we have ever observed. Capping it to "
  1413. "%dms.", (int)cbt->close_ms, 2*max_time);
  1414. cbt->close_ms = 2*max_time;
  1415. }
  1416. cbt->have_computed_timeout = 1;
  1417. return 1;
  1418. }
  1419. /**
  1420. * Exposed function to compute a new timeout. Dispatches events and
  1421. * also filters out extremely high timeout values.
  1422. */
  1423. void
  1424. circuit_build_times_set_timeout(circuit_build_times_t *cbt)
  1425. {
  1426. long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  1427. double timeout_rate;
  1428. /*
  1429. * Just return if we aren't using adaptive timeouts
  1430. */
  1431. if (circuit_build_times_disabled())
  1432. return;
  1433. if (!circuit_build_times_set_timeout_worker(cbt))
  1434. return;
  1435. if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
  1436. log_warn(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
  1437. cbt->timeout_ms, circuit_build_times_min_timeout());
  1438. cbt->timeout_ms = circuit_build_times_min_timeout();
  1439. if (cbt->close_ms < cbt->timeout_ms) {
  1440. /* This shouldn't happen because of MAX() in timeout_worker above,
  1441. * but doing it just in case */
  1442. cbt->close_ms = circuit_build_times_initial_timeout();
  1443. }
  1444. }
  1445. control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);
  1446. timeout_rate = circuit_build_times_timeout_rate(cbt);
  1447. if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
  1448. log_info(LD_CIRC,
  1449. "Based on %d circuit times, it looks like we don't need to "
  1450. "wait so long for circuits to finish. We will now assume a "
  1451. "circuit is too slow to use after waiting %ld seconds.",
  1452. cbt->total_build_times,
  1453. tor_lround(cbt->timeout_ms/1000));
  1454. log_info(LD_CIRC,
  1455. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1456. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1457. timeout_rate);
  1458. } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
  1459. log_info(LD_CIRC,
  1460. "Based on %d circuit times, it looks like we need to wait "
  1461. "longer for circuits to finish. We will now assume a "
  1462. "circuit is too slow to use after waiting %ld seconds.",
  1463. cbt->total_build_times,
  1464. tor_lround(cbt->timeout_ms/1000));
  1465. log_info(LD_CIRC,
  1466. "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
  1467. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
  1468. timeout_rate);
  1469. } else {
  1470. log_info(LD_CIRC,
  1471. "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
  1472. " r: %f) based on %d circuit times",
  1473. tor_lround(cbt->timeout_ms/1000),
  1474. cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
  1475. cbt->total_build_times);
  1476. }
  1477. }
  1478. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  1479. * and with the high bit specified by conn-\>circ_id_type, until we get
  1480. * a circ_id that is not in use by any other circuit on that conn.
  1481. *
  1482. * Return it, or 0 if can't get a unique circ_id.
  1483. */
  1484. static circid_t
  1485. get_unique_circ_id_by_conn(or_connection_t *conn)
  1486. {
  1487. circid_t test_circ_id;
  1488. circid_t attempts=0;
  1489. circid_t high_bit;
  1490. tor_assert(conn);
  1491. if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  1492. log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
  1493. "a client with no identity.");
  1494. return 0;
  1495. }
  1496. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  1497. do {
  1498. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  1499. * circID such that (high_bit|test_circ_id) is not already used. */
  1500. test_circ_id = conn->next_circ_id++;
  1501. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  1502. test_circ_id = 1;
  1503. conn->next_circ_id = 2;
  1504. }
  1505. if (++attempts > 1<<15) {
  1506. /* Make sure we don't loop forever if all circ_id's are used. This
  1507. * matters because it's an external DoS opportunity.
  1508. */
  1509. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  1510. return 0;
  1511. }
  1512. test_circ_id |= high_bit;
  1513. } while (circuit_id_in_use_on_orconn(test_circ_id, conn));
  1514. return test_circ_id;
  1515. }
  1516. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  1517. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  1518. * list information about link status in a more verbose format using spaces.
  1519. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  1520. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  1521. * names.
  1522. */
  1523. static char *
  1524. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  1525. {
  1526. crypt_path_t *hop;
  1527. smartlist_t *elements;
  1528. const char *states[] = {"closed", "waiting for keys", "open"};
  1529. char *s;
  1530. elements = smartlist_new();
  1531. if (verbose) {
  1532. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  1533. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  1534. circ->build_state->is_internal ? "internal" : "exit",
  1535. circ->build_state->need_uptime ? " (high-uptime)" : "",
  1536. circ->build_state->desired_path_len,
  1537. circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  1538. circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
  1539. (nickname?nickname:"*unnamed*"));
  1540. }
  1541. hop = circ->cpath;
  1542. do {
  1543. char *elt;
  1544. const char *id;
  1545. const node_t *node;
  1546. if (!hop)
  1547. break;
  1548. if (!verbose && hop->state != CPATH_STATE_OPEN)
  1549. break;
  1550. if (!hop->extend_info)
  1551. break;
  1552. id = hop->extend_info->identity_digest;
  1553. if (verbose_names) {
  1554. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  1555. if ((node = node_get_by_id(id))) {
  1556. node_get_verbose_nickname(node, elt);
  1557. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  1558. elt[0] = '$';
  1559. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1560. elt[HEX_DIGEST_LEN+1]= '~';
  1561. strlcpy(elt+HEX_DIGEST_LEN+2,
  1562. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  1563. } else {
  1564. elt[0] = '$';
  1565. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1566. }
  1567. } else { /* ! verbose_names */
  1568. node = node_get_by_id(id);
  1569. if (node && node_is_named(node)) {
  1570. elt = tor_strdup(node_get_nickname(node));
  1571. } else {
  1572. elt = tor_malloc(HEX_DIGEST_LEN+2);
  1573. elt[0] = '$';
  1574. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  1575. }
  1576. }
  1577. tor_assert(elt);
  1578. if (verbose) {
  1579. tor_assert(hop->state <= 2);
  1580. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  1581. tor_free(elt);
  1582. } else {
  1583. smartlist_add(elements, elt);
  1584. }
  1585. hop = hop->next;
  1586. } while (hop != circ->cpath);
  1587. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  1588. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1589. smartlist_free(elements);
  1590. return s;
  1591. }
  1592. /** If <b>verbose</b> is false, allocate and return a comma-separated
  1593. * list of the currently built elements of <b>circ</b>. If
  1594. * <b>verbose</b> is true, also list information about link status in
  1595. * a more verbose format using spaces.
  1596. */
  1597. char *
  1598. circuit_list_path(origin_circuit_t *circ, int verbose)
  1599. {
  1600. return circuit_list_path_impl(circ, verbose, 0);
  1601. }
  1602. /** Allocate and return a comma-separated list of the currently built elements
  1603. * of <b>circ</b>, giving each as a verbose nickname.
  1604. */
  1605. char *
  1606. circuit_list_path_for_controller(origin_circuit_t *circ)
  1607. {
  1608. return circuit_list_path_impl(circ, 0, 1);
  1609. }
  1610. /** Log, at severity <b>severity</b>, the nicknames of each router in
  1611. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  1612. * exit point.
  1613. */
  1614. void
  1615. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  1616. {
  1617. char *s = circuit_list_path(circ,1);
  1618. tor_log(severity,domain,"%s",s);
  1619. tor_free(s);
  1620. }
  1621. /** Tell the rep(utation)hist(ory) module about the status of the links
  1622. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  1623. * extended; the _first_ hop that isn't open (if any) is marked as
  1624. * unable to extend.
  1625. */
  1626. /* XXXX Someday we should learn from OR circuits too. */
  1627. void
  1628. circuit_rep_hist_note_result(origin_circuit_t *circ)
  1629. {
  1630. crypt_path_t *hop;
  1631. const char *prev_digest = NULL;
  1632. hop = circ->cpath;
  1633. if (!hop) /* circuit hasn't started building yet. */
  1634. return;
  1635. if (server_mode(get_options())) {
  1636. const routerinfo_t *me = router_get_my_routerinfo();
  1637. if (!me)
  1638. return;
  1639. prev_digest = me->cache_info.identity_digest;
  1640. }
  1641. do {
  1642. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  1643. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  1644. if (prev_digest) {
  1645. if (hop->state == CPATH_STATE_OPEN)
  1646. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  1647. else {
  1648. rep_hist_note_extend_failed(prev_digest, node->identity);
  1649. break;
  1650. }
  1651. }
  1652. prev_digest = node->identity;
  1653. } else {
  1654. prev_digest = NULL;
  1655. }
  1656. hop=hop->next;
  1657. } while (hop!=circ->cpath);
  1658. }
  1659. /** Pick all the entries in our cpath. Stop and return 0 when we're
  1660. * happy, or return -1 if an error occurs. */
  1661. static int
  1662. onion_populate_cpath(origin_circuit_t *circ)
  1663. {
  1664. int r;
  1665. again:
  1666. r = onion_extend_cpath(circ);
  1667. if (r < 0) {
  1668. log_info(LD_CIRC,"Generating cpath hop failed.");
  1669. return -1;
  1670. }
  1671. if (r == 0)
  1672. goto again;
  1673. return 0; /* if r == 1 */
  1674. }
  1675. /** Create and return a new origin circuit. Initialize its purpose and
  1676. * build-state based on our arguments. The <b>flags</b> argument is a
  1677. * bitfield of CIRCLAUNCH_* flags. */
  1678. origin_circuit_t *
  1679. origin_circuit_init(uint8_t purpose, int flags)
  1680. {
  1681. /* sets circ->p_circ_id and circ->p_conn */
  1682. origin_circuit_t *circ = origin_circuit_new();
  1683. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
  1684. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  1685. circ->build_state->onehop_tunnel =
  1686. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  1687. circ->build_state->need_uptime =
  1688. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  1689. circ->build_state->need_capacity =
  1690. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  1691. circ->build_state->is_internal =
  1692. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  1693. circ->_base.purpose = purpose;
  1694. return circ;
  1695. }
  1696. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  1697. * is defined, then use that as your exit router, else choose a suitable
  1698. * exit node.
  1699. *
  1700. * Also launch a connection to the first OR in the chosen path, if
  1701. * it's not open already.
  1702. */
  1703. origin_circuit_t *
  1704. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  1705. {
  1706. origin_circuit_t *circ;
  1707. int err_reason = 0;
  1708. circ = origin_circuit_init(purpose, flags);
  1709. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  1710. onion_populate_cpath(circ) < 0) {
  1711. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  1712. return NULL;
  1713. }
  1714. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  1715. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  1716. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1717. return NULL;
  1718. }
  1719. return circ;
  1720. }
  1721. /** Start establishing the first hop of our circuit. Figure out what
  1722. * OR we should connect to, and if necessary start the connection to
  1723. * it. If we're already connected, then send the 'create' cell.
  1724. * Return 0 for ok, -reason if circ should be marked-for-close. */
  1725. int
  1726. circuit_handle_first_hop(origin_circuit_t *circ)
  1727. {
  1728. crypt_path_t *firsthop;
  1729. or_connection_t *n_conn;
  1730. int err_reason = 0;
  1731. const char *msg = NULL;
  1732. int should_launch = 0;
  1733. firsthop = onion_next_hop_in_cpath(circ->cpath);
  1734. tor_assert(firsthop);
  1735. tor_assert(firsthop->extend_info);
  1736. /* now see if we're already connected to the first OR in 'route' */
  1737. log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",
  1738. fmt_addr(&firsthop->extend_info->addr),
  1739. firsthop->extend_info->port);
  1740. n_conn = connection_or_get_for_extend(firsthop->extend_info->identity_digest,
  1741. &firsthop->extend_info->addr,
  1742. &msg,
  1743. &should_launch);
  1744. if (!n_conn) {
  1745. /* not currently connected in a useful way. */
  1746. log_info(LD_CIRC, "Next router is %s: %s",
  1747. safe_str_client(extend_info_describe(firsthop->extend_info)),
  1748. msg?msg:"???");
  1749. circ->_base.n_hop = extend_info_dup(firsthop->extend_info);
  1750. if (should_launch) {
  1751. if (circ->build_state->onehop_tunnel)
  1752. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  1753. n_conn = connection_or_connect(&firsthop->extend_info->addr,
  1754. firsthop->extend_info->port,
  1755. firsthop->extend_info->identity_digest);
  1756. if (!n_conn) { /* connect failed, forget the whole thing */
  1757. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  1758. return -END_CIRC_REASON_CONNECTFAILED;
  1759. }
  1760. }
  1761. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  1762. /* return success. The onion/circuit/etc will be taken care of
  1763. * automatically (may already have been) whenever n_conn reaches
  1764. * OR_CONN_STATE_OPEN.
  1765. */
  1766. return 0;
  1767. } else { /* it's already open. use it. */
  1768. tor_assert(!circ->_base.n_hop);
  1769. circ->_base.n_conn = n_conn;
  1770. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  1771. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  1772. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  1773. return err_reason;
  1774. }
  1775. }
  1776. return 0;
  1777. }
  1778. /** Find any circuits that are waiting on <b>or_conn</b> to become
  1779. * open and get them to send their create cells forward.
  1780. *
  1781. * Status is 1 if connect succeeded, or 0 if connect failed.
  1782. */
  1783. void
  1784. circuit_n_conn_done(or_connection_t *or_conn, int status)
  1785. {
  1786. smartlist_t *pending_circs;
  1787. int err_reason = 0;
  1788. log_debug(LD_CIRC,"or_conn to %s/%s, status=%d",
  1789. or_conn->nickname ? or_conn->nickname : "NULL",
  1790. or_conn->_base.address, status);
  1791. pending_circs = smartlist_new();
  1792. circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
  1793. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  1794. {
  1795. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  1796. * leaving them in in case it's possible for the status of a circuit to
  1797. * change as we're going down the list. */
  1798. if (circ->marked_for_close || circ->n_conn || !circ->n_hop ||
  1799. circ->state != CIRCUIT_STATE_OR_WAIT)
  1800. continue;
  1801. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  1802. /* Look at addr/port. This is an unkeyed connection. */
  1803. if (!tor_addr_eq(&circ->n_hop->addr, &or_conn->_base.addr) ||
  1804. circ->n_hop->port != or_conn->_base.port)
  1805. continue;
  1806. } else {
  1807. /* We expected a key. See if it's the right one. */
  1808. if (tor_memneq(or_conn->identity_digest,
  1809. circ->n_hop->identity_digest, DIGEST_LEN))
  1810. continue;
  1811. }
  1812. if (!status) { /* or_conn failed; close circ */
  1813. log_info(LD_CIRC,"or_conn failed. Closing circ.");
  1814. circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
  1815. continue;
  1816. }
  1817. log_debug(LD_CIRC, "Found circ, sending create cell.");
  1818. /* circuit_deliver_create_cell will set n_circ_id and add us to
  1819. * orconn_circuid_circuit_map, so we don't need to call
  1820. * set_circid_orconn here. */
  1821. circ->n_conn = or_conn;
  1822. extend_info_free(circ->n_hop);
  1823. circ->n_hop = NULL;
  1824. if (CIRCUIT_IS_ORIGIN(circ)) {
  1825. if ((err_reason =
  1826. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  1827. log_info(LD_CIRC,
  1828. "send_next_onion_skin failed; circuit marked for closing.");
  1829. circuit_mark_for_close(circ, -err_reason);
  1830. continue;
  1831. /* XXX could this be bad, eg if next_onion_skin failed because conn
  1832. * died? */
  1833. }
  1834. } else {
  1835. /* pull the create cell out of circ->onionskin, and send it */
  1836. tor_assert(circ->n_conn_onionskin);
  1837. if (circuit_deliver_create_cell(circ,CELL_CREATE,
  1838. circ->n_conn_onionskin)<0) {
  1839. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  1840. continue;
  1841. }
  1842. tor_free(circ->n_conn_onionskin);
  1843. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  1844. }
  1845. }
  1846. SMARTLIST_FOREACH_END(circ);
  1847. smartlist_free(pending_circs);
  1848. }
  1849. /** Find a new circid that isn't currently in use on the circ->n_conn
  1850. * for the outgoing
  1851. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  1852. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  1853. * to this circuit.
  1854. * Return -1 if we failed to find a suitable circid, else return 0.
  1855. */
  1856. static int
  1857. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
  1858. const char *payload)
  1859. {
  1860. cell_t cell;
  1861. circid_t id;
  1862. tor_assert(circ);
  1863. tor_assert(circ->n_conn);
  1864. tor_assert(payload);
  1865. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  1866. id = get_unique_circ_id_by_conn(circ->n_conn);
  1867. if (!id) {
  1868. log_warn(LD_CIRC,"failed to get unique circID.");
  1869. return -1;
  1870. }
  1871. log_debug(LD_CIRC,"Chosen circID %u.", id);
  1872. circuit_set_n_circid_orconn(circ, id, circ->n_conn);
  1873. memset(&cell, 0, sizeof(cell_t));
  1874. cell.command = cell_type;
  1875. cell.circ_id = circ->n_circ_id;
  1876. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  1877. append_cell_to_circuit_queue(circ, circ->n_conn, &cell,
  1878. CELL_DIRECTION_OUT, 0);
  1879. if (CIRCUIT_IS_ORIGIN(circ)) {
  1880. /* mark it so it gets better rate limiting treatment. */
  1881. circ->n_conn->client_used = time(NULL);
  1882. }
  1883. return 0;
  1884. }
  1885. /** We've decided to start our reachability testing. If all
  1886. * is set, log this to the user. Return 1 if we did, or 0 if
  1887. * we chose not to log anything. */
  1888. int
  1889. inform_testing_reachability(void)
  1890. {
  1891. char dirbuf[128];
  1892. const routerinfo_t *me = router_get_my_routerinfo();
  1893. if (!me)
  1894. return 0;
  1895. control_event_server_status(LOG_NOTICE,
  1896. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  1897. me->address, me->or_port);
  1898. if (me->dir_port) {
  1899. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  1900. me->address, me->dir_port);
  1901. control_event_server_status(LOG_NOTICE,
  1902. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  1903. me->address, me->dir_port);
  1904. }
  1905. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  1906. "(this may take up to %d minutes -- look for log "
  1907. "messages indicating success)",
  1908. me->address, me->or_port,
  1909. me->dir_port ? dirbuf : "",
  1910. me->dir_port ? "are" : "is",
  1911. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  1912. return 1;
  1913. }
  1914. /** Return true iff we should send a create_fast cell to start building a given
  1915. * circuit */
  1916. static INLINE int
  1917. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  1918. {
  1919. const or_options_t *options = get_options();
  1920. tor_assert(circ->cpath);
  1921. tor_assert(circ->cpath->extend_info);
  1922. if (!circ->cpath->extend_info->onion_key)
  1923. return 1; /* our hand is forced: only a create_fast will work. */
  1924. if (!options->FastFirstHopPK)
  1925. return 0; /* we prefer to avoid create_fast */
  1926. if (public_server_mode(options)) {
  1927. /* We're a server, and we know an onion key. We can choose.
  1928. * Prefer to blend our circuit into the other circuits we are
  1929. * creating on behalf of others. */
  1930. return 0;
  1931. }
  1932. return 1;
  1933. }
  1934. /** Return true if <b>circ</b> is the type of circuit we want to count
  1935. * timeouts from. In particular, we want it to have not completed yet
  1936. * (already completing indicates we cannibalized it), and we want it to
  1937. * have exactly three hops.
  1938. */
  1939. int
  1940. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  1941. {
  1942. return !circ->has_opened
  1943. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  1944. }
  1945. /** This is the backbone function for building circuits.
  1946. *
  1947. * If circ's first hop is closed, then we need to build a create
  1948. * cell and send it forward.
  1949. *
  1950. * Otherwise, we need to build a relay extend cell and send it
  1951. * forward.
  1952. *
  1953. * Return -reason if we want to tear down circ, else return 0.
  1954. */
  1955. int
  1956. circuit_send_next_onion_skin(origin_circuit_t *circ)
  1957. {
  1958. crypt_path_t *hop;
  1959. const node_t *node;
  1960. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  1961. char *onionskin;
  1962. size_t payload_len;
  1963. tor_assert(circ);
  1964. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  1965. int fast;
  1966. uint8_t cell_type;
  1967. log_debug(LD_CIRC,"First skin; sending create cell.");
  1968. if (circ->build_state->onehop_tunnel)
  1969. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  1970. else
  1971. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  1972. node = node_get_by_id(circ->_base.n_conn->identity_digest);
  1973. fast = should_use_create_fast_for_circuit(circ);
  1974. if (!fast) {
  1975. /* We are an OR and we know the right onion key: we should
  1976. * send an old slow create cell.
  1977. */
  1978. cell_type = CELL_CREATE;
  1979. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  1980. &(circ->cpath->dh_handshake_state),
  1981. payload) < 0) {
  1982. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  1983. return - END_CIRC_REASON_INTERNAL;
  1984. }
  1985. note_request("cell: create", 1);
  1986. } else {
  1987. /* We are not an OR, and we're building the first hop of a circuit to a
  1988. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  1989. * and a DH operation. */
  1990. cell_type = CELL_CREATE_FAST;
  1991. memset(payload, 0, sizeof(payload));
  1992. crypto_rand((char*) circ->cpath->fast_handshake_state,
  1993. sizeof(circ->cpath->fast_handshake_state));
  1994. memcpy(payload, circ->cpath->fast_handshake_state,
  1995. sizeof(circ->cpath->fast_handshake_state));
  1996. note_request("cell: create fast", 1);
  1997. }
  1998. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
  1999. return - END_CIRC_REASON_RESOURCELIMIT;
  2000. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  2001. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2002. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  2003. fast ? "CREATE_FAST" : "CREATE",
  2004. node ? node_describe(node) : "<unnamed>");
  2005. } else {
  2006. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  2007. tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
  2008. log_debug(LD_CIRC,"starting to send subsequent skin.");
  2009. hop = onion_next_hop_in_cpath(circ->cpath);
  2010. if (!hop) {
  2011. /* done building the circuit. whew. */
  2012. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  2013. if (circuit_timeout_want_to_count_circ(circ)) {
  2014. struct timeval end;
  2015. long timediff;
  2016. tor_gettimeofday(&end);
  2017. timediff = tv_mdiff(&circ->_base.timestamp_created, &end);
  2018. /*
  2019. * If the circuit build time is much greater than we would have cut
  2020. * it off at, we probably had a suspend event along this codepath,
  2021. * and we should discard the value.
  2022. */
  2023. if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
  2024. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  2025. "Assuming clock jump. Purpose %d (%s)", timediff,
  2026. circ->_base.purpose,
  2027. circuit_purpose_to_string(circ->_base.purpose));
  2028. } else if (!circuit_build_times_disabled()) {
  2029. /* Only count circuit times if the network is live */
  2030. if (circuit_build_times_network_check_live(&circ_times)) {
  2031. circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
  2032. circuit_build_times_set_timeout(&circ_times);
  2033. }
  2034. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  2035. circuit_build_times_network_circ_success(&circ_times);
  2036. }
  2037. }
  2038. }
  2039. log_info(LD_CIRC,"circuit built!");
  2040. circuit_reset_failure_count(0);
  2041. /* Don't count cannibalized or onehop circs for path bias */
  2042. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  2043. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  2044. } else {
  2045. entry_guard_t *guard =
  2046. entry_guard_get_by_id_digest(circ->_base.n_conn->identity_digest);
  2047. if (guard) {
  2048. guard->circuit_successes++;
  2049. log_info(LD_PROTOCOL, "Got success count %u/%u for guard %s=%s",
  2050. guard->circuit_successes, guard->first_hops,
  2051. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  2052. if (guard->first_hops < guard->circuit_successes) {
  2053. log_warn(LD_BUG, "Unexpectedly high circuit_successes (%u/%u) "
  2054. "for guard %s",
  2055. guard->circuit_successes, guard->first_hops,
  2056. guard->nickname);
  2057. }
  2058. }
  2059. }
  2060. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  2061. const or_options_t *options = get_options();
  2062. can_complete_circuit=1;
  2063. /* FFFF Log a count of known routers here */
  2064. log_notice(LD_GENERAL,
  2065. "Tor has successfully opened a circuit. "
  2066. "Looks like client functionality is working.");
  2067. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  2068. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  2069. clear_broken_connection_map(1);
  2070. if (server_mode(options) && !check_whether_orport_reachable()) {
  2071. inform_testing_reachability();
  2072. consider_testing_reachability(1, 1);
  2073. }
  2074. }
  2075. circuit_rep_hist_note_result(circ);
  2076. circuit_has_opened(circ); /* do other actions as necessary */
  2077. /* We're done with measurement circuits here. Just close them */
  2078. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  2079. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  2080. return 0;
  2081. }
  2082. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  2083. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  2084. return - END_CIRC_REASON_INTERNAL;
  2085. }
  2086. set_uint32(payload, tor_addr_to_ipv4n(&hop->extend_info->addr));
  2087. set_uint16(payload+4, htons(hop->extend_info->port));
  2088. onionskin = payload+2+4;
  2089. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
  2090. hop->extend_info->identity_digest, DIGEST_LEN);
  2091. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  2092. if (onion_skin_create(hop->extend_info->onion_key,
  2093. &(hop->dh_handshake_state), onionskin) < 0) {
  2094. log_warn(LD_CIRC,"onion_skin_create failed.");
  2095. return - END_CIRC_REASON_INTERNAL;
  2096. }
  2097. log_info(LD_CIRC,"Sending extend relay cell.");
  2098. note_request("cell: extend", 1);
  2099. /* send it to hop->prev, because it will transfer
  2100. * it to a create cell and then send to hop */
  2101. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  2102. RELAY_COMMAND_EXTEND,
  2103. payload, payload_len, hop->prev) < 0)
  2104. return 0; /* circuit is closed */
  2105. hop->state = CPATH_STATE_AWAITING_KEYS;
  2106. }
  2107. return 0;
  2108. }
  2109. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  2110. * something has also gone wrong with our network: notify the user,
  2111. * and abandon all not-yet-used circuits. */
  2112. void
  2113. circuit_note_clock_jumped(int seconds_elapsed)
  2114. {
  2115. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  2116. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  2117. "assuming established circuits no longer work.",
  2118. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  2119. seconds_elapsed >=0 ? "forward" : "backward");
  2120. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  2121. seconds_elapsed);
  2122. can_complete_circuit=0; /* so it'll log when it works again */
  2123. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  2124. "CLOCK_JUMPED");
  2125. circuit_mark_all_unused_circs();
  2126. circuit_expire_all_dirty_circs();
  2127. }
  2128. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  2129. * skin and identity digest for the next hop. If we're already connected,
  2130. * pass the onion skin to the next hop using a create cell; otherwise
  2131. * launch a new OR connection, and <b>circ</b> will notice when the
  2132. * connection succeeds or fails.
  2133. *
  2134. * Return -1 if we want to warn and tear down the circuit, else return 0.
  2135. */
  2136. int
  2137. circuit_extend(cell_t *cell, circuit_t *circ)
  2138. {
  2139. or_connection_t *n_conn;
  2140. relay_header_t rh;
  2141. char *onionskin;
  2142. char *id_digest=NULL;
  2143. uint32_t n_addr32;
  2144. uint16_t n_port;
  2145. tor_addr_t n_addr;
  2146. const char *msg = NULL;
  2147. int should_launch = 0;
  2148. if (circ->n_conn) {
  2149. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2150. "n_conn already set. Bug/attack. Closing.");
  2151. return -1;
  2152. }
  2153. if (circ->n_hop) {
  2154. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2155. "conn to next hop already launched. Bug/attack. Closing.");
  2156. return -1;
  2157. }
  2158. if (!server_mode(get_options())) {
  2159. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2160. "Got an extend cell, but running as a client. Closing.");
  2161. return -1;
  2162. }
  2163. relay_header_unpack(&rh, cell->payload);
  2164. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  2165. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2166. "Wrong length %d on extend cell. Closing circuit.",
  2167. rh.length);
  2168. return -1;
  2169. }
  2170. n_addr32 = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  2171. n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  2172. onionskin = (char*) cell->payload+RELAY_HEADER_SIZE+4+2;
  2173. id_digest = (char*) cell->payload+RELAY_HEADER_SIZE+4+2+
  2174. ONIONSKIN_CHALLENGE_LEN;
  2175. tor_addr_from_ipv4h(&n_addr, n_addr32);
  2176. if (!n_port || !n_addr32) {
  2177. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2178. "Client asked me to extend to zero destination port or addr.");
  2179. return -1;
  2180. }
  2181. /* Check if they asked us for 0000..0000. We support using
  2182. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  2183. * but we don't want to let people send us extend cells for empty
  2184. * fingerprints -- a) because it opens the user up to a mitm attack,
  2185. * and b) because it lets an attacker force the relay to hold open a
  2186. * new TLS connection for each extend request. */
  2187. if (tor_digest_is_zero(id_digest)) {
  2188. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2189. "Client asked me to extend without specifying an id_digest.");
  2190. return -1;
  2191. }
  2192. /* Next, check if we're being asked to connect to the hop that the
  2193. * extend cell came from. There isn't any reason for that, and it can
  2194. * assist circular-path attacks. */
  2195. if (tor_memeq(id_digest, TO_OR_CIRCUIT(circ)->p_conn->identity_digest,
  2196. DIGEST_LEN)) {
  2197. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2198. "Client asked me to extend back to the previous hop.");
  2199. return -1;
  2200. }
  2201. n_conn = connection_or_get_for_extend(id_digest,
  2202. &n_addr,
  2203. &msg,
  2204. &should_launch);
  2205. if (!n_conn) {
  2206. log_debug(LD_CIRC|LD_OR,"Next router (%s:%d): %s",
  2207. fmt_addr(&n_addr), (int)n_port, msg?msg:"????");
  2208. circ->n_hop = extend_info_alloc(NULL /*nickname*/,
  2209. id_digest,
  2210. NULL /*onion_key*/,
  2211. &n_addr, n_port);
  2212. circ->n_conn_onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  2213. memcpy(circ->n_conn_onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  2214. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  2215. if (should_launch) {
  2216. /* we should try to open a connection */
  2217. n_conn = connection_or_connect(&n_addr, n_port, id_digest);
  2218. if (!n_conn) {
  2219. log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
  2220. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  2221. return 0;
  2222. }
  2223. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  2224. }
  2225. /* return success. The onion/circuit/etc will be taken care of
  2226. * automatically (may already have been) whenever n_conn reaches
  2227. * OR_CONN_STATE_OPEN.
  2228. */
  2229. return 0;
  2230. }
  2231. tor_assert(!circ->n_hop); /* Connection is already established. */
  2232. circ->n_conn = n_conn;
  2233. log_debug(LD_CIRC,"n_conn is %s:%u",
  2234. n_conn->_base.address,n_conn->_base.port);
  2235. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  2236. return -1;
  2237. return 0;
  2238. }
  2239. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  2240. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  2241. * used as follows:
  2242. * - 20 to initialize f_digest
  2243. * - 20 to initialize b_digest
  2244. * - 16 to key f_crypto
  2245. * - 16 to key b_crypto
  2246. *
  2247. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  2248. */
  2249. int
  2250. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  2251. int reverse)
  2252. {
  2253. crypto_digest_t *tmp_digest;
  2254. crypto_cipher_t *tmp_crypto;
  2255. tor_assert(cpath);
  2256. tor_assert(key_data);
  2257. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  2258. cpath->f_digest || cpath->b_digest));
  2259. cpath->f_digest = crypto_digest_new();
  2260. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  2261. cpath->b_digest = crypto_digest_new();
  2262. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  2263. if (!(cpath->f_crypto =
  2264. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  2265. log_warn(LD_BUG,"Forward cipher initialization failed.");
  2266. return -1;
  2267. }
  2268. if (!(cpath->b_crypto =
  2269. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  2270. log_warn(LD_BUG,"Backward cipher initialization failed.");
  2271. return -1;
  2272. }
  2273. if (reverse) {
  2274. tmp_digest = cpath->f_digest;
  2275. cpath->f_digest = cpath->b_digest;
  2276. cpath->b_digest = tmp_digest;
  2277. tmp_crypto = cpath->f_crypto;
  2278. cpath->f_crypto = cpath->b_crypto;
  2279. cpath->b_crypto = tmp_crypto;
  2280. }
  2281. return 0;
  2282. }
  2283. /** The minimum number of first hop completions before we start
  2284. * thinking about warning about path bias and dropping guards */
  2285. static int
  2286. pathbias_get_min_circs(const or_options_t *options)
  2287. {
  2288. #define DFLT_PATH_BIAS_MIN_CIRC 20
  2289. if (options->PathBiasCircThreshold >= 5)
  2290. return options->PathBiasCircThreshold;
  2291. else
  2292. return networkstatus_get_param(NULL, "pb_mincircs",
  2293. DFLT_PATH_BIAS_MIN_CIRC,
  2294. 5, INT32_MAX);
  2295. }
  2296. static double
  2297. pathbias_get_notice_rate(const or_options_t *options)
  2298. {
  2299. #define DFLT_PATH_BIAS_NOTICE_PCT 40
  2300. if (options->PathBiasNoticeRate >= 0.0)
  2301. return options->PathBiasNoticeRate;
  2302. else
  2303. return networkstatus_get_param(NULL, "pb_noticepct",
  2304. DFLT_PATH_BIAS_NOTICE_PCT, 0, 100)/100.0;
  2305. }
  2306. static double
  2307. pathbias_get_disable_rate(const or_options_t *options)
  2308. {
  2309. // XXX: This needs tuning based on use + experimentation before we set it
  2310. #define DFLT_PATH_BIAS_DISABLE_PCT 0
  2311. if (options->PathBiasDisableRate >= 0.0)
  2312. return options->PathBiasDisableRate;
  2313. else
  2314. return networkstatus_get_param(NULL, "pb_disablepct",
  2315. DFLT_PATH_BIAS_DISABLE_PCT, 0, 100)/100.0;
  2316. }
  2317. static int
  2318. pathbias_get_scale_threshold(const or_options_t *options)
  2319. {
  2320. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 200
  2321. if (options->PathBiasScaleThreshold >= 2)
  2322. return options->PathBiasScaleThreshold;
  2323. else
  2324. return networkstatus_get_param(NULL, "pb_scalecircs",
  2325. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  2326. INT32_MAX);
  2327. }
  2328. static int
  2329. pathbias_get_scale_factor(const or_options_t *options)
  2330. {
  2331. #define DFLT_PATH_BIAS_SCALE_FACTOR 4
  2332. if (options->PathBiasScaleFactor >= 1)
  2333. return options->PathBiasScaleFactor;
  2334. else
  2335. return networkstatus_get_param(NULL, "pb_scalefactor",
  2336. DFLT_PATH_BIAS_SCALE_THRESHOLD, 1, INT32_MAX);
  2337. }
  2338. /** Increment the number of times we successfully extended a circuit to
  2339. * 'guard', first checking if the failure rate is high enough that we should
  2340. * eliminate the guard. Return -1 if the guard looks no good; return 0 if the
  2341. * guard looks fine. */
  2342. static int
  2343. entry_guard_inc_first_hop_count(entry_guard_t *guard)
  2344. {
  2345. const or_options_t *options = get_options();
  2346. entry_guards_changed();
  2347. if (guard->first_hops > (unsigned)pathbias_get_min_circs(options)) {
  2348. /* Note: We rely on the < comparison here to allow us to set a 0
  2349. * rate and disable the feature entirely. If refactoring, don't
  2350. * change to <= */
  2351. if (guard->circuit_successes/((double)guard->first_hops)
  2352. < pathbias_get_disable_rate(options)) {
  2353. log_warn(LD_PROTOCOL,
  2354. "Extremely low circuit success rate %u/%u for guard %s=%s. "
  2355. "This might indicate an attack, or a bug.",
  2356. guard->circuit_successes, guard->first_hops, guard->nickname,
  2357. hex_str(guard->identity, DIGEST_LEN));
  2358. guard->path_bias_disabled = 1;
  2359. guard->bad_since = approx_time();
  2360. return -1;
  2361. } else if (guard->circuit_successes/((double)guard->first_hops)
  2362. < pathbias_get_notice_rate(options)
  2363. && !guard->path_bias_notice) {
  2364. guard->path_bias_notice = 1;
  2365. log_notice(LD_PROTOCOL,
  2366. "Low circuit success rate %u/%u for guard %s=%s.",
  2367. guard->circuit_successes, guard->first_hops, guard->nickname,
  2368. hex_str(guard->identity, DIGEST_LEN));
  2369. }
  2370. }
  2371. /* If we get a ton of circuits, just scale everything down */
  2372. if (guard->first_hops > (unsigned)pathbias_get_scale_threshold(options)) {
  2373. const int scale_factor = pathbias_get_scale_factor(options);
  2374. guard->first_hops /= scale_factor;
  2375. guard->circuit_successes /= scale_factor;
  2376. }
  2377. guard->first_hops++;
  2378. log_info(LD_PROTOCOL, "Got success count %u/%u for guard %s",
  2379. guard->circuit_successes, guard->first_hops, guard->nickname);
  2380. return 0;
  2381. }
  2382. /** A created or extended cell came back to us on the circuit, and it included
  2383. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  2384. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  2385. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  2386. *
  2387. * Calculate the appropriate keys and digests, make sure KH is
  2388. * correct, and initialize this hop of the cpath.
  2389. *
  2390. * Return - reason if we want to mark circ for close, else return 0.
  2391. */
  2392. int
  2393. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  2394. const uint8_t *reply)
  2395. {
  2396. char keys[CPATH_KEY_MATERIAL_LEN];
  2397. crypt_path_t *hop;
  2398. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  2399. hop = circ->cpath;
  2400. /* Don't count cannibalized or onehop circs for path bias */
  2401. if (!circ->has_opened && !circ->build_state->onehop_tunnel) {
  2402. entry_guard_t *guard;
  2403. guard = entry_guard_get_by_id_digest(
  2404. circ->_base.n_conn->identity_digest);
  2405. if (guard) {
  2406. if (entry_guard_inc_first_hop_count(guard) < 0) {
  2407. /* Bogus guard; we already warned. */
  2408. return -END_CIRC_REASON_TORPROTOCOL;
  2409. }
  2410. }
  2411. }
  2412. } else {
  2413. hop = onion_next_hop_in_cpath(circ->cpath);
  2414. if (!hop) { /* got an extended when we're all done? */
  2415. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  2416. return - END_CIRC_REASON_TORPROTOCOL;
  2417. }
  2418. }
  2419. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  2420. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  2421. if (onion_skin_client_handshake(hop->dh_handshake_state, (char*)reply,keys,
  2422. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  2423. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  2424. return -END_CIRC_REASON_TORPROTOCOL;
  2425. }
  2426. /* Remember hash of g^xy */
  2427. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  2428. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  2429. if (fast_client_handshake(hop->fast_handshake_state, reply,
  2430. (uint8_t*)keys,
  2431. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  2432. log_warn(LD_CIRC,"fast_client_handshake failed.");
  2433. return -END_CIRC_REASON_TORPROTOCOL;
  2434. }
  2435. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  2436. } else {
  2437. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  2438. return -END_CIRC_REASON_TORPROTOCOL;
  2439. }
  2440. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  2441. hop->dh_handshake_state = NULL;
  2442. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  2443. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  2444. return -END_CIRC_REASON_TORPROTOCOL;
  2445. }
  2446. hop->state = CPATH_STATE_OPEN;
  2447. log_info(LD_CIRC,"Finished building %scircuit hop:",
  2448. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  2449. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  2450. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  2451. return 0;
  2452. }
  2453. /** We received a relay truncated cell on circ.
  2454. *
  2455. * Since we don't ask for truncates currently, getting a truncated
  2456. * means that a connection broke or an extend failed. For now,
  2457. * just give up: for circ to close, and return 0.
  2458. */
  2459. int
  2460. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
  2461. {
  2462. // crypt_path_t *victim;
  2463. // connection_t *stream;
  2464. tor_assert(circ);
  2465. tor_assert(layer);
  2466. /* XXX Since we don't ask for truncates currently, getting a truncated
  2467. * means that a connection broke or an extend failed. For now,
  2468. * just give up.
  2469. */
  2470. circuit_mark_for_close(TO_CIRCUIT(circ),
  2471. END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
  2472. return 0;
  2473. #if 0
  2474. while (layer->next != circ->cpath) {
  2475. /* we need to clear out layer->next */
  2476. victim = layer->next;
  2477. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  2478. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  2479. if (stream->cpath_layer == victim) {
  2480. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  2481. stream->stream_id);
  2482. /* no need to send 'end' relay cells,
  2483. * because the other side's already dead
  2484. */
  2485. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  2486. }
  2487. }
  2488. layer->next = victim->next;
  2489. circuit_free_cpath_node(victim);
  2490. }
  2491. log_info(LD_CIRC, "finished");
  2492. return 0;
  2493. #endif
  2494. }
  2495. /** Given a response payload and keys, initialize, then send a created
  2496. * cell back.
  2497. */
  2498. int
  2499. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  2500. const char *keys)
  2501. {
  2502. cell_t cell;
  2503. crypt_path_t *tmp_cpath;
  2504. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  2505. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  2506. memset(&cell, 0, sizeof(cell_t));
  2507. cell.command = cell_type;
  2508. cell.circ_id = circ->p_circ_id;
  2509. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  2510. memcpy(cell.payload, payload,
  2511. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  2512. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  2513. (unsigned int)get_uint32(keys),
  2514. (unsigned int)get_uint32(keys+20));
  2515. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  2516. log_warn(LD_BUG,"Circuit initialization failed");
  2517. tor_free(tmp_cpath);
  2518. return -1;
  2519. }
  2520. circ->n_digest = tmp_cpath->f_digest;
  2521. circ->n_crypto = tmp_cpath->f_crypto;
  2522. circ->p_digest = tmp_cpath->b_digest;
  2523. circ->p_crypto = tmp_cpath->b_crypto;
  2524. tmp_cpath->magic = 0;
  2525. tor_free(tmp_cpath);
  2526. if (cell_type == CELL_CREATED)
  2527. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  2528. else
  2529. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  2530. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  2531. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  2532. circ->p_conn, &cell, CELL_DIRECTION_IN, 0);
  2533. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  2534. circ->is_first_hop ? "created_fast" : "created");
  2535. if (!is_local_addr(&circ->p_conn->_base.addr) &&
  2536. !connection_or_nonopen_was_started_here(circ->p_conn)) {
  2537. /* record that we could process create cells from a non-local conn
  2538. * that we didn't initiate; presumably this means that create cells
  2539. * can reach us too. */
  2540. router_orport_found_reachable();
  2541. }
  2542. return 0;
  2543. }
  2544. /** Choose a length for a circuit of purpose <b>purpose</b>.
  2545. * Default length is 3 + the number of endpoints that would give something
  2546. * away. If the routerlist <b>routers</b> doesn't have enough routers
  2547. * to handle the desired path length, return as large a path length as
  2548. * is feasible, except if it's less than 2, in which case return -1.
  2549. */
  2550. static int
  2551. new_route_len(uint8_t purpose, extend_info_t *exit,
  2552. smartlist_t *nodes)
  2553. {
  2554. int num_acceptable_routers;
  2555. int routelen;
  2556. tor_assert(nodes);
  2557. routelen = DEFAULT_ROUTE_LEN;
  2558. if (exit &&
  2559. purpose != CIRCUIT_PURPOSE_TESTING &&
  2560. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  2561. routelen++;
  2562. num_acceptable_routers = count_acceptable_nodes(nodes);
  2563. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  2564. routelen, num_acceptable_routers, smartlist_len(nodes));
  2565. if (num_acceptable_routers < 2) {
  2566. log_info(LD_CIRC,
  2567. "Not enough acceptable routers (%d). Discarding this circuit.",
  2568. num_acceptable_routers);
  2569. return -1;
  2570. }
  2571. if (num_acceptable_routers < routelen) {
  2572. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  2573. routelen, num_acceptable_routers);
  2574. routelen = num_acceptable_routers;
  2575. }
  2576. return routelen;
  2577. }
  2578. /** Return a newly allocated list of uint16_t * for each predicted port not
  2579. * handled by a current circuit. */
  2580. static smartlist_t *
  2581. circuit_get_unhandled_ports(time_t now)
  2582. {
  2583. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  2584. circuit_remove_handled_ports(dest);
  2585. return dest;
  2586. }
  2587. /** Return 1 if we already have circuits present or on the way for
  2588. * all anticipated ports. Return 0 if we should make more.
  2589. *
  2590. * If we're returning 0, set need_uptime and need_capacity to
  2591. * indicate any requirements that the unhandled ports have.
  2592. */
  2593. int
  2594. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  2595. int *need_capacity)
  2596. {
  2597. int i, enough;
  2598. uint16_t *port;
  2599. smartlist_t *sl = circuit_get_unhandled_ports(now);
  2600. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  2601. tor_assert(need_uptime);
  2602. tor_assert(need_capacity);
  2603. // Always predict need_capacity
  2604. *need_capacity = 1;
  2605. enough = (smartlist_len(sl) == 0);
  2606. for (i = 0; i < smartlist_len(sl); ++i) {
  2607. port = smartlist_get(sl, i);
  2608. if (smartlist_string_num_isin(LongLivedServices, *port))
  2609. *need_uptime = 1;
  2610. tor_free(port);
  2611. }
  2612. smartlist_free(sl);
  2613. return enough;
  2614. }
  2615. /** Return 1 if <b>node</b> can handle one or more of the ports in
  2616. * <b>needed_ports</b>, else return 0.
  2617. */
  2618. static int
  2619. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  2620. { /* XXXX MOVE */
  2621. int i;
  2622. uint16_t port;
  2623. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  2624. addr_policy_result_t r;
  2625. /* alignment issues aren't a worry for this dereference, since
  2626. needed_ports is explicitly a smartlist of uint16_t's */
  2627. port = *(uint16_t *)smartlist_get(needed_ports, i);
  2628. tor_assert(port);
  2629. if (node)
  2630. r = compare_tor_addr_to_node_policy(NULL, port, node);
  2631. else
  2632. continue;
  2633. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  2634. return 1;
  2635. }
  2636. return 0;
  2637. }
  2638. /** Return true iff <b>conn</b> needs another general circuit to be
  2639. * built. */
  2640. static int
  2641. ap_stream_wants_exit_attention(connection_t *conn)
  2642. {
  2643. entry_connection_t *entry;
  2644. if (conn->type != CONN_TYPE_AP)
  2645. return 0;
  2646. entry = TO_ENTRY_CONN(conn);
  2647. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  2648. !conn->marked_for_close &&
  2649. !(entry->want_onehop) && /* ignore one-hop streams */
  2650. !(entry->use_begindir) && /* ignore targeted dir fetches */
  2651. !(entry->chosen_exit_name) && /* ignore defined streams */
  2652. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  2653. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  2654. MIN_CIRCUITS_HANDLING_STREAM))
  2655. return 1;
  2656. return 0;
  2657. }
  2658. /** Return a pointer to a suitable router to be the exit node for the
  2659. * general-purpose circuit we're about to build.
  2660. *
  2661. * Look through the connection array, and choose a router that maximizes
  2662. * the number of pending streams that can exit from this router.
  2663. *
  2664. * Return NULL if we can't find any suitable routers.
  2665. */
  2666. static const node_t *
  2667. choose_good_exit_server_general(int need_uptime, int need_capacity)
  2668. {
  2669. int *n_supported;
  2670. int n_pending_connections = 0;
  2671. smartlist_t *connections;
  2672. int best_support = -1;
  2673. int n_best_support=0;
  2674. const or_options_t *options = get_options();
  2675. const smartlist_t *the_nodes;
  2676. const node_t *node=NULL;
  2677. connections = get_connection_array();
  2678. /* Count how many connections are waiting for a circuit to be built.
  2679. * We use this for log messages now, but in the future we may depend on it.
  2680. */
  2681. SMARTLIST_FOREACH(connections, connection_t *, conn,
  2682. {
  2683. if (ap_stream_wants_exit_attention(conn))
  2684. ++n_pending_connections;
  2685. });
  2686. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  2687. // n_pending_connections);
  2688. /* Now we count, for each of the routers in the directory, how many
  2689. * of the pending connections could possibly exit from that
  2690. * router (n_supported[i]). (We can't be sure about cases where we
  2691. * don't know the IP address of the pending connection.)
  2692. *
  2693. * -1 means "Don't use this router at all."
  2694. */
  2695. the_nodes = nodelist_get_list();
  2696. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  2697. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2698. const int i = node_sl_idx;
  2699. if (router_digest_is_me(node->identity)) {
  2700. n_supported[i] = -1;
  2701. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  2702. /* XXX there's probably a reverse predecessor attack here, but
  2703. * it's slow. should we take this out? -RD
  2704. */
  2705. continue;
  2706. }
  2707. if (!node_has_descriptor(node)) {
  2708. n_supported[i] = -1;
  2709. continue;
  2710. }
  2711. if (!node->is_running || node->is_bad_exit) {
  2712. n_supported[i] = -1;
  2713. continue; /* skip routers that are known to be down or bad exits */
  2714. }
  2715. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  2716. /* never pick a non-general node as a random exit. */
  2717. n_supported[i] = -1;
  2718. continue;
  2719. }
  2720. if (routerset_contains_node(options->_ExcludeExitNodesUnion, node)) {
  2721. n_supported[i] = -1;
  2722. continue; /* user asked us not to use it, no matter what */
  2723. }
  2724. if (options->ExitNodes &&
  2725. !routerset_contains_node(options->ExitNodes, node)) {
  2726. n_supported[i] = -1;
  2727. continue; /* not one of our chosen exit nodes */
  2728. }
  2729. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  2730. n_supported[i] = -1;
  2731. continue; /* skip routers that are not suitable. Don't worry if
  2732. * this makes us reject all the possible routers: if so,
  2733. * we'll retry later in this function with need_update and
  2734. * need_capacity set to 0. */
  2735. }
  2736. if (!(node->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  2737. /* if it's invalid and we don't want it */
  2738. n_supported[i] = -1;
  2739. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  2740. // router->nickname, i);
  2741. continue; /* skip invalid routers */
  2742. }
  2743. if (options->ExcludeSingleHopRelays &&
  2744. node_allows_single_hop_exits(node)) {
  2745. n_supported[i] = -1;
  2746. continue;
  2747. }
  2748. if (node_exit_policy_rejects_all(node)) {
  2749. n_supported[i] = -1;
  2750. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  2751. // router->nickname, i);
  2752. continue; /* skip routers that reject all */
  2753. }
  2754. n_supported[i] = 0;
  2755. /* iterate over connections */
  2756. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  2757. if (!ap_stream_wants_exit_attention(conn))
  2758. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  2759. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  2760. ++n_supported[i];
  2761. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  2762. // router->nickname, i, n_supported[i]);
  2763. } else {
  2764. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  2765. // router->nickname, i);
  2766. }
  2767. } SMARTLIST_FOREACH_END(conn);
  2768. if (n_pending_connections > 0 && n_supported[i] == 0) {
  2769. /* Leave best_support at -1 if that's where it is, so we can
  2770. * distinguish it later. */
  2771. continue;
  2772. }
  2773. if (n_supported[i] > best_support) {
  2774. /* If this router is better than previous ones, remember its index
  2775. * and goodness, and start counting how many routers are this good. */
  2776. best_support = n_supported[i]; n_best_support=1;
  2777. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  2778. // router->nickname);
  2779. } else if (n_supported[i] == best_support) {
  2780. /* If this router is _as good_ as the best one, just increment the
  2781. * count of equally good routers.*/
  2782. ++n_best_support;
  2783. }
  2784. } SMARTLIST_FOREACH_END(node);
  2785. log_info(LD_CIRC,
  2786. "Found %d servers that might support %d/%d pending connections.",
  2787. n_best_support, best_support >= 0 ? best_support : 0,
  2788. n_pending_connections);
  2789. /* If any routers definitely support any pending connections, choose one
  2790. * at random. */
  2791. if (best_support > 0) {
  2792. smartlist_t *supporting = smartlist_new();
  2793. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  2794. if (n_supported[node_sl_idx] == best_support)
  2795. smartlist_add(supporting, (void*)node);
  2796. });
  2797. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2798. smartlist_free(supporting);
  2799. } else {
  2800. /* Either there are no pending connections, or no routers even seem to
  2801. * possibly support any of them. Choose a router at random that satisfies
  2802. * at least one predicted exit port. */
  2803. int attempt;
  2804. smartlist_t *needed_ports, *supporting;
  2805. if (best_support == -1) {
  2806. if (need_uptime || need_capacity) {
  2807. log_info(LD_CIRC,
  2808. "We couldn't find any live%s%s routers; falling back "
  2809. "to list of all routers.",
  2810. need_capacity?", fast":"",
  2811. need_uptime?", stable":"");
  2812. tor_free(n_supported);
  2813. return choose_good_exit_server_general(0, 0);
  2814. }
  2815. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  2816. "choosing a doomed exit at random.",
  2817. options->_ExcludeExitNodesUnion ? " or are Excluded" : "");
  2818. }
  2819. supporting = smartlist_new();
  2820. needed_ports = circuit_get_unhandled_ports(time(NULL));
  2821. for (attempt = 0; attempt < 2; attempt++) {
  2822. /* try once to pick only from routers that satisfy a needed port,
  2823. * then if there are none, pick from any that support exiting. */
  2824. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  2825. if (n_supported[node_sl_idx] != -1 &&
  2826. (attempt || node_handles_some_port(node, needed_ports))) {
  2827. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  2828. // try, router->nickname);
  2829. smartlist_add(supporting, (void*)node);
  2830. }
  2831. } SMARTLIST_FOREACH_END(node);
  2832. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  2833. if (node)
  2834. break;
  2835. smartlist_clear(supporting);
  2836. /* If we reach this point, we can't actually support any unhandled
  2837. * predicted ports, so clear all the remaining ones. */
  2838. if (smartlist_len(needed_ports))
  2839. rep_hist_remove_predicted_ports(needed_ports);
  2840. }
  2841. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  2842. smartlist_free(needed_ports);
  2843. smartlist_free(supporting);
  2844. }
  2845. tor_free(n_supported);
  2846. if (node) {
  2847. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  2848. return node;
  2849. }
  2850. if (options->ExitNodes) {
  2851. log_warn(LD_CIRC,
  2852. "No specified %sexit routers seem to be running: "
  2853. "can't choose an exit.",
  2854. options->_ExcludeExitNodesUnion ? "non-excluded " : "");
  2855. }
  2856. return NULL;
  2857. }
  2858. /** Return a pointer to a suitable router to be the exit node for the
  2859. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  2860. * if no router is suitable).
  2861. *
  2862. * For general-purpose circuits, pass it off to
  2863. * choose_good_exit_server_general()
  2864. *
  2865. * For client-side rendezvous circuits, choose a random node, weighted
  2866. * toward the preferences in 'options'.
  2867. */
  2868. static const node_t *
  2869. choose_good_exit_server(uint8_t purpose,
  2870. int need_uptime, int need_capacity, int is_internal)
  2871. {
  2872. const or_options_t *options = get_options();
  2873. router_crn_flags_t flags = CRN_NEED_DESC;
  2874. if (need_uptime)
  2875. flags |= CRN_NEED_UPTIME;
  2876. if (need_capacity)
  2877. flags |= CRN_NEED_CAPACITY;
  2878. switch (purpose) {
  2879. case CIRCUIT_PURPOSE_C_GENERAL:
  2880. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  2881. flags |= CRN_ALLOW_INVALID;
  2882. if (is_internal) /* pick it like a middle hop */
  2883. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2884. else
  2885. return choose_good_exit_server_general(need_uptime,need_capacity);
  2886. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2887. if (options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS)
  2888. flags |= CRN_ALLOW_INVALID;
  2889. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  2890. }
  2891. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  2892. tor_fragile_assert();
  2893. return NULL;
  2894. }
  2895. /** Log a warning if the user specified an exit for the circuit that
  2896. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  2897. static void
  2898. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  2899. {
  2900. const or_options_t *options = get_options();
  2901. routerset_t *rs = options->ExcludeNodes;
  2902. const char *description;
  2903. uint8_t purpose = circ->_base.purpose;
  2904. if (circ->build_state->onehop_tunnel)
  2905. return;
  2906. switch (purpose)
  2907. {
  2908. default:
  2909. case CIRCUIT_PURPOSE_OR:
  2910. case CIRCUIT_PURPOSE_INTRO_POINT:
  2911. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  2912. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  2913. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  2914. (int)purpose,
  2915. circuit_purpose_to_string(purpose));
  2916. return;
  2917. case CIRCUIT_PURPOSE_C_GENERAL:
  2918. if (circ->build_state->is_internal)
  2919. return;
  2920. description = "requested exit node";
  2921. rs = options->_ExcludeExitNodesUnion;
  2922. break;
  2923. case CIRCUIT_PURPOSE_C_INTRODUCING:
  2924. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  2925. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  2926. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  2927. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  2928. case CIRCUIT_PURPOSE_S_REND_JOINED:
  2929. case CIRCUIT_PURPOSE_TESTING:
  2930. return;
  2931. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  2932. case CIRCUIT_PURPOSE_C_REND_READY:
  2933. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  2934. case CIRCUIT_PURPOSE_C_REND_JOINED:
  2935. description = "chosen rendezvous point";
  2936. break;
  2937. case CIRCUIT_PURPOSE_CONTROLLER:
  2938. rs = options->_ExcludeExitNodesUnion;
  2939. description = "controller-selected circuit target";
  2940. break;
  2941. }
  2942. if (routerset_contains_extendinfo(rs, exit)) {
  2943. /* We should never get here if StrictNodes is set to 1. */
  2944. if (options->StrictNodes) {
  2945. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  2946. "even though StrictNodes is set. Please report. "
  2947. "(Circuit purpose: %s)",
  2948. description, extend_info_describe(exit),
  2949. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2950. circuit_purpose_to_string(purpose));
  2951. } else {
  2952. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  2953. "ExcludeNodes%s, because no better options were available. To "
  2954. "prevent this (and possibly break your Tor functionality), "
  2955. "set the StrictNodes configuration option. "
  2956. "(Circuit purpose: %s)",
  2957. description, extend_info_describe(exit),
  2958. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  2959. circuit_purpose_to_string(purpose));
  2960. }
  2961. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  2962. }
  2963. return;
  2964. }
  2965. /** Decide a suitable length for circ's cpath, and pick an exit
  2966. * router (or use <b>exit</b> if provided). Store these in the
  2967. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  2968. static int
  2969. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  2970. {
  2971. cpath_build_state_t *state = circ->build_state;
  2972. if (state->onehop_tunnel) {
  2973. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  2974. state->desired_path_len = 1;
  2975. } else {
  2976. int r = new_route_len(circ->_base.purpose, exit, nodelist_get_list());
  2977. if (r < 1) /* must be at least 1 */
  2978. return -1;
  2979. state->desired_path_len = r;
  2980. }
  2981. if (exit) { /* the circuit-builder pre-requested one */
  2982. warn_if_last_router_excluded(circ, exit);
  2983. log_info(LD_CIRC,"Using requested exit node '%s'",
  2984. extend_info_describe(exit));
  2985. exit = extend_info_dup(exit);
  2986. } else { /* we have to decide one */
  2987. const node_t *node =
  2988. choose_good_exit_server(circ->_base.purpose, state->need_uptime,
  2989. state->need_capacity, state->is_internal);
  2990. if (!node) {
  2991. log_warn(LD_CIRC,"failed to choose an exit server");
  2992. return -1;
  2993. }
  2994. exit = extend_info_from_node(node, 0);
  2995. tor_assert(exit);
  2996. }
  2997. state->chosen_exit = exit;
  2998. return 0;
  2999. }
  3000. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  3001. * hop to the cpath reflecting this. Don't send the next extend cell --
  3002. * the caller will do this if it wants to.
  3003. */
  3004. int
  3005. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  3006. {
  3007. cpath_build_state_t *state;
  3008. tor_assert(exit);
  3009. tor_assert(circ);
  3010. state = circ->build_state;
  3011. tor_assert(state);
  3012. extend_info_free(state->chosen_exit);
  3013. state->chosen_exit = extend_info_dup(exit);
  3014. ++circ->build_state->desired_path_len;
  3015. onion_append_hop(&circ->cpath, exit);
  3016. return 0;
  3017. }
  3018. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  3019. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  3020. * send the next extend cell to begin connecting to that hop.
  3021. */
  3022. int
  3023. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  3024. {
  3025. int err_reason = 0;
  3026. warn_if_last_router_excluded(circ, exit);
  3027. circuit_append_new_exit(circ, exit);
  3028. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  3029. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  3030. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  3031. extend_info_describe(exit));
  3032. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  3033. return -1;
  3034. }
  3035. return 0;
  3036. }
  3037. /** Return the number of routers in <b>routers</b> that are currently up
  3038. * and available for building circuits through.
  3039. */
  3040. static int
  3041. count_acceptable_nodes(smartlist_t *nodes)
  3042. {
  3043. int num=0;
  3044. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  3045. // log_debug(LD_CIRC,
  3046. // "Contemplating whether router %d (%s) is a new option.",
  3047. // i, r->nickname);
  3048. if (! node->is_running)
  3049. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  3050. continue;
  3051. if (! node->is_valid)
  3052. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  3053. continue;
  3054. if (! node_has_descriptor(node))
  3055. continue;
  3056. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  3057. * allows this node in some places, then we're getting an inaccurate
  3058. * count. For now, be conservative and don't count it. But later we
  3059. * should try to be smarter. */
  3060. ++num;
  3061. } SMARTLIST_FOREACH_END(node);
  3062. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  3063. return num;
  3064. }
  3065. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  3066. * This function is used to extend cpath by another hop.
  3067. */
  3068. void
  3069. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  3070. {
  3071. if (*head_ptr) {
  3072. new_hop->next = (*head_ptr);
  3073. new_hop->prev = (*head_ptr)->prev;
  3074. (*head_ptr)->prev->next = new_hop;
  3075. (*head_ptr)->prev = new_hop;
  3076. } else {
  3077. *head_ptr = new_hop;
  3078. new_hop->prev = new_hop->next = new_hop;
  3079. }
  3080. }
  3081. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  3082. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  3083. * to length <b>cur_len</b> to decide a suitable middle hop for a
  3084. * circuit. In particular, make sure we don't pick the exit node or its
  3085. * family, and make sure we don't duplicate any previous nodes or their
  3086. * families. */
  3087. static const node_t *
  3088. choose_good_middle_server(uint8_t purpose,
  3089. cpath_build_state_t *state,
  3090. crypt_path_t *head,
  3091. int cur_len)
  3092. {
  3093. int i;
  3094. const node_t *r, *choice;
  3095. crypt_path_t *cpath;
  3096. smartlist_t *excluded;
  3097. const or_options_t *options = get_options();
  3098. router_crn_flags_t flags = CRN_NEED_DESC;
  3099. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  3100. purpose <= _CIRCUIT_PURPOSE_MAX);
  3101. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  3102. excluded = smartlist_new();
  3103. if ((r = build_state_get_exit_node(state))) {
  3104. nodelist_add_node_and_family(excluded, r);
  3105. }
  3106. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  3107. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  3108. nodelist_add_node_and_family(excluded, r);
  3109. }
  3110. }
  3111. if (state->need_uptime)
  3112. flags |= CRN_NEED_UPTIME;
  3113. if (state->need_capacity)
  3114. flags |= CRN_NEED_CAPACITY;
  3115. if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
  3116. flags |= CRN_ALLOW_INVALID;
  3117. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  3118. smartlist_free(excluded);
  3119. return choice;
  3120. }
  3121. /** Pick a good entry server for the circuit to be built according to
  3122. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  3123. * router (if we're an OR), and respect firewall settings; if we're
  3124. * configured to use entry guards, return one.
  3125. *
  3126. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  3127. * guard, not for any particular circuit.
  3128. */
  3129. static const node_t *
  3130. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  3131. {
  3132. const node_t *choice;
  3133. smartlist_t *excluded;
  3134. const or_options_t *options = get_options();
  3135. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  3136. const node_t *node;
  3137. if (state && options->UseEntryGuards &&
  3138. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  3139. /* This request is for an entry server to use for a regular circuit,
  3140. * and we use entry guard nodes. Just return one of the guard nodes. */
  3141. return choose_random_entry(state);
  3142. }
  3143. excluded = smartlist_new();
  3144. if (state && (node = build_state_get_exit_node(state))) {
  3145. /* Exclude the exit node from the state, if we have one. Also exclude its
  3146. * family. */
  3147. nodelist_add_node_and_family(excluded, node);
  3148. }
  3149. if (firewall_is_fascist_or()) {
  3150. /* Exclude all ORs that we can't reach through our firewall */
  3151. smartlist_t *nodes = nodelist_get_list();
  3152. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  3153. if (!fascist_firewall_allows_node(node))
  3154. smartlist_add(excluded, (void*)node);
  3155. });
  3156. }
  3157. /* and exclude current entry guards and their families, if applicable */
  3158. if (options->UseEntryGuards && entry_guards) {
  3159. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3160. {
  3161. if ((node = node_get_by_id(entry->identity))) {
  3162. nodelist_add_node_and_family(excluded, node);
  3163. }
  3164. });
  3165. }
  3166. if (state) {
  3167. if (state->need_uptime)
  3168. flags |= CRN_NEED_UPTIME;
  3169. if (state->need_capacity)
  3170. flags |= CRN_NEED_CAPACITY;
  3171. }
  3172. if (options->_AllowInvalid & ALLOW_INVALID_ENTRY)
  3173. flags |= CRN_ALLOW_INVALID;
  3174. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  3175. smartlist_free(excluded);
  3176. return choice;
  3177. }
  3178. /** Return the first non-open hop in cpath, or return NULL if all
  3179. * hops are open. */
  3180. static crypt_path_t *
  3181. onion_next_hop_in_cpath(crypt_path_t *cpath)
  3182. {
  3183. crypt_path_t *hop = cpath;
  3184. do {
  3185. if (hop->state != CPATH_STATE_OPEN)
  3186. return hop;
  3187. hop = hop->next;
  3188. } while (hop != cpath);
  3189. return NULL;
  3190. }
  3191. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  3192. * based on <b>state</b>. Append the hop info to head_ptr.
  3193. */
  3194. static int
  3195. onion_extend_cpath(origin_circuit_t *circ)
  3196. {
  3197. uint8_t purpose = circ->_base.purpose;
  3198. cpath_build_state_t *state = circ->build_state;
  3199. int cur_len = circuit_get_cpath_len(circ);
  3200. extend_info_t *info = NULL;
  3201. if (cur_len >= state->desired_path_len) {
  3202. log_debug(LD_CIRC, "Path is complete: %d steps long",
  3203. state->desired_path_len);
  3204. return 1;
  3205. }
  3206. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  3207. state->desired_path_len);
  3208. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  3209. info = extend_info_dup(state->chosen_exit);
  3210. } else if (cur_len == 0) { /* picking first node */
  3211. const node_t *r = choose_good_entry_server(purpose, state);
  3212. if (r) {
  3213. /* If we're extending to a bridge, use the preferred address
  3214. rather than the primary, for potentially extending to an IPv6
  3215. bridge. */
  3216. int use_pref_addr = (r->ri != NULL &&
  3217. r->ri->purpose == ROUTER_PURPOSE_BRIDGE);
  3218. info = extend_info_from_node(r, use_pref_addr);
  3219. tor_assert(info);
  3220. }
  3221. } else {
  3222. const node_t *r =
  3223. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  3224. if (r) {
  3225. info = extend_info_from_node(r, 0);
  3226. tor_assert(info);
  3227. }
  3228. }
  3229. if (!info) {
  3230. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  3231. "this circuit.", cur_len);
  3232. return -1;
  3233. }
  3234. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  3235. extend_info_describe(info),
  3236. cur_len+1, build_state_get_exit_nickname(state));
  3237. onion_append_hop(&circ->cpath, info);
  3238. extend_info_free(info);
  3239. return 0;
  3240. }
  3241. /** Create a new hop, annotate it with information about its
  3242. * corresponding router <b>choice</b>, and append it to the
  3243. * end of the cpath <b>head_ptr</b>. */
  3244. static int
  3245. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  3246. {
  3247. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  3248. /* link hop into the cpath, at the end. */
  3249. onion_append_to_cpath(head_ptr, hop);
  3250. hop->magic = CRYPT_PATH_MAGIC;
  3251. hop->state = CPATH_STATE_CLOSED;
  3252. hop->extend_info = extend_info_dup(choice);
  3253. hop->package_window = circuit_initial_package_window();
  3254. hop->deliver_window = CIRCWINDOW_START;
  3255. return 0;
  3256. }
  3257. /** Allocate a new extend_info object based on the various arguments. */
  3258. extend_info_t *
  3259. extend_info_alloc(const char *nickname, const char *digest,
  3260. crypto_pk_t *onion_key,
  3261. const tor_addr_t *addr, uint16_t port)
  3262. {
  3263. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  3264. memcpy(info->identity_digest, digest, DIGEST_LEN);
  3265. if (nickname)
  3266. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  3267. if (onion_key)
  3268. info->onion_key = crypto_pk_dup_key(onion_key);
  3269. tor_addr_copy(&info->addr, addr);
  3270. info->port = port;
  3271. return info;
  3272. }
  3273. /** Allocate and return a new extend_info_t that can be used to build
  3274. * a circuit to or through the router <b>r</b>. Use the primary
  3275. * address of the router unless <b>for_direct_connect</b> is true, in
  3276. * which case the preferred address is used instead. */
  3277. extend_info_t *
  3278. extend_info_from_router(const routerinfo_t *r, int for_direct_connect)
  3279. {
  3280. tor_addr_port_t ap;
  3281. tor_assert(r);
  3282. if (for_direct_connect)
  3283. router_get_pref_orport(r, &ap);
  3284. else
  3285. router_get_prim_orport(r, &ap);
  3286. return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
  3287. r->onion_pkey, &ap.addr, ap.port);
  3288. }
  3289. /** Allocate and return a new extend_info that can be used to build a
  3290. * circuit to or through the node <b>node</b>. Use the primary address
  3291. * of the node unless <b>for_direct_connect</b> is true, in which case
  3292. * the preferred address is used instead. May return NULL if there is
  3293. * not enough info about <b>node</b> to extend to it--for example, if
  3294. * there is no routerinfo_t or microdesc_t.
  3295. **/
  3296. extend_info_t *
  3297. extend_info_from_node(const node_t *node, int for_direct_connect)
  3298. {
  3299. if (node->ri) {
  3300. return extend_info_from_router(node->ri, for_direct_connect);
  3301. } else if (node->rs && node->md) {
  3302. tor_addr_t addr;
  3303. tor_addr_from_ipv4h(&addr, node->rs->addr);
  3304. return extend_info_alloc(node->rs->nickname,
  3305. node->identity,
  3306. node->md->onion_pkey,
  3307. &addr,
  3308. node->rs->or_port);
  3309. } else {
  3310. return NULL;
  3311. }
  3312. }
  3313. /** Release storage held by an extend_info_t struct. */
  3314. void
  3315. extend_info_free(extend_info_t *info)
  3316. {
  3317. if (!info)
  3318. return;
  3319. crypto_pk_free(info->onion_key);
  3320. tor_free(info);
  3321. }
  3322. /** Allocate and return a new extend_info_t with the same contents as
  3323. * <b>info</b>. */
  3324. extend_info_t *
  3325. extend_info_dup(extend_info_t *info)
  3326. {
  3327. extend_info_t *newinfo;
  3328. tor_assert(info);
  3329. newinfo = tor_malloc(sizeof(extend_info_t));
  3330. memcpy(newinfo, info, sizeof(extend_info_t));
  3331. if (info->onion_key)
  3332. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  3333. else
  3334. newinfo->onion_key = NULL;
  3335. return newinfo;
  3336. }
  3337. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  3338. * If there is no chosen exit, or if we don't know the routerinfo_t for
  3339. * the chosen exit, return NULL.
  3340. */
  3341. const node_t *
  3342. build_state_get_exit_node(cpath_build_state_t *state)
  3343. {
  3344. if (!state || !state->chosen_exit)
  3345. return NULL;
  3346. return node_get_by_id(state->chosen_exit->identity_digest);
  3347. }
  3348. /** Return the nickname for the chosen exit router in <b>state</b>. If
  3349. * there is no chosen exit, or if we don't know the routerinfo_t for the
  3350. * chosen exit, return NULL.
  3351. */
  3352. const char *
  3353. build_state_get_exit_nickname(cpath_build_state_t *state)
  3354. {
  3355. if (!state || !state->chosen_exit)
  3356. return NULL;
  3357. return state->chosen_exit->nickname;
  3358. }
  3359. /** Check whether the entry guard <b>e</b> is usable, given the directory
  3360. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  3361. * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
  3362. * accordingly. Return true iff the entry guard's status changes.
  3363. *
  3364. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  3365. */
  3366. static int
  3367. entry_guard_set_status(entry_guard_t *e, const node_t *node,
  3368. time_t now, const or_options_t *options,
  3369. const char **reason)
  3370. {
  3371. char buf[HEX_DIGEST_LEN+1];
  3372. int changed = 0;
  3373. *reason = NULL;
  3374. /* Do we want to mark this guard as bad? */
  3375. if (!node)
  3376. *reason = "unlisted";
  3377. else if (!node->is_running)
  3378. *reason = "down";
  3379. else if (options->UseBridges && (!node->ri ||
  3380. node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
  3381. *reason = "not a bridge";
  3382. else if (options->UseBridges && !node_is_a_configured_bridge(node))
  3383. *reason = "not a configured bridge";
  3384. else if (!options->UseBridges && !node->is_possible_guard &&
  3385. !routerset_contains_node(options->EntryNodes,node))
  3386. *reason = "not recommended as a guard";
  3387. else if (routerset_contains_node(options->ExcludeNodes, node))
  3388. *reason = "excluded";
  3389. else if (e->path_bias_disabled)
  3390. *reason = "path-biased";
  3391. if (*reason && ! e->bad_since) {
  3392. /* Router is newly bad. */
  3393. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  3394. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  3395. e->nickname, buf, *reason);
  3396. e->bad_since = now;
  3397. control_event_guard(e->nickname, e->identity, "BAD");
  3398. changed = 1;
  3399. } else if (!*reason && e->bad_since) {
  3400. /* There's nothing wrong with the router any more. */
  3401. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  3402. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  3403. "marking as ok.", e->nickname, buf);
  3404. e->bad_since = 0;
  3405. control_event_guard(e->nickname, e->identity, "GOOD");
  3406. changed = 1;
  3407. }
  3408. return changed;
  3409. }
  3410. /** Return true iff enough time has passed since we last tried to connect
  3411. * to the unreachable guard <b>e</b> that we're willing to try again. */
  3412. static int
  3413. entry_is_time_to_retry(entry_guard_t *e, time_t now)
  3414. {
  3415. long diff;
  3416. if (e->last_attempted < e->unreachable_since)
  3417. return 1;
  3418. diff = now - e->unreachable_since;
  3419. if (diff < 6*60*60)
  3420. return now > (e->last_attempted + 60*60);
  3421. else if (diff < 3*24*60*60)
  3422. return now > (e->last_attempted + 4*60*60);
  3423. else if (diff < 7*24*60*60)
  3424. return now > (e->last_attempted + 18*60*60);
  3425. else
  3426. return now > (e->last_attempted + 36*60*60);
  3427. }
  3428. /** Return the node corresponding to <b>e</b>, if <b>e</b> is
  3429. * working well enough that we are willing to use it as an entry
  3430. * right now. (Else return NULL.) In particular, it must be
  3431. * - Listed as either up or never yet contacted;
  3432. * - Present in the routerlist;
  3433. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  3434. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  3435. * (unless it's a configured EntryNode);
  3436. * - Allowed by our current ReachableORAddresses config option; and
  3437. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  3438. * is true).
  3439. *
  3440. * If the answer is no, set *<b>msg</b> to an explanation of why.
  3441. */
  3442. static INLINE const node_t *
  3443. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
  3444. int assume_reachable, const char **msg)
  3445. {
  3446. const node_t *node;
  3447. const or_options_t *options = get_options();
  3448. tor_assert(msg);
  3449. if (e->path_bias_disabled) {
  3450. *msg = "path-biased";
  3451. return NULL;
  3452. }
  3453. if (e->bad_since) {
  3454. *msg = "bad";
  3455. return NULL;
  3456. }
  3457. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  3458. if (!assume_reachable && !e->can_retry &&
  3459. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  3460. *msg = "unreachable";
  3461. return NULL;
  3462. }
  3463. node = node_get_by_id(e->identity);
  3464. if (!node || !node_has_descriptor(node)) {
  3465. *msg = "no descriptor";
  3466. return NULL;
  3467. }
  3468. if (get_options()->UseBridges) {
  3469. if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
  3470. *msg = "not a bridge";
  3471. return NULL;
  3472. }
  3473. if (!node_is_a_configured_bridge(node)) {
  3474. *msg = "not a configured bridge";
  3475. return NULL;
  3476. }
  3477. } else { /* !get_options()->UseBridges */
  3478. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  3479. *msg = "not general-purpose";
  3480. return NULL;
  3481. }
  3482. }
  3483. if (routerset_contains_node(options->EntryNodes, node)) {
  3484. /* they asked for it, they get it */
  3485. need_uptime = need_capacity = 0;
  3486. }
  3487. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  3488. *msg = "not fast/stable";
  3489. return NULL;
  3490. }
  3491. if (!fascist_firewall_allows_node(node)) {
  3492. *msg = "unreachable by config";
  3493. return NULL;
  3494. }
  3495. return node;
  3496. }
  3497. /** Return the number of entry guards that we think are usable. */
  3498. static int
  3499. num_live_entry_guards(void)
  3500. {
  3501. int n = 0;
  3502. const char *msg;
  3503. if (! entry_guards)
  3504. return 0;
  3505. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3506. {
  3507. if (entry_is_live(entry, 0, 1, 0, &msg))
  3508. ++n;
  3509. });
  3510. return n;
  3511. }
  3512. /** If <b>digest</b> matches the identity of any node in the
  3513. * entry_guards list, return that node. Else return NULL. */
  3514. static entry_guard_t *
  3515. entry_guard_get_by_id_digest(const char *digest)
  3516. {
  3517. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3518. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  3519. return entry;
  3520. );
  3521. return NULL;
  3522. }
  3523. /** Dump a description of our list of entry guards to the log at level
  3524. * <b>severity</b>. */
  3525. static void
  3526. log_entry_guards(int severity)
  3527. {
  3528. smartlist_t *elements = smartlist_new();
  3529. char *s;
  3530. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e)
  3531. {
  3532. const char *msg = NULL;
  3533. if (entry_is_live(e, 0, 1, 0, &msg))
  3534. smartlist_add_asprintf(elements, "%s [%s] (up %s)",
  3535. e->nickname,
  3536. hex_str(e->identity, DIGEST_LEN),
  3537. e->made_contact ? "made-contact" : "never-contacted");
  3538. else
  3539. smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
  3540. e->nickname,
  3541. hex_str(e->identity, DIGEST_LEN),
  3542. msg,
  3543. e->made_contact ? "made-contact" : "never-contacted");
  3544. }
  3545. SMARTLIST_FOREACH_END(e);
  3546. s = smartlist_join_strings(elements, ",", 0, NULL);
  3547. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  3548. smartlist_free(elements);
  3549. log_fn(severity,LD_CIRC,"%s",s);
  3550. tor_free(s);
  3551. }
  3552. /** Called when one or more guards that we would previously have used for some
  3553. * purpose are no longer in use because a higher-priority guard has become
  3554. * usable again. */
  3555. static void
  3556. control_event_guard_deferred(void)
  3557. {
  3558. /* XXXX We don't actually have a good way to figure out _how many_ entries
  3559. * are live for some purpose. We need an entry_is_even_slightly_live()
  3560. * function for this to work right. NumEntryGuards isn't reliable: if we
  3561. * need guards with weird properties, we can have more than that number
  3562. * live.
  3563. **/
  3564. #if 0
  3565. int n = 0;
  3566. const char *msg;
  3567. const or_options_t *options = get_options();
  3568. if (!entry_guards)
  3569. return;
  3570. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  3571. {
  3572. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  3573. if (n++ == options->NumEntryGuards) {
  3574. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  3575. return;
  3576. }
  3577. }
  3578. });
  3579. #endif
  3580. }
  3581. /** Add a new (preferably stable and fast) router to our
  3582. * entry_guards list. Return a pointer to the router if we succeed,
  3583. * or NULL if we can't find any more suitable entries.
  3584. *
  3585. * If <b>chosen</b> is defined, use that one, and if it's not
  3586. * already in our entry_guards list, put it at the *beginning*.
  3587. * Else, put the one we pick at the end of the list. */
  3588. static const node_t *
  3589. add_an_entry_guard(const node_t *chosen, int reset_status, int prepend)
  3590. {
  3591. const node_t *node;
  3592. entry_guard_t *entry;
  3593. if (chosen) {
  3594. node = chosen;
  3595. entry = entry_guard_get_by_id_digest(node->identity);
  3596. if (entry) {
  3597. if (reset_status) {
  3598. entry->bad_since = 0;
  3599. entry->can_retry = 1;
  3600. }
  3601. return NULL;
  3602. }
  3603. } else {
  3604. node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  3605. if (!node)
  3606. return NULL;
  3607. }
  3608. entry = tor_malloc_zero(sizeof(entry_guard_t));
  3609. log_info(LD_CIRC, "Chose %s as new entry guard.",
  3610. node_describe(node));
  3611. strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
  3612. memcpy(entry->identity, node->identity, DIGEST_LEN);
  3613. /* Choose expiry time smudged over the past month. The goal here
  3614. * is to a) spread out when Tor clients rotate their guards, so they
  3615. * don't all select them on the same day, and b) avoid leaving a
  3616. * precise timestamp in the state file about when we first picked
  3617. * this guard. For details, see the Jan 2010 or-dev thread. */
  3618. entry->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  3619. entry->chosen_by_version = tor_strdup(VERSION);
  3620. if (prepend)
  3621. smartlist_insert(entry_guards, 0, entry);
  3622. else
  3623. smartlist_add(entry_guards, entry);
  3624. control_event_guard(entry->nickname, entry->identity, "NEW");
  3625. control_event_guard_deferred();
  3626. log_entry_guards(LOG_INFO);
  3627. return node;
  3628. }
  3629. /** If the use of entry guards is configured, choose more entry guards
  3630. * until we have enough in the list. */
  3631. static void
  3632. pick_entry_guards(const or_options_t *options)
  3633. {
  3634. int changed = 0;
  3635. tor_assert(entry_guards);
  3636. while (num_live_entry_guards() < options->NumEntryGuards) {
  3637. if (!add_an_entry_guard(NULL, 0, 0))
  3638. break;
  3639. changed = 1;
  3640. }
  3641. if (changed)
  3642. entry_guards_changed();
  3643. }
  3644. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  3645. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  3646. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  3647. /** Release all storage held by <b>e</b>. */
  3648. static void
  3649. entry_guard_free(entry_guard_t *e)
  3650. {
  3651. if (!e)
  3652. return;
  3653. tor_free(e->chosen_by_version);
  3654. tor_free(e);
  3655. }
  3656. /** Remove any entry guard which was selected by an unknown version of Tor,
  3657. * or which was selected by a version of Tor that's known to select
  3658. * entry guards badly, or which was selected more 2 months ago. */
  3659. /* XXXX The "obsolete guards" and "chosen long ago guards" things should
  3660. * probably be different functions. */
  3661. static int
  3662. remove_obsolete_entry_guards(time_t now)
  3663. {
  3664. int changed = 0, i;
  3665. for (i = 0; i < smartlist_len(entry_guards); ++i) {
  3666. entry_guard_t *entry = smartlist_get(entry_guards, i);
  3667. const char *ver = entry->chosen_by_version;
  3668. const char *msg = NULL;
  3669. tor_version_t v;
  3670. int version_is_bad = 0, date_is_bad = 0;
  3671. if (!ver) {
  3672. msg = "does not say what version of Tor it was selected by";
  3673. version_is_bad = 1;
  3674. } else if (tor_version_parse(ver, &v)) {
  3675. msg = "does not seem to be from any recognized version of Tor";
  3676. version_is_bad = 1;
  3677. } else {
  3678. char *tor_ver = NULL;
  3679. tor_asprintf(&tor_ver, "Tor %s", ver);
  3680. if ((tor_version_as_new_as(tor_ver, "0.1.0.10-alpha") &&
  3681. !tor_version_as_new_as(tor_ver, "0.1.2.16-dev")) ||
  3682. (tor_version_as_new_as(tor_ver, "0.2.0.0-alpha") &&
  3683. !tor_version_as_new_as(tor_ver, "0.2.0.6-alpha")) ||
  3684. /* above are bug 440; below are bug 1217 */
  3685. (tor_version_as_new_as(tor_ver, "0.2.1.3-alpha") &&
  3686. !tor_version_as_new_as(tor_ver, "0.2.1.23")) ||
  3687. (tor_version_as_new_as(tor_ver, "0.2.2.0-alpha") &&
  3688. !tor_version_as_new_as(tor_ver, "0.2.2.7-alpha"))) {
  3689. msg = "was selected without regard for guard bandwidth";
  3690. version_is_bad = 1;
  3691. }
  3692. tor_free(tor_ver);
  3693. }
  3694. if (!version_is_bad && entry->chosen_on_date + 3600*24*60 < now) {
  3695. /* It's been 2 months since the date listed in our state file. */
  3696. msg = "was selected several months ago";
  3697. date_is_bad = 1;
  3698. }
  3699. if (version_is_bad || date_is_bad) { /* we need to drop it */
  3700. char dbuf[HEX_DIGEST_LEN+1];
  3701. tor_assert(msg);
  3702. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  3703. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  3704. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  3705. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  3706. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3707. entry_guard_free(entry);
  3708. smartlist_del_keeporder(entry_guards, i--);
  3709. log_entry_guards(LOG_INFO);
  3710. changed = 1;
  3711. }
  3712. }
  3713. return changed ? 1 : 0;
  3714. }
  3715. /** Remove all entry guards that have been down or unlisted for so
  3716. * long that we don't think they'll come up again. Return 1 if we
  3717. * removed any, or 0 if we did nothing. */
  3718. static int
  3719. remove_dead_entry_guards(time_t now)
  3720. {
  3721. char dbuf[HEX_DIGEST_LEN+1];
  3722. char tbuf[ISO_TIME_LEN+1];
  3723. int i;
  3724. int changed = 0;
  3725. for (i = 0; i < smartlist_len(entry_guards); ) {
  3726. entry_guard_t *entry = smartlist_get(entry_guards, i);
  3727. if (entry->bad_since &&
  3728. ! entry->path_bias_disabled &&
  3729. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  3730. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  3731. format_local_iso_time(tbuf, entry->bad_since);
  3732. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  3733. "since %s local time; removing.",
  3734. entry->nickname, dbuf, tbuf);
  3735. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3736. entry_guard_free(entry);
  3737. smartlist_del_keeporder(entry_guards, i);
  3738. log_entry_guards(LOG_INFO);
  3739. changed = 1;
  3740. } else
  3741. ++i;
  3742. }
  3743. return changed ? 1 : 0;
  3744. }
  3745. /** A new directory or router-status has arrived; update the down/listed
  3746. * status of the entry guards.
  3747. *
  3748. * An entry is 'down' if the directory lists it as nonrunning.
  3749. * An entry is 'unlisted' if the directory doesn't include it.
  3750. *
  3751. * Don't call this on startup; only on a fresh download. Otherwise we'll
  3752. * think that things are unlisted.
  3753. */
  3754. void
  3755. entry_guards_compute_status(const or_options_t *options, time_t now)
  3756. {
  3757. int changed = 0;
  3758. digestmap_t *reasons;
  3759. if (! entry_guards)
  3760. return;
  3761. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  3762. entry_nodes_should_be_added();
  3763. reasons = digestmap_new();
  3764. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
  3765. {
  3766. const node_t *r = node_get_by_id(entry->identity);
  3767. const char *reason = NULL;
  3768. if (entry_guard_set_status(entry, r, now, options, &reason))
  3769. changed = 1;
  3770. if (entry->bad_since)
  3771. tor_assert(reason);
  3772. if (reason)
  3773. digestmap_set(reasons, entry->identity, (char*)reason);
  3774. }
  3775. SMARTLIST_FOREACH_END(entry);
  3776. if (remove_dead_entry_guards(now))
  3777. changed = 1;
  3778. if (remove_obsolete_entry_guards(now))
  3779. changed = 1;
  3780. if (changed) {
  3781. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
  3782. const char *reason = digestmap_get(reasons, entry->identity);
  3783. const char *live_msg = "";
  3784. const node_t *r = entry_is_live(entry, 0, 1, 0, &live_msg);
  3785. log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
  3786. entry->nickname,
  3787. hex_str(entry->identity, DIGEST_LEN),
  3788. entry->unreachable_since ? "unreachable" : "reachable",
  3789. entry->bad_since ? "unusable" : "usable",
  3790. reason ? ", ": "",
  3791. reason ? reason : "",
  3792. r ? "live" : "not live / ",
  3793. r ? "" : live_msg);
  3794. } SMARTLIST_FOREACH_END(entry);
  3795. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  3796. num_live_entry_guards(), smartlist_len(entry_guards));
  3797. log_entry_guards(LOG_INFO);
  3798. entry_guards_changed();
  3799. }
  3800. digestmap_free(reasons, NULL);
  3801. }
  3802. /** Called when a connection to an OR with the identity digest <b>digest</b>
  3803. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  3804. * If the OR is an entry, change that entry's up/down status.
  3805. * Return 0 normally, or -1 if we want to tear down the new connection.
  3806. *
  3807. * If <b>mark_relay_status</b>, also call router_set_status() on this
  3808. * relay.
  3809. *
  3810. * XXX024 change succeeded and mark_relay_status into 'int flags'.
  3811. */
  3812. int
  3813. entry_guard_register_connect_status(const char *digest, int succeeded,
  3814. int mark_relay_status, time_t now)
  3815. {
  3816. int changed = 0;
  3817. int refuse_conn = 0;
  3818. int first_contact = 0;
  3819. entry_guard_t *entry = NULL;
  3820. int idx = -1;
  3821. char buf[HEX_DIGEST_LEN+1];
  3822. if (! entry_guards)
  3823. return 0;
  3824. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  3825. tor_assert(e);
  3826. if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
  3827. entry = e;
  3828. idx = e_sl_idx;
  3829. break;
  3830. }
  3831. } SMARTLIST_FOREACH_END(e);
  3832. if (!entry)
  3833. return 0;
  3834. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  3835. if (succeeded) {
  3836. if (entry->unreachable_since) {
  3837. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  3838. entry->nickname, buf);
  3839. entry->can_retry = 0;
  3840. entry->unreachable_since = 0;
  3841. entry->last_attempted = now;
  3842. control_event_guard(entry->nickname, entry->identity, "UP");
  3843. changed = 1;
  3844. }
  3845. if (!entry->made_contact) {
  3846. entry->made_contact = 1;
  3847. first_contact = changed = 1;
  3848. }
  3849. } else { /* ! succeeded */
  3850. if (!entry->made_contact) {
  3851. /* We've never connected to this one. */
  3852. log_info(LD_CIRC,
  3853. "Connection to never-contacted entry guard '%s' (%s) failed. "
  3854. "Removing from the list. %d/%d entry guards usable/new.",
  3855. entry->nickname, buf,
  3856. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  3857. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  3858. entry_guard_free(entry);
  3859. smartlist_del_keeporder(entry_guards, idx);
  3860. log_entry_guards(LOG_INFO);
  3861. changed = 1;
  3862. } else if (!entry->unreachable_since) {
  3863. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  3864. "Marking as unreachable.", entry->nickname, buf);
  3865. entry->unreachable_since = entry->last_attempted = now;
  3866. control_event_guard(entry->nickname, entry->identity, "DOWN");
  3867. changed = 1;
  3868. entry->can_retry = 0; /* We gave it an early chance; no good. */
  3869. } else {
  3870. char tbuf[ISO_TIME_LEN+1];
  3871. format_iso_time(tbuf, entry->unreachable_since);
  3872. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  3873. "'%s' (%s). It has been unreachable since %s.",
  3874. entry->nickname, buf, tbuf);
  3875. entry->last_attempted = now;
  3876. entry->can_retry = 0; /* We gave it an early chance; no good. */
  3877. }
  3878. }
  3879. /* if the caller asked us to, also update the is_running flags for this
  3880. * relay */
  3881. if (mark_relay_status)
  3882. router_set_status(digest, succeeded);
  3883. if (first_contact) {
  3884. /* We've just added a new long-term entry guard. Perhaps the network just
  3885. * came back? We should give our earlier entries another try too,
  3886. * and close this connection so we don't use it before we've given
  3887. * the others a shot. */
  3888. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  3889. if (e == entry)
  3890. break;
  3891. if (e->made_contact) {
  3892. const char *msg;
  3893. const node_t *r = entry_is_live(e, 0, 1, 1, &msg);
  3894. if (r && e->unreachable_since) {
  3895. refuse_conn = 1;
  3896. e->can_retry = 1;
  3897. }
  3898. }
  3899. });
  3900. if (refuse_conn) {
  3901. log_info(LD_CIRC,
  3902. "Connected to new entry guard '%s' (%s). Marking earlier "
  3903. "entry guards up. %d/%d entry guards usable/new.",
  3904. entry->nickname, buf,
  3905. num_live_entry_guards(), smartlist_len(entry_guards));
  3906. log_entry_guards(LOG_INFO);
  3907. changed = 1;
  3908. }
  3909. }
  3910. if (changed)
  3911. entry_guards_changed();
  3912. return refuse_conn ? -1 : 0;
  3913. }
  3914. /** When we try to choose an entry guard, should we parse and add
  3915. * config's EntryNodes first? */
  3916. static int should_add_entry_nodes = 0;
  3917. /** Called when the value of EntryNodes changes in our configuration. */
  3918. void
  3919. entry_nodes_should_be_added(void)
  3920. {
  3921. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  3922. "relays at the front of the entry guard list.");
  3923. should_add_entry_nodes = 1;
  3924. }
  3925. /** Adjust the entry guards list so that it only contains entries from
  3926. * EntryNodes, adding new entries from EntryNodes to the list as needed. */
  3927. static void
  3928. entry_guards_set_from_config(const or_options_t *options)
  3929. {
  3930. smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
  3931. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  3932. tor_assert(entry_guards);
  3933. should_add_entry_nodes = 0;
  3934. if (!options->EntryNodes) {
  3935. /* It's possible that a controller set EntryNodes, thus making
  3936. * should_add_entry_nodes set, then cleared it again, all before the
  3937. * call to choose_random_entry() that triggered us. If so, just return.
  3938. */
  3939. return;
  3940. }
  3941. {
  3942. char *string = routerset_to_string(options->EntryNodes);
  3943. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  3944. tor_free(string);
  3945. }
  3946. entry_nodes = smartlist_new();
  3947. worse_entry_nodes = smartlist_new();
  3948. entry_fps = smartlist_new();
  3949. old_entry_guards_on_list = smartlist_new();
  3950. old_entry_guards_not_on_list = smartlist_new();
  3951. /* Split entry guards into those on the list and those not. */
  3952. routerset_get_all_nodes(entry_nodes, options->EntryNodes,
  3953. options->ExcludeNodes, 0);
  3954. SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
  3955. smartlist_add(entry_fps, (void*)node->identity));
  3956. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  3957. if (smartlist_digest_isin(entry_fps, e->identity))
  3958. smartlist_add(old_entry_guards_on_list, e);
  3959. else
  3960. smartlist_add(old_entry_guards_not_on_list, e);
  3961. });
  3962. /* Remove all currently configured guard nodes, excluded nodes, unreachable
  3963. * nodes, or non-Guard nodes from entry_nodes. */
  3964. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  3965. if (entry_guard_get_by_id_digest(node->identity)) {
  3966. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3967. continue;
  3968. } else if (routerset_contains_node(options->ExcludeNodes, node)) {
  3969. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3970. continue;
  3971. } else if (!fascist_firewall_allows_node(node)) {
  3972. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3973. continue;
  3974. } else if (! node->is_possible_guard) {
  3975. smartlist_add(worse_entry_nodes, (node_t*)node);
  3976. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  3977. }
  3978. } SMARTLIST_FOREACH_END(node);
  3979. /* Now build the new entry_guards list. */
  3980. smartlist_clear(entry_guards);
  3981. /* First, the previously configured guards that are in EntryNodes. */
  3982. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  3983. /* Next, scramble the rest of EntryNodes, putting the guards first. */
  3984. smartlist_shuffle(entry_nodes);
  3985. smartlist_shuffle(worse_entry_nodes);
  3986. smartlist_add_all(entry_nodes, worse_entry_nodes);
  3987. /* Next, the rest of EntryNodes */
  3988. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  3989. add_an_entry_guard(node, 0, 0);
  3990. if (smartlist_len(entry_guards) > options->NumEntryGuards * 10)
  3991. break;
  3992. } SMARTLIST_FOREACH_END(node);
  3993. log_notice(LD_GENERAL, "%d entries in guards", smartlist_len(entry_guards));
  3994. /* Finally, free the remaining previously configured guards that are not in
  3995. * EntryNodes. */
  3996. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  3997. entry_guard_free(e));
  3998. smartlist_free(entry_nodes);
  3999. smartlist_free(worse_entry_nodes);
  4000. smartlist_free(entry_fps);
  4001. smartlist_free(old_entry_guards_on_list);
  4002. smartlist_free(old_entry_guards_not_on_list);
  4003. entry_guards_changed();
  4004. }
  4005. /** Return 0 if we're fine adding arbitrary routers out of the
  4006. * directory to our entry guard list, or return 1 if we have a
  4007. * list already and we must stick to it.
  4008. */
  4009. int
  4010. entry_list_is_constrained(const or_options_t *options)
  4011. {
  4012. if (options->EntryNodes)
  4013. return 1;
  4014. if (options->UseBridges)
  4015. return 1;
  4016. return 0;
  4017. }
  4018. /** Pick a live (up and listed) entry guard from entry_guards. If
  4019. * <b>state</b> is non-NULL, this is for a specific circuit --
  4020. * make sure not to pick this circuit's exit or any node in the
  4021. * exit's family. If <b>state</b> is NULL, we're looking for a random
  4022. * guard (likely a bridge). */
  4023. const node_t *
  4024. choose_random_entry(cpath_build_state_t *state)
  4025. {
  4026. const or_options_t *options = get_options();
  4027. smartlist_t *live_entry_guards = smartlist_new();
  4028. smartlist_t *exit_family = smartlist_new();
  4029. const node_t *chosen_exit =
  4030. state?build_state_get_exit_node(state) : NULL;
  4031. const node_t *node = NULL;
  4032. int need_uptime = state ? state->need_uptime : 0;
  4033. int need_capacity = state ? state->need_capacity : 0;
  4034. int preferred_min, consider_exit_family = 0;
  4035. if (chosen_exit) {
  4036. nodelist_add_node_and_family(exit_family, chosen_exit);
  4037. consider_exit_family = 1;
  4038. }
  4039. if (!entry_guards)
  4040. entry_guards = smartlist_new();
  4041. if (should_add_entry_nodes)
  4042. entry_guards_set_from_config(options);
  4043. if (!entry_list_is_constrained(options) &&
  4044. smartlist_len(entry_guards) < options->NumEntryGuards)
  4045. pick_entry_guards(options);
  4046. retry:
  4047. smartlist_clear(live_entry_guards);
  4048. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
  4049. const char *msg;
  4050. node = entry_is_live(entry, need_uptime, need_capacity, 0, &msg);
  4051. if (!node)
  4052. continue; /* down, no point */
  4053. if (node == chosen_exit)
  4054. continue; /* don't pick the same node for entry and exit */
  4055. if (consider_exit_family && smartlist_isin(exit_family, node))
  4056. continue; /* avoid relays that are family members of our exit */
  4057. #if 0 /* since EntryNodes is always strict now, this clause is moot */
  4058. if (options->EntryNodes &&
  4059. !routerset_contains_node(options->EntryNodes, node)) {
  4060. /* We've come to the end of our preferred entry nodes. */
  4061. if (smartlist_len(live_entry_guards))
  4062. goto choose_and_finish; /* only choose from the ones we like */
  4063. if (options->StrictNodes) {
  4064. /* in theory this case should never happen, since
  4065. * entry_guards_set_from_config() drops unwanted relays */
  4066. tor_fragile_assert();
  4067. } else {
  4068. log_info(LD_CIRC,
  4069. "No relays from EntryNodes available. Using others.");
  4070. }
  4071. }
  4072. #endif
  4073. smartlist_add(live_entry_guards, (void*)node);
  4074. if (!entry->made_contact) {
  4075. /* Always start with the first not-yet-contacted entry
  4076. * guard. Otherwise we might add several new ones, pick
  4077. * the second new one, and now we've expanded our entry
  4078. * guard list without needing to. */
  4079. goto choose_and_finish;
  4080. }
  4081. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  4082. goto choose_and_finish; /* we have enough */
  4083. } SMARTLIST_FOREACH_END(entry);
  4084. if (entry_list_is_constrained(options)) {
  4085. /* If we prefer the entry nodes we've got, and we have at least
  4086. * one choice, that's great. Use it. */
  4087. preferred_min = 1;
  4088. } else {
  4089. /* Try to have at least 2 choices available. This way we don't
  4090. * get stuck with a single live-but-crummy entry and just keep
  4091. * using him.
  4092. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  4093. preferred_min = 2;
  4094. }
  4095. if (smartlist_len(live_entry_guards) < preferred_min) {
  4096. if (!entry_list_is_constrained(options)) {
  4097. /* still no? try adding a new entry then */
  4098. /* XXX if guard doesn't imply fast and stable, then we need
  4099. * to tell add_an_entry_guard below what we want, or it might
  4100. * be a long time til we get it. -RD */
  4101. node = add_an_entry_guard(NULL, 0, 0);
  4102. if (node) {
  4103. entry_guards_changed();
  4104. /* XXX we start over here in case the new node we added shares
  4105. * a family with our exit node. There's a chance that we'll just
  4106. * load up on entry guards here, if the network we're using is
  4107. * one big family. Perhaps we should teach add_an_entry_guard()
  4108. * to understand nodes-to-avoid-if-possible? -RD */
  4109. goto retry;
  4110. }
  4111. }
  4112. if (!node && need_uptime) {
  4113. need_uptime = 0; /* try without that requirement */
  4114. goto retry;
  4115. }
  4116. if (!node && need_capacity) {
  4117. /* still no? last attempt, try without requiring capacity */
  4118. need_capacity = 0;
  4119. goto retry;
  4120. }
  4121. #if 0
  4122. /* Removing this retry logic: if we only allow one exit, and it is in the
  4123. same family as all our entries, then we are just plain not going to win
  4124. here. */
  4125. if (!node && entry_list_is_constrained(options) && consider_exit_family) {
  4126. /* still no? if we're using bridges or have strictentrynodes
  4127. * set, and our chosen exit is in the same family as all our
  4128. * bridges/entry guards, then be flexible about families. */
  4129. consider_exit_family = 0;
  4130. goto retry;
  4131. }
  4132. #endif
  4133. /* live_entry_guards may be empty below. Oh well, we tried. */
  4134. }
  4135. choose_and_finish:
  4136. if (entry_list_is_constrained(options)) {
  4137. /* We need to weight by bandwidth, because our bridges or entryguards
  4138. * were not already selected proportional to their bandwidth. */
  4139. node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  4140. } else {
  4141. /* We choose uniformly at random here, because choose_good_entry_server()
  4142. * already weights its choices by bandwidth, so we don't want to
  4143. * *double*-weight our guard selection. */
  4144. node = smartlist_choose(live_entry_guards);
  4145. }
  4146. smartlist_free(live_entry_guards);
  4147. smartlist_free(exit_family);
  4148. return node;
  4149. }
  4150. /** Parse <b>state</b> and learn about the entry guards it describes.
  4151. * If <b>set</b> is true, and there are no errors, replace the global
  4152. * entry_list with what we find.
  4153. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  4154. * describing the error, and return -1.
  4155. */
  4156. int
  4157. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  4158. {
  4159. entry_guard_t *node = NULL;
  4160. smartlist_t *new_entry_guards = smartlist_new();
  4161. config_line_t *line;
  4162. time_t now = time(NULL);
  4163. const char *state_version = state->TorVersion;
  4164. digestmap_t *added_by = digestmap_new();
  4165. *msg = NULL;
  4166. for (line = state->EntryGuards; line; line = line->next) {
  4167. if (!strcasecmp(line->key, "EntryGuard")) {
  4168. smartlist_t *args = smartlist_new();
  4169. node = tor_malloc_zero(sizeof(entry_guard_t));
  4170. /* all entry guards on disk have been contacted */
  4171. node->made_contact = 1;
  4172. smartlist_add(new_entry_guards, node);
  4173. smartlist_split_string(args, line->value, " ",
  4174. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4175. if (smartlist_len(args)<2) {
  4176. *msg = tor_strdup("Unable to parse entry nodes: "
  4177. "Too few arguments to EntryGuard");
  4178. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  4179. *msg = tor_strdup("Unable to parse entry nodes: "
  4180. "Bad nickname for EntryGuard");
  4181. } else {
  4182. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  4183. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  4184. strlen(smartlist_get(args,1)))<0) {
  4185. *msg = tor_strdup("Unable to parse entry nodes: "
  4186. "Bad hex digest for EntryGuard");
  4187. }
  4188. }
  4189. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  4190. smartlist_free(args);
  4191. if (*msg)
  4192. break;
  4193. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  4194. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  4195. time_t when;
  4196. time_t last_try = 0;
  4197. if (!node) {
  4198. *msg = tor_strdup("Unable to parse entry nodes: "
  4199. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  4200. break;
  4201. }
  4202. if (parse_iso_time(line->value, &when)<0) {
  4203. *msg = tor_strdup("Unable to parse entry nodes: "
  4204. "Bad time in EntryGuardDownSince/UnlistedSince");
  4205. break;
  4206. }
  4207. if (when > now) {
  4208. /* It's a bad idea to believe info in the future: you can wind
  4209. * up with timeouts that aren't allowed to happen for years. */
  4210. continue;
  4211. }
  4212. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  4213. /* ignore failure */
  4214. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  4215. }
  4216. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  4217. node->unreachable_since = when;
  4218. node->last_attempted = last_try;
  4219. } else {
  4220. node->bad_since = when;
  4221. }
  4222. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  4223. char d[DIGEST_LEN];
  4224. /* format is digest version date */
  4225. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  4226. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  4227. continue;
  4228. }
  4229. if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
  4230. line->value[HEX_DIGEST_LEN] != ' ') {
  4231. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  4232. "hex digest", escaped(line->value));
  4233. continue;
  4234. }
  4235. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  4236. } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
  4237. const or_options_t *options = get_options();
  4238. unsigned hop_cnt, success_cnt;
  4239. if (tor_sscanf(line->value, "%u %u", &success_cnt, &hop_cnt) != 2) {
  4240. log_warn(LD_GENERAL, "Unable to parse guard path bias info: "
  4241. "Misformated EntryGuardPathBias %s", escaped(line->value));
  4242. continue;
  4243. }
  4244. node->first_hops = hop_cnt;
  4245. node->circuit_successes = success_cnt;
  4246. log_info(LD_GENERAL, "Read %u/%u path bias for node %s",
  4247. node->circuit_successes, node->first_hops, node->nickname);
  4248. /* Note: We rely on the < comparison here to allow us to set a 0
  4249. * rate and disable the feature entirely. If refactoring, don't
  4250. * change to <= */
  4251. if (node->circuit_successes/((double)node->first_hops)
  4252. < pathbias_get_disable_rate(options)) {
  4253. node->path_bias_disabled = 1;
  4254. log_info(LD_GENERAL,
  4255. "Path bias is too high (%u/%u); disabling node %s",
  4256. node->circuit_successes, node->first_hops, node->nickname);
  4257. }
  4258. } else {
  4259. log_warn(LD_BUG, "Unexpected key %s", line->key);
  4260. }
  4261. }
  4262. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  4263. {
  4264. char *sp;
  4265. char *val = digestmap_get(added_by, e->identity);
  4266. if (val && (sp = strchr(val, ' '))) {
  4267. time_t when;
  4268. *sp++ = '\0';
  4269. if (parse_iso_time(sp, &when)<0) {
  4270. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  4271. } else {
  4272. e->chosen_by_version = tor_strdup(val);
  4273. e->chosen_on_date = when;
  4274. }
  4275. } else {
  4276. if (state_version) {
  4277. e->chosen_by_version = tor_strdup(state_version);
  4278. e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
  4279. }
  4280. }
  4281. if (node->path_bias_disabled && !node->bad_since)
  4282. node->bad_since = time(NULL);
  4283. });
  4284. if (*msg || !set) {
  4285. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  4286. entry_guard_free(e));
  4287. smartlist_free(new_entry_guards);
  4288. } else { /* !err && set */
  4289. if (entry_guards) {
  4290. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  4291. entry_guard_free(e));
  4292. smartlist_free(entry_guards);
  4293. }
  4294. entry_guards = new_entry_guards;
  4295. entry_guards_dirty = 0;
  4296. /* XXX024 hand new_entry_guards to this func, and move it up a
  4297. * few lines, so we don't have to re-dirty it */
  4298. if (remove_obsolete_entry_guards(now))
  4299. entry_guards_dirty = 1;
  4300. }
  4301. digestmap_free(added_by, _tor_free);
  4302. return *msg ? -1 : 0;
  4303. }
  4304. /** Our list of entry guards has changed, or some element of one
  4305. * of our entry guards has changed. Write the changes to disk within
  4306. * the next few minutes.
  4307. */
  4308. static void
  4309. entry_guards_changed(void)
  4310. {
  4311. time_t when;
  4312. entry_guards_dirty = 1;
  4313. /* or_state_save() will call entry_guards_update_state(). */
  4314. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  4315. or_state_mark_dirty(get_or_state(), when);
  4316. }
  4317. /** If the entry guard info has not changed, do nothing and return.
  4318. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  4319. * a new one out of the global entry_guards list, and then mark
  4320. * <b>state</b> dirty so it will get saved to disk.
  4321. */
  4322. void
  4323. entry_guards_update_state(or_state_t *state)
  4324. {
  4325. config_line_t **next, *line;
  4326. if (! entry_guards_dirty)
  4327. return;
  4328. config_free_lines(state->EntryGuards);
  4329. next = &state->EntryGuards;
  4330. *next = NULL;
  4331. if (!entry_guards)
  4332. entry_guards = smartlist_new();
  4333. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  4334. {
  4335. char dbuf[HEX_DIGEST_LEN+1];
  4336. if (!e->made_contact)
  4337. continue; /* don't write this one to disk */
  4338. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4339. line->key = tor_strdup("EntryGuard");
  4340. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  4341. tor_asprintf(&line->value, "%s %s", e->nickname, dbuf);
  4342. next = &(line->next);
  4343. if (e->unreachable_since) {
  4344. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4345. line->key = tor_strdup("EntryGuardDownSince");
  4346. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  4347. format_iso_time(line->value, e->unreachable_since);
  4348. if (e->last_attempted) {
  4349. line->value[ISO_TIME_LEN] = ' ';
  4350. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  4351. }
  4352. next = &(line->next);
  4353. }
  4354. if (e->bad_since) {
  4355. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4356. line->key = tor_strdup("EntryGuardUnlistedSince");
  4357. line->value = tor_malloc(ISO_TIME_LEN+1);
  4358. format_iso_time(line->value, e->bad_since);
  4359. next = &(line->next);
  4360. }
  4361. if (e->chosen_on_date && e->chosen_by_version &&
  4362. !strchr(e->chosen_by_version, ' ')) {
  4363. char d[HEX_DIGEST_LEN+1];
  4364. char t[ISO_TIME_LEN+1];
  4365. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4366. line->key = tor_strdup("EntryGuardAddedBy");
  4367. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  4368. format_iso_time(t, e->chosen_on_date);
  4369. tor_asprintf(&line->value, "%s %s %s",
  4370. d, e->chosen_by_version, t);
  4371. next = &(line->next);
  4372. }
  4373. if (e->first_hops) {
  4374. *next = line = tor_malloc_zero(sizeof(config_line_t));
  4375. line->key = tor_strdup("EntryGuardPathBias");
  4376. tor_asprintf(&line->value, "%u %u",
  4377. e->circuit_successes, e->first_hops);
  4378. next = &(line->next);
  4379. }
  4380. });
  4381. if (!get_options()->AvoidDiskWrites)
  4382. or_state_mark_dirty(get_or_state(), 0);
  4383. entry_guards_dirty = 0;
  4384. }
  4385. /** If <b>question</b> is the string "entry-guards", then dump
  4386. * to *<b>answer</b> a newly allocated string describing all of
  4387. * the nodes in the global entry_guards list. See control-spec.txt
  4388. * for details.
  4389. * For backward compatibility, we also handle the string "helper-nodes".
  4390. * */
  4391. int
  4392. getinfo_helper_entry_guards(control_connection_t *conn,
  4393. const char *question, char **answer,
  4394. const char **errmsg)
  4395. {
  4396. (void) conn;
  4397. (void) errmsg;
  4398. if (!strcmp(question,"entry-guards") ||
  4399. !strcmp(question,"helper-nodes")) {
  4400. smartlist_t *sl = smartlist_new();
  4401. char tbuf[ISO_TIME_LEN+1];
  4402. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  4403. if (!entry_guards)
  4404. entry_guards = smartlist_new();
  4405. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  4406. const char *status = NULL;
  4407. time_t when = 0;
  4408. const node_t *node;
  4409. if (!e->made_contact) {
  4410. status = "never-connected";
  4411. } else if (e->bad_since) {
  4412. when = e->bad_since;
  4413. status = "unusable";
  4414. } else {
  4415. status = "up";
  4416. }
  4417. node = node_get_by_id(e->identity);
  4418. if (node) {
  4419. node_get_verbose_nickname(node, nbuf);
  4420. } else {
  4421. nbuf[0] = '$';
  4422. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  4423. /* e->nickname field is not very reliable if we don't know about
  4424. * this router any longer; don't include it. */
  4425. }
  4426. if (when) {
  4427. format_iso_time(tbuf, when);
  4428. smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
  4429. } else {
  4430. smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
  4431. }
  4432. } SMARTLIST_FOREACH_END(e);
  4433. *answer = smartlist_join_strings(sl, "", 0, NULL);
  4434. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  4435. smartlist_free(sl);
  4436. }
  4437. return 0;
  4438. }
  4439. /** A list of configured bridges. Whenever we actually get a descriptor
  4440. * for one, we add it as an entry guard. Note that the order of bridges
  4441. * in this list does not necessarily correspond to the order of bridges
  4442. * in the torrc. */
  4443. static smartlist_t *bridge_list = NULL;
  4444. /** Mark every entry of the bridge list to be removed on our next call to
  4445. * sweep_bridge_list unless it has first been un-marked. */
  4446. void
  4447. mark_bridge_list(void)
  4448. {
  4449. if (!bridge_list)
  4450. bridge_list = smartlist_new();
  4451. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b,
  4452. b->marked_for_removal = 1);
  4453. }
  4454. /** Remove every entry of the bridge list that was marked with
  4455. * mark_bridge_list if it has not subsequently been un-marked. */
  4456. void
  4457. sweep_bridge_list(void)
  4458. {
  4459. if (!bridge_list)
  4460. bridge_list = smartlist_new();
  4461. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
  4462. if (b->marked_for_removal) {
  4463. SMARTLIST_DEL_CURRENT(bridge_list, b);
  4464. bridge_free(b);
  4465. }
  4466. } SMARTLIST_FOREACH_END(b);
  4467. }
  4468. /** Initialize the bridge list to empty, creating it if needed. */
  4469. static void
  4470. clear_bridge_list(void)
  4471. {
  4472. if (!bridge_list)
  4473. bridge_list = smartlist_new();
  4474. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, bridge_free(b));
  4475. smartlist_clear(bridge_list);
  4476. }
  4477. /** Free the bridge <b>bridge</b>. */
  4478. static void
  4479. bridge_free(bridge_info_t *bridge)
  4480. {
  4481. if (!bridge)
  4482. return;
  4483. tor_free(bridge->transport_name);
  4484. tor_free(bridge);
  4485. }
  4486. /** Return a bridge pointer if <b>ri</b> is one of our known bridges
  4487. * (either by comparing keys if possible, else by comparing addr/port).
  4488. * Else return NULL. */
  4489. static bridge_info_t *
  4490. get_configured_bridge_by_addr_port_digest(const tor_addr_t *addr,
  4491. uint16_t port,
  4492. const char *digest)
  4493. {
  4494. if (!bridge_list)
  4495. return NULL;
  4496. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  4497. {
  4498. if (tor_digest_is_zero(bridge->identity) &&
  4499. !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
  4500. bridge->port == port)
  4501. return bridge;
  4502. if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
  4503. return bridge;
  4504. }
  4505. SMARTLIST_FOREACH_END(bridge);
  4506. return NULL;
  4507. }
  4508. /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
  4509. * it up via router descriptor <b>ri</b>. */
  4510. static bridge_info_t *
  4511. get_configured_bridge_by_routerinfo(const routerinfo_t *ri)
  4512. {
  4513. tor_addr_port_t ap;
  4514. router_get_pref_orport(ri, &ap);
  4515. return get_configured_bridge_by_addr_port_digest(&ap.addr, ap.port,
  4516. ri->cache_info.identity_digest);
  4517. }
  4518. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  4519. int
  4520. routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
  4521. {
  4522. return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
  4523. }
  4524. /** Return 1 if <b>node</b> is one of our configured bridges, else 0. */
  4525. int
  4526. node_is_a_configured_bridge(const node_t *node)
  4527. {
  4528. int retval = 0; /* Negative. */
  4529. smartlist_t *orports = NULL;
  4530. if (!node)
  4531. goto out;
  4532. orports = node_get_all_orports(node);
  4533. if (orports == NULL)
  4534. goto out;
  4535. SMARTLIST_FOREACH_BEGIN(orports, tor_addr_port_t *, orport) {
  4536. if (get_configured_bridge_by_addr_port_digest(&orport->addr, orport->port,
  4537. node->identity) != NULL) {
  4538. retval = 1;
  4539. goto out;
  4540. }
  4541. } SMARTLIST_FOREACH_END(orport);
  4542. out:
  4543. if (orports != NULL) {
  4544. SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
  4545. smartlist_free(orports);
  4546. orports = NULL;
  4547. }
  4548. return retval;
  4549. }
  4550. /** We made a connection to a router at <b>addr</b>:<b>port</b>
  4551. * without knowing its digest. Its digest turned out to be <b>digest</b>.
  4552. * If it was a bridge, and we still don't know its digest, record it.
  4553. */
  4554. void
  4555. learned_router_identity(const tor_addr_t *addr, uint16_t port,
  4556. const char *digest)
  4557. {
  4558. bridge_info_t *bridge =
  4559. get_configured_bridge_by_addr_port_digest(addr, port, digest);
  4560. if (bridge && tor_digest_is_zero(bridge->identity)) {
  4561. memcpy(bridge->identity, digest, DIGEST_LEN);
  4562. log_notice(LD_DIR, "Learned fingerprint %s for bridge %s:%d",
  4563. hex_str(digest, DIGEST_LEN), fmt_addr(addr), port);
  4564. }
  4565. }
  4566. /** Return true if <b>bridge</b> has the same identity digest as
  4567. * <b>digest</b>. If <b>digest</b> is NULL, it matches
  4568. * bridges with unspecified identity digests. */
  4569. static int
  4570. bridge_has_digest(const bridge_info_t *bridge, const char *digest)
  4571. {
  4572. if (digest)
  4573. return tor_memeq(digest, bridge->identity, DIGEST_LEN);
  4574. else
  4575. return tor_digest_is_zero(bridge->identity);
  4576. }
  4577. /** We are about to add a new bridge at <b>addr</b>:<b>port</b>, with optional
  4578. * <b>digest</b> and <b>transport_name</b>. Mark for removal any previously
  4579. * existing bridge with the same address and port, and warn the user as
  4580. * appropriate.
  4581. */
  4582. static void
  4583. bridge_resolve_conflicts(const tor_addr_t *addr, uint16_t port,
  4584. const char *digest, const char *transport_name)
  4585. {
  4586. /* Iterate the already-registered bridge list:
  4587. If you find a bridge with the same adress and port, mark it for
  4588. removal. It doesn't make sense to have two active bridges with
  4589. the same IP:PORT. If the bridge in question has a different
  4590. digest or transport than <b>digest</b>/<b>transport_name</b>,
  4591. it's probably a misconfiguration and we should warn the user.
  4592. */
  4593. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge) {
  4594. if (bridge->marked_for_removal)
  4595. continue;
  4596. if (tor_addr_eq(&bridge->addr, addr) && (bridge->port == port)) {
  4597. bridge->marked_for_removal = 1;
  4598. if (!bridge_has_digest(bridge, digest) ||
  4599. strcmp_opt(bridge->transport_name, transport_name)) {
  4600. /* warn the user */
  4601. char *bridge_description_new, *bridge_description_old;
  4602. tor_asprintf(&bridge_description_new, "%s:%u:%s:%s",
  4603. fmt_addr(addr), port,
  4604. digest ? hex_str(digest, DIGEST_LEN) : "",
  4605. transport_name ? transport_name : "");
  4606. tor_asprintf(&bridge_description_old, "%s:%u:%s:%s",
  4607. fmt_addr(&bridge->addr), bridge->port,
  4608. tor_digest_is_zero(bridge->identity) ?
  4609. "" : hex_str(bridge->identity,DIGEST_LEN),
  4610. bridge->transport_name ? bridge->transport_name : "");
  4611. log_warn(LD_GENERAL,"Tried to add bridge '%s', but we found a conflict"
  4612. " with the already registered bridge '%s'. We will discard"
  4613. " the old bridge and keep '%s'. If this is not what you"
  4614. " wanted, please change your configuration file accordingly.",
  4615. bridge_description_new, bridge_description_old,
  4616. bridge_description_new);
  4617. tor_free(bridge_description_new);
  4618. tor_free(bridge_description_old);
  4619. }
  4620. }
  4621. } SMARTLIST_FOREACH_END(bridge);
  4622. }
  4623. /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
  4624. * is set, it tells us the identity key too. If we already had the
  4625. * bridge in our list, unmark it, and don't actually add anything new.
  4626. * If <b>transport_name</b> is non-NULL - the bridge is associated with a
  4627. * pluggable transport - we assign the transport to the bridge. */
  4628. void
  4629. bridge_add_from_config(const tor_addr_t *addr, uint16_t port,
  4630. const char *digest, const char *transport_name)
  4631. {
  4632. bridge_info_t *b;
  4633. bridge_resolve_conflicts(addr, port, digest, transport_name);
  4634. b = tor_malloc_zero(sizeof(bridge_info_t));
  4635. tor_addr_copy(&b->addr, addr);
  4636. b->port = port;
  4637. if (digest)
  4638. memcpy(b->identity, digest, DIGEST_LEN);
  4639. if (transport_name)
  4640. b->transport_name = tor_strdup(transport_name);
  4641. b->fetch_status.schedule = DL_SCHED_BRIDGE;
  4642. if (!bridge_list)
  4643. bridge_list = smartlist_new();
  4644. smartlist_add(bridge_list, b);
  4645. }
  4646. /** Return true iff <b>routerset</b> contains the bridge <b>bridge</b>. */
  4647. static int
  4648. routerset_contains_bridge(const routerset_t *routerset,
  4649. const bridge_info_t *bridge)
  4650. {
  4651. int result;
  4652. extend_info_t *extinfo;
  4653. tor_assert(bridge);
  4654. if (!routerset)
  4655. return 0;
  4656. extinfo = extend_info_alloc(
  4657. NULL, bridge->identity, NULL, &bridge->addr, bridge->port);
  4658. result = routerset_contains_extendinfo(routerset, extinfo);
  4659. extend_info_free(extinfo);
  4660. return result;
  4661. }
  4662. /** If <b>digest</b> is one of our known bridges, return it. */
  4663. static bridge_info_t *
  4664. find_bridge_by_digest(const char *digest)
  4665. {
  4666. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  4667. {
  4668. if (tor_memeq(bridge->identity, digest, DIGEST_LEN))
  4669. return bridge;
  4670. });
  4671. return NULL;
  4672. }
  4673. /* DOCDOC find_transport_name_by_bridge_addrport */
  4674. const char *
  4675. find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
  4676. {
  4677. if (!bridge_list)
  4678. return NULL;
  4679. SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
  4680. if (tor_addr_eq(&bridge->addr, addr) &&
  4681. (bridge->port == port))
  4682. return bridge->transport_name;
  4683. } SMARTLIST_FOREACH_END(bridge);
  4684. return NULL;
  4685. }
  4686. /** If <b>addr</b> and <b>port</b> match the address and port of a
  4687. * bridge of ours that uses pluggable transports, place its transport
  4688. * in <b>transport</b>.
  4689. *
  4690. * Return 0 on success (found a transport, or found a bridge with no
  4691. * transport, or found no bridge); return -1 if we should be using a
  4692. * transport, but the transport could not be found.
  4693. */
  4694. int
  4695. find_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port,
  4696. const transport_t **transport)
  4697. {
  4698. *transport = NULL;
  4699. if (!bridge_list)
  4700. return 0;
  4701. SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
  4702. if (tor_addr_eq(&bridge->addr, addr) &&
  4703. (bridge->port == port)) { /* bridge matched */
  4704. if (bridge->transport_name) { /* it also uses pluggable transports */
  4705. *transport = transport_get_by_name(bridge->transport_name);
  4706. if (*transport == NULL) { /* it uses pluggable transports, but
  4707. the transport could not be found! */
  4708. return -1;
  4709. }
  4710. return 0;
  4711. } else { /* bridge matched, but it doesn't use transports. */
  4712. break;
  4713. }
  4714. }
  4715. } SMARTLIST_FOREACH_END(bridge);
  4716. *transport = NULL;
  4717. return 0;
  4718. }
  4719. /** We need to ask <b>bridge</b> for its server descriptor. */
  4720. static void
  4721. launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
  4722. {
  4723. char *address;
  4724. const or_options_t *options = get_options();
  4725. if (connection_get_by_type_addr_port_purpose(
  4726. CONN_TYPE_DIR, &bridge->addr, bridge->port,
  4727. DIR_PURPOSE_FETCH_SERVERDESC))
  4728. return; /* it's already on the way */
  4729. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  4730. download_status_mark_impossible(&bridge->fetch_status);
  4731. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  4732. safe_str_client(fmt_addr(&bridge->addr)));
  4733. return;
  4734. }
  4735. address = tor_dup_addr(&bridge->addr);
  4736. directory_initiate_command(address, &bridge->addr,
  4737. bridge->port, 0,
  4738. 0, /* does not matter */
  4739. 1, bridge->identity,
  4740. DIR_PURPOSE_FETCH_SERVERDESC,
  4741. ROUTER_PURPOSE_BRIDGE,
  4742. 0, "authority.z", NULL, 0, 0);
  4743. tor_free(address);
  4744. }
  4745. /** Fetching the bridge descriptor from the bridge authority returned a
  4746. * "not found". Fall back to trying a direct fetch. */
  4747. void
  4748. retry_bridge_descriptor_fetch_directly(const char *digest)
  4749. {
  4750. bridge_info_t *bridge = find_bridge_by_digest(digest);
  4751. if (!bridge)
  4752. return; /* not found? oh well. */
  4753. launch_direct_bridge_descriptor_fetch(bridge);
  4754. }
  4755. /** For each bridge in our list for which we don't currently have a
  4756. * descriptor, fetch a new copy of its descriptor -- either directly
  4757. * from the bridge or via a bridge authority. */
  4758. void
  4759. fetch_bridge_descriptors(const or_options_t *options, time_t now)
  4760. {
  4761. int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
  4762. int ask_bridge_directly;
  4763. int can_use_bridge_authority;
  4764. if (!bridge_list)
  4765. return;
  4766. /* If we still have unconfigured managed proxies, don't go and
  4767. connect to a bridge. */
  4768. if (pt_proxies_configuration_pending())
  4769. return;
  4770. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  4771. {
  4772. if (!download_status_is_ready(&bridge->fetch_status, now,
  4773. IMPOSSIBLE_TO_DOWNLOAD))
  4774. continue; /* don't bother, no need to retry yet */
  4775. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  4776. download_status_mark_impossible(&bridge->fetch_status);
  4777. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  4778. safe_str_client(fmt_addr(&bridge->addr)));
  4779. continue;
  4780. }
  4781. /* schedule another fetch as if this one will fail, in case it does */
  4782. download_status_failed(&bridge->fetch_status, 0);
  4783. can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
  4784. num_bridge_auths;
  4785. ask_bridge_directly = !can_use_bridge_authority ||
  4786. !options->UpdateBridgesFromAuthority;
  4787. log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
  4788. ask_bridge_directly, tor_digest_is_zero(bridge->identity),
  4789. !options->UpdateBridgesFromAuthority, !num_bridge_auths);
  4790. if (ask_bridge_directly &&
  4791. !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
  4792. log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
  4793. "firewall policy. %s.", fmt_addr(&bridge->addr),
  4794. bridge->port,
  4795. can_use_bridge_authority ?
  4796. "Asking bridge authority instead" : "Skipping");
  4797. if (can_use_bridge_authority)
  4798. ask_bridge_directly = 0;
  4799. else
  4800. continue;
  4801. }
  4802. if (ask_bridge_directly) {
  4803. /* we need to ask the bridge itself for its descriptor. */
  4804. launch_direct_bridge_descriptor_fetch(bridge);
  4805. } else {
  4806. /* We have a digest and we want to ask an authority. We could
  4807. * combine all the requests into one, but that may give more
  4808. * hints to the bridge authority than we want to give. */
  4809. char resource[10 + HEX_DIGEST_LEN];
  4810. memcpy(resource, "fp/", 3);
  4811. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  4812. bridge->identity, DIGEST_LEN);
  4813. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  4814. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  4815. resource);
  4816. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  4817. ROUTER_PURPOSE_BRIDGE, resource, 0);
  4818. }
  4819. }
  4820. SMARTLIST_FOREACH_END(bridge);
  4821. }
  4822. /** If our <b>bridge</b> is configured to be a different address than
  4823. * the bridge gives in <b>node</b>, rewrite the routerinfo
  4824. * we received to use the address we meant to use. Now we handle
  4825. * multihomed bridges better.
  4826. */
  4827. static void
  4828. rewrite_node_address_for_bridge(const bridge_info_t *bridge, node_t *node)
  4829. {
  4830. /* XXXX move this function. */
  4831. /* XXXX overridden addresses should really live in the node_t, so that the
  4832. * routerinfo_t and the microdesc_t can be immutable. But we can only
  4833. * do that safely if we know that no function that connects to an OR
  4834. * does so through an address from any source other than node_get_addr().
  4835. */
  4836. tor_addr_t addr;
  4837. if (node->ri) {
  4838. routerinfo_t *ri = node->ri;
  4839. tor_addr_from_ipv4h(&addr, ri->addr);
  4840. if ((!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
  4841. bridge->port == ri->or_port) ||
  4842. (!tor_addr_compare(&bridge->addr, &ri->ipv6_addr, CMP_EXACT) &&
  4843. bridge->port == ri->ipv6_orport)) {
  4844. /* they match, so no need to do anything */
  4845. } else {
  4846. if (tor_addr_family(&bridge->addr) == AF_INET) {
  4847. ri->addr = tor_addr_to_ipv4h(&bridge->addr);
  4848. tor_free(ri->address);
  4849. ri->address = tor_dup_ip(ri->addr);
  4850. ri->or_port = bridge->port;
  4851. log_info(LD_DIR,
  4852. "Adjusted bridge routerinfo for '%s' to match configured "
  4853. "address %s:%d.",
  4854. ri->nickname, ri->address, ri->or_port);
  4855. } else if (tor_addr_family(&bridge->addr) == AF_INET6) {
  4856. tor_addr_copy(&ri->ipv6_addr, &bridge->addr);
  4857. ri->ipv6_orport = bridge->port;
  4858. log_info(LD_DIR,
  4859. "Adjusted bridge routerinfo for '%s' to match configured "
  4860. "address %s:%d.",
  4861. ri->nickname, fmt_addr(&ri->ipv6_addr), ri->ipv6_orport);
  4862. } else {
  4863. log_err(LD_BUG, "Address family not supported: %d.",
  4864. tor_addr_family(&bridge->addr));
  4865. return;
  4866. }
  4867. }
  4868. /* Indicate that we prefer connecting to this bridge over the
  4869. protocol that the bridge address indicates. Last bridge
  4870. descriptor handled wins. */
  4871. ri->ipv6_preferred = tor_addr_family(&bridge->addr) == AF_INET6;
  4872. /* XXXipv6 we lack support for falling back to another address for
  4873. the same relay, warn the user */
  4874. if (!tor_addr_is_null(&ri->ipv6_addr)) {
  4875. tor_addr_port_t ap;
  4876. router_get_pref_orport(ri, &ap);
  4877. log_notice(LD_CONFIG,
  4878. "Bridge '%s' has both an IPv4 and an IPv6 address. "
  4879. "Will prefer using its %s address (%s:%d).",
  4880. ri->nickname,
  4881. ri->ipv6_preferred ? "IPv6" : "IPv4",
  4882. fmt_addr(&ap.addr), ap.port);
  4883. }
  4884. }
  4885. if (node->rs) {
  4886. routerstatus_t *rs = node->rs;
  4887. tor_addr_from_ipv4h(&addr, rs->addr);
  4888. if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
  4889. bridge->port == rs->or_port) {
  4890. /* they match, so no need to do anything */
  4891. } else {
  4892. rs->addr = tor_addr_to_ipv4h(&bridge->addr);
  4893. rs->or_port = bridge->port;
  4894. log_info(LD_DIR,
  4895. "Adjusted bridge routerstatus for '%s' to match "
  4896. "configured address %s:%d.",
  4897. rs->nickname, fmt_addr(&bridge->addr), rs->or_port);
  4898. }
  4899. }
  4900. }
  4901. /** We just learned a descriptor for a bridge. See if that
  4902. * digest is in our entry guard list, and add it if not. */
  4903. void
  4904. learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
  4905. {
  4906. tor_assert(ri);
  4907. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  4908. if (get_options()->UseBridges) {
  4909. int first = !any_bridge_descriptors_known();
  4910. bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
  4911. time_t now = time(NULL);
  4912. router_set_status(ri->cache_info.identity_digest, 1);
  4913. if (bridge) { /* if we actually want to use this one */
  4914. node_t *node;
  4915. /* it's here; schedule its re-fetch for a long time from now. */
  4916. if (!from_cache)
  4917. download_status_reset(&bridge->fetch_status);
  4918. node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  4919. tor_assert(node);
  4920. rewrite_node_address_for_bridge(bridge, node);
  4921. add_an_entry_guard(node, 1, 1);
  4922. log_notice(LD_DIR, "new bridge descriptor '%s' (%s): %s", ri->nickname,
  4923. from_cache ? "cached" : "fresh", router_describe(ri));
  4924. /* set entry->made_contact so if it goes down we don't drop it from
  4925. * our entry node list */
  4926. entry_guard_register_connect_status(ri->cache_info.identity_digest,
  4927. 1, 0, now);
  4928. if (first)
  4929. routerlist_retry_directory_downloads(now);
  4930. }
  4931. }
  4932. }
  4933. /** Return 1 if any of our entry guards have descriptors that
  4934. * are marked with purpose 'bridge' and are running. Else return 0.
  4935. *
  4936. * We use this function to decide if we're ready to start building
  4937. * circuits through our bridges, or if we need to wait until the
  4938. * directory "server/authority" requests finish. */
  4939. int
  4940. any_bridge_descriptors_known(void)
  4941. {
  4942. tor_assert(get_options()->UseBridges);
  4943. return choose_random_entry(NULL)!=NULL ? 1 : 0;
  4944. }
  4945. /** Return 1 if there are any directory conns fetching bridge descriptors
  4946. * that aren't marked for close. We use this to guess if we should tell
  4947. * the controller that we have a problem. */
  4948. int
  4949. any_pending_bridge_descriptor_fetches(void)
  4950. {
  4951. smartlist_t *conns = get_connection_array();
  4952. SMARTLIST_FOREACH(conns, connection_t *, conn,
  4953. {
  4954. if (conn->type == CONN_TYPE_DIR &&
  4955. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  4956. TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
  4957. !conn->marked_for_close &&
  4958. conn->linked &&
  4959. conn->linked_conn && !conn->linked_conn->marked_for_close) {
  4960. log_debug(LD_DIR, "found one: %s", conn->address);
  4961. return 1;
  4962. }
  4963. });
  4964. return 0;
  4965. }
  4966. /** Return 1 if we have at least one descriptor for an entry guard
  4967. * (bridge or member of EntryNodes) and all descriptors we know are
  4968. * down. Else return 0. If <b>act</b> is 1, then mark the down guards
  4969. * up; else just observe and report. */
  4970. static int
  4971. entries_retry_helper(const or_options_t *options, int act)
  4972. {
  4973. const node_t *node;
  4974. int any_known = 0;
  4975. int any_running = 0;
  4976. int need_bridges = options->UseBridges != 0;
  4977. if (!entry_guards)
  4978. entry_guards = smartlist_new();
  4979. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  4980. node = node_get_by_id(e->identity);
  4981. if (node && node_has_descriptor(node) &&
  4982. node_is_bridge(node) == need_bridges) {
  4983. any_known = 1;
  4984. if (node->is_running)
  4985. any_running = 1; /* some entry is both known and running */
  4986. else if (act) {
  4987. /* Mark all current connections to this OR as unhealthy, since
  4988. * otherwise there could be one that started 30 seconds
  4989. * ago, and in 30 seconds it will time out, causing us to mark
  4990. * the node down and undermine the retry attempt. We mark even
  4991. * the established conns, since if the network just came back
  4992. * we'll want to attach circuits to fresh conns. */
  4993. connection_or_set_bad_connections(node->identity, 1);
  4994. /* mark this entry node for retry */
  4995. router_set_status(node->identity, 1);
  4996. e->can_retry = 1;
  4997. e->bad_since = 0;
  4998. }
  4999. }
  5000. } SMARTLIST_FOREACH_END(e);
  5001. log_debug(LD_DIR, "%d: any_known %d, any_running %d",
  5002. act, any_known, any_running);
  5003. return any_known && !any_running;
  5004. }
  5005. /** Do we know any descriptors for our bridges / entrynodes, and are
  5006. * all the ones we have descriptors for down? */
  5007. int
  5008. entries_known_but_down(const or_options_t *options)
  5009. {
  5010. tor_assert(entry_list_is_constrained(options));
  5011. return entries_retry_helper(options, 0);
  5012. }
  5013. /** Mark all down known bridges / entrynodes up. */
  5014. void
  5015. entries_retry_all(const or_options_t *options)
  5016. {
  5017. tor_assert(entry_list_is_constrained(options));
  5018. entries_retry_helper(options, 1);
  5019. }
  5020. /** Return true if we've ever had a bridge running a Tor version that can't
  5021. * provide microdescriptors to us. In that case fall back to asking for
  5022. * full descriptors. Eventually all bridges will support microdescriptors
  5023. * and we can take this check out; see bug 4013. */
  5024. int
  5025. any_bridges_dont_support_microdescriptors(void)
  5026. {
  5027. const node_t *node;
  5028. static int ever_answered_yes = 0;
  5029. if (!get_options()->UseBridges || !entry_guards)
  5030. return 0;
  5031. if (ever_answered_yes)
  5032. return 1; /* if we ever answer 'yes', always answer 'yes' */
  5033. SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
  5034. node = node_get_by_id(e->identity);
  5035. if (node && node->ri &&
  5036. node_is_bridge(node) && node_is_a_configured_bridge(node) &&
  5037. !tor_version_supports_microdescriptors(node->ri->platform)) {
  5038. /* This is one of our current bridges, and we know enough about
  5039. * it to know that it won't be able to answer our microdescriptor
  5040. * questions. */
  5041. ever_answered_yes = 1;
  5042. return 1;
  5043. }
  5044. } SMARTLIST_FOREACH_END(e);
  5045. return 0;
  5046. }
  5047. /** Release all storage held by the list of entry guards and related
  5048. * memory structs. */
  5049. void
  5050. entry_guards_free_all(void)
  5051. {
  5052. if (entry_guards) {
  5053. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  5054. entry_guard_free(e));
  5055. smartlist_free(entry_guards);
  5056. entry_guards = NULL;
  5057. }
  5058. clear_bridge_list();
  5059. smartlist_free(bridge_list);
  5060. bridge_list = NULL;
  5061. }