circuitbuild.c 135 KB

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