circuitbuild.c 75 KB

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