circuitbuild.c 153 KB

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