circuitbuild.c 73 KB

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