circuitbuild.c 124 KB

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