circuitbuild.c 78 KB

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