circuitbuild.c 188 KB

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