circuitbuild.c 77 KB

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