circuitbuild.c 153 KB

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