circuitbuild.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200
  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. const routerinfo_t *me = router_get_my_routerinfo();
  549. if (!me)
  550. return 0;
  551. control_event_server_status(LOG_NOTICE,
  552. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  553. me->address, me->or_port);
  554. if (me->dir_port) {
  555. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  556. me->address, me->dir_port);
  557. control_event_server_status(LOG_NOTICE,
  558. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  559. me->address, me->dir_port);
  560. }
  561. log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  562. "(this may take up to %d minutes -- look for log "
  563. "messages indicating success)",
  564. me->address, me->or_port,
  565. me->dir_port ? dirbuf : "",
  566. me->dir_port ? "are" : "is",
  567. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  568. return 1;
  569. }
  570. /** Return true iff we should send a create_fast cell to start building a given
  571. * circuit */
  572. static INLINE int
  573. should_use_create_fast_for_circuit(origin_circuit_t *circ)
  574. {
  575. const or_options_t *options = get_options();
  576. tor_assert(circ->cpath);
  577. tor_assert(circ->cpath->extend_info);
  578. if (!circ->cpath->extend_info->onion_key)
  579. return 1; /* our hand is forced: only a create_fast will work. */
  580. if (public_server_mode(options)) {
  581. /* We're a server, and we know an onion key. We can choose.
  582. * Prefer to blend our circuit into the other circuits we are
  583. * creating on behalf of others. */
  584. return 0;
  585. }
  586. if (options->FastFirstHopPK == -1) {
  587. /* option is "auto", so look at the consensus. */
  588. return networkstatus_get_param(NULL, "usecreatefast", 1, 0, 1);
  589. }
  590. return options->FastFirstHopPK;
  591. }
  592. /** Return true if <b>circ</b> is the type of circuit we want to count
  593. * timeouts from. In particular, we want it to have not completed yet
  594. * (already completing indicates we cannibalized it), and we want it to
  595. * have exactly three hops.
  596. */
  597. int
  598. circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
  599. {
  600. return !circ->has_opened
  601. && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
  602. }
  603. #ifdef CURVE25519_ENABLED
  604. /** Return true if the ntor handshake is enabled in the configuration, or if
  605. * it's been set to "auto" in the configuration and it's enabled in the
  606. * consensus. */
  607. static int
  608. circuits_can_use_ntor(void)
  609. {
  610. const or_options_t *options = get_options();
  611. if (options->UseNTorHandshake != -1)
  612. return options->UseNTorHandshake;
  613. return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
  614. }
  615. #endif
  616. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  617. * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
  618. * accordingly. */
  619. static void
  620. circuit_pick_create_handshake(uint8_t *cell_type_out,
  621. uint16_t *handshake_type_out,
  622. const extend_info_t *ei)
  623. {
  624. #ifdef CURVE25519_ENABLED
  625. if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
  626. CURVE25519_PUBKEY_LEN) &&
  627. circuits_can_use_ntor()) {
  628. *cell_type_out = CELL_CREATE2;
  629. *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
  630. return;
  631. }
  632. #else
  633. (void) ei;
  634. #endif
  635. *cell_type_out = CELL_CREATE;
  636. *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
  637. }
  638. /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
  639. * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
  640. * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
  641. * EXTEND cell to do so, and set *<b>cell_type_out</b> and
  642. * *<b>create_cell_type_out</b> accordingly. */
  643. static void
  644. circuit_pick_extend_handshake(uint8_t *cell_type_out,
  645. uint8_t *create_cell_type_out,
  646. uint16_t *handshake_type_out,
  647. const node_t *node_prev,
  648. const extend_info_t *ei)
  649. {
  650. uint8_t t;
  651. circuit_pick_create_handshake(&t, handshake_type_out, ei);
  652. /* XXXX024 The check for whether the node has a curve25519 key is a bad
  653. * proxy for whether it can do extend2 cells; once a version that
  654. * handles extend2 cells is out, remove it. */
  655. if (node_prev &&
  656. *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
  657. (node_has_curve25519_onion_key(node_prev) ||
  658. (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
  659. *cell_type_out = RELAY_COMMAND_EXTEND2;
  660. *create_cell_type_out = CELL_CREATE2;
  661. } else {
  662. *cell_type_out = RELAY_COMMAND_EXTEND;
  663. *create_cell_type_out = CELL_CREATE;
  664. }
  665. }
  666. /** This is the backbone function for building circuits.
  667. *
  668. * If circ's first hop is closed, then we need to build a create
  669. * cell and send it forward.
  670. *
  671. * Otherwise, we need to build a relay extend cell and send it
  672. * forward.
  673. *
  674. * Return -reason if we want to tear down circ, else return 0.
  675. */
  676. int
  677. circuit_send_next_onion_skin(origin_circuit_t *circ)
  678. {
  679. crypt_path_t *hop;
  680. const node_t *node;
  681. tor_assert(circ);
  682. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  683. /* This is the first hop. */
  684. create_cell_t cc;
  685. int fast;
  686. int len;
  687. log_debug(LD_CIRC,"First skin; sending create cell.");
  688. memset(&cc, 0, sizeof(cc));
  689. if (circ->build_state->onehop_tunnel)
  690. control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
  691. else
  692. control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
  693. node = node_get_by_id(circ->base_.n_chan->identity_digest);
  694. fast = should_use_create_fast_for_circuit(circ);
  695. if (!fast) {
  696. /* We are an OR and we know the right onion key: we should
  697. * send a create cell.
  698. */
  699. circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
  700. circ->cpath->extend_info);
  701. note_request("cell: create", 1);
  702. } else {
  703. /* We are not an OR, and we're building the first hop of a circuit to a
  704. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  705. * and a DH operation. */
  706. cc.cell_type = CELL_CREATE_FAST;
  707. cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
  708. note_request("cell: create fast", 1);
  709. }
  710. len = onion_skin_create(cc.handshake_type,
  711. circ->cpath->extend_info,
  712. &circ->cpath->handshake_state,
  713. cc.onionskin);
  714. if (len < 0) {
  715. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  716. return - END_CIRC_REASON_INTERNAL;
  717. }
  718. cc.handshake_len = len;
  719. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
  720. return - END_CIRC_REASON_RESOURCELIMIT;
  721. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  722. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  723. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  724. fast ? "CREATE_FAST" : "CREATE",
  725. node ? node_describe(node) : "<unnamed>");
  726. } else {
  727. extend_cell_t ec;
  728. int len;
  729. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  730. tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
  731. log_debug(LD_CIRC,"starting to send subsequent skin.");
  732. hop = onion_next_hop_in_cpath(circ->cpath);
  733. memset(&ec, 0, sizeof(ec));
  734. if (!hop) {
  735. /* done building the circuit. whew. */
  736. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  737. if (circuit_timeout_want_to_count_circ(circ)) {
  738. struct timeval end;
  739. long timediff;
  740. tor_gettimeofday(&end);
  741. timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
  742. /*
  743. * If the circuit build time is much greater than we would have cut
  744. * it off at, we probably had a suspend event along this codepath,
  745. * and we should discard the value.
  746. */
  747. if (timediff < 0 ||
  748. timediff > 2*get_circuit_build_close_time_ms()+1000) {
  749. log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
  750. "Assuming clock jump. Purpose %d (%s)", timediff,
  751. circ->base_.purpose,
  752. circuit_purpose_to_string(circ->base_.purpose));
  753. } else if (!circuit_build_times_disabled()) {
  754. /* Only count circuit times if the network is live */
  755. if (circuit_build_times_network_check_live(
  756. get_circuit_build_times())) {
  757. circuit_build_times_add_time(get_circuit_build_times_mutable(),
  758. (build_time_t)timediff);
  759. circuit_build_times_set_timeout(get_circuit_build_times_mutable());
  760. }
  761. if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  762. circuit_build_times_network_circ_success(
  763. get_circuit_build_times_mutable());
  764. }
  765. }
  766. }
  767. log_info(LD_CIRC,"circuit built!");
  768. circuit_reset_failure_count(0);
  769. if (circ->build_state->onehop_tunnel || circ->has_opened) {
  770. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
  771. }
  772. pathbias_count_build_success(circ);
  773. circuit_rep_hist_note_result(circ);
  774. circuit_has_opened(circ); /* do other actions as necessary */
  775. if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
  776. const or_options_t *options = get_options();
  777. can_complete_circuit=1;
  778. /* FFFF Log a count of known routers here */
  779. log_notice(LD_GENERAL,
  780. "Tor has successfully opened a circuit. "
  781. "Looks like client functionality is working.");
  782. control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
  783. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  784. clear_broken_connection_map(1);
  785. if (server_mode(options) && !check_whether_orport_reachable()) {
  786. inform_testing_reachability();
  787. consider_testing_reachability(1, 1);
  788. }
  789. }
  790. /* We're done with measurement circuits here. Just close them */
  791. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  792. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  793. }
  794. return 0;
  795. }
  796. if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
  797. log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
  798. return - END_CIRC_REASON_INTERNAL;
  799. }
  800. {
  801. const node_t *prev_node;
  802. prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
  803. circuit_pick_extend_handshake(&ec.cell_type,
  804. &ec.create_cell.cell_type,
  805. &ec.create_cell.handshake_type,
  806. prev_node,
  807. hop->extend_info);
  808. }
  809. tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
  810. ec.orport_ipv4.port = hop->extend_info->port;
  811. tor_addr_make_unspec(&ec.orport_ipv6.addr);
  812. memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
  813. len = onion_skin_create(ec.create_cell.handshake_type,
  814. hop->extend_info,
  815. &hop->handshake_state,
  816. ec.create_cell.onionskin);
  817. if (len < 0) {
  818. log_warn(LD_CIRC,"onion_skin_create failed.");
  819. return - END_CIRC_REASON_INTERNAL;
  820. }
  821. ec.create_cell.handshake_len = len;
  822. log_info(LD_CIRC,"Sending extend relay cell.");
  823. note_request("cell: extend", 1);
  824. {
  825. uint8_t command = 0;
  826. uint16_t payload_len=0;
  827. uint8_t payload[RELAY_PAYLOAD_SIZE];
  828. if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
  829. log_warn(LD_CIRC,"Couldn't format extend cell");
  830. return -END_CIRC_REASON_INTERNAL;
  831. }
  832. /* send it to hop->prev, because it will transfer
  833. * it to a create cell and then send to hop */
  834. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  835. command,
  836. (char*)payload, payload_len,
  837. hop->prev) < 0)
  838. return 0; /* circuit is closed */
  839. }
  840. hop->state = CPATH_STATE_AWAITING_KEYS;
  841. }
  842. return 0;
  843. }
  844. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  845. * something has also gone wrong with our network: notify the user,
  846. * and abandon all not-yet-used circuits. */
  847. void
  848. circuit_note_clock_jumped(int seconds_elapsed)
  849. {
  850. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  851. tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  852. "assuming established circuits no longer work.",
  853. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  854. seconds_elapsed >=0 ? "forward" : "backward");
  855. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  856. seconds_elapsed);
  857. can_complete_circuit=0; /* so it'll log when it works again */
  858. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  859. "CLOCK_JUMPED");
  860. circuit_mark_all_unused_circs();
  861. circuit_mark_all_dirty_circs_as_unusable();
  862. }
  863. /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
  864. * skin and identity digest for the next hop. If we're already connected,
  865. * pass the onion skin to the next hop using a create cell; otherwise
  866. * launch a new OR connection, and <b>circ</b> will notice when the
  867. * connection succeeds or fails.
  868. *
  869. * Return -1 if we want to warn and tear down the circuit, else return 0.
  870. */
  871. int
  872. circuit_extend(cell_t *cell, circuit_t *circ)
  873. {
  874. channel_t *n_chan;
  875. relay_header_t rh;
  876. extend_cell_t ec;
  877. const char *msg = NULL;
  878. int should_launch = 0;
  879. if (circ->n_chan) {
  880. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  881. "n_chan already set. Bug/attack. Closing.");
  882. return -1;
  883. }
  884. if (circ->n_hop) {
  885. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  886. "conn to next hop already launched. Bug/attack. Closing.");
  887. return -1;
  888. }
  889. if (!server_mode(get_options())) {
  890. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  891. "Got an extend cell, but running as a client. Closing.");
  892. return -1;
  893. }
  894. relay_header_unpack(&rh, cell->payload);
  895. if (extend_cell_parse(&ec, rh.command,
  896. cell->payload+RELAY_HEADER_SIZE,
  897. rh.length) < 0) {
  898. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  899. "Can't parse extend cell. Closing circuit.");
  900. return -1;
  901. }
  902. if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
  903. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  904. "Client asked me to extend to zero destination port or addr.");
  905. return -1;
  906. }
  907. if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
  908. !get_options()->ExtendAllowPrivateAddresses) {
  909. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  910. "Client asked me to extend to a private address");
  911. return -1;
  912. }
  913. /* Check if they asked us for 0000..0000. We support using
  914. * an empty fingerprint for the first hop (e.g. for a bridge relay),
  915. * but we don't want to let people send us extend cells for empty
  916. * fingerprints -- a) because it opens the user up to a mitm attack,
  917. * and b) because it lets an attacker force the relay to hold open a
  918. * new TLS connection for each extend request. */
  919. if (tor_digest_is_zero((const char*)ec.node_id)) {
  920. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  921. "Client asked me to extend without specifying an id_digest.");
  922. return -1;
  923. }
  924. /* Next, check if we're being asked to connect to the hop that the
  925. * extend cell came from. There isn't any reason for that, and it can
  926. * assist circular-path attacks. */
  927. if (tor_memeq(ec.node_id,
  928. TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
  929. DIGEST_LEN)) {
  930. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  931. "Client asked me to extend back to the previous hop.");
  932. return -1;
  933. }
  934. n_chan = channel_get_for_extend((const char*)ec.node_id,
  935. &ec.orport_ipv4.addr,
  936. &msg,
  937. &should_launch);
  938. if (!n_chan) {
  939. log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
  940. fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
  941. msg?msg:"????");
  942. circ->n_hop = extend_info_new(NULL /*nickname*/,
  943. (const char*)ec.node_id,
  944. NULL /*onion_key*/,
  945. NULL /*curve25519_key*/,
  946. &ec.orport_ipv4.addr,
  947. ec.orport_ipv4.port);
  948. circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
  949. sizeof(ec.create_cell));
  950. circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
  951. if (should_launch) {
  952. /* we should try to open a connection */
  953. n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
  954. ec.orport_ipv4.port,
  955. (const char*)ec.node_id);
  956. if (!n_chan) {
  957. log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
  958. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  959. return 0;
  960. }
  961. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  962. }
  963. /* return success. The onion/circuit/etc will be taken care of
  964. * automatically (may already have been) whenever n_chan reaches
  965. * OR_CONN_STATE_OPEN.
  966. */
  967. return 0;
  968. }
  969. tor_assert(!circ->n_hop); /* Connection is already established. */
  970. circ->n_chan = n_chan;
  971. log_debug(LD_CIRC,
  972. "n_chan is %s",
  973. channel_get_canonical_remote_descr(n_chan));
  974. if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
  975. return -1;
  976. return 0;
  977. }
  978. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  979. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  980. * used as follows:
  981. * - 20 to initialize f_digest
  982. * - 20 to initialize b_digest
  983. * - 16 to key f_crypto
  984. * - 16 to key b_crypto
  985. *
  986. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  987. */
  988. int
  989. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  990. int reverse)
  991. {
  992. crypto_digest_t *tmp_digest;
  993. crypto_cipher_t *tmp_crypto;
  994. tor_assert(cpath);
  995. tor_assert(key_data);
  996. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  997. cpath->f_digest || cpath->b_digest));
  998. cpath->f_digest = crypto_digest_new();
  999. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  1000. cpath->b_digest = crypto_digest_new();
  1001. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  1002. if (!(cpath->f_crypto =
  1003. crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
  1004. log_warn(LD_BUG,"Forward cipher initialization failed.");
  1005. return -1;
  1006. }
  1007. if (!(cpath->b_crypto =
  1008. crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
  1009. log_warn(LD_BUG,"Backward cipher initialization failed.");
  1010. return -1;
  1011. }
  1012. if (reverse) {
  1013. tmp_digest = cpath->f_digest;
  1014. cpath->f_digest = cpath->b_digest;
  1015. cpath->b_digest = tmp_digest;
  1016. tmp_crypto = cpath->f_crypto;
  1017. cpath->f_crypto = cpath->b_crypto;
  1018. cpath->b_crypto = tmp_crypto;
  1019. }
  1020. return 0;
  1021. }
  1022. /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
  1023. * (The body of <b>reply</b> varies depending on what sort of handshake
  1024. * this is.)
  1025. *
  1026. * Calculate the appropriate keys and digests, make sure KH is
  1027. * correct, and initialize this hop of the cpath.
  1028. *
  1029. * Return - reason if we want to mark circ for close, else return 0.
  1030. */
  1031. int
  1032. circuit_finish_handshake(origin_circuit_t *circ,
  1033. const created_cell_t *reply)
  1034. {
  1035. char keys[CPATH_KEY_MATERIAL_LEN];
  1036. crypt_path_t *hop;
  1037. int rv;
  1038. if ((rv = pathbias_count_build_attempt(circ)) < 0)
  1039. return rv;
  1040. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
  1041. hop = circ->cpath;
  1042. } else {
  1043. hop = onion_next_hop_in_cpath(circ->cpath);
  1044. if (!hop) { /* got an extended when we're all done? */
  1045. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  1046. return - END_CIRC_REASON_TORPROTOCOL;
  1047. }
  1048. }
  1049. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1050. {
  1051. if (onion_skin_client_handshake(hop->handshake_state.tag,
  1052. &hop->handshake_state,
  1053. reply->reply, reply->handshake_len,
  1054. (uint8_t*)keys, sizeof(keys),
  1055. (uint8_t*)hop->rend_circ_nonce) < 0) {
  1056. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  1057. return -END_CIRC_REASON_TORPROTOCOL;
  1058. }
  1059. }
  1060. onion_handshake_state_release(&hop->handshake_state);
  1061. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1062. return -END_CIRC_REASON_TORPROTOCOL;
  1063. }
  1064. hop->state = CPATH_STATE_OPEN;
  1065. log_info(LD_CIRC,"Finished building circuit hop:");
  1066. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  1067. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  1068. return 0;
  1069. }
  1070. /** We received a relay truncated cell on circ.
  1071. *
  1072. * Since we don't send truncates currently, getting a truncated
  1073. * means that a connection broke or an extend failed. For now,
  1074. * just give up: force circ to close, and return 0.
  1075. */
  1076. int
  1077. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
  1078. {
  1079. // crypt_path_t *victim;
  1080. // connection_t *stream;
  1081. tor_assert(circ);
  1082. tor_assert(layer);
  1083. /* XXX Since we don't send truncates currently, getting a truncated
  1084. * means that a connection broke or an extend failed. For now,
  1085. * just give up.
  1086. */
  1087. circuit_mark_for_close(TO_CIRCUIT(circ),
  1088. END_CIRC_REASON_FLAG_REMOTE|reason);
  1089. return 0;
  1090. #if 0
  1091. while (layer->next != circ->cpath) {
  1092. /* we need to clear out layer->next */
  1093. victim = layer->next;
  1094. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  1095. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  1096. if (stream->cpath_layer == victim) {
  1097. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  1098. stream->stream_id);
  1099. /* no need to send 'end' relay cells,
  1100. * because the other side's already dead
  1101. */
  1102. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  1103. }
  1104. }
  1105. layer->next = victim->next;
  1106. circuit_free_cpath_node(victim);
  1107. }
  1108. log_info(LD_CIRC, "finished");
  1109. return 0;
  1110. #endif
  1111. }
  1112. /** Given a response payload and keys, initialize, then send a created
  1113. * cell back.
  1114. */
  1115. int
  1116. onionskin_answer(or_circuit_t *circ,
  1117. const created_cell_t *created_cell,
  1118. const char *keys,
  1119. const uint8_t *rend_circ_nonce)
  1120. {
  1121. cell_t cell;
  1122. crypt_path_t *tmp_cpath;
  1123. if (created_cell_format(&cell, created_cell) < 0) {
  1124. log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
  1125. (int)created_cell->cell_type, (int)created_cell->handshake_len);
  1126. return -1;
  1127. }
  1128. cell.circ_id = circ->p_circ_id;
  1129. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  1130. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  1131. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  1132. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  1133. (unsigned int)get_uint32(keys),
  1134. (unsigned int)get_uint32(keys+20));
  1135. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  1136. log_warn(LD_BUG,"Circuit initialization failed");
  1137. tor_free(tmp_cpath);
  1138. return -1;
  1139. }
  1140. circ->n_digest = tmp_cpath->f_digest;
  1141. circ->n_crypto = tmp_cpath->f_crypto;
  1142. circ->p_digest = tmp_cpath->b_digest;
  1143. circ->p_crypto = tmp_cpath->b_crypto;
  1144. tmp_cpath->magic = 0;
  1145. tor_free(tmp_cpath);
  1146. memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
  1147. circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
  1148. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  1149. circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
  1150. log_debug(LD_CIRC,"Finished sending '%s' cell.",
  1151. circ->is_first_hop ? "created_fast" : "created");
  1152. if (!channel_is_local(circ->p_chan) &&
  1153. !channel_is_outgoing(circ->p_chan)) {
  1154. /* record that we could process create cells from a non-local conn
  1155. * that we didn't initiate; presumably this means that create cells
  1156. * can reach us too. */
  1157. router_orport_found_reachable();
  1158. }
  1159. return 0;
  1160. }
  1161. /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
  1162. * number of endpoints that would give something away about our destination.
  1163. *
  1164. * If the routerlist <b>nodes</b> doesn't have enough routers
  1165. * to handle the desired path length, return -1.
  1166. */
  1167. static int
  1168. new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
  1169. {
  1170. int num_acceptable_routers;
  1171. int routelen;
  1172. tor_assert(nodes);
  1173. routelen = DEFAULT_ROUTE_LEN;
  1174. if (exit &&
  1175. purpose != CIRCUIT_PURPOSE_TESTING &&
  1176. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  1177. routelen++;
  1178. num_acceptable_routers = count_acceptable_nodes(nodes);
  1179. log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
  1180. routelen, num_acceptable_routers, smartlist_len(nodes));
  1181. if (num_acceptable_routers < routelen) {
  1182. log_info(LD_CIRC,
  1183. "Not enough acceptable routers (%d/%d). Discarding this circuit.",
  1184. num_acceptable_routers, routelen);
  1185. return -1;
  1186. }
  1187. return routelen;
  1188. }
  1189. /** Return a newly allocated list of uint16_t * for each predicted port not
  1190. * handled by a current circuit. */
  1191. static smartlist_t *
  1192. circuit_get_unhandled_ports(time_t now)
  1193. {
  1194. smartlist_t *dest = rep_hist_get_predicted_ports(now);
  1195. circuit_remove_handled_ports(dest);
  1196. return dest;
  1197. }
  1198. /** Return 1 if we already have circuits present or on the way for
  1199. * all anticipated ports. Return 0 if we should make more.
  1200. *
  1201. * If we're returning 0, set need_uptime and need_capacity to
  1202. * indicate any requirements that the unhandled ports have.
  1203. */
  1204. int
  1205. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  1206. int *need_capacity)
  1207. {
  1208. int i, enough;
  1209. uint16_t *port;
  1210. smartlist_t *sl = circuit_get_unhandled_ports(now);
  1211. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  1212. tor_assert(need_uptime);
  1213. tor_assert(need_capacity);
  1214. // Always predict need_capacity
  1215. *need_capacity = 1;
  1216. enough = (smartlist_len(sl) == 0);
  1217. for (i = 0; i < smartlist_len(sl); ++i) {
  1218. port = smartlist_get(sl, i);
  1219. if (smartlist_contains_int_as_string(LongLivedServices, *port))
  1220. *need_uptime = 1;
  1221. tor_free(port);
  1222. }
  1223. smartlist_free(sl);
  1224. return enough;
  1225. }
  1226. /** Return 1 if <b>node</b> can handle one or more of the ports in
  1227. * <b>needed_ports</b>, else return 0.
  1228. */
  1229. static int
  1230. node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
  1231. { /* XXXX MOVE */
  1232. int i;
  1233. uint16_t port;
  1234. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1235. addr_policy_result_t r;
  1236. /* alignment issues aren't a worry for this dereference, since
  1237. needed_ports is explicitly a smartlist of uint16_t's */
  1238. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1239. tor_assert(port);
  1240. if (node)
  1241. r = compare_tor_addr_to_node_policy(NULL, port, node);
  1242. else
  1243. continue;
  1244. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1245. return 1;
  1246. }
  1247. return 0;
  1248. }
  1249. /** Return true iff <b>conn</b> needs another general circuit to be
  1250. * built. */
  1251. static int
  1252. ap_stream_wants_exit_attention(connection_t *conn)
  1253. {
  1254. entry_connection_t *entry;
  1255. if (conn->type != CONN_TYPE_AP)
  1256. return 0;
  1257. entry = TO_ENTRY_CONN(conn);
  1258. if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1259. !conn->marked_for_close &&
  1260. !(entry->want_onehop) && /* ignore one-hop streams */
  1261. !(entry->use_begindir) && /* ignore targeted dir fetches */
  1262. !(entry->chosen_exit_name) && /* ignore defined streams */
  1263. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1264. !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
  1265. MIN_CIRCUITS_HANDLING_STREAM))
  1266. return 1;
  1267. return 0;
  1268. }
  1269. /** Return a pointer to a suitable router to be the exit node for the
  1270. * general-purpose circuit we're about to build.
  1271. *
  1272. * Look through the connection array, and choose a router that maximizes
  1273. * the number of pending streams that can exit from this router.
  1274. *
  1275. * Return NULL if we can't find any suitable routers.
  1276. */
  1277. static const node_t *
  1278. choose_good_exit_server_general(int need_uptime, int need_capacity)
  1279. {
  1280. int *n_supported;
  1281. int n_pending_connections = 0;
  1282. smartlist_t *connections;
  1283. int best_support = -1;
  1284. int n_best_support=0;
  1285. const or_options_t *options = get_options();
  1286. const smartlist_t *the_nodes;
  1287. const node_t *node=NULL;
  1288. connections = get_connection_array();
  1289. /* Count how many connections are waiting for a circuit to be built.
  1290. * We use this for log messages now, but in the future we may depend on it.
  1291. */
  1292. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1293. {
  1294. if (ap_stream_wants_exit_attention(conn))
  1295. ++n_pending_connections;
  1296. });
  1297. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1298. // n_pending_connections);
  1299. /* Now we count, for each of the routers in the directory, how many
  1300. * of the pending connections could possibly exit from that
  1301. * router (n_supported[i]). (We can't be sure about cases where we
  1302. * don't know the IP address of the pending connection.)
  1303. *
  1304. * -1 means "Don't use this router at all."
  1305. */
  1306. the_nodes = nodelist_get_list();
  1307. n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
  1308. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1309. const int i = node_sl_idx;
  1310. if (router_digest_is_me(node->identity)) {
  1311. n_supported[i] = -1;
  1312. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1313. /* XXX there's probably a reverse predecessor attack here, but
  1314. * it's slow. should we take this out? -RD
  1315. */
  1316. continue;
  1317. }
  1318. if (!node_has_descriptor(node)) {
  1319. n_supported[i] = -1;
  1320. continue;
  1321. }
  1322. if (!node->is_running || node->is_bad_exit) {
  1323. n_supported[i] = -1;
  1324. continue; /* skip routers that are known to be down or bad exits */
  1325. }
  1326. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  1327. /* never pick a non-general node as a random exit. */
  1328. n_supported[i] = -1;
  1329. continue;
  1330. }
  1331. if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
  1332. n_supported[i] = -1;
  1333. continue; /* user asked us not to use it, no matter what */
  1334. }
  1335. if (options->ExitNodes &&
  1336. !routerset_contains_node(options->ExitNodes, node)) {
  1337. n_supported[i] = -1;
  1338. continue; /* not one of our chosen exit nodes */
  1339. }
  1340. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  1341. n_supported[i] = -1;
  1342. continue; /* skip routers that are not suitable. Don't worry if
  1343. * this makes us reject all the possible routers: if so,
  1344. * we'll retry later in this function with need_update and
  1345. * need_capacity set to 0. */
  1346. }
  1347. if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
  1348. /* if it's invalid and we don't want it */
  1349. n_supported[i] = -1;
  1350. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1351. // router->nickname, i);
  1352. continue; /* skip invalid routers */
  1353. }
  1354. if (options->ExcludeSingleHopRelays &&
  1355. node_allows_single_hop_exits(node)) {
  1356. n_supported[i] = -1;
  1357. continue;
  1358. }
  1359. if (node_exit_policy_rejects_all(node)) {
  1360. n_supported[i] = -1;
  1361. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1362. // router->nickname, i);
  1363. continue; /* skip routers that reject all */
  1364. }
  1365. n_supported[i] = 0;
  1366. /* iterate over connections */
  1367. SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
  1368. if (!ap_stream_wants_exit_attention(conn))
  1369. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1370. if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
  1371. ++n_supported[i];
  1372. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1373. // router->nickname, i, n_supported[i]);
  1374. } else {
  1375. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1376. // router->nickname, i);
  1377. }
  1378. } SMARTLIST_FOREACH_END(conn);
  1379. if (n_pending_connections > 0 && n_supported[i] == 0) {
  1380. /* Leave best_support at -1 if that's where it is, so we can
  1381. * distinguish it later. */
  1382. continue;
  1383. }
  1384. if (n_supported[i] > best_support) {
  1385. /* If this router is better than previous ones, remember its index
  1386. * and goodness, and start counting how many routers are this good. */
  1387. best_support = n_supported[i]; n_best_support=1;
  1388. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1389. // router->nickname);
  1390. } else if (n_supported[i] == best_support) {
  1391. /* If this router is _as good_ as the best one, just increment the
  1392. * count of equally good routers.*/
  1393. ++n_best_support;
  1394. }
  1395. } SMARTLIST_FOREACH_END(node);
  1396. log_info(LD_CIRC,
  1397. "Found %d servers that might support %d/%d pending connections.",
  1398. n_best_support, best_support >= 0 ? best_support : 0,
  1399. n_pending_connections);
  1400. /* If any routers definitely support any pending connections, choose one
  1401. * at random. */
  1402. if (best_support > 0) {
  1403. smartlist_t *supporting = smartlist_new();
  1404. SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
  1405. if (n_supported[node_sl_idx] == best_support)
  1406. smartlist_add(supporting, (void*)node);
  1407. });
  1408. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1409. smartlist_free(supporting);
  1410. } else {
  1411. /* Either there are no pending connections, or no routers even seem to
  1412. * possibly support any of them. Choose a router at random that satisfies
  1413. * at least one predicted exit port. */
  1414. int attempt;
  1415. smartlist_t *needed_ports, *supporting;
  1416. if (best_support == -1) {
  1417. if (need_uptime || need_capacity) {
  1418. log_info(LD_CIRC,
  1419. "We couldn't find any live%s%s routers; falling back "
  1420. "to list of all routers.",
  1421. need_capacity?", fast":"",
  1422. need_uptime?", stable":"");
  1423. tor_free(n_supported);
  1424. return choose_good_exit_server_general(0, 0);
  1425. }
  1426. log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
  1427. "choosing a doomed exit at random.",
  1428. options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
  1429. }
  1430. supporting = smartlist_new();
  1431. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1432. for (attempt = 0; attempt < 2; attempt++) {
  1433. /* try once to pick only from routers that satisfy a needed port,
  1434. * then if there are none, pick from any that support exiting. */
  1435. SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
  1436. if (n_supported[node_sl_idx] != -1 &&
  1437. (attempt || node_handles_some_port(node, needed_ports))) {
  1438. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1439. // try, router->nickname);
  1440. smartlist_add(supporting, (void*)node);
  1441. }
  1442. } SMARTLIST_FOREACH_END(node);
  1443. node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
  1444. if (node)
  1445. break;
  1446. smartlist_clear(supporting);
  1447. /* If we reach this point, we can't actually support any unhandled
  1448. * predicted ports, so clear all the remaining ones. */
  1449. if (smartlist_len(needed_ports))
  1450. rep_hist_remove_predicted_ports(needed_ports);
  1451. }
  1452. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1453. smartlist_free(needed_ports);
  1454. smartlist_free(supporting);
  1455. }
  1456. tor_free(n_supported);
  1457. if (node) {
  1458. log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
  1459. return node;
  1460. }
  1461. if (options->ExitNodes) {
  1462. log_warn(LD_CIRC,
  1463. "No specified %sexit routers seem to be running: "
  1464. "can't choose an exit.",
  1465. options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
  1466. }
  1467. return NULL;
  1468. }
  1469. /** Return a pointer to a suitable router to be the exit node for the
  1470. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1471. * if no router is suitable).
  1472. *
  1473. * For general-purpose circuits, pass it off to
  1474. * choose_good_exit_server_general()
  1475. *
  1476. * For client-side rendezvous circuits, choose a random node, weighted
  1477. * toward the preferences in 'options'.
  1478. */
  1479. static const node_t *
  1480. choose_good_exit_server(uint8_t purpose,
  1481. int need_uptime, int need_capacity, int is_internal)
  1482. {
  1483. const or_options_t *options = get_options();
  1484. router_crn_flags_t flags = CRN_NEED_DESC;
  1485. if (need_uptime)
  1486. flags |= CRN_NEED_UPTIME;
  1487. if (need_capacity)
  1488. flags |= CRN_NEED_CAPACITY;
  1489. switch (purpose) {
  1490. case CIRCUIT_PURPOSE_C_GENERAL:
  1491. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1492. flags |= CRN_ALLOW_INVALID;
  1493. if (is_internal) /* pick it like a middle hop */
  1494. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1495. else
  1496. return choose_good_exit_server_general(need_uptime,need_capacity);
  1497. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1498. if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
  1499. flags |= CRN_ALLOW_INVALID;
  1500. return router_choose_random_node(NULL, options->ExcludeNodes, flags);
  1501. }
  1502. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1503. tor_fragile_assert();
  1504. return NULL;
  1505. }
  1506. /** Log a warning if the user specified an exit for the circuit that
  1507. * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
  1508. static void
  1509. warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
  1510. {
  1511. const or_options_t *options = get_options();
  1512. routerset_t *rs = options->ExcludeNodes;
  1513. const char *description;
  1514. uint8_t purpose = circ->base_.purpose;
  1515. if (circ->build_state->onehop_tunnel)
  1516. return;
  1517. switch (purpose)
  1518. {
  1519. default:
  1520. case CIRCUIT_PURPOSE_OR:
  1521. case CIRCUIT_PURPOSE_INTRO_POINT:
  1522. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  1523. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  1524. log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
  1525. (int)purpose,
  1526. circuit_purpose_to_string(purpose));
  1527. return;
  1528. case CIRCUIT_PURPOSE_C_GENERAL:
  1529. if (circ->build_state->is_internal)
  1530. return;
  1531. description = "requested exit node";
  1532. rs = options->ExcludeExitNodesUnion_;
  1533. break;
  1534. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1535. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  1536. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  1537. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1538. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1539. case CIRCUIT_PURPOSE_S_REND_JOINED:
  1540. case CIRCUIT_PURPOSE_TESTING:
  1541. return;
  1542. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1543. case CIRCUIT_PURPOSE_C_REND_READY:
  1544. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  1545. case CIRCUIT_PURPOSE_C_REND_JOINED:
  1546. description = "chosen rendezvous point";
  1547. break;
  1548. case CIRCUIT_PURPOSE_CONTROLLER:
  1549. rs = options->ExcludeExitNodesUnion_;
  1550. description = "controller-selected circuit target";
  1551. break;
  1552. }
  1553. if (routerset_contains_extendinfo(rs, exit)) {
  1554. /* We should never get here if StrictNodes is set to 1. */
  1555. if (options->StrictNodes) {
  1556. log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
  1557. "even though StrictNodes is set. Please report. "
  1558. "(Circuit purpose: %s)",
  1559. description, extend_info_describe(exit),
  1560. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1561. circuit_purpose_to_string(purpose));
  1562. } else {
  1563. log_warn(LD_CIRC, "Using %s '%s' which is listed in "
  1564. "ExcludeNodes%s, because no better options were available. To "
  1565. "prevent this (and possibly break your Tor functionality), "
  1566. "set the StrictNodes configuration option. "
  1567. "(Circuit purpose: %s)",
  1568. description, extend_info_describe(exit),
  1569. rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
  1570. circuit_purpose_to_string(purpose));
  1571. }
  1572. circuit_log_path(LOG_WARN, LD_CIRC, circ);
  1573. }
  1574. return;
  1575. }
  1576. /** Decide a suitable length for circ's cpath, and pick an exit
  1577. * router (or use <b>exit</b> if provided). Store these in the
  1578. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1579. static int
  1580. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1581. {
  1582. cpath_build_state_t *state = circ->build_state;
  1583. if (state->onehop_tunnel) {
  1584. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1585. state->desired_path_len = 1;
  1586. } else {
  1587. int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
  1588. if (r < 1) /* must be at least 1 */
  1589. return -1;
  1590. state->desired_path_len = r;
  1591. }
  1592. if (exit) { /* the circuit-builder pre-requested one */
  1593. warn_if_last_router_excluded(circ, exit);
  1594. log_info(LD_CIRC,"Using requested exit node '%s'",
  1595. extend_info_describe(exit));
  1596. exit = extend_info_dup(exit);
  1597. } else { /* we have to decide one */
  1598. const node_t *node =
  1599. choose_good_exit_server(circ->base_.purpose, state->need_uptime,
  1600. state->need_capacity, state->is_internal);
  1601. if (!node) {
  1602. log_warn(LD_CIRC,"failed to choose an exit server");
  1603. return -1;
  1604. }
  1605. exit = extend_info_from_node(node, 0);
  1606. tor_assert(exit);
  1607. }
  1608. state->chosen_exit = exit;
  1609. return 0;
  1610. }
  1611. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1612. * hop to the cpath reflecting this. Don't send the next extend cell --
  1613. * the caller will do this if it wants to.
  1614. */
  1615. int
  1616. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1617. {
  1618. cpath_build_state_t *state;
  1619. tor_assert(exit);
  1620. tor_assert(circ);
  1621. state = circ->build_state;
  1622. tor_assert(state);
  1623. extend_info_free(state->chosen_exit);
  1624. state->chosen_exit = extend_info_dup(exit);
  1625. ++circ->build_state->desired_path_len;
  1626. onion_append_hop(&circ->cpath, exit);
  1627. return 0;
  1628. }
  1629. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1630. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1631. * send the next extend cell to begin connecting to that hop.
  1632. */
  1633. int
  1634. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1635. {
  1636. int err_reason = 0;
  1637. warn_if_last_router_excluded(circ, exit);
  1638. tor_gettimeofday(&circ->base_.timestamp_began);
  1639. circuit_append_new_exit(circ, exit);
  1640. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1641. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1642. log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
  1643. extend_info_describe(exit));
  1644. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1645. return -1;
  1646. }
  1647. // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
  1648. return 0;
  1649. }
  1650. /** Return the number of routers in <b>routers</b> that are currently up
  1651. * and available for building circuits through.
  1652. */
  1653. static int
  1654. count_acceptable_nodes(smartlist_t *nodes)
  1655. {
  1656. int num=0;
  1657. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  1658. // log_debug(LD_CIRC,
  1659. // "Contemplating whether router %d (%s) is a new option.",
  1660. // i, r->nickname);
  1661. if (! node->is_running)
  1662. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1663. continue;
  1664. if (! node->is_valid)
  1665. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1666. continue;
  1667. if (! node_has_descriptor(node))
  1668. continue;
  1669. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1670. * allows this node in some places, then we're getting an inaccurate
  1671. * count. For now, be conservative and don't count it. But later we
  1672. * should try to be smarter. */
  1673. ++num;
  1674. } SMARTLIST_FOREACH_END(node);
  1675. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1676. return num;
  1677. }
  1678. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1679. * This function is used to extend cpath by another hop.
  1680. */
  1681. void
  1682. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1683. {
  1684. if (*head_ptr) {
  1685. new_hop->next = (*head_ptr);
  1686. new_hop->prev = (*head_ptr)->prev;
  1687. (*head_ptr)->prev->next = new_hop;
  1688. (*head_ptr)->prev = new_hop;
  1689. } else {
  1690. *head_ptr = new_hop;
  1691. new_hop->prev = new_hop->next = new_hop;
  1692. }
  1693. }
  1694. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1695. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1696. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1697. * circuit. In particular, make sure we don't pick the exit node or its
  1698. * family, and make sure we don't duplicate any previous nodes or their
  1699. * families. */
  1700. static const node_t *
  1701. choose_good_middle_server(uint8_t purpose,
  1702. cpath_build_state_t *state,
  1703. crypt_path_t *head,
  1704. int cur_len)
  1705. {
  1706. int i;
  1707. const node_t *r, *choice;
  1708. crypt_path_t *cpath;
  1709. smartlist_t *excluded;
  1710. const or_options_t *options = get_options();
  1711. router_crn_flags_t flags = CRN_NEED_DESC;
  1712. tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
  1713. purpose <= CIRCUIT_PURPOSE_MAX_);
  1714. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1715. excluded = smartlist_new();
  1716. if ((r = build_state_get_exit_node(state))) {
  1717. nodelist_add_node_and_family(excluded, r);
  1718. }
  1719. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1720. if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
  1721. nodelist_add_node_and_family(excluded, r);
  1722. }
  1723. }
  1724. if (state->need_uptime)
  1725. flags |= CRN_NEED_UPTIME;
  1726. if (state->need_capacity)
  1727. flags |= CRN_NEED_CAPACITY;
  1728. if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
  1729. flags |= CRN_ALLOW_INVALID;
  1730. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1731. smartlist_free(excluded);
  1732. return choice;
  1733. }
  1734. /** Pick a good entry server for the circuit to be built according to
  1735. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1736. * router (if we're an OR), and respect firewall settings; if we're
  1737. * configured to use entry guards, return one.
  1738. *
  1739. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1740. * guard, not for any particular circuit.
  1741. */
  1742. /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
  1743. const node_t *
  1744. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1745. {
  1746. const node_t *choice;
  1747. smartlist_t *excluded;
  1748. const or_options_t *options = get_options();
  1749. router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
  1750. const node_t *node;
  1751. if (state && options->UseEntryGuards &&
  1752. (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
  1753. /* This request is for an entry server to use for a regular circuit,
  1754. * and we use entry guard nodes. Just return one of the guard nodes. */
  1755. return choose_random_entry(state);
  1756. }
  1757. excluded = smartlist_new();
  1758. if (state && (node = build_state_get_exit_node(state))) {
  1759. /* Exclude the exit node from the state, if we have one. Also exclude its
  1760. * family. */
  1761. nodelist_add_node_and_family(excluded, node);
  1762. }
  1763. if (firewall_is_fascist_or()) {
  1764. /* Exclude all ORs that we can't reach through our firewall */
  1765. smartlist_t *nodes = nodelist_get_list();
  1766. SMARTLIST_FOREACH(nodes, const node_t *, node, {
  1767. if (!fascist_firewall_allows_node(node))
  1768. smartlist_add(excluded, (void*)node);
  1769. });
  1770. }
  1771. /* and exclude current entry guards and their families, if applicable */
  1772. /*XXXX025 use the using_as_guard flag to accomplish this.*/
  1773. if (options->UseEntryGuards) {
  1774. SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
  1775. {
  1776. if ((node = node_get_by_id(entry->identity))) {
  1777. nodelist_add_node_and_family(excluded, node);
  1778. }
  1779. });
  1780. }
  1781. if (state) {
  1782. if (state->need_uptime)
  1783. flags |= CRN_NEED_UPTIME;
  1784. if (state->need_capacity)
  1785. flags |= CRN_NEED_CAPACITY;
  1786. }
  1787. if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
  1788. flags |= CRN_ALLOW_INVALID;
  1789. choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
  1790. smartlist_free(excluded);
  1791. return choice;
  1792. }
  1793. /** Return the first non-open hop in cpath, or return NULL if all
  1794. * hops are open. */
  1795. static crypt_path_t *
  1796. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1797. {
  1798. crypt_path_t *hop = cpath;
  1799. do {
  1800. if (hop->state != CPATH_STATE_OPEN)
  1801. return hop;
  1802. hop = hop->next;
  1803. } while (hop != cpath);
  1804. return NULL;
  1805. }
  1806. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1807. * based on <b>state</b>. Append the hop info to head_ptr.
  1808. *
  1809. * Return 1 if the path is complete, 0 if we successfully added a hop,
  1810. * and -1 on error.
  1811. */
  1812. static int
  1813. onion_extend_cpath(origin_circuit_t *circ)
  1814. {
  1815. uint8_t purpose = circ->base_.purpose;
  1816. cpath_build_state_t *state = circ->build_state;
  1817. int cur_len = circuit_get_cpath_len(circ);
  1818. extend_info_t *info = NULL;
  1819. if (cur_len >= state->desired_path_len) {
  1820. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1821. state->desired_path_len);
  1822. return 1;
  1823. }
  1824. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1825. state->desired_path_len);
  1826. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1827. info = extend_info_dup(state->chosen_exit);
  1828. } else if (cur_len == 0) { /* picking first node */
  1829. const node_t *r = choose_good_entry_server(purpose, state);
  1830. if (r) {
  1831. /* If we're a client, use the preferred address rather than the
  1832. primary address, for potentially connecting to an IPv6 OR
  1833. port. */
  1834. info = extend_info_from_node(r, server_mode(get_options()) == 0);
  1835. tor_assert(info);
  1836. }
  1837. } else {
  1838. const node_t *r =
  1839. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1840. if (r) {
  1841. info = extend_info_from_node(r, 0);
  1842. tor_assert(info);
  1843. }
  1844. }
  1845. if (!info) {
  1846. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1847. "this circuit.", cur_len);
  1848. return -1;
  1849. }
  1850. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1851. extend_info_describe(info),
  1852. cur_len+1, build_state_get_exit_nickname(state));
  1853. onion_append_hop(&circ->cpath, info);
  1854. extend_info_free(info);
  1855. return 0;
  1856. }
  1857. /** Create a new hop, annotate it with information about its
  1858. * corresponding router <b>choice</b>, and append it to the
  1859. * end of the cpath <b>head_ptr</b>. */
  1860. static int
  1861. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1862. {
  1863. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1864. /* link hop into the cpath, at the end. */
  1865. onion_append_to_cpath(head_ptr, hop);
  1866. hop->magic = CRYPT_PATH_MAGIC;
  1867. hop->state = CPATH_STATE_CLOSED;
  1868. hop->extend_info = extend_info_dup(choice);
  1869. hop->package_window = circuit_initial_package_window();
  1870. hop->deliver_window = CIRCWINDOW_START;
  1871. return 0;
  1872. }
  1873. /** Allocate a new extend_info object based on the various arguments. */
  1874. extend_info_t *
  1875. extend_info_new(const char *nickname, const char *digest,
  1876. crypto_pk_t *onion_key,
  1877. const curve25519_public_key_t *curve25519_key,
  1878. const tor_addr_t *addr, uint16_t port)
  1879. {
  1880. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  1881. memcpy(info->identity_digest, digest, DIGEST_LEN);
  1882. if (nickname)
  1883. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  1884. if (onion_key)
  1885. info->onion_key = crypto_pk_dup_key(onion_key);
  1886. #ifdef CURVE25519_ENABLED
  1887. if (curve25519_key)
  1888. memcpy(&info->curve25519_onion_key, curve25519_key,
  1889. sizeof(curve25519_public_key_t));
  1890. #else
  1891. (void)curve25519_key;
  1892. #endif
  1893. tor_addr_copy(&info->addr, addr);
  1894. info->port = port;
  1895. return info;
  1896. }
  1897. /** Allocate and return a new extend_info that can be used to build a
  1898. * circuit to or through the node <b>node</b>. Use the primary address
  1899. * of the node (i.e. its IPv4 address) unless
  1900. * <b>for_direct_connect</b> is true, in which case the preferred
  1901. * address is used instead. May return NULL if there is not enough
  1902. * info about <b>node</b> to extend to it--for example, if there is no
  1903. * routerinfo_t or microdesc_t.
  1904. **/
  1905. extend_info_t *
  1906. extend_info_from_node(const node_t *node, int for_direct_connect)
  1907. {
  1908. tor_addr_port_t ap;
  1909. if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
  1910. return NULL;
  1911. if (for_direct_connect)
  1912. node_get_pref_orport(node, &ap);
  1913. else
  1914. node_get_prim_orport(node, &ap);
  1915. log_debug(LD_CIRC, "using %s for %s",
  1916. fmt_addrport(&ap.addr, ap.port),
  1917. node->ri ? node->ri->nickname : node->rs->nickname);
  1918. if (node->ri)
  1919. return extend_info_new(node->ri->nickname,
  1920. node->identity,
  1921. node->ri->onion_pkey,
  1922. node->ri->onion_curve25519_pkey,
  1923. &ap.addr,
  1924. ap.port);
  1925. else if (node->rs && node->md)
  1926. return extend_info_new(node->rs->nickname,
  1927. node->identity,
  1928. node->md->onion_pkey,
  1929. node->md->onion_curve25519_pkey,
  1930. &ap.addr,
  1931. ap.port);
  1932. else
  1933. return NULL;
  1934. }
  1935. /** Release storage held by an extend_info_t struct. */
  1936. void
  1937. extend_info_free(extend_info_t *info)
  1938. {
  1939. if (!info)
  1940. return;
  1941. crypto_pk_free(info->onion_key);
  1942. tor_free(info);
  1943. }
  1944. /** Allocate and return a new extend_info_t with the same contents as
  1945. * <b>info</b>. */
  1946. extend_info_t *
  1947. extend_info_dup(extend_info_t *info)
  1948. {
  1949. extend_info_t *newinfo;
  1950. tor_assert(info);
  1951. newinfo = tor_malloc(sizeof(extend_info_t));
  1952. memcpy(newinfo, info, sizeof(extend_info_t));
  1953. if (info->onion_key)
  1954. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1955. else
  1956. newinfo->onion_key = NULL;
  1957. return newinfo;
  1958. }
  1959. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1960. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1961. * the chosen exit, return NULL.
  1962. */
  1963. const node_t *
  1964. build_state_get_exit_node(cpath_build_state_t *state)
  1965. {
  1966. if (!state || !state->chosen_exit)
  1967. return NULL;
  1968. return node_get_by_id(state->chosen_exit->identity_digest);
  1969. }
  1970. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1971. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1972. * chosen exit, return NULL.
  1973. */
  1974. const char *
  1975. build_state_get_exit_nickname(cpath_build_state_t *state)
  1976. {
  1977. if (!state || !state->chosen_exit)
  1978. return NULL;
  1979. return state->chosen_exit->nickname;
  1980. }