circuitbuild.c 162 KB

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