circuitbuild.c 126 KB

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