circuitbuild.c 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223
  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-2013, 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. #include "channel.h"
  12. #include "circpathbias.h"
  13. #include "circuitbuild.h"
  14. #include "circuitlist.h"
  15. #include "circuitstats.h"
  16. #include "circuituse.h"
  17. #include "command.h"
  18. #include "config.h"
  19. #include "confparse.h"
  20. #include "connection.h"
  21. #include "connection_edge.h"
  22. #include "connection_or.h"
  23. #include "control.h"
  24. #include "directory.h"
  25. #include "entrynodes.h"
  26. #include "main.h"
  27. #include "microdesc.h"
  28. #include "networkstatus.h"
  29. #include "nodelist.h"
  30. #include "onion.h"
  31. #include "onion_tap.h"
  32. #include "onion_fast.h"
  33. #include "policies.h"
  34. #include "transports.h"
  35. #include "relay.h"
  36. #include "rephist.h"
  37. #include "router.h"
  38. #include "routerlist.h"
  39. #include "routerparse.h"
  40. #include "routerset.h"
  41. #include "crypto.h"
  42. #ifndef MIN
  43. #define MIN(a,b) ((a)<(b)?(a):(b))
  44. #endif
  45. static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
  46. uint16_t port,
  47. const char *id_digest);
  48. static int circuit_deliver_create_cell(circuit_t *circ,
  49. const create_cell_t *create_cell,
  50. int relayed);
  51. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  52. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  53. static int onion_extend_cpath(origin_circuit_t *circ);
  54. static int count_acceptable_nodes(smartlist_t *routers);
  55. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  56. #ifdef CURVE25519_ENABLED
  57. static int circuits_can_use_ntor(void);
  58. #endif
  59. /** This function tries to get a channel to the specified endpoint,
  60. * and then calls command_setup_channel() to give it the right
  61. * callbacks.
  62. */
  63. static channel_t *
  64. channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
  65. const char *id_digest)
  66. {
  67. channel_t *chan;
  68. chan = channel_connect(addr, port, id_digest);
  69. if (chan) command_setup_channel(chan);
  70. return chan;
  71. }
  72. /** Search for a value for circ_id that we can use on <b>chan</b> for an
  73. * outbound circuit, until we get a circ_id that is not in use by any other
  74. * circuit on that conn.
  75. *
  76. * Return it, or 0 if can't get a unique circ_id.
  77. */
  78. static circid_t
  79. get_unique_circ_id_by_chan(channel_t *chan)
  80. {
  81. #define MAX_CIRCID_ATTEMPTS 64
  82. circid_t test_circ_id;
  83. circid_t attempts=0;
  84. circid_t high_bit, max_range, mask;
  85. tor_assert(chan);
  86. if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  87. log_warn(LD_BUG,
  88. "Trying to pick a circuit ID for a connection from "
  89. "a client with no identity.");
  90. return 0;
  91. }
  92. max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
  93. mask = max_range - 1;
  94. high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
  95. do {
  96. if (++attempts > MAX_CIRCID_ATTEMPTS) {
  97. /* Make sure we don't loop forever because all circuit IDs are used.
  98. *
  99. * Once, we would try until we had tried every possible circuit ID. But
  100. * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
  101. * circuit IDs, and then give up.
  102. *
  103. * This potentially causes us to give up early if our circuit ID space
  104. * is nearly full. If we have N circuit IDs in use, then we will reject
  105. * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
  106. * This means that in practice, a few percent of our circuit ID capacity
  107. * will go unused.
  108. *
  109. * The alternative here, though, is to do a linear search over the
  110. * whole circuit ID space every time we extend a circuit, which is
  111. * not so great either.
  112. */
  113. if (! chan->warned_circ_ids_exhausted) {
  114. chan->warned_circ_ids_exhausted = 1;
  115. log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
  116. "circID support, with %u inbound and %u outbound circuits. "
  117. "Failing a circuit.",
  118. chan->wide_circ_ids ? "with" : "without",
  119. chan->num_p_circuits, chan->num_n_circuits);
  120. }
  121. return 0;
  122. }
  123. crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
  124. test_circ_id &= mask;
  125. test_circ_id |= high_bit;
  126. } while (circuit_id_in_use_on_channel(test_circ_id, chan));
  127. return test_circ_id;
  128. }
  129. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  130. * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
  131. * list information about link status in a more verbose format using spaces.
  132. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  133. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  134. * names.
  135. */
  136. static char *
  137. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  138. {
  139. crypt_path_t *hop;
  140. smartlist_t *elements;
  141. const char *states[] = {"closed", "waiting for keys", "open"};
  142. char *s;
  143. elements = smartlist_new();
  144. if (verbose) {
  145. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  146. smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
  147. circ->build_state->is_internal ? "internal" : "exit",
  148. circ->build_state->need_uptime ? " (high-uptime)" : "",
  149. circ->build_state->desired_path_len,
  150. circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
  151. circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
  152. (nickname?nickname:"*unnamed*"));
  153. }
  154. hop = circ->cpath;
  155. do {
  156. char *elt;
  157. const char *id;
  158. const node_t *node;
  159. if (!hop)
  160. break;
  161. if (!verbose && hop->state != CPATH_STATE_OPEN)
  162. break;
  163. if (!hop->extend_info)
  164. break;
  165. id = hop->extend_info->identity_digest;
  166. if (verbose_names) {
  167. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  168. if ((node = node_get_by_id(id))) {
  169. node_get_verbose_nickname(node, elt);
  170. } else if (is_legal_nickname(hop->extend_info->nickname)) {
  171. elt[0] = '$';
  172. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  173. elt[HEX_DIGEST_LEN+1]= '~';
  174. strlcpy(elt+HEX_DIGEST_LEN+2,
  175. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  176. } else {
  177. elt[0] = '$';
  178. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  179. }
  180. } else { /* ! verbose_names */
  181. node = node_get_by_id(id);
  182. if (node && node_is_named(node)) {
  183. elt = tor_strdup(node_get_nickname(node));
  184. } else {
  185. elt = tor_malloc(HEX_DIGEST_LEN+2);
  186. elt[0] = '$';
  187. base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
  188. }
  189. }
  190. tor_assert(elt);
  191. if (verbose) {
  192. tor_assert(hop->state <= 2);
  193. smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
  194. tor_free(elt);
  195. } else {
  196. smartlist_add(elements, elt);
  197. }
  198. hop = hop->next;
  199. } while (hop != circ->cpath);
  200. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  201. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  202. smartlist_free(elements);
  203. return s;
  204. }
  205. /** If <b>verbose</b> is false, allocate and return a comma-separated
  206. * list of the currently built elements of <b>circ</b>. If
  207. * <b>verbose</b> is true, also list information about link status in
  208. * a more verbose format using spaces.
  209. */
  210. char *
  211. circuit_list_path(origin_circuit_t *circ, int verbose)
  212. {
  213. return circuit_list_path_impl(circ, verbose, 0);
  214. }
  215. /** Allocate and return a comma-separated list of the currently built elements
  216. * of <b>circ</b>, giving each as a verbose nickname.
  217. */
  218. char *
  219. circuit_list_path_for_controller(origin_circuit_t *circ)
  220. {
  221. return circuit_list_path_impl(circ, 0, 1);
  222. }
  223. /** Log, at severity <b>severity</b>, the nicknames of each router in
  224. * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
  225. * exit point.
  226. */
  227. void
  228. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  229. {
  230. char *s = circuit_list_path(circ,1);
  231. tor_log(severity,domain,"%s",s);
  232. tor_free(s);
  233. }
  234. /** Tell the rep(utation)hist(ory) module about the status of the links
  235. * in <b>circ</b>. Hops that have become OPEN are marked as successfully
  236. * extended; the _first_ hop that isn't open (if any) is marked as
  237. * unable to extend.
  238. */
  239. /* XXXX Someday we should learn from OR circuits too. */
  240. void
  241. circuit_rep_hist_note_result(origin_circuit_t *circ)
  242. {
  243. crypt_path_t *hop;
  244. const char *prev_digest = NULL;
  245. hop = circ->cpath;
  246. if (!hop) /* circuit hasn't started building yet. */
  247. return;
  248. if (server_mode(get_options())) {
  249. const routerinfo_t *me = router_get_my_routerinfo();
  250. if (!me)
  251. return;
  252. prev_digest = me->cache_info.identity_digest;
  253. }
  254. do {
  255. const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
  256. if (node) { /* Why do we check this? We know the identity. -NM XXXX */
  257. if (prev_digest) {
  258. if (hop->state == CPATH_STATE_OPEN)
  259. rep_hist_note_extend_succeeded(prev_digest, node->identity);
  260. else {
  261. rep_hist_note_extend_failed(prev_digest, node->identity);
  262. break;
  263. }
  264. }
  265. prev_digest = node->identity;
  266. } else {
  267. prev_digest = NULL;
  268. }
  269. hop=hop->next;
  270. } while (hop!=circ->cpath);
  271. }
  272. #ifdef CURVE25519_ENABLED
  273. /** Return 1 iff at least one node in circ's cpath supports ntor. */
  274. static int
  275. circuit_cpath_supports_ntor(const origin_circuit_t *circ)
  276. {
  277. crypt_path_t *head = circ->cpath, *cpath = circ->cpath;
  278. cpath = head;
  279. do {
  280. if (cpath->extend_info &&
  281. !tor_mem_is_zero(
  282. (const char*)cpath->extend_info->curve25519_onion_key.public_key,
  283. CURVE25519_PUBKEY_LEN))
  284. return 1;
  285. cpath = cpath->next;
  286. } while (cpath != head);
  287. return 0;
  288. }
  289. #else
  290. #define circuit_cpath_supports_ntor(circ) 0
  291. #endif
  292. /** Pick all the entries in our cpath. Stop and return 0 when we're
  293. * happy, or return -1 if an error occurs. */
  294. static int
  295. onion_populate_cpath(origin_circuit_t *circ)
  296. {
  297. int n_tries = 0;
  298. #ifdef CURVE25519_ENABLED
  299. const int using_ntor = circuits_can_use_ntor();
  300. #else
  301. const int using_ntor = 0;
  302. #endif
  303. #define MAX_POPULATE_ATTEMPTS 32
  304. while (1) {
  305. int r = onion_extend_cpath(circ);
  306. if (r < 0) {
  307. log_info(LD_CIRC,"Generating cpath hop failed.");
  308. return -1;
  309. }
  310. if (r == 1) {
  311. /* This circuit doesn't need/shouldn't be forced to have an ntor hop */
  312. if (circ->build_state->desired_path_len <= 1 || ! using_ntor)
  313. return 0;
  314. /* This circuit has an ntor hop. great! */
  315. if (circuit_cpath_supports_ntor(circ))
  316. return 0;
  317. /* No node in the circuit supports ntor. Have we already tried too many
  318. * times? */
  319. if (++n_tries >= MAX_POPULATE_ATTEMPTS)
  320. break;
  321. /* Clear the path and retry */
  322. circuit_clear_cpath(circ);
  323. }
  324. }
  325. log_warn(LD_CIRC, "I tried for %d times, but I couldn't build a %d-hop "
  326. "circuit with at least one node that supports ntor.",
  327. MAX_POPULATE_ATTEMPTS,
  328. circ->build_state->desired_path_len);
  329. return -1;
  330. }
  331. /** Create and return a new origin circuit. Initialize its purpose and
  332. * build-state based on our arguments. The <b>flags</b> argument is a
  333. * bitfield of CIRCLAUNCH_* flags. */
  334. origin_circuit_t *
  335. origin_circuit_init(uint8_t purpose, int flags)
  336. {
  337. /* sets circ->p_circ_id and circ->p_chan */
  338. origin_circuit_t *circ = origin_circuit_new();
  339. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
  340. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  341. circ->build_state->onehop_tunnel =
  342. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  343. circ->build_state->need_uptime =
  344. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  345. circ->build_state->need_capacity =
  346. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  347. circ->build_state->is_internal =
  348. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  349. circ->base_.purpose = purpose;
  350. return circ;
  351. }
  352. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  353. * is defined, then use that as your exit router, else choose a suitable
  354. * exit node.
  355. *
  356. * Also launch a connection to the first OR in the chosen path, if
  357. * it's not open already.
  358. */
  359. origin_circuit_t *
  360. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  361. {
  362. origin_circuit_t *circ;
  363. int err_reason = 0;
  364. circ = origin_circuit_init(purpose, flags);
  365. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  366. onion_populate_cpath(circ) < 0) {
  367. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  368. return NULL;
  369. }
  370. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  371. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  372. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  373. return NULL;
  374. }
  375. return circ;
  376. }
  377. /** Start establishing the first hop of our circuit. Figure out what
  378. * OR we should connect to, and if necessary start the connection to
  379. * it. If we're already connected, then send the 'create' cell.
  380. * Return 0 for ok, -reason if circ should be marked-for-close. */
  381. int
  382. circuit_handle_first_hop(origin_circuit_t *circ)
  383. {
  384. crypt_path_t *firsthop;
  385. channel_t *n_chan;
  386. int err_reason = 0;
  387. const char *msg = NULL;
  388. int should_launch = 0;
  389. firsthop = onion_next_hop_in_cpath(circ->cpath);
  390. tor_assert(firsthop);
  391. tor_assert(firsthop->extend_info);
  392. /* now see if we're already connected to the first OR in 'route' */
  393. log_debug(LD_CIRC,"Looking for firsthop '%s'",
  394. fmt_addrport(&firsthop->extend_info->addr,
  395. firsthop->extend_info->port));
  396. n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
  397. &firsthop->extend_info->addr,
  398. &msg,
  399. &should_launch);
  400. if (!n_chan) {
  401. /* not currently connected in a useful way. */
  402. log_info(LD_CIRC, "Next router is %s: %s",
  403. safe_str_client(extend_info_describe(firsthop->extend_info)),
  404. msg?msg:"???");
  405. circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
  406. if (should_launch) {
  407. if (circ->build_state->onehop_tunnel)
  408. control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
  409. n_chan = channel_connect_for_circuit(
  410. &firsthop->extend_info->addr,
  411. firsthop->extend_info->port,
  412. firsthop->extend_info->identity_digest);
  413. if (!n_chan) { /* connect failed, forget the whole thing */
  414. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  415. return -END_CIRC_REASON_CONNECTFAILED;
  416. }
  417. }
  418. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  419. /* return success. The onion/circuit/etc will be taken care of
  420. * automatically (may already have been) whenever n_chan reaches
  421. * OR_CONN_STATE_OPEN.
  422. */
  423. return 0;
  424. } else { /* it's already open. use it. */
  425. tor_assert(!circ->base_.n_hop);
  426. circ->base_.n_chan = n_chan;
  427. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  428. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  429. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  430. return err_reason;
  431. }
  432. }
  433. return 0;
  434. }
  435. /** Find any circuits that are waiting on <b>or_conn</b> to become
  436. * open and get them to send their create cells forward.
  437. *
  438. * Status is 1 if connect succeeded, or 0 if connect failed.
  439. */
  440. void
  441. circuit_n_chan_done(channel_t *chan, int status)
  442. {
  443. smartlist_t *pending_circs;
  444. int err_reason = 0;
  445. tor_assert(chan);
  446. log_debug(LD_CIRC,"chan to %s/%s, status=%d",
  447. chan->nickname ? chan->nickname : "NULL",
  448. channel_get_canonical_remote_descr(chan), status);
  449. pending_circs = smartlist_new();
  450. circuit_get_all_pending_on_channel(pending_circs, chan);
  451. SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
  452. {
  453. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  454. * leaving them in in case it's possible for the status of a circuit to
  455. * change as we're going down the list. */
  456. if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
  457. circ->state != CIRCUIT_STATE_CHAN_WAIT)
  458. continue;
  459. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  460. /* Look at addr/port. This is an unkeyed connection. */
  461. if (!channel_matches_extend_info(chan, circ->n_hop))
  462. continue;
  463. } else {
  464. /* We expected a key. See if it's the right one. */
  465. if (tor_memneq(chan->identity_digest,
  466. circ->n_hop->identity_digest, DIGEST_LEN))
  467. continue;
  468. }
  469. if (!status) { /* chan failed; close circ */
  470. log_info(LD_CIRC,"Channel failed; closing circ.");
  471. circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
  472. continue;
  473. }
  474. log_debug(LD_CIRC, "Found circ, sending create cell.");
  475. /* circuit_deliver_create_cell will set n_circ_id and add us to
  476. * chan_circuid_circuit_map, so we don't need to call
  477. * set_circid_chan here. */
  478. circ->n_chan = chan;
  479. extend_info_free(circ->n_hop);
  480. circ->n_hop = NULL;
  481. if (CIRCUIT_IS_ORIGIN(circ)) {
  482. if ((err_reason =
  483. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  484. log_info(LD_CIRC,
  485. "send_next_onion_skin failed; circuit marked for closing.");
  486. circuit_mark_for_close(circ, -err_reason);
  487. continue;
  488. /* XXX could this be bad, eg if next_onion_skin failed because conn
  489. * died? */
  490. }
  491. } else {
  492. /* pull the create cell out of circ->n_chan_create_cell, and send it */
  493. tor_assert(circ->n_chan_create_cell);
  494. if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
  495. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  496. continue;
  497. }
  498. tor_free(circ->n_chan_create_cell);
  499. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  500. }
  501. }
  502. SMARTLIST_FOREACH_END(circ);
  503. smartlist_free(pending_circs);
  504. }
  505. /** Find a new circid that isn't currently in use on the circ->n_chan
  506. * for the outgoing
  507. * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
  508. * circuit. If <b>relayed</b> is true, this is a create cell somebody
  509. * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
  510. * it. Return -1 if we failed to find a suitable circid, else return 0.
  511. */
  512. static int
  513. circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
  514. int relayed)
  515. {
  516. cell_t cell;
  517. circid_t id;
  518. int r;
  519. tor_assert(circ);
  520. tor_assert(circ->n_chan);
  521. tor_assert(create_cell);
  522. tor_assert(create_cell->cell_type == CELL_CREATE ||
  523. create_cell->cell_type == CELL_CREATE_FAST ||
  524. create_cell->cell_type == CELL_CREATE2);
  525. id = get_unique_circ_id_by_chan(circ->n_chan);
  526. if (!id) {
  527. log_warn(LD_CIRC,"failed to get unique circID.");
  528. return -1;
  529. }
  530. log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
  531. circuit_set_n_circid_chan(circ, id, circ->n_chan);
  532. memset(&cell, 0, sizeof(cell_t));
  533. r = relayed ? create_cell_format_relayed(&cell, create_cell)
  534. : create_cell_format(&cell, create_cell);
  535. if (r < 0) {
  536. log_warn(LD_CIRC,"Couldn't format create cell");
  537. return -1;
  538. }
  539. cell.circ_id = circ->n_circ_id;
  540. append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
  541. CELL_DIRECTION_OUT, 0);
  542. if (CIRCUIT_IS_ORIGIN(circ)) {
  543. /* Update began timestamp for circuits starting their first hop */
  544. if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
  545. if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
  546. log_warn(LD_CIRC,
  547. "Got first hop for a circuit without an opened channel. "
  548. "State: %s.", channel_state_to_string(circ->n_chan->state));
  549. tor_fragile_assert();
  550. }
  551. tor_gettimeofday(&circ->timestamp_began);
  552. }
  553. /* mark it so it gets better rate limiting treatment. */
  554. channel_timestamp_client(circ->n_chan);
  555. }
  556. return 0;
  557. }
  558. /** We've decided to start our reachability testing. If all
  559. * is set, log this to the user. Return 1 if we did, or 0 if
  560. * we chose not to log anything. */
  561. int
  562. inform_testing_reachability(void)
  563. {
  564. char dirbuf[128];
  565. char *address;
  566. const routerinfo_t *me = router_get_my_routerinfo();
  567. if (!me)
  568. return 0;
  569. address = tor_dup_ip(me->addr);
  570. control_event_server_status(LOG_NOTICE,
  571. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  572. address, me->or_port);
  573. if (me->dir_port) {
  574. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  575. address, me->dir_port);
  576. control_event_server_status(LOG_NOTICE,
  577. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  578. address, me->dir_port);
  579. }
  580. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  581. "(this may take up to %d minutes -- look for log "
  582. "messages indicating success)",
  583. address, me->or_port,
  584. me->dir_port ? dirbuf : "",
  585. me->dir_port ? "are" : "is",
  586. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  587. tor_free(address);
  588. return 1;
  589. }
  590. /** Return true iff we should send a create_fast cell to start building a given
  591. * circuit */
  592. static INLINE int
  593. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  594. {
  595. const or_options_t *options = get_options();
  596. tor_assert(circ->cpath);
  597. tor_assert(circ->cpath->extend_info);
  598. if (!circ->cpath->extend_info->onion_key)
  599. return 1; /* our hand is forced: only a create_fast will work. */
  600. if (public_server_mode(options)) {
  601. /* We're a server, and we know an onion key. We can choose.
  602. * Prefer to blend our circuit into the other circuits we are
  603. * creating on behalf of others. */
  604. return 0;
  605. }
  606. if (options->FastFirstHopPK == -1) {
  607. /* option is "auto", so look at the consensus. */
  608. return networkstatus_get_param(NULL, "usecreatefast", 1, 0, 1);
  609. }
  610. return options->FastFirstHopPK;
  611. }
  612. /** Return true if <b>circ</b> is the type of circuit we want to count
  613. * timeouts from. In particular, we want it to have not completed yet
  614. * (already completing indicates we cannibalized it), and we want it to
  615. * have exactly three hops.
  616. */
  617. int
  618. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  619. {
  620. return !circ->has_opened
  621. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  622. }
  623. #ifdef CURVE25519_ENABLED
  624. /** Return true if the ntor handshake is enabled in the configuration, or if
  625. * it's been set to "auto" in the configuration and it's enabled in the
  626. * consensus. */
  627. static int
  628. circuits_can_use_ntor(void)
  629. {
  630. const or_options_t *options = get_options();
  631. if (options->UseNTorHandshake != -1)
  632. return options->UseNTorHandshake;
  633. return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
  634. }
  635. #endif
  636. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  637. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  638. * accordingly. */
  639. static void
  640. circuit_pick_create_handshake(uint8_t *cell_type_out,
  641. uint16_t *handshake_type_out,
  642. const extend_info_t *ei)
  643. {
  644. #ifdef CURVE25519_ENABLED
  645. if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
  646. CURVE25519_PUBKEY_LEN) &&
  647. circuits_can_use_ntor()) {
  648. *cell_type_out = CELL_CREATE2;
  649. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  650. return;
  651. }
  652. #else
  653. (void) ei;
  654. #endif
  655. *cell_type_out = CELL_CREATE;
  656. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  657. }
  658. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  659. * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
  660. * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
  661. * EXTEND cell to do so, and set *<b>cell_type_out</b> and
  662. * *<b>create_cell_type_out</b> accordingly. */
  663. static void
  664. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  665. uint8_t *create_cell_type_out,
  666. uint16_t *handshake_type_out,
  667. const node_t *node_prev,
  668. const extend_info_t *ei)
  669. {
  670. uint8_t t;
  671. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  672. /* XXXX024 The check for whether the node has a curve25519 key is a bad
  673. * proxy for whether it can do extend2 cells; once a version that
  674. * handles extend2 cells is out, remove it. */
  675. if (node_prev &&
  676. *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
  677. (node_has_curve25519_onion_key(node_prev) ||
  678. (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
  679. *cell_type_out = RELAY_COMMAND_EXTEND2;
  680. *create_cell_type_out = CELL_CREATE2;
  681. } else {
  682. *cell_type_out = RELAY_COMMAND_EXTEND;
  683. *create_cell_type_out = CELL_CREATE;
  684. }
  685. }
  686. /** This is the backbone function for building circuits.
  687. *
  688. * If circ's first hop is closed, then we need to build a create
  689. * cell and send it forward.
  690. *
  691. * Otherwise, we need to build a relay extend cell and send it
  692. * forward.
  693. *
  694. * Return -reason if we want to tear down circ, else return 0.
  695. */
  696. int
  697. circuit_send_next_onion_skin(origin_circuit_t *circ)
  698. {
  699. crypt_path_t *hop;
  700. const node_t *node;
  701. tor_assert(circ);
  702. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  703. /* This is the first hop. */
  704. create_cell_t cc;
  705. int fast;
  706. int len;
  707. log_debug(LD_CIRC,"First skin; sending create cell.");
  708. memset(&cc, 0, sizeof(cc));
  709. if (circ->build_state->onehop_tunnel)
  710. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  711. else
  712. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  713. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  714. fast = should_use_create_fast_for_circuit(circ);
  715. if (!fast) {
  716. /* We are an OR and we know the right onion key: we should
  717. * send a create cell.
  718. */
  719. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  720. circ->cpath->extend_info);
  721. note_request("cell: create", 1);
  722. } else {
  723. /* We are not an OR, and we're building the first hop of a circuit to a
  724. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  725. * and a DH operation. */
  726. cc.cell_type = CELL_CREATE_FAST;
  727. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  728. note_request("cell: create fast", 1);
  729. }
  730. len = onion_skin_create(cc.handshake_type,
  731. circ->cpath->extend_info,
  732. &circ->cpath->handshake_state,
  733. cc.onionskin);
  734. if (len < 0) {
  735. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  736. return - END_CIRC_REASON_INTERNAL;
  737. }
  738. cc.handshake_len = len;
  739. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  740. return - END_CIRC_REASON_RESOURCELIMIT;
  741. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  742. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  743. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  744. fast ? "CREATE_FAST" : "CREATE",
  745. node ? node_describe(node) : "<unnamed>");
  746. } else {
  747. extend_cell_t ec;
  748. int len;
  749. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  750. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  751. log_debug(LD_CIRC,"starting to send subsequent skin.");
  752. hop = onion_next_hop_in_cpath(circ->cpath);
  753. memset(&ec, 0, sizeof(ec));
  754. if (!hop) {
  755. /* done building the circuit. whew. */
  756. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  757. if (circuit_timeout_want_to_count_circ(circ)) {
  758. struct timeval end;
  759. long timediff;
  760. tor_gettimeofday(&end);
  761. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  762. /*
  763. * If the circuit build time is much greater than we would have cut
  764. * it off at, we probably had a suspend event along this codepath,
  765. * and we should discard the value.
  766. */
  767. if (timediff < 0 ||
  768. timediff > 2*get_circuit_build_close_time_ms()+1000) {
  769. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  770. "Assuming clock jump. Purpose %d (%s)", timediff,
  771. circ->base_.purpose,
  772. circuit_purpose_to_string(circ->base_.purpose));
  773. } else if (!circuit_build_times_disabled()) {
  774. /* Only count circuit times if the network is live */
  775. if (circuit_build_times_network_check_live(
  776. get_circuit_build_times())) {
  777. circuit_build_times_add_time(get_circuit_build_times_mutable(),
  778. (build_time_t)timediff);
  779. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  780. }
  781. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  782. circuit_build_times_network_circ_success(
  783. get_circuit_build_times_mutable());
  784. }
  785. }
  786. }
  787. log_info(LD_CIRC,"circuit built!");
  788. circuit_reset_failure_count(0);
  789. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  790. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  791. }
  792. pathbias_count_build_success(circ);
  793. circuit_rep_hist_note_result(circ);
  794. circuit_has_opened(circ); /* do other actions as necessary */
  795. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  796. const or_options_t *options = get_options();
  797. can_complete_circuit=1;
  798. /* FFFF Log a count of known routers here */
  799. log_notice(LD_GENERAL,
  800. "Tor has successfully opened a circuit. "
  801. "Looks like client functionality is working.");
  802. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  803. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  804. clear_broken_connection_map(1);
  805. if (server_mode(options) && !check_whether_orport_reachable()) {
  806. inform_testing_reachability();
  807. consider_testing_reachability(1, 1);
  808. }
  809. }
  810. /* We're done with measurement circuits here. Just close them */
  811. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  812. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  813. }
  814. return 0;
  815. }
  816. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  817. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  818. return - END_CIRC_REASON_INTERNAL;
  819. }
  820. {
  821. const node_t *prev_node;
  822. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  823. circuit_pick_extend_handshake(&ec.cell_type,
  824. &ec.create_cell.cell_type,
  825. &ec.create_cell.handshake_type,
  826. prev_node,
  827. hop->extend_info);
  828. }
  829. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  830. ec.orport_ipv4.port = hop->extend_info->port;
  831. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  832. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  833. len = onion_skin_create(ec.create_cell.handshake_type,
  834. hop->extend_info,
  835. &hop->handshake_state,
  836. ec.create_cell.onionskin);
  837. if (len < 0) {
  838. log_warn(LD_CIRC,"onion_skin_create failed.");
  839. return - END_CIRC_REASON_INTERNAL;
  840. }
  841. ec.create_cell.handshake_len = len;
  842. log_info(LD_CIRC,"Sending extend relay cell.");
  843. note_request("cell: extend", 1);
  844. {
  845. uint8_t command = 0;
  846. uint16_t payload_len=0;
  847. uint8_t payload[RELAY_PAYLOAD_SIZE];
  848. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  849. log_warn(LD_CIRC,"Couldn't format extend cell");
  850. return -END_CIRC_REASON_INTERNAL;
  851. }
  852. /* send it to hop->prev, because it will transfer
  853. * it to a create cell and then send to hop */
  854. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  855. command,
  856. (char*)payload, payload_len,
  857. hop->prev) < 0)
  858. return 0; /* circuit is closed */
  859. }
  860. hop->state = CPATH_STATE_AWAITING_KEYS;
  861. }
  862. return 0;
  863. }
  864. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  865. * something has also gone wrong with our network: notify the user,
  866. * and abandon all not-yet-used circuits. */
  867. void
  868. circuit_note_clock_jumped(int seconds_elapsed)
  869. {
  870. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  871. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  872. "assuming established circuits no longer work.",
  873. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  874. seconds_elapsed >=0 ? "forward" : "backward");
  875. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  876. seconds_elapsed);
  877. can_complete_circuit=0; /* so it'll log when it works again */
  878. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  879. "CLOCK_JUMPED");
  880. circuit_mark_all_unused_circs();
  881. circuit_mark_all_dirty_circs_as_unusable();
  882. }
  883. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  884. * skin and identity digest for the next hop. If we're already connected,
  885. * pass the onion skin to the next hop using a create cell; otherwise
  886. * launch a new OR connection, and <b>circ</b> will notice when the
  887. * connection succeeds or fails.
  888. *
  889. * Return -1 if we want to warn and tear down the circuit, else return 0.
  890. */
  891. int
  892. circuit_extend(cell_t *cell, circuit_t *circ)
  893. {
  894. channel_t *n_chan;
  895. relay_header_t rh;
  896. extend_cell_t ec;
  897. const char *msg = NULL;
  898. int should_launch = 0;
  899. if (circ->n_chan) {
  900. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  901. "n_chan already set. Bug/attack. Closing.");
  902. return -1;
  903. }
  904. if (circ->n_hop) {
  905. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  906. "conn to next hop already launched. Bug/attack. Closing.");
  907. return -1;
  908. }
  909. if (!server_mode(get_options())) {
  910. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  911. "Got an extend cell, but running as a client. Closing.");
  912. return -1;
  913. }
  914. relay_header_unpack(&rh, cell->payload);
  915. if (extend_cell_parse(&ec, rh.command,
  916. cell->payload+RELAY_HEADER_SIZE,
  917. rh.length) < 0) {
  918. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  919. "Can't parse extend cell. Closing circuit.");
  920. return -1;
  921. }
  922. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  923. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  924. "Client asked me to extend to zero destination port or addr.");
  925. return -1;
  926. }
  927. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  928. !get_options()->ExtendAllowPrivateAddresses) {
  929. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  930. "Client asked me to extend to a private address");
  931. return -1;
  932. }
  933. /* Check if they asked us for 0000..0000. We support using
  934. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  935. * but we don't want to let people send us extend cells for empty
  936. * fingerprints -- a) because it opens the user up to a mitm attack,
  937. * and b) because it lets an attacker force the relay to hold open a
  938. * new TLS connection for each extend request. */
  939. if (tor_digest_is_zero((const char*)ec.node_id)) {
  940. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  941. "Client asked me to extend without specifying an id_digest.");
  942. return -1;
  943. }
  944. /* Next, check if we're being asked to connect to the hop that the
  945. * extend cell came from. There isn't any reason for that, and it can
  946. * assist circular-path attacks. */
  947. if (tor_memeq(ec.node_id,
  948. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  949. DIGEST_LEN)) {
  950. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  951. "Client asked me to extend back to the previous hop.");
  952. return -1;
  953. }
  954. n_chan = channel_get_for_extend((const char*)ec.node_id,
  955. &ec.orport_ipv4.addr,
  956. &msg,
  957. &should_launch);
  958. if (!n_chan) {
  959. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  960. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  961. msg?msg:"????");
  962. circ->n_hop = extend_info_new(NULL /*nickname*/,
  963. (const char*)ec.node_id,
  964. NULL /*onion_key*/,
  965. NULL /*curve25519_key*/,
  966. &ec.orport_ipv4.addr,
  967. ec.orport_ipv4.port);
  968. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  969. sizeof(ec.create_cell));
  970. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  971. if (should_launch) {
  972. /* we should try to open a connection */
  973. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  974. ec.orport_ipv4.port,
  975. (const char*)ec.node_id);
  976. if (!n_chan) {
  977. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  978. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  979. return 0;
  980. }
  981. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  982. }
  983. /* return success. The onion/circuit/etc will be taken care of
  984. * automatically (may already have been) whenever n_chan reaches
  985. * OR_CONN_STATE_OPEN.
  986. */
  987. return 0;
  988. }
  989. tor_assert(!circ->n_hop); /* Connection is already established. */
  990. circ->n_chan = n_chan;
  991. log_debug(LD_CIRC,
  992. "n_chan is %s",
  993. channel_get_canonical_remote_descr(n_chan));
  994. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  995. return -1;
  996. return 0;
  997. }
  998. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  999. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  1000. * used as follows:
  1001. * - 20 to initialize f_digest
  1002. * - 20 to initialize b_digest
  1003. * - 16 to key f_crypto
  1004. * - 16 to key b_crypto
  1005. *
  1006. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  1007. */
  1008. int
  1009. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  1010. int reverse)
  1011. {
  1012. crypto_digest_t *tmp_digest;
  1013. crypto_cipher_t *tmp_crypto;
  1014. tor_assert(cpath);
  1015. tor_assert(key_data);
  1016. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  1017. cpath->f_digest || cpath->b_digest));
  1018. cpath->f_digest = crypto_digest_new();
  1019. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  1020. cpath->b_digest = crypto_digest_new();
  1021. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  1022. if (!(cpath->f_crypto =
  1023. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  1024. log_warn(LD_BUG,"Forward cipher initialization failed.");
  1025. return -1;
  1026. }
  1027. if (!(cpath->b_crypto =
  1028. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  1029. log_warn(LD_BUG,"Backward cipher initialization failed.");
  1030. return -1;
  1031. }
  1032. if (reverse) {
  1033. tmp_digest = cpath->f_digest;
  1034. cpath->f_digest = cpath->b_digest;
  1035. cpath->b_digest = tmp_digest;
  1036. tmp_crypto = cpath->f_crypto;
  1037. cpath->f_crypto = cpath->b_crypto;
  1038. cpath->b_crypto = tmp_crypto;
  1039. }
  1040. return 0;
  1041. }
  1042. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  1043. * (The body of <b>reply</b> varies depending on what sort of handshake
  1044. * this is.)
  1045. *
  1046. * Calculate the appropriate keys and digests, make sure KH is
  1047. * correct, and initialize this hop of the cpath.
  1048. *
  1049. * Return - reason if we want to mark circ for close, else return 0.
  1050. */
  1051. int
  1052. circuit_finish_handshake(origin_circuit_t *circ,
  1053. const created_cell_t *reply)
  1054. {
  1055. char keys[CPATH_KEY_MATERIAL_LEN];
  1056. crypt_path_t *hop;
  1057. int rv;
  1058. if ((rv = pathbias_count_build_attempt(circ)) < 0)
  1059. return rv;
  1060. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1061. hop = circ->cpath;
  1062. } else {
  1063. hop = onion_next_hop_in_cpath(circ->cpath);
  1064. if (!hop) { /* got an extended when we're all done? */
  1065. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1066. return - END_CIRC_REASON_TORPROTOCOL;
  1067. }
  1068. }
  1069. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1070. {
  1071. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1072. &hop->handshake_state,
  1073. reply->reply, reply->handshake_len,
  1074. (uint8_t*)keys, sizeof(keys),
  1075. (uint8_t*)hop->rend_circ_nonce) < 0) {
  1076. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1077. return -END_CIRC_REASON_TORPROTOCOL;
  1078. }
  1079. }
  1080. onion_handshake_state_release(&hop->handshake_state);
  1081. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1082. return -END_CIRC_REASON_TORPROTOCOL;
  1083. }
  1084. hop->state = CPATH_STATE_OPEN;
  1085. log_info(LD_CIRC,"Finished building circuit hop:");
  1086. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1087. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1088. return 0;
  1089. }
  1090. /** We received a relay truncated cell on circ.
  1091. *
  1092. * Since we don't send truncates currently, getting a truncated
  1093. * means that a connection broke or an extend failed. For now,
  1094. * just give up: force circ to close, and return 0.
  1095. */
  1096. int
  1097. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1098. {
  1099. // crypt_path_t *victim;
  1100. // connection_t *stream;
  1101. tor_assert(circ);
  1102. tor_assert(layer);
  1103. /* XXX Since we don't send truncates currently, getting a truncated
  1104. * means that a connection broke or an extend failed. For now,
  1105. * just give up.
  1106. */
  1107. circuit_mark_for_close(TO_CIRCUIT(circ),
  1108. END_CIRC_REASON_FLAG_REMOTE|reason);
  1109. return 0;
  1110. #if 0
  1111. while (layer->next != circ->cpath) {
  1112. /* we need to clear out layer->next */
  1113. victim = layer->next;
  1114. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1115. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1116. if (stream->cpath_layer == victim) {
  1117. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1118. stream->stream_id);
  1119. /* no need to send 'end' relay cells,
  1120. * because the other side's already dead
  1121. */
  1122. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1123. }
  1124. }
  1125. layer->next = victim->next;
  1126. circuit_free_cpath_node(victim);
  1127. }
  1128. log_info(LD_CIRC, "finished");
  1129. return 0;
  1130. #endif
  1131. }
  1132. /** Given a response payload and keys, initialize, then send a created
  1133. * cell back.
  1134. */
  1135. int
  1136. onionskin_answer(or_circuit_t *circ,
  1137. const created_cell_t *created_cell,
  1138. const char *keys,
  1139. const uint8_t *rend_circ_nonce)
  1140. {
  1141. cell_t cell;
  1142. crypt_path_t *tmp_cpath;
  1143. if (created_cell_format(&cell, created_cell) < 0) {
  1144. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  1145. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  1146. return -1;
  1147. }
  1148. cell.circ_id = circ->p_circ_id;
  1149. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1150. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1151. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1152. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1153. (unsigned int)get_uint32(keys),
  1154. (unsigned int)get_uint32(keys+20));
  1155. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1156. log_warn(LD_BUG,"Circuit initialization failed");
  1157. tor_free(tmp_cpath);
  1158. return -1;
  1159. }
  1160. circ->n_digest = tmp_cpath->f_digest;
  1161. circ->n_crypto = tmp_cpath->f_crypto;
  1162. circ->p_digest = tmp_cpath->b_digest;
  1163. circ->p_crypto = tmp_cpath->b_crypto;
  1164. tmp_cpath->magic = 0;
  1165. tor_free(tmp_cpath);
  1166. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1167. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1168. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1169. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1170. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1171. circ->is_first_hop ? "created_fast" : "created");
  1172. if (!channel_is_local(circ->p_chan) &&
  1173. !channel_is_outgoing(circ->p_chan)) {
  1174. /* record that we could process create cells from a non-local conn
  1175. * that we didn't initiate; presumably this means that create cells
  1176. * can reach us too. */
  1177. router_orport_found_reachable();
  1178. }
  1179. return 0;
  1180. }
  1181. /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
  1182. * number of endpoints that would give something away about our destination.
  1183. *
  1184. * If the routerlist <b>nodes</b> doesn't have enough routers
  1185. * to handle the desired path length, return -1.
  1186. */
  1187. static int
  1188. new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
  1189. {
  1190. int num_acceptable_routers;
  1191. int routelen;
  1192. tor_assert(nodes);
  1193. routelen = DEFAULT_ROUTE_LEN;
  1194. if (exit &&
  1195. purpose != CIRCUIT_PURPOSE_TESTING &&
  1196. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1197. routelen++;
  1198. num_acceptable_routers = count_acceptable_nodes(nodes);
  1199. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1200. routelen, num_acceptable_routers, smartlist_len(nodes));
  1201. if (num_acceptable_routers < routelen) {
  1202. log_info(LD_CIRC,
  1203. "Not enough acceptable routers (%d/%d). Discarding this circuit.",
  1204. num_acceptable_routers, routelen);
  1205. return -1;
  1206. }
  1207. return routelen;
  1208. }
  1209. /** Return a newly allocated list of uint16_t * for each predicted port not
  1210. * handled by a current circuit. */
  1211. static smartlist_t *
  1212. circuit_get_unhandled_ports(time_t now)
  1213. {
  1214. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1215. circuit_remove_handled_ports(dest);
  1216. return dest;
  1217. }
  1218. /** Return 1 if we already have circuits present or on the way for
  1219. * all anticipated ports. Return 0 if we should make more.
  1220. *
  1221. * If we're returning 0, set need_uptime and need_capacity to
  1222. * indicate any requirements that the unhandled ports have.
  1223. */
  1224. int
  1225. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1226. int *need_capacity)
  1227. {
  1228. int i, enough;
  1229. uint16_t *port;
  1230. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1231. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1232. tor_assert(need_uptime);
  1233. tor_assert(need_capacity);
  1234. // Always predict need_capacity
  1235. *need_capacity = 1;
  1236. enough = (smartlist_len(sl) == 0);
  1237. for (i = 0; i < smartlist_len(sl); ++i) {
  1238. port = smartlist_get(sl, i);
  1239. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  1240. *need_uptime = 1;
  1241. tor_free(port);
  1242. }
  1243. smartlist_free(sl);
  1244. return enough;
  1245. }
  1246. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1247. * <b>needed_ports</b>, else return 0.
  1248. */
  1249. static int
  1250. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1251. { /* XXXX MOVE */
  1252. int i;
  1253. uint16_t port;
  1254. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1255. addr_policy_result_t r;
  1256. /* alignment issues aren't a worry for this dereference, since
  1257. needed_ports is explicitly a smartlist of uint16_t's */
  1258. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1259. tor_assert(port);
  1260. if (node)
  1261. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1262. else
  1263. continue;
  1264. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1265. return 1;
  1266. }
  1267. return 0;
  1268. }
  1269. /** Return true iff <b>conn</b> needs another general circuit to be
  1270. * built. */
  1271. static int
  1272. ap_stream_wants_exit_attention(connection_t *conn)
  1273. {
  1274. entry_connection_t *entry;
  1275. if (conn->type != CONN_TYPE_AP)
  1276. return 0;
  1277. entry = TO_ENTRY_CONN(conn);
  1278. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1279. !conn->marked_for_close &&
  1280. !(entry->want_onehop) && /* ignore one-hop streams */
  1281. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1282. !(entry->chosen_exit_name) && /* ignore defined streams */
  1283. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1284. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1285. MIN_CIRCUITS_HANDLING_STREAM))
  1286. return 1;
  1287. return 0;
  1288. }
  1289. /** Return a pointer to a suitable router to be the exit node for the
  1290. * general-purpose circuit we're about to build.
  1291. *
  1292. * Look through the connection array, and choose a router that maximizes
  1293. * the number of pending streams that can exit from this router.
  1294. *
  1295. * Return NULL if we can't find any suitable routers.
  1296. */
  1297. static const node_t *
  1298. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1299. {
  1300. int *n_supported;
  1301. int n_pending_connections = 0;
  1302. smartlist_t *connections;
  1303. int best_support = -1;
  1304. int n_best_support=0;
  1305. const or_options_t *options = get_options();
  1306. const smartlist_t *the_nodes;
  1307. const node_t *node=NULL;
  1308. connections = get_connection_array();
  1309. /* Count how many connections are waiting for a circuit to be built.
  1310. * We use this for log messages now, but in the future we may depend on it.
  1311. */
  1312. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1313. {
  1314. if (ap_stream_wants_exit_attention(conn))
  1315. ++n_pending_connections;
  1316. });
  1317. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1318. // n_pending_connections);
  1319. /* Now we count, for each of the routers in the directory, how many
  1320. * of the pending connections could possibly exit from that
  1321. * router (n_supported[i]). (We can't be sure about cases where we
  1322. * don't know the IP address of the pending connection.)
  1323. *
  1324. * -1 means "Don't use this router at all."
  1325. */
  1326. the_nodes = nodelist_get_list();
  1327. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1328. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1329. const int i = node_sl_idx;
  1330. if (router_digest_is_me(node->identity)) {
  1331. n_supported[i] = -1;
  1332. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1333. /* XXX there's probably a reverse predecessor attack here, but
  1334. * it's slow. should we take this out? -RD
  1335. */
  1336. continue;
  1337. }
  1338. if (!node_has_descriptor(node)) {
  1339. n_supported[i] = -1;
  1340. continue;
  1341. }
  1342. if (!node->is_running || node->is_bad_exit) {
  1343. n_supported[i] = -1;
  1344. continue; /* skip routers that are known to be down or bad exits */
  1345. }
  1346. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1347. /* never pick a non-general node as a random exit. */
  1348. n_supported[i] = -1;
  1349. continue;
  1350. }
  1351. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1352. n_supported[i] = -1;
  1353. continue; /* user asked us not to use it, no matter what */
  1354. }
  1355. if (options->ExitNodes &&
  1356. !routerset_contains_node(options->ExitNodes, node)) {
  1357. n_supported[i] = -1;
  1358. continue; /* not one of our chosen exit nodes */
  1359. }
  1360. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1361. n_supported[i] = -1;
  1362. continue; /* skip routers that are not suitable. Don't worry if
  1363. * this makes us reject all the possible routers: if so,
  1364. * we'll retry later in this function with need_update and
  1365. * need_capacity set to 0. */
  1366. }
  1367. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1368. /* if it's invalid and we don't want it */
  1369. n_supported[i] = -1;
  1370. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1371. // router->nickname, i);
  1372. continue; /* skip invalid routers */
  1373. }
  1374. if (options->ExcludeSingleHopRelays &&
  1375. node_allows_single_hop_exits(node)) {
  1376. n_supported[i] = -1;
  1377. continue;
  1378. }
  1379. if (node_exit_policy_rejects_all(node)) {
  1380. n_supported[i] = -1;
  1381. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1382. // router->nickname, i);
  1383. continue; /* skip routers that reject all */
  1384. }
  1385. n_supported[i] = 0;
  1386. /* iterate over connections */
  1387. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1388. if (!ap_stream_wants_exit_attention(conn))
  1389. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1390. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1391. ++n_supported[i];
  1392. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1393. // router->nickname, i, n_supported[i]);
  1394. } else {
  1395. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1396. // router->nickname, i);
  1397. }
  1398. } SMARTLIST_FOREACH_END(conn);
  1399. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1400. /* Leave best_support at -1 if that's where it is, so we can
  1401. * distinguish it later. */
  1402. continue;
  1403. }
  1404. if (n_supported[i] > best_support) {
  1405. /* If this router is better than previous ones, remember its index
  1406. * and goodness, and start counting how many routers are this good. */
  1407. best_support = n_supported[i]; n_best_support=1;
  1408. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1409. // router->nickname);
  1410. } else if (n_supported[i] == best_support) {
  1411. /* If this router is _as good_ as the best one, just increment the
  1412. * count of equally good routers.*/
  1413. ++n_best_support;
  1414. }
  1415. } SMARTLIST_FOREACH_END(node);
  1416. log_info(LD_CIRC,
  1417. "Found %d servers that might support %d/%d pending connections.",
  1418. n_best_support, best_support >= 0 ? best_support : 0,
  1419. n_pending_connections);
  1420. /* If any routers definitely support any pending connections, choose one
  1421. * at random. */
  1422. if (best_support > 0) {
  1423. smartlist_t *supporting = smartlist_new();
  1424. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1425. if (n_supported[node_sl_idx] == best_support)
  1426. smartlist_add(supporting, (void*)node);
  1427. });
  1428. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1429. smartlist_free(supporting);
  1430. } else {
  1431. /* Either there are no pending connections, or no routers even seem to
  1432. * possibly support any of them. Choose a router at random that satisfies
  1433. * at least one predicted exit port. */
  1434. int attempt;
  1435. smartlist_t *needed_ports, *supporting;
  1436. if (best_support == -1) {
  1437. if (need_uptime || need_capacity) {
  1438. log_info(LD_CIRC,
  1439. "We couldn't find any live%s%s routers; falling back "
  1440. "to list of all routers.",
  1441. need_capacity?", fast":"",
  1442. need_uptime?", stable":"");
  1443. tor_free(n_supported);
  1444. return choose_good_exit_server_general(0, 0);
  1445. }
  1446. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1447. "choosing a doomed exit at random.",
  1448. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1449. }
  1450. supporting = smartlist_new();
  1451. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1452. for (attempt = 0; attempt < 2; attempt++) {
  1453. /* try once to pick only from routers that satisfy a needed port,
  1454. * then if there are none, pick from any that support exiting. */
  1455. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1456. if (n_supported[node_sl_idx] != -1 &&
  1457. (attempt || node_handles_some_port(node, needed_ports))) {
  1458. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1459. // try, router->nickname);
  1460. smartlist_add(supporting, (void*)node);
  1461. }
  1462. } SMARTLIST_FOREACH_END(node);
  1463. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1464. if (node)
  1465. break;
  1466. smartlist_clear(supporting);
  1467. /* If we reach this point, we can't actually support any unhandled
  1468. * predicted ports, so clear all the remaining ones. */
  1469. if (smartlist_len(needed_ports))
  1470. rep_hist_remove_predicted_ports(needed_ports);
  1471. }
  1472. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1473. smartlist_free(needed_ports);
  1474. smartlist_free(supporting);
  1475. }
  1476. tor_free(n_supported);
  1477. if (node) {
  1478. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  1479. return node;
  1480. }
  1481. if (options->ExitNodes) {
  1482. log_warn(LD_CIRC,
  1483. "No specified %sexit routers seem to be running: "
  1484. "can't choose an exit.",
  1485. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1486. }
  1487. return NULL;
  1488. }
  1489. /** Return a pointer to a suitable router to be the exit node for the
  1490. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1491. * if no router is suitable).
  1492. *
  1493. * For general-purpose circuits, pass it off to
  1494. * choose_good_exit_server_general()
  1495. *
  1496. * For client-side rendezvous circuits, choose a random node, weighted
  1497. * toward the preferences in 'options'.
  1498. */
  1499. static const node_t *
  1500. choose_good_exit_server(uint8_t purpose,
  1501. int need_uptime, int need_capacity, int is_internal)
  1502. {
  1503. const or_options_t *options = get_options();
  1504. router_crn_flags_t flags = CRN_NEED_DESC;
  1505. if (need_uptime)
  1506. flags |= CRN_NEED_UPTIME;
  1507. if (need_capacity)
  1508. flags |= CRN_NEED_CAPACITY;
  1509. switch (purpose) {
  1510. case CIRCUIT_PURPOSE_C_GENERAL:
  1511. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1512. flags |= CRN_ALLOW_INVALID;
  1513. if (is_internal) /* pick it like a middle hop */
  1514. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1515. else
  1516. return choose_good_exit_server_general(need_uptime,need_capacity);
  1517. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1518. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  1519. flags |= CRN_ALLOW_INVALID;
  1520. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1521. }
  1522. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1523. tor_fragile_assert();
  1524. return NULL;
  1525. }
  1526. /** Log a warning if the user specified an exit for the circuit that
  1527. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1528. static void
  1529. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1530. {
  1531. const or_options_t *options = get_options();
  1532. routerset_t *rs = options->ExcludeNodes;
  1533. const char *description;
  1534. uint8_t purpose = circ->base_.purpose;
  1535. if (circ->build_state->onehop_tunnel)
  1536. return;
  1537. switch (purpose)
  1538. {
  1539. default:
  1540. case CIRCUIT_PURPOSE_OR:
  1541. case CIRCUIT_PURPOSE_INTRO_POINT:
  1542. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1543. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1544. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1545. (int)purpose,
  1546. circuit_purpose_to_string(purpose));
  1547. return;
  1548. case CIRCUIT_PURPOSE_C_GENERAL:
  1549. if (circ->build_state->is_internal)
  1550. return;
  1551. description = "requested exit node";
  1552. rs = options->ExcludeExitNodesUnion_;
  1553. break;
  1554. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1555. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1556. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1557. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1558. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1559. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1560. case CIRCUIT_PURPOSE_TESTING:
  1561. return;
  1562. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1563. case CIRCUIT_PURPOSE_C_REND_READY:
  1564. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1565. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1566. description = "chosen rendezvous point";
  1567. break;
  1568. case CIRCUIT_PURPOSE_CONTROLLER:
  1569. rs = options->ExcludeExitNodesUnion_;
  1570. description = "controller-selected circuit target";
  1571. break;
  1572. }
  1573. if (routerset_contains_extendinfo(rs, exit)) {
  1574. /* We should never get here if StrictNodes is set to 1. */
  1575. if (options->StrictNodes) {
  1576. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1577. "even though StrictNodes is set. Please report. "
  1578. "(Circuit purpose: %s)",
  1579. description, extend_info_describe(exit),
  1580. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1581. circuit_purpose_to_string(purpose));
  1582. } else {
  1583. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1584. "ExcludeNodes%s, because no better options were available. To "
  1585. "prevent this (and possibly break your Tor functionality), "
  1586. "set the StrictNodes configuration option. "
  1587. "(Circuit purpose: %s)",
  1588. description, extend_info_describe(exit),
  1589. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1590. circuit_purpose_to_string(purpose));
  1591. }
  1592. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1593. }
  1594. return;
  1595. }
  1596. /** Decide a suitable length for circ's cpath, and pick an exit
  1597. * router (or use <b>exit</b> if provided). Store these in the
  1598. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1599. static int
  1600. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1601. {
  1602. cpath_build_state_t *state = circ->build_state;
  1603. if (state->onehop_tunnel) {
  1604. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1605. state->desired_path_len = 1;
  1606. } else {
  1607. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  1608. if (r < 1) /* must be at least 1 */
  1609. return -1;
  1610. state->desired_path_len = r;
  1611. }
  1612. if (exit) { /* the circuit-builder pre-requested one */
  1613. warn_if_last_router_excluded(circ, exit);
  1614. log_info(LD_CIRC,"Using requested exit node '%s'",
  1615. extend_info_describe(exit));
  1616. exit = extend_info_dup(exit);
  1617. } else { /* we have to decide one */
  1618. const node_t *node =
  1619. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1620. state->need_capacity, state->is_internal);
  1621. if (!node) {
  1622. log_warn(LD_CIRC,"failed to choose an exit server");
  1623. return -1;
  1624. }
  1625. exit = extend_info_from_node(node, 0);
  1626. tor_assert(exit);
  1627. }
  1628. state->chosen_exit = exit;
  1629. return 0;
  1630. }
  1631. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1632. * hop to the cpath reflecting this. Don't send the next extend cell --
  1633. * the caller will do this if it wants to.
  1634. */
  1635. int
  1636. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1637. {
  1638. cpath_build_state_t *state;
  1639. tor_assert(exit);
  1640. tor_assert(circ);
  1641. state = circ->build_state;
  1642. tor_assert(state);
  1643. extend_info_free(state->chosen_exit);
  1644. state->chosen_exit = extend_info_dup(exit);
  1645. ++circ->build_state->desired_path_len;
  1646. onion_append_hop(&circ->cpath, exit);
  1647. return 0;
  1648. }
  1649. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1650. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1651. * send the next extend cell to begin connecting to that hop.
  1652. */
  1653. int
  1654. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1655. {
  1656. int err_reason = 0;
  1657. warn_if_last_router_excluded(circ, exit);
  1658. tor_gettimeofday(&circ->base_.timestamp_began);
  1659. circuit_append_new_exit(circ, exit);
  1660. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1661. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1662. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  1663. extend_info_describe(exit));
  1664. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1665. return -1;
  1666. }
  1667. // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
  1668. return 0;
  1669. }
  1670. /** Return the number of routers in <b>routers</b> that are currently up
  1671. * and available for building circuits through.
  1672. */
  1673. static int
  1674. count_acceptable_nodes(smartlist_t *nodes)
  1675. {
  1676. int num=0;
  1677. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  1678. // log_debug(LD_CIRC,
  1679. // "Contemplating whether router %d (%s) is a new option.",
  1680. // i, r->nickname);
  1681. if (! node->is_running)
  1682. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1683. continue;
  1684. if (! node->is_valid)
  1685. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1686. continue;
  1687. if (! node_has_descriptor(node))
  1688. continue;
  1689. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1690. * allows this node in some places, then we're getting an inaccurate
  1691. * count. For now, be conservative and don't count it. But later we
  1692. * should try to be smarter. */
  1693. ++num;
  1694. } SMARTLIST_FOREACH_END(node);
  1695. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1696. return num;
  1697. }
  1698. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1699. * This function is used to extend cpath by another hop.
  1700. */
  1701. void
  1702. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1703. {
  1704. if (*head_ptr) {
  1705. new_hop->next = (*head_ptr);
  1706. new_hop->prev = (*head_ptr)->prev;
  1707. (*head_ptr)->prev->next = new_hop;
  1708. (*head_ptr)->prev = new_hop;
  1709. } else {
  1710. *head_ptr = new_hop;
  1711. new_hop->prev = new_hop->next = new_hop;
  1712. }
  1713. }
  1714. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1715. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1716. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1717. * circuit. In particular, make sure we don't pick the exit node or its
  1718. * family, and make sure we don't duplicate any previous nodes or their
  1719. * families. */
  1720. static const node_t *
  1721. choose_good_middle_server(uint8_t purpose,
  1722. cpath_build_state_t *state,
  1723. crypt_path_t *head,
  1724. int cur_len)
  1725. {
  1726. int i;
  1727. const node_t *r, *choice;
  1728. crypt_path_t *cpath;
  1729. smartlist_t *excluded;
  1730. const or_options_t *options = get_options();
  1731. router_crn_flags_t flags = CRN_NEED_DESC;
  1732. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  1733. purpose <= CIRCUIT_PURPOSE_MAX_);
  1734. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1735. excluded = smartlist_new();
  1736. if ((r = build_state_get_exit_node(state))) {
  1737. nodelist_add_node_and_family(excluded, r);
  1738. }
  1739. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1740. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  1741. nodelist_add_node_and_family(excluded, r);
  1742. }
  1743. }
  1744. if (state->need_uptime)
  1745. flags |= CRN_NEED_UPTIME;
  1746. if (state->need_capacity)
  1747. flags |= CRN_NEED_CAPACITY;
  1748. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1749. flags |= CRN_ALLOW_INVALID;
  1750. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1751. smartlist_free(excluded);
  1752. return choice;
  1753. }
  1754. /** Pick a good entry server for the circuit to be built according to
  1755. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1756. * router (if we're an OR), and respect firewall settings; if we're
  1757. * configured to use entry guards, return one.
  1758. *
  1759. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1760. * guard, not for any particular circuit.
  1761. */
  1762. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1763. const node_t *
  1764. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1765. {
  1766. const node_t *choice;
  1767. smartlist_t *excluded;
  1768. const or_options_t *options = get_options();
  1769. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  1770. const node_t *node;
  1771. if (state && options->UseEntryGuards &&
  1772. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  1773. /* This request is for an entry server to use for a regular circuit,
  1774. * and we use entry guard nodes. Just return one of the guard nodes. */
  1775. return choose_random_entry(state);
  1776. }
  1777. excluded = smartlist_new();
  1778. if (state && (node = build_state_get_exit_node(state))) {
  1779. /* Exclude the exit node from the state, if we have one. Also exclude its
  1780. * family. */
  1781. nodelist_add_node_and_family(excluded, node);
  1782. }
  1783. if (firewall_is_fascist_or()) {
  1784. /* Exclude all ORs that we can't reach through our firewall */
  1785. smartlist_t *nodes = nodelist_get_list();
  1786. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  1787. if (!fascist_firewall_allows_node(node))
  1788. smartlist_add(excluded, (void*)node);
  1789. });
  1790. }
  1791. /* and exclude current entry guards and their families, if applicable */
  1792. /*XXXX025 use the using_as_guard flag to accomplish this.*/
  1793. if (options->UseEntryGuards) {
  1794. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  1795. {
  1796. if ((node = node_get_by_id(entry->identity))) {
  1797. nodelist_add_node_and_family(excluded, node);
  1798. }
  1799. });
  1800. }
  1801. if (state) {
  1802. if (state->need_uptime)
  1803. flags |= CRN_NEED_UPTIME;
  1804. if (state->need_capacity)
  1805. flags |= CRN_NEED_CAPACITY;
  1806. }
  1807. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  1808. flags |= CRN_ALLOW_INVALID;
  1809. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1810. smartlist_free(excluded);
  1811. return choice;
  1812. }
  1813. /** Return the first non-open hop in cpath, or return NULL if all
  1814. * hops are open. */
  1815. static crypt_path_t *
  1816. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1817. {
  1818. crypt_path_t *hop = cpath;
  1819. do {
  1820. if (hop->state != CPATH_STATE_OPEN)
  1821. return hop;
  1822. hop = hop->next;
  1823. } while (hop != cpath);
  1824. return NULL;
  1825. }
  1826. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1827. * based on <b>state</b>. Append the hop info to head_ptr.
  1828. *
  1829. * Return 1 if the path is complete, 0 if we successfully added a hop,
  1830. * and -1 on error.
  1831. */
  1832. static int
  1833. onion_extend_cpath(origin_circuit_t *circ)
  1834. {
  1835. uint8_t purpose = circ->base_.purpose;
  1836. cpath_build_state_t *state = circ->build_state;
  1837. int cur_len = circuit_get_cpath_len(circ);
  1838. extend_info_t *info = NULL;
  1839. if (cur_len >= state->desired_path_len) {
  1840. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1841. state->desired_path_len);
  1842. return 1;
  1843. }
  1844. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1845. state->desired_path_len);
  1846. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1847. info = extend_info_dup(state->chosen_exit);
  1848. } else if (cur_len == 0) { /* picking first node */
  1849. const node_t *r = choose_good_entry_server(purpose, state);
  1850. if (r) {
  1851. /* If we're a client, use the preferred address rather than the
  1852. primary address, for potentially connecting to an IPv6 OR
  1853. port. */
  1854. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  1855. tor_assert(info);
  1856. }
  1857. } else {
  1858. const node_t *r =
  1859. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1860. if (r) {
  1861. info = extend_info_from_node(r, 0);
  1862. tor_assert(info);
  1863. }
  1864. }
  1865. if (!info) {
  1866. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1867. "this circuit.", cur_len);
  1868. return -1;
  1869. }
  1870. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1871. extend_info_describe(info),
  1872. cur_len+1, build_state_get_exit_nickname(state));
  1873. onion_append_hop(&circ->cpath, info);
  1874. extend_info_free(info);
  1875. return 0;
  1876. }
  1877. /** Create a new hop, annotate it with information about its
  1878. * corresponding router <b>choice</b>, and append it to the
  1879. * end of the cpath <b>head_ptr</b>. */
  1880. static int
  1881. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1882. {
  1883. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1884. /* link hop into the cpath, at the end. */
  1885. onion_append_to_cpath(head_ptr, hop);
  1886. hop->magic = CRYPT_PATH_MAGIC;
  1887. hop->state = CPATH_STATE_CLOSED;
  1888. hop->extend_info = extend_info_dup(choice);
  1889. hop->package_window = circuit_initial_package_window();
  1890. hop->deliver_window = CIRCWINDOW_START;
  1891. return 0;
  1892. }
  1893. /** Allocate a new extend_info object based on the various arguments. */
  1894. extend_info_t *
  1895. extend_info_new(const char *nickname, const char *digest,
  1896. crypto_pk_t *onion_key,
  1897. const curve25519_public_key_t *curve25519_key,
  1898. const tor_addr_t *addr, uint16_t port)
  1899. {
  1900. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  1901. memcpy(info->identity_digest, digest, DIGEST_LEN);
  1902. if (nickname)
  1903. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  1904. if (onion_key)
  1905. info->onion_key = crypto_pk_dup_key(onion_key);
  1906. #ifdef CURVE25519_ENABLED
  1907. if (curve25519_key)
  1908. memcpy(&info->curve25519_onion_key, curve25519_key,
  1909. sizeof(curve25519_public_key_t));
  1910. #else
  1911. (void)curve25519_key;
  1912. #endif
  1913. tor_addr_copy(&info->addr, addr);
  1914. info->port = port;
  1915. return info;
  1916. }
  1917. /** Allocate and return a new extend_info that can be used to build a
  1918. * circuit to or through the node <b>node</b>. Use the primary address
  1919. * of the node (i.e. its IPv4 address) unless
  1920. * <b>for_direct_connect</b> is true, in which case the preferred
  1921. * address is used instead. May return NULL if there is not enough
  1922. * info about <b>node</b> to extend to it--for example, if there is no
  1923. * routerinfo_t or microdesc_t.
  1924. **/
  1925. extend_info_t *
  1926. extend_info_from_node(const node_t *node, int for_direct_connect)
  1927. {
  1928. tor_addr_port_t ap;
  1929. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  1930. return NULL;
  1931. if (for_direct_connect)
  1932. node_get_pref_orport(node, &ap);
  1933. else
  1934. node_get_prim_orport(node, &ap);
  1935. log_debug(LD_CIRC, "using %s for %s",
  1936. fmt_addrport(&ap.addr, ap.port),
  1937. node->ri ? node->ri->nickname : node->rs->nickname);
  1938. if (node->ri)
  1939. return extend_info_new(node->ri->nickname,
  1940. node->identity,
  1941. node->ri->onion_pkey,
  1942. node->ri->onion_curve25519_pkey,
  1943. &ap.addr,
  1944. ap.port);
  1945. else if (node->rs && node->md)
  1946. return extend_info_new(node->rs->nickname,
  1947. node->identity,
  1948. node->md->onion_pkey,
  1949. node->md->onion_curve25519_pkey,
  1950. &ap.addr,
  1951. ap.port);
  1952. else
  1953. return NULL;
  1954. }
  1955. /** Release storage held by an extend_info_t struct. */
  1956. void
  1957. extend_info_free(extend_info_t *info)
  1958. {
  1959. if (!info)
  1960. return;
  1961. crypto_pk_free(info->onion_key);
  1962. tor_free(info);
  1963. }
  1964. /** Allocate and return a new extend_info_t with the same contents as
  1965. * <b>info</b>. */
  1966. extend_info_t *
  1967. extend_info_dup(extend_info_t *info)
  1968. {
  1969. extend_info_t *newinfo;
  1970. tor_assert(info);
  1971. newinfo = tor_malloc(sizeof(extend_info_t));
  1972. memcpy(newinfo, info, sizeof(extend_info_t));
  1973. if (info->onion_key)
  1974. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1975. else
  1976. newinfo->onion_key = NULL;
  1977. return newinfo;
  1978. }
  1979. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1980. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1981. * the chosen exit, return NULL.
  1982. */
  1983. const node_t *
  1984. build_state_get_exit_node(cpath_build_state_t *state)
  1985. {
  1986. if (!state || !state->chosen_exit)
  1987. return NULL;
  1988. return node_get_by_id(state->chosen_exit->identity_digest);
  1989. }
  1990. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1991. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1992. * chosen exit, return NULL.
  1993. */
  1994. const char *
  1995. build_state_get_exit_nickname(cpath_build_state_t *state)
  1996. {
  1997. if (!state || !state->chosen_exit)
  1998. return NULL;
  1999. return state->chosen_exit->nickname;
  2000. }