circuitbuild.c 178 KB

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