circuitbuild.c 75 KB

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