circuitbuild.c 108 KB

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