circuitbuild.c 81 KB

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