circuitbuild.c 164 KB

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