circuitbuild.c 136 KB

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