circuitbuild.c 82 KB

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