circuitbuild.c 197 KB

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