circuitbuild.c 83 KB

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