circuitbuild.c 110 KB

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